Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.60.28.0 fix wave 5: #5558 and private-page privacy, large-brain onboarding, legacy job recovery, stale atoms and facts restore, eval-wave lane A (#5839)

Garry Tan0588aea6d616
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 2a5465bd7d..23c73bd5fc 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 9c461310b5..ef91e40c71 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 48f0ca0ff6..0d4f3594a5 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -138,9 +138,11 @@ jobs:
bun-version: ${{ matrix.bun }}
- run: bun install --frozen-lockfile --ignore-scripts
- name: Boundary and transport regressions
- run: bun test --timeout 60000 test/frontmatter-security.test.ts test/data-frontmatter.test.ts test/authorization-boundaries.test.ts test/url-safety.test.ts test/guarded-http.test.ts
+ run: bun test --timeout 60000 test/frontmatter-security.test.ts test/data-frontmatter.test.ts test/authorization-boundaries.test.ts test/url-safety.test.ts test/guarded-http.test.ts test/bundle-files-segments.test.ts
- name: Isolated TLS and proxy regressions
run: bun test --timeout 60000 test/guarded-http-tls.serial.test.ts
+ - name: Colon-slug Windows refusals and bound explicit reads (#5032, #5081)
+ run: bun test --timeout 60000 test/colon-slug-windows-5032.test.ts test/cross-lane-5081-5032.test.ts
dependency-audit:
if: ${{ github.event_name != 'workflow_dispatch' || inputs.native_only != true }}
diff --git a/AGENTS.md b/AGENTS.md
index 0db4332934..99ba758b07 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -132,7 +132,7 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
cumulative across `--resume`; a paid step that would exceed it is not
started while free steps still run. Without `--include-repairs`, repair
steps are listed as skipped. `--json` classifies each finding `cleared`,
- `pending`, `consent_required`, `operator_required` or `unsupported`.
+ `pending`, `consent_required`, `operator_required`, `explicit_kind_required` or `unsupported`.
Stale extraction uses source-scoped database pages, including DB-only
pages; it does not require a repository sync first. Empty brains (no
entity pages) or unconfigured embedding keys hit a `max_reachable_score`
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index adc956e3fd..3f7cf45bc4 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.60.27.0 -->
+<!-- gbrain-runbook-stamp: 0.60.28.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cf13ada029..244039a5cd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,168 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.28.0] - 2026-10-01
+
+**Fix wave 5: session start stops showing another session's text, private pages stay out of ambient recall, big brain repos onboard again, old queued jobs stop wedging synthesize, and the cleanups promised last wave ship.**
+
+Session start used to print a "Last session activity" line taken from whichever session on the machine wrote last. On a host where several agents or people share one machine, that could put one session's private text in front of another. The line is gone, along with the buffer behind it, and nothing turns it back on.
+
+A second privacy leak: `volunteer_context`, the per-turn hook block and `gbrain compile-context` could surface a `visibility: private` page's title and synopsis, including to remote MCP callers. Ambient recall now hides private pages the same way remote search does.
+
+Brain repos with more than about 10,000 files could not be added, claimed or moved: every attempt failed with a "1 MiB" error. That limit is gone. A 50,000-file repo now adds in under a second on our test machine.
+
+If you upgraded across v0.50, old queued jobs from before that release blocked every worker, so synthesize failed on every run and captures to `/ingest` returned a server error. Now old jobs are released or reused where that is safe, `/ingest` answers with a clear 409 and the fix, and `gbrain doctor` walks you through reviewing the rest.
+
+And the leftovers. `gbrain repair stale-atoms` cleans up search atoms that quote text a page no longer has, and `gbrain repair extractor-facts` brings back conversation facts an older release expired. `gbrain projections drain` rebuilds a search backlog right away instead of waiting on a drain that took 2 pages at a time. A stdio agent bound to one source can read the other sources you federated. Plus more than a dozen smaller fixes. Eight community pull requests went into this release.
+
+| After upgrading | Before | After |
+| --- | --- | --- |
+| Session start on a shared machine | could show another session's last message | shows only this workspace's own notes |
+| A private page in `volunteer_context`, the turn block or `compile-context` | title and synopsis shown | hidden (local CLI `volunteer_context` still sees it) |
+| `sources add` on a 50,000-file repo | `request_too_large` | under 1 s (PGLite and Postgres) |
+| A capture that hits a pre-v0.50 job | HTTP 500 | 202, or 409 with the recovery command |
+| Search atoms of deleted or rewritten pages | stay searchable | retired by `gbrain repair stale-atoms` after you review them |
+| Resident projection rebuild | 2 pages per tick | up to 100 pages per pass |
+| An exported key that differs from your config key | silently wins | still wins, with one warning naming both |
+
+## To take advantage of v0.60.28.0
+
+`gbrain upgrade` installs the binary. There is no schema migration. Most fixes take effect only in a process that runs the new binary, so restart everything that runs gbrain.
+
+**What you'll notice.** `gbrain doctor` may name new findings after the upgrade: `legacy_job_authority`, `text_projection_readiness`, `atom_provenance_drift`, `extractor_facts_expired` or `embedding_key_source`. `gbrain repair --all` and `gbrain doctor --remediate` list `stale-atoms` and `extractor-facts` with their preview command instead of running them. A non-default brain's autopilot job gets its own name and log file. Session start no longer shows a `Last session activity` line.
+
+**Why.** These are leftovers of earlier releases: jobs queued before v0.50, atoms and facts an older extraction left behind, and a projection backlog the resident drained 2 pages at a time. The two cleanups that delete or restore data run only when you name them and only on the exact set you previewed.
+
+**What to run.**
+
+1. **Restart every host and resident `gbrain serve`.** Stop autopilot and workers, stop each `gbrain serve` (HTTP services and harnesses that start stdio servers), run `gbrain upgrade` on each host, check `gbrain --version` through each launcher's own binary path, then restart. `gbrain sources writer status --json` shows the last version each host wrote with; it is history, not proof every process upgraded.
+2. **If you set `GBRAIN_HOOKS=0` to work around the session-start leak (#5558), remove it** from the environment your harness starts from (shell profile or service) and restart the harness. It also turns off session capture and persistence.
+3. **Run doctor, then fix what it names in this order:**
+ ```bash
+ gbrain doctor
+ # legacy jobs: stop gbrain serve, autopilot and workers first
+ gbrain jobs cancel <active id> # each active job doctor lists
+ gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"
+ gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused" --expect <hash> --yes
+ # restart serve and workers, then the search backlog:
+ gbrain projections drain # on PGLite, only while no resident holds the brain
+ # stale atoms and expired facts: preview, then apply the printed hash after you agree
+ gbrain repair stale-atoms --source <id>
+ gbrain repair stale-atoms --source <id> --apply --expect <hash>
+ gbrain repair extractor-facts
+ gbrain repair extractor-facts --apply --expect <hash>
+ gbrain doctor
+ ```
+4. **Code indexes re-chunk once.** `CHUNKER_VERSION` moves 7 → 8 so short `const f = () =>` functions keep their own named chunk; the next sync or `gbrain embed --stale` re-chunks code pages once.
+5. **Several brains on one host:** re-run `gbrain autopilot --install` for each non-default brain (`GBRAIN_HOME=<brain parent>`), then for the default brain.
+6. **Your agent reads `skills/migrations/v0.60.28.0.md`** the next time you talk to it. The full symptom table is in [Recover after upgrading](docs/guides/repair.md#fix-wave-5).
+7. **If any step fails,** file an issue at https://github.com/garrytan/gbrain/issues with the output of `gbrain doctor` and `~/.gbrain/upgrade-errors.jsonl` if it exists.
+
+**Say to your agent:** *"We upgraded gbrain. Restart what runs it, then walk me through what doctor finds, in order, before changing anything."* or *"Preview the stale atoms in my brain and tell me what you'd retire."*
+
+### Behavior changes
+
+- Session start never shows another session's activity. The `Last session activity` line and the stop-hook buffer behind it are removed, with deliberately no opt-in to restore them (#5558). Buffers an older release left in `~/.gbrain/transcripts/live/` are deleted by the stop hook after 7 days.
+- `volunteer_context` (for remote callers, honoring `search.remote_private_pages` like search), the per-turn hook block, the serve IPC `resolve` handler and `gbrain compile-context` exclude private pages, including derived-private atoms and concepts. The trusted local CLI still sees them in `volunteer_context`.
+- `CHUNKER_VERSION` 7 → 8: code pages re-chunk once.
+- `POST /ingest` returns 409 `{error: "permission_denied", message, hint, docs_url}` instead of 500 when a capture's key (or waiting cap) lands on a job row from before v0.50; completed legacy keys are reused (202) and dead or cancelled ones released.
+- Resubmitting over a job key from before v0.50 no longer fails: dead or cancelled keys are released, completed or failed rows are reused by local producers, and remote `submit_job` callers are refused over terminal legacy keys and resubmit with a new key.
+- `gbrain repair --all`, `gbrain repair` with no kind, the remediation plan and `gbrain doctor --remediate` exclude the explicit-only kinds `stale-atoms` and `extractor-facts`: they are listed with their preview command (`explicit_kind_required`) and never run. A finding only they clear does not fail `--remediate`'s exit status.
+- Autopilot jobs are named per brain. The default brain (`~/.gbrain`) keeps `com.gbrain.autopilot`, `gbrain-autopilot.service`, `~/.gbrain/start-autopilot.sh` and an unmarked crontab line; any other `GBRAIN_HOME` gets names with its own suffix (from `<brain>/.gbrain/autopilot-install-id`), a marked crontab line, and logs to `<brain>/.gbrain/autopilot.log`.
+- New stderr warning, once per process and never from `gbrain hook`, when an exported provider key differs from the matching config key. The environment still wins; `gbrain config unset <key>` silences it.
+- New stderr error `embedding_auth_failed` on the first embedding 401 or 403 in a process, naming the key source in effect. Provider error text is scrubbed of key values, masked key echoes and key fragments before it reaches CLI output, `--json` or job errors.
+- The upgraded resident drains up to 100 projection pages per pass (2 while writes wait) instead of 2 per tick.
+- Managed `remember` for a person or company with no page keeps that entity's name as the fact's subject, so the same commitment for two absent people is two facts, as on an unmanaged brain.
+- `serve --http` keeps serving when its stdout or stderr pipe closes; stdio `serve` still exits.
+- A bare `gbrain upgrade` on an exact-tag Bun install that did not move now exits 1 with the reinstall command (it used to say "Upgrade complete").
+- `embed` on Postgres caps its worker count at the connection pool (`GBRAIN_POOL_SIZE`, default 10); an explicit higher `GBRAIN_EMBED_CONCURRENCY` prints one warning.
+- Migration children (backfills, smoke tests, autopilot install) run the CLI that runs the migration instead of the `gbrain` on PATH.
+- `sources writer deactivate` no longer refuses on held Google or GitHub items: it copies them into each source's classic state file (`carried_holds`).
+- `gbrain connect --install` for Codex, Claude Code and opencode prints where the token lives and how to replace it.
+- `search` and `query` treat `types: []` as no type filter (over MCP and the CLI); the CLI also accepts `""` and whitespace-only strings. Over MCP, `types` must still be an array, so omit it or pass `[]`.
+- Colon slugs such as `calendar:abc` are writable again; on Windows a write whose file name would contain `:` is refused with `colon_slug_windows_write_through`.
+- Every host and resident `gbrain serve` must be restarted for these to apply.
+
+### Itemized changes
+
+#### Privacy
+
+- **Session start shows only this session's own context (#5558).** The session-start digest printed the newest stop-buffer entry on the machine, whatever agent or session wrote it. The line and the stop-hook buffer write are removed, the stop hook garbage-collects buffers older binaries left, and a test runs every hook event against buffers other sessions left and asserts none of their text appears. There is no setting that restores the cross-session line.
+
+#### Large brains and harness access
+
+- **Repos over ~10,000 files onboard again (#5790).** Stored worktree manifests carry only `digest` and `file_count`, not a per-file hash map, so `sources add`, `claim`, `rebind`, `archive`, `remove`, clone, reclone and `sources writer transfer` no longer hit the 1 MiB metadata bound. Rows written by older releases stay valid and are compacted on their next rewrite (no migration). Above 5,000 files, human output reports `sources.manifest_hash` progress on stderr, and `sources writer transfer prepare/accept` hash the worktree before opening the database transaction. Measured with 50,000 files (3.4 MB) on a 4-vCPU machine: `sources add`, `claim` and transfer prepare and accept each under 1 s on PGLite and Postgres; peak memory growth about 100 MB on Postgres and 325 MB on PGLite.
+- **`gbrain connect --install` says where the bearer token lives (#5775).** For Codex, Claude Code and opencode the receipt prints `token_storage`, `config_path`, `renew_command`, `if_exposed` and `token_warning`, and `--fresh-token` forces a new token exchange. `docs/mcp/CODEX.md` and the hosted harness guide now say the token is stored inline in the harness config.
+- **A mounted brain's `gbrain serve` accepts writes (#5237).** A resident `serve` in a `.gbrain-mount` project binds its persistence owner for the mounted brain, so CLI writes no longer fail `owner_unavailable` and MCP writes no longer stay queued.
+- **Backup coverage sees private remotes (#5794).** The remote probe passes `HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, the proxy variables and, on Windows, `USERPROFILE`, `APPDATA` and `SystemRoot`, so your Git config and credential helpers apply.
+
+#### Atoms, facts and sync
+
+- **Managed re-extraction retires atoms it no longer produces (#5770).** Retired atoms are soft-deleted with `retired_by`, and a later extraction that produces one again restores it. Contributed by @cmontemuino (PR #5774).
+- **New `gbrain repair stale-atoms`** (explicit-only, preview-bound) retires atoms that drifted before this release: atoms of deleted pages (`origin_gone`) and atoms of edited pages whose new text was already extracted (`origin_changed`). `--apply --expect <hash>` retires exactly the previewed set; atoms stay recoverable through `restore_page` for 72 hours.
+- **New `gbrain repair extractor-facts` (#5731).** Restores conversation-extractor facts the pre-v0.60.11.0 projection expired. Facts with receipt evidence restore by default, ambiguous ones only with `--include-ambiguous` and that preview's hash; superseded, withdrawn and duplicated facts never come back. Database-only: no page or file is rewritten. Doctor `extractor_facts_expired` counts candidates.
+- **Managed `remember` keeps attribution for absent entities.** A single fact for a person or company with no page keeps the resolver's fallback slug, so dedup and withdrawal are per entity. The facts backstop is unchanged.
+- **Read-only mirror sources (#5409).** `gbrain sources mirror-readonly <id>` marks a source whose Git remote is authoritative: managed sync and page writes never write files into its checkout, receipts say `storage: "database_only"`, and `gbrain sources mirror-writable <id>` undoes it. Off by default.
+- **Managed sync stops recording a sticky `source_changed`** when a pinned commit trails the page's own queued write (#5777). Contributed by @howardpark (PR #5778).
+- **Withdrawals no longer wedge on `RESOLVER.md` or a locally edited page (#5396).** The page is listed in the effect's `data.skipped` (`metafile` or `file_database_drift`) and the request's Git and embedding effects proceed.
+
+#### Jobs and the v0.50 upgrade
+
+- **Old queued jobs stop blocking synthesize and `/ingest` (#5157, #5114).** One coalesce rule for rows with no submission authority covers every submission path. Thanks to @hausenpepper, whose PR #5048 found the fast-path fix.
+- **New `gbrain jobs authorize-legacy --select <filter>` and `gbrain jobs cancel --select <filter>`.** Both preview by default (counts by job and status, the first 20 ids, paid-provider job names, a hash), and `--expect <hash> --yes` applies exactly the previewed set. Refusals are coded: `legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`.
+- **New doctor check `legacy_job_authority`** counts the rows that block workers and prints the filled commands; `gbrain post-upgrade` names the read-only recovery preview when live legacy rows exist.
+
+#### Search and projections
+
+- **New `gbrain projections drain [--limit n] [--json]` (#5401)** rebuilds queued text projections now (exit 0, 1 when pages failed, 2 when it did not run). On PGLite with a resident owner it refuses with `projection_owner_resident` and prints the stop, drain and restart commands, naming this brain's own autopilot job. Doctor `text_projection_readiness` names the drain, or reports the resident's pending count.
+- **`search` and `query` accept an empty type filter (#5390).** `types: []` means no filter instead of `invalid_params`, and the CLI also accepts `""` and whitespace-only strings (MCP still requires an array, so omit `types` or pass `[]`); `['']`, `' , '` and `',,'` still fail. Contributed by @RerankerGuo (PR #5781).
+- **Provider key source (#5137).** The shadow warning and doctor check `embedding_key_source` say which key is in effect; see the behavior changes above.
+
+#### Sources and agents
+
+- **A bound stdio agent can read federated sources (#5081).** A stdio `gbrain serve` bound with `GBRAIN_SOURCE` or a `.gbrain-source` pin can read a `federated: true` source by naming it in `source_id` (`search`, `query`, `get_page`, `list_pages`, `resolve_slugs`, `recall`). Unqualified reads stay on the bound source, and a source with `federated: false` still reads only itself. An unbound stdio connection or a no-grant HTTP token may likewise name any source its unqualified reads already span. Refusals now say why.
+- **Colon slugs are writable again (#5032).** Contributed by @javieraldape (PR #5044). On Windows a write whose file name would contain `:` is refused before admission with `colon_slug_windows_write_through`, database-only writes succeed (including into a read-only mirror source), and `gbrain sync` skips each such file with that named refusal instead of failing the run.
+- **`gbrain frontmatter validate --fix` keeps correct `slug:` fields (#5053).** It compares against the brain-root-relative path, so it no longer deletes them or re-keys pages.
+- **`recall --source default` means the default source (#5535).** An explicit `--source default` no longer falls through to `GBRAIN_SOURCE` or `sources.default`. Contributed by @RerankerGuo (PR #5706).
+- **`think` saves syntheses to the source it drew from (#5426),** and each citation binds to a page in those sources instead of the first page anywhere with that slug.
+
+#### Hosts, upgrades and autopilot
+
+- **Autopilot jobs per brain (#5195).** `--status` and `--uninstall` act only on this brain's job; `--status` prints the job names, install-id path, wrapper and log, and flags a moved brain's missing wrapper and a legacy shared job. A job whose wrapper runs another live brain is never replaced or removed (`autopilot_job_owned_by_other_brain`).
+- **Migrations follow `GBRAIN_HOME` (#5549).** The v0.11.0 and v0.22.4 orchestrators resolve their state through the brain home instead of `$HOME`. Contributed by @andreineacsu (PR #5696).
+- **Migration children run the running CLI (#5184),** not whatever `gbrain` is on PATH.
+- **`gbrain upgrade` stops reporting false success (#5311)** on an exact-tag Bun install that did not move.
+- **`serve --http` survives a closed log pipe (#5079).**
+- **`embed --stale` no longer waits on itself (#5183)** when `GBRAIN_EMBED_CONCURRENCY` exceeds the Postgres pool.
+- **`sources writer deactivate` carries held connector items** into classic mode instead of refusing.
+- **An autopilot cycle no longer stales a `sources reconcile` preview:** the reconcile policy digest ignores the cycle stamps.
+
+#### Ambient recall, transcripts and code intelligence (from the eval-category wave)
+
+- **Private pages stay out of ambient recall (N8).** `resolveEntitiesToPointers` applies the remote-search private-page predicate on every arm (title, slug, surname, alias, CJK), so `volunteer_context` and the turn block no longer return a private page's title or synopsis; `compile-context` no longer writes private titles and excerpts into `.claude/gbrain-context.md` or `AGENTS.md`.
+- **Open-loop nudges measure grace from the oldest unanswered message (N7).** A run that started days ago is no longer hidden by a fresh follow-up; CC-only mail does not start the clock.
+- **Bold labels are not a conversation (N12).** A body with three or more `**Name**` turns where no speaker speaks twice no longer parses as a chat.
+- **Offset timestamps import on the right day (N12).** Transcript render and the Claude export, Claude Code, Codex and OpenClaw adapters normalize offset-bearing timestamps to UTC; UTC strings pass through unchanged.
+- **Short arrow functions keep their names in code search (N13).** `const f = () =>` and function-expression declarations keep a named chunk instead of merging into a const run.
+- **Code intelligence reports resolved edges as resolved, and a walk ignores other languages' namesakes (N13).**
+
+#### Models, skills and summaries
+
+- **Claude Opus 5.5 is priced (#5359, #5494):** $4 in, $20 out per million tokens, so `--max-cost` runs on it estimate instead of failing with `no_pricing`.
+- **Voice gates work without Anthropic credit (#5165):** the judge model resolves through the key-aware utility tier.
+- **Skill bundles publish on Windows (#5776):** paths are checked per segment.
+- **`brain-pdf` keeps the whole page (#5772):** a portable parser strips only the leading frontmatter block, on macOS and Linux.
+- **Chunk synopses stop failing forever on emoji at the cut (#5316):** the document is truncated on a surrogate-pair boundary. Contributed by @furuchanchan (PR #5387).
+- **Google embedding rejections no longer use up a migration budget:** a request-shaped rejection (400, 413, 422) settles at zero cost for Google, whose billing documentation says rejected requests are not charged. Other providers keep the debit until they document the same.
+
+### For contributors
+
+- `src/core/error-catalogue.ts` maps each wave 5 refusal to its stable code and docs anchor; `test/error-catalogue.test.ts` fails when an anchor in `docs/guides/repair.md` or `docs/guides/write-refusals.md` is renamed.
+- `explicit_only` on `RepairKindSpec` is read by `REPAIR_HELP`, `--all`, the remediation plan and the banner, and enforced inside the runners, so a supplied remediation step cannot run an explicit-only kind.
+- `src/core/persistence/preview-approval.ts` (`previewHash`, `saveApprovedSet`, `loadApprovedSet`) backs every preview-bound apply: `authorize-legacy --select`, `jobs cancel --select`, `stale-atoms` and `extractor-facts`. An approved set older than 7 days refuses with `preview_changed`.
+- `HOOK_EVENTS` in `src/commands/hook.ts` is the dispatcher's event list and the session-isolation matrix test's input.
+- New guide anchors: `docs/guides/repair.md#fix-wave-5`, `#projection-drain`, `#embedding-key-source`, `#stale-atoms`, `#extractor-facts`.
+
## [0.60.27.0] - 2026-10-01
**GBrain now needs Bun 1.4 or newer, because a bug in older Bun releases could make GBrain wait forever on a helper process that had already finished.**
diff --git a/TODOS.md b/TODOS.md
index ca78ecdd4c..3cceac2684 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -17,14 +17,47 @@
- [ ] **P3 — Time the System One quickstart on a fresh machine (`/devex-review`).**
**What:** measure the documented key-in-hand to first-decision clock against the under-5-minute target. **Effort:** S. **Priority:** P3.
+## Fix wave 5 follow-ups (filed 2026-10-01, follow-up from v0.60.28.0)
+
+- [ ] **P3 — Windows: unmanaged sync refuses a repo under an 8.3 short path.**
+ **What:** `resolveSyncRepo` (`src/commands/sync/preflight.ts`) compares `realpathSync(scope)` with the git root git reports. On Windows `realpathSync` keeps an 8.3 component (`RUNNER~1`) while git returns the long form, so the scope-entry guard refuses with "resolves outside git repo". Seen on the windows-latest runner, whose TEMP is a short path; the #5032 test fixture now starts from `realpathSync.native(tmpdir())`. **Fix:** compare `realpathSync.native` on both sides. **Effort:** S. **Priority:** P3.
+- [ ] **P2 — Codex managed block is a singleton shared by `connect --harness codex` and `bootstrap harness` (#5775 follow-up).**
+ **What:** `src/core/bootstrap/codex-toml.ts` keeps exactly one `# gbrain:bootstrap-harness-v1 begin/end` pair per file; `writeCodexHttpServerBlock` strips any existing managed block regardless of its server name and writes its own, and `removeCodexHttpServerBlock(path, name)` removes the block whatever name it holds. Writing `[mcp_servers.gbrain]` (connect) then `[mcp_servers.gbrain-framework]` (bootstrap) leaves only the second; removing `gbrain-framework` while the block holds `gbrain` deletes it. `connect --install` refuses over a bootstrap-written block, but `bootstrap harness` and `bootstrap harness --remove` silently replace or remove a connect-installed block. **Fix:** per-name markers, or an ownership check in the bootstrap lane. **Effort:** S-M. **Priority:** P2.
+- [ ] **P3 — Expired inline-token warning for `connect --status` (#5775 follow-up).**
+ **What:** `gbrain connect --harness <id> --status` could flag an inline token past `expires_at` and print the `renew_command`. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Backup probe: honor a user's SSH command.**
+ **What:** the remote-ref probe replaces `GIT_SSH_COMMAND` with its own `-oBatchMode=yes` command (`src/core/backup/repository.ts`), so deploy-key users who select keys that way stay `unavailable`. **Fix:** merge the user's identity options with BatchMode. Deploy keys work today through `~/.ssh/config`. **Cons:** parsing a user shell command is fragile. **Effort:** S. **Priority:** P3.
+- [ ] **P2 — CI large-brain smoke tier.**
+ **What:** 10k-50k file brains for `sources add`, `claim` and sync beyond the one recorded case in `test/e2e/persistence-large-manifest-50k.test.ts`. **Why:** #5790 (1 MiB manifest bound) and #5401 (2-page projection drain) both reached users before a test saw a large brain. **Cons:** CI time and cost. **Effort:** M. **Priority:** P2.
+- [ ] **P3 — Cost estimate for bulk-approved paid legacy jobs.**
+ **What:** `gbrain jobs authorize-legacy --select` previews mark paid-provider job names but do not estimate spend; approving thousands of old synthesize jobs can spend money. **Fix:** a per-handler cost model in the preview. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — Remote-op contract test for type-zero optional parameters (#5390 remainder).**
+ **What:** `search`/`query` now treat `types: []`, `""` and whitespace-only strings as no filter on the CLI, but over MCP `types: ""` is still refused by the array type check. **Fix:** one contract test across remote ops asserting how each optional parameter's empty value (`[]`, `""`, `null`) is handled, then align the schema checks. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Key the session-start context pack by a raw-id hash.**
+ **What:** the SessionStart context pack keys its cursor on `sanitizeSessionId(session_id)` (`src/commands/hook.ts`, ambient recall arm), so two raw ids that sanitize to the same string share a cursor. **Fix:** key on a hash of the raw id in both the session-start and compact arms together. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — Colon-slug escape mapping for Windows portability (#5032 follow-up).**
+ **What:** colon slugs such as `calendar:abc` are writable again, but on Windows a write whose file name would contain `:` is refused (`colon_slug_windows_write_through`) and sync skips such files. **Fix:** a reversible slug-to-filename escape for `:` so colon-slug brains stay portable to Windows checkouts. **Cons:** a filename mapping every reader and writer must agree on. **Effort:** M. **Priority:** P3.
+- [ ] **P2 — #4951: PGLite `serve --http` wedges on stale planner statistics.**
+ **What:** a reporter saw `readAdjacencyBoosts` take about 72 s with nested-loop plans; a full `ANALYZE` on pages, links, sources, timeline_entries and content_chunks dropped it to 21 ms. PGLite has no autovacuum and runs queries on the main thread, so a slow plan looks like a wedge. Cause likely, unverified for `get_links`. **Fix:** run `ANALYZE` on the hot tables after migrations, bulk import or sync and periodically from the owner, plus a doctor check for stale `last_analyze`. **Effort:** S-M. **Priority:** P2.
+- [ ] **P3 — #5190: pin `search_path` for the two fact functions.**
+ **What:** `gbrain_fact_fingerprint` and `gbrain_preserve_fact_withdrawal` (`src/core/facts/withdrawal-schema.ts`) have no pinned `search_path` (Supabase linter warning). `gbrain_fact_fingerprint` backs an index expression and must stay inlinable, so qualify its calls (`pg_catalog.`) instead of `SET search_path`; pin only the trigger function. **Effort:** S. **Priority:** P3.
+- [ ] **P2 — #5205: resident `serve` pool-size guidance.**
+ **What:** a `serve` boot never completed at `GBRAIN_POOL_SIZE=2`, which our remediation text still recommends (`src/core/pg-access-classify.ts`, `src/commands/db-repair.ts`). The deadlock mechanism is unverified. **Fix:** measure the connection need of a resident `serve` first, then change the guidance (the reporter measured 6 as the minimum at which the projection worker drains) and fail fast with a pool-size message. **Effort:** S once measured. **Priority:** P2.
+- [ ] **P3 — #5250: signal when `GBRAIN_SOURCE` narrows an unqualified stdio read.**
+ **What:** a stdio connection bound with `GBRAIN_SOURCE` (or `__all__`) can return nothing for an unqualified read with no hint why, so agents conclude the brain is empty. **Fix:** a response note naming the binding when it narrowed the read. **Effort:** S. **Priority:** P3.
+- [ ] **P3 — #5216: orphan-repair command for PGLite.**
+ **What:** migration 150's volatile default rewrites `pages` and hits a torn TOAST chunk on a corrupt PGLite brain; doctor's `child_table_orphans` prints raw `DELETE` SQL that PGLite users cannot run. **Fix:** `gbrain repair orphans` running doctor's own cleanup, plus a re-import-from-canonical-file repair for a torn body. Changing migration 150 itself is high risk for a corruption edge case and stays out. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — #5279: abandon an unactivated writer claim.**
+ **What:** a claim that was never activated leaves ownership markers that fence legacy sync, and there is no undo before activation. **Fix:** `gbrain sources writer claim <source> --abandon`, refused once the brain is enabled, that removes only markers stamped with this brain and claim. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — #5041: classic write-through for `extract_atoms` and `synthesize_concepts`.**
+ **What:** on classic brains with `sync.repo_path`, atoms and concepts are written to the database only; neither phase calls `writePageThrough`. Managed brains publish them through maintenance publication. **Fix:** opt-in write-through for generated pages, careful not to write raw-input types into gitignored paths. **Effort:** M. **Priority:** P3.
+- [ ] **P3 — #5061: `getStats`/`getHealth` cost on large Postgres brains.**
+ **What:** both are uncached full aggregates, and `getHealth` runs a per-page links count; they are reachable from the CLI, `/admin/api/full-stats` and the MCP stats and health ops, so a client polling them loads a large brain. The admin dashboard itself does not poll them. **Fix:** a short TTL cache or estimate counts on the HTTP and MCP paths. **Effort:** M. **Priority:** P3.
+
## Fix wave 4 follow-ups (filed 2026-09-30, follow-up from v0.60.20.0)
-- [ ] **P2 — #5731 residual: restore extractor facts the pre-fix projection expired (wave 5).**
- **What:** the #5731 fix stops the canonical projection from expiring conversation-extractor facts, but rows it expired before the fix stay expired. **Fix:** the explicit-only `gbrain repair extractor-facts` kind from the wave 4 plan: a preview that lists every candidate with its class and evidence and a preview hash, `--apply` that restores only defect-evidenced rows through a named maintenance intent, `--include-ambiguous <hash>` for rows a fence takeover could explain, and a stale-hash refusal. **Why deferred:** below the wave 4 cut line. **Effort:** M. **Priority:** P2.
- [ ] **P3 — #5751 follow-up: `gbrain repair file-normalization` (wave 5).**
**What:** managed working-tree sync now skips unchanged legacy files whose bytes differ from what gbrain reads back (for example non-UTF-8), and the summary tells the user to re-save them. **Fix:** an explicit-only repair kind that rewrites each such file in canonical form through a canonical file publication followed by its Git effect, reported by `gbrain repair`, remediation and the post-upgrade banner as `explicit_kind_required`. **Why deferred:** below the wave 4 cut line. **Effort:** M. **Priority:** P3.
-- [ ] **P3 — Carry connector holds across `gbrain sources writer deactivate`.**
- **What:** a managed brain keeps connector holds in the managed connector checkpoint, which classic mode does not read, so deactivate refuses while any item is held (exit: fix the cause `gbrain sources status <id>` names, then `gbrain sources retry-held <id>` and `gbrain sync --source <id>`). An item that can never succeed therefore blocks deactivation. **Fix:** copy `item_holds` into the classic state file during deactivation, so a still-failing item stays held and visible instead of blocking the mode change. **Effort:** S. **Priority:** P3.
- [ ] **P3 — Convert a bound connector's filesystem worktree to database-only operation (#5673).**
**What:** `gbrain sources set-path <id> --clear` refuses a connector source that has a live persistence source binding, because its worktree still owns that checkout; that refusal is the interim exit. **Fix:** a supported conversion that retires the connector's worktree binding and leaves it syncing database-only. **Effort:** M. **Priority:** P3.
@@ -54,7 +87,7 @@
### Recovery layer
- [ ] **P1 — Bounded replay window for lifetime request IDs (wave-2 CEO-E7).**
- **What:** every admitted write keeps a permanent request ID for replay protection, so the principal and brain lifetime-ID limits only move later (`persistence_capacity` warns at 80% and names a `gbrain config set` value). **Fix:** a bounded replay window with a documented horizon and an eviction rule that never replays a committed write twice; size it from the default of 600 admissions a day (about 417 days of headroom at the default limit). **Effort:** L. **Priority:** P1.
+ **What:** every admitted write keeps a permanent request ID for replay protection, so the principal and brain lifetime-ID limits only move later (`persistence_capacity` warns at 80% and names a `gbrain config set` value). **Fix:** a bounded replay window with a documented horizon and an eviction rule that never replays a committed write twice; size it from the default of 600 admissions a day (about 417 days of headroom at the default limit). **Trigger:** start when the first `persistence_capacity` warning is reported from a real brain. **Effort:** L. **Priority:** P1.
- [ ] **P1 — Opt-in `min_writer_version` floor.**
**What:** the `writer_version` doctor advisory only observes: a binary older than v0.60.5.0 can still delete database-only timeline rows. **Fix:** an opt-in floor enforced at admission and publication by the database (reusing the `writer_protocol_floor` trigger pattern), a binary version declaration older binaries lack, quiescence to enable it, and a floor that cannot be lowered. Eng estimate 1,500-3,000 changed lines against 800-1,500 for the advisory. **Effort:** L. **Priority:** P1.
- [ ] **P2 — #5226 part 2.** Revisit only after part 1 is confirmed fixed with pacing on. **Priority:** P2.
@@ -64,12 +97,11 @@
- [ ] **P3 — `source-paths` / `source-uris` repair kinds and the metadata-repair intent (dropped from W8).** Revisit when `invalid_source_uri` reports arrive; the manual step in `docs/guides/write-refusals.md` stands until then. **Priority:** P3.
- [ ] **P3 — Doctor check for unpushed managed commits by age (#5198 thread).** **Priority:** P3.
- [ ] **P3 — #5392 inert single-writer mode.** Recommended no: resolve through the #5198/#5254 family instead. Recorded so the decision is visible. **Priority:** P3.
-- [ ] **P3 — Retire `safeChunkUpgradeAdvisory`.** Post-upgrade now reports `safe_index_pending` through the recovery banner; the function remains only for `test/safe-chunk-reseal.test.ts`. Move that assertion onto the doctor check and delete the function. **Effort:** S. **Priority:** P3.
### Connectors
- [ ] **P1 — Move the cycle stamps out of `sources.config`.**
- **What:** `runCycle` writes `last_source_cycle_at` / `last_full_cycle_at` into `sources.config` after every source cycle; that rotating blob was the root cause behind #5686. v0.60.11.0 keys connector identity on parsed settings instead, but nine files still read the stamps from the blob. **Fix:** dedicated columns or a cycle-state row, with a migration; community PR #5695 sketched one.
+ **What:** `runCycle` writes `last_source_cycle_at` / `last_full_cycle_at` into `sources.config` after every source cycle; that rotating blob was the root cause behind #5686. v0.60.11.0 keys connector identity on parsed settings instead, but nine files still read the stamps from the blob. **Fix:** dedicated columns or a cycle-state row, with a migration; community PR #5695 sketched one. `reconcilePolicyDigest` now excludes `last_source_cycle_at`/`last_full_cycle_at` (v0.60.28.0), so an autopilot cycle no longer stales a `gbrain sources reconcile` preview; moving the stamps out of `sources.config` stays open.
- [ ] **P2 — Per-source "admit even if unchanged" bypass for the #5470 no-op skip.**
**What:** there is no way to force one connector, import or sync source to republish unchanged pages (for example after a renderer fix that keeps content hashes). **Fix:** a source-scoped, one-run flag that disables the kernel skip; `--reset-checkpoint` only re-walks.
- [ ] **P3 — Configurable connector pending-wait budget, clamped to the run's deadline.**
@@ -89,10 +121,8 @@
### Maintenance writers
-- [ ] **P2 — Managed `writeSingleFact` keeps unresolved entity attribution.**
- **What:** on a managed brain a single fact for an entity with no page is stored database-only with `entity_slug` NULL (the response now reports that honestly), so the same claim for a second absent entity dedups against the first. The shared `managed_facts_entity` preparer accepts only the row's slug or NULL. **Fix:** an opt-in intent flag used only by `writeSingleFact`: `publishManagedFacts` keeps the resolver's fallback slug on `memory/unattributed` rows, and `prepareManagedFactsMutation` allows that slug on rows without a row number and passes it to `insertFact`, so dedup is per entity; add a test pinning the facts backstop's unchanged replay and dedup contract.
-- [ ] **P3 — Release the reservation of other permanent embedding rejections.**
- **What:** the migration budget now refunds a provider token-limit rejection (it bills nothing), but the drain's per-chunk fan-out after another permanent 4xx (400/413/422) keeps the failed batch's maximum debit; the overshoot and exhaustion refusal bound it, but it can stop a migration early. **Fix:** map those unbilled rejections through the same `invokeAI` rejection mapper, with a test at exactly the printed cap.
+- [ ] **P3 — Release the reservation of other permanent embedding rejections, per provider.**
+ **What:** v0.60.28.0 settles a request-shaped embedding rejection (HTTP 400, 413 or 422) at zero usage only for Google, whose billing FAQ says rejected requests are not charged. OpenAI, Voyage and the other embedding recipes publish no such statement, so their rejections keep the maximum debit against a `gbrain migrate embeddings --max-cost-usd` authorization and a migration can still stop early at the cap. **Fix:** add each provider to the unbilled-rejection list only after its documentation (or a billing-console check) confirms rejected requests are free, with a test at exactly the printed cap. **Effort:** S per provider. **Priority:** P3.
## Test-audit follow-ups (filed 2026-09-29)
diff --git a/VERSION b/VERSION
index ffc4da6137..a3343a8bc4 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.60.27.0
+0.60.28.0
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index d798f4b289..f9a9c26036 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -28,7 +28,8 @@ boundary and add its link here rather than raising the cap.
| [Canonical reconciliation](key-files/canonical-reconciliation.md) | Exact-page repair, private retained originals, derived atom state and receipt diagnostics |
| [Company-brain ingestion](key-files/company-brain.md) | Inspection, admission, receipts, derived relationships and schema; [operator guide](../guides/company-brain-ingestion.md) |
| [Commands (1/6)](key-files/commands-1.md) | `src/commands/agent-logs.ts` through `src/commands/db-repair.ts` |
-| [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` through `src/commands/embed.ts` |
+| [Commands (2/6)](key-files/commands-2.md) | `src/commands/doctor.ts` and `src/commands/doctor/` |
+| [Commands (2/6, continued)](key-files/commands-2-continued.md) | `src/commands/dream-retriage.ts` through `src/commands/embed.ts` |
| [Commands (3/6)](key-files/commands-3.md) | `src/commands/engine-status.ts` through `src/commands/frontmatter-install-hook.ts` |
| [Commands (4/6)](key-files/commands-4.md) | `src/commands/graph-query.ts` through `src/commands/reindex-search-vector.ts` |
| [Commands (5/6)](key-files/commands-5.md) | `src/commands/reindex.ts` through `src/commands/storage.ts` |
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 95b29a9ae4..9e3a09e81a 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -192,3 +192,8 @@ src/core/schema-migrations/v142-takes-embedding-dimension-matches-config.ts 1 sc
src/core/schema-migrations/v144-open-loops.ts 1 schema Schema installation and forward-reference DDL; coordinated activation quiesces canonical writers.
src/core/persistence/connector-path.ts 1 coordinator Connector path clear locks the source row, refuses filesystem sources and bound connectors, and runs as a coordinated write on managed brains.
src/core/source-delete.ts 1 engine_guard Unmanaged source delete with its incarnation binding; managed brains route removal through source lifecycle first and the writer guard refuses a direct delete.
+src/core/repair/extractor-facts.ts 1 coordinator `gbrain repair extractor-facts` (#5731) clears expired_at on preview-approved conversation-extractor facts and gives each a fresh row number. On a managed brain the UPDATE runs only inside the managed_maintenance_restore_extractor_facts publication (withCoordinatedWrite, page key locked, each fact reclassified first); an unmanaged brain runs the same function in one transaction under the page lock.
+src/core/persistence/atom-maintenance.ts 1 coordinator A managed atom retirement stamps retired_by/retired_at on the tombstone inside the coordinator publication of its managed_atom_delete request, after the page deletion path removed the canonical file, so the database row and file change commit or roll back together.
+src/core/repair/stale-atoms.ts 2 coordinator gbrain repair stale-atoms retires an atom on a managed brain through a managed_maintenance_retire_stale_atoms coordinated request (the marker stamp runs in its publication); only an unmanaged brain soft-deletes and stamps in a direct page-locked transaction, where no canonical writer enforcement applies.
+src/commands/sources-mirror.ts 1 engine_guard `gbrain sources mirror-readonly|mirror-writable` (#5409) updates only sources.config.mirror_read_only, exactly as `sources federate` updates sources.config.federated; the sources managed_writer_guard trigger governs the row and no page, fact or file is written.
+src/core/persistence/mirror-read-only.ts 1 coordinator classifyMirrorPage stamps pages.database_only_reason=mirror_read_only only inside the coordinator publication transaction of a page write that published no file into a read-only mirror source (#5409), as classifyUnboundPage does for unbound sources.
diff --git a/docs/architecture/conversation-parser-patterns.md b/docs/architecture/conversation-parser-patterns.md
index 22dca7e57c..23b06093b1 100644
--- a/docs/architecture/conversation-parser-patterns.md
+++ b/docs/architecture/conversation-parser-patterns.md
@@ -137,7 +137,7 @@ formats:
- `**Speaker** (09:15): text` uses `bold-paren-time`.
- `**Speaker** (9:15 AM): text` uses `bold-paren-time-12h`.
-- `**Speaker:** text` uses `bold-name-no-time`.
+- `**Speaker:** text` uses `bold-name-no-time`. Its `repeat_speaker_min_turns: 3` structure gate returns no_match when three or more turns never repeat a speaker — a status note's `**Status:**`/`**Owner:**`/`**Next step:**` labels are not a conversation (gbrain-evals N12-1).
- `**Speaker** (2026-04-09 9:15 AM): text` uses `imessage-slack`.
Keeping these examples in both `test_negative` and parser regression tests makes
diff --git a/docs/architecture/key-files/agent-bootstrap-continued.md b/docs/architecture/key-files/agent-bootstrap-continued.md
index d3e32017fd..0022ef7088 100644
--- a/docs/architecture/key-files/agent-bootstrap-continued.md
+++ b/docs/architecture/key-files/agent-bootstrap-continued.md
@@ -27,7 +27,7 @@
- `src/core/transcripts/render.ts` — session → conversation page(s) for `gbrain transcripts ingest`. `redactSession` is two-phase over message text, speaker labels, title and every raw-meta string, BEFORE any engine write: `planRedaction(…, { highEntropy: true, echoValues })` on every field into ONE session-wide echo dictionary, then `applyRedaction` per field, so a bearer or high-entropy value claimed in one message is scrubbed where it recurs bare in any other field, in either order; echoes add nothing to `redactionCount` (fail-closed: a scanner/pattern throw aborts the session), then the operator pattern file; nested raw-meta values are dropped. This is the only lane that opts into the entropy heuristic (pasted `.env` lines are most likely here). Rendering shares the imessage-slack anchor regex with the parser and escapes body lines that would forge it; long sessions split into `-pN` parts under the embed-skip threshold. Each `RenderedPart` carries the `frontmatter` it owns and its `body`; on re-ingest `runTranscriptsIngest` carries any other key already on the page (a review flag another tool added) onto the re-rendered part, except the re-derived safety and atom-scan markers (#5431, `test/transcripts-retitle.test.ts`).
- `src/core/context/sensitivity-scan.ts` — composed detector for compiled-context entries (secret-scan → PII → path shapes → operator blocklist → operator pattern file). secret-scan OWNS credential-shaped families it also matches: a PII finding whose value (raw, or with the `Bearer ` keyword stripped) matches a secret finding's fingerprint is not reported twice; short bearer tokens under secret-scan's floor still surface as `pii:bearer`. Every family honors the same `.gbrain-scan-allow` fingerprint escape hatch.
- `src/core/backup/status-file.ts` — ENGINE-FREE core of the monthly backup-coverage check: the cached verdict (`~/.gbrain/backup-status.json`, schema `gbrain-backup-status-v1`; fail-open load, atomic tmp+rename write, `invalidateBackupStatus()` fired by the fix paths — `bootstrap repo` receipt write, `sources harden`, `workspacePush` finish on ok when the cache carried a warn or failing/unpushed totals (a routine healthy push leaves an ok cache alone, preserving the monthly throttle)), the notice renderer (`backupNoticeText(s, 'human'|'aggregate')` — human ≤300 chars names assets, aggregate is counts-only for remote surfaces; the remote-privacy pin), and the bounded nag gate shared by every render channel (`backupNagGate(channel, s)` on `backup-nag-state.json`, OWN schema `gbrain-backup-nag-v1` — skillpack `loadNagState` would drop the extra fields on round-trip, so only the pure policy fns `decideNagAction`/`recordNagDisplay` are reused). Budget = AND of: 24h cross-channel dampener (`last_shown_at`), per-channel ceiling 3 per pseudo-version (`YYYY-MM(checked_at)` + no-remote fingerprint — month rollover or a changed verdict re-surfaces; a same-month recompute with an unchanged verdict stays quiet), and a global cap of 3 recorded impressions per month (`global_shown_count`/`global_month`). `backupNagReadOnlyConsult` is the OpenClaw context-engine's never-writes variant; `backupSpawnDue`/`recordBackupSpawn` debounce the session-end detached spawn (no sidecar file); `maybeEmitBackupNag` is the cli.ts startup rail body (skip set incl. serve/call/jobs; `BACKUP_LOCAL_ONLY <n>` machine marker + human line). Off switches: `GBRAIN_BACKUP_CHECK=0`, config `backup.check_enabled`; interval env `GBRAIN_BACKUP_CHECK_DAYS` > config `backup.check_interval_days` > 30; values <1 or non-numeric fall back to the 30-day default (`DAYS=0` never means "always stale"; `config set` rejects <1 outright). Tests: `test/backup-status-file.serial.test.ts`. Remote evidence is identity-bound and one-hour-limited; absent, stale, future-dated or inconsistent evidence cannot produce verified recovery counts, and failed refresh does not overwrite cache.
-- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. Tests: `test/backup-verification.serial.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.
+- `src/core/backup/coverage.ts` + `src/core/backup/repository.ts` — local Git discovery and bounded remote readback. Trusted non-quiet local backup CLI/doctor may read at most eight refs per sweep with a shared eight-second budget, two-second subprocess timeout and no prompts, pushes or fetches; pending/oldest evidence rotates first. Both git calls run with `backupGitEnv()`, an allowlist (`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, proxy variables, and Windows profile variables) under the no-prompt overrides, so user Git config and credential helpers apply but `GIT_DIR`/`GIT_WORK_TREE` never do (#5794). `currentBackupEvidence` retains one-hour readback only while source kind/id, physical Git directory, HEAD, branch, origin, push-status identity and clean tree match. `recoverable_repos` counts clean matching remote HEADs, while `configured_repos` counts configuration; expired, failed, mismatched, dirty or budget-exhausted observations cannot turn coverage green. New matching readback can supersede historical push failure without erasing it. Background/stdio are local-only; remote MCP doctor uses aggregate cache only. A failed refresh is degraded and does not overwrite a valid cache. Git covers committed files, not DB-only facts/config/credentials. Tests: `test/backup-verification.serial.test.ts`, `test/backup-git-env.test.ts`, `test/backup-coverage.serial.test.ts`, `test/e2e/backup-coverage-parity.test.ts`.
- `src/core/workspace-push.ts` — `gbrain sources push`: deny-glob backstop (tracked `*.pglite`/`.env*` refused regardless of .gitignore state) → stage FIRST → secret-scan the STAGED index blobs via `git cat-file` (closes the scan-then-stage TOCTOU — scanned bytes == committed bytes) → commit FIRST → divergence-safe pull → push, under one cross-platform lock (mkdir-atomic; flock is not a dependency — macOS). The pre-push secret gate FAILS CLOSED: an unreadable, oversized (> `PUSH_MAX_SCAN_BYTES`), or otherwise unscannable staged blob returns `blocked_unscannable` (nothing committed) instead of sailing through — only a confirmed staged deletion is skipped, and binary/NUL-sniffed blobs are scanned anyway. Statuses map to exit codes in `src/commands/sources.ts`: `pushed`/`skipped_in_flight` → 0; `blocked_secrets`/`blocked_tracked_deny`/`blocked_unscannable`/`refused_visibility` → 5; `pull_conflict`/`push_failed`/other → 1. Refuses public AND unverifiable remotes (never fail-open); pushes even on clean trees; writes `<home>/bootstrap/push-status.json`. Parent-repo-aware (a source may be a subdirectory of the workspace repo).
- `src/core/gbrain-home.ts` — the single GBRAIN_HOME resolution choke point (delegates to config's parent-dir semantics; 0700 on create) — durability, push, hooks, and bootstrap all route through it so home semantics cannot drift.
- `src/core/bootstrap/verify.ts` + `status.ts` — verify is the definition of done: fail-soft check suite over the REAL write path (put_page op → write-through file under `brain/` → in-process sweep → graph floor via link tables → recall), the keyless magic-moment check (`## Facts` fence → zero-LLM reconciliation → world-visibility read-back), source_id collision resolution (as the one bootstrap subcommand holding an engine: a manifest `source_id` already registered to a DIFFERENT checkout → derives a stable `workspace-<8char-path-hash>`, persists it to agent.json, names the re-register steps — every consumer reads `manifest.source_id`), the `embedding_plane` check (keyed installs live-embed ONE probe string and compare the RETURNED width to the actual `content_chunks.embedding` width — a plane split is a named FAIL with the recovery command, keyless passes, a dead probe warns; runs BEFORE the roundtrip so a keyless-passing roundtrip can never certify a brain whose keyed writes all fail), token sweep, byte floors, secret scan, deny globs, repo privacy, hooks smoke (in-process IPC), capability report, first-run tour; snapshots kept last-5 under `<home>/bootstrap/`. status owns the ordered PHASES list (the runbook defers to it), artifact-first detection, install.jsonl, the runbook version-stamp skew check, and the support blob doctor/agents relay verbatim.
diff --git a/docs/architecture/key-files/commands-1.md b/docs/architecture/key-files/commands-1.md
index 0d8805f480..2c9fd7967b 100644
--- a/docs/architecture/key-files/commands-1.md
+++ b/docs/architecture/key-files/commands-1.md
@@ -16,7 +16,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/auth.ts` — token management. `gbrain auth create/list/revoke/test` for legacy bearer tokens (`create --scopes read,write` narrows a token via the `scopes TEXT[]` column with mint-time validation — a typo'd scope refuses loudly, never silently denies or widens; `list` shows id + scopes columns with grandfathered rows rendered honestly; `revoke --id <uuid>` revokes exactly one row since names are not unique, and bulk revoke-by-name says when it hit several; `permissions set-takes-holders` MERGES into the permissions JSONB via `COALESCE(permissions,'{}'::jsonb) || $2::jsonb` — a whole-object replace would silently wipe the `source_id` federation grant), plus `gbrain auth register-client` and `gbrain auth revoke-client <client_id>` for OAuth 2.1 client lifecycle. `revoke-client` runs an atomic `DELETE...RETURNING` on `oauth_clients`; FK `ON DELETE CASCADE` on `oauth_tokens.client_id` and `oauth_codes.client_id` purges every active token + auth code in one transaction; `process.exit(1)` on no-such-client (idempotent). Legacy tokens stored as SHA-256 hashes in `access_tokens`; OAuth clients in `oauth_clients`; legacy tokens with no scopes grant grandfather to `read+write+admin` on the OAuth HTTP server (no migration); scoped tokens are honored at exactly their grant. Every SQL site routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` (and `executeRawJsonb` for the takes-holders `permissions` JSONB column) so `gbrain auth` works against PGLite; the takes-holders write goes through `executeRawJsonb(engine, sql, [name, hash], [{takes_holders:[...]}])` which round-trips with `jsonb_typeof = 'object'`. `register-client` accepts `--source <id>` (write authority, scalar), `--federated-read <S1,S2,...>` (read scope, array), and `--token-ttl <seconds>` (per-client access-token TTL persisted to `oauth_clients.token_ttl`, bounds `TOKEN_TTL_MIN_SECONDS`=60 to `TOKEN_TTL_MAX_SECONDS`=7,776,000/90d) and prints the resolved `Write source` + `Federated reads`; clients without a `source_id` backfill to `'default'` via migration v60. The registration core is the exported `registerScopedClient(sql, engine, name, parsed, opts)` — exit-free, print-free, injected-handle (engine-bound callers like `agent register` pass the dispatcher's engine; a second `withConfiguredSql` engine self-deadlocks PGLite's single-writer lock), returns a `RegisteredClient` data object and throws on failure; the thin CLI wrapper owns exit/print. Its printer `formatRegisterClientOutput` is a BYTE-PINNED contract (connect.ts's `defaultRegisterOAuthClient` regex-scrapes `Client ID:`/`Client Secret:` from it in production) — pinned by `test/auth-register-client-output-pin.test.ts`. `preflightOauthClientColumns(sql)` probes `information_schema.columns` for the optional columns (`token_ttl`, `surface`, `federated_read`, `source_id`, `deleted_at`) so statement shapes are decided BEFORE any transaction — Postgres/PGLite abort the whole tx on any statement error (25P02) and SqlQuery has no savepoint seam, so "catch 42703 and continue" inside a tx is impossible; skipped optional writes surface as `RegisteredClient.skipped` with an apply-migrations hint. `gbrain auth clients [--usage] [--days N] [--json]` lists clients with scopes, per-client surface, write source (`source_id`), and federated reads (`federated_read`) — one projection-widened SELECT with a degrade ladder for pre-migration brains (drops the newest columns first, never errors); `--usage` joins per-client op-call counts via `src/core/mcp-usage.ts`. The bare `gbrain auth create <name>` form (no `--takes-holders`) mints a token via the exported pure `parseAuthCreateArgs(rest)`. Pinned by `test/auth-create-args.test.ts` + `test/auth-register-client-args.test.ts`.
- `src/commands/autopilot-pause.ts` — engine-free `gbrain autopilot pause [--reason <text>]` / `resume`: writes or removes the operator marker `autopilot-operator-paused` (`autopilotOperatorPauseMarkerPath` in `src/core/autopilot-paths.ts`, with `autopilotPaused()` and `autopilotPauseReason()`). The daemon loop and job workers honor it like the migration hold; `--install` (and so `gbrain upgrade`) clears only a leaked migration hold, and resume never clears a migration or restore hold. Test: `test/autopilot-operator-pause.test.ts`.
-- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`.
+- `src/commands/autopilot.ts` — `gbrain autopilot --install`: self-maintaining brain daemon (sync+extract+embed). Freshness sync jobs always send an explicit positive-polarity `pull` value derived from the source's parsed `remote_url`, so local-only sources skip pull and PGLite JSON-string configs behave like Postgres objects. Consumes `detectTini()` from `src/core/minions/spawn-helpers.ts`, resolved once at startup. Composes a `ChildWorkerSupervisor` instance for spawn-and-respawn with `--max-rss 2048` and soft `maxCrashes: 5`, preferring the current source/compiled CLI over PATH. The child worker performs private-queue recovery only after its driver/selected-child readiness and schema check; autopilot does not duplicate that recovery before spawn. A configuration-blocked child leaves the owning daemon alive and heartbeating but gates dispatch, worker restarts and engine work until explicit owner restart after repair. `--status --json` adds processing readiness, reason and runtime identities without replacing existing freshness/exit semantics; see [the owner-specific repair guide](../../guides/minions-fix.md). `onMaxCrashesExceeded` routes through autopilot's own `shutdown('max_crashes')` so the autopilot lockfile gets cleaned up. `shutdown()` drains via `childSupervisor.killChild('SIGTERM')` + `awaitChildExit(35_000)`. Pinned by `test/autopilot-fanout-wiring.test.ts` and `test/autopilot-supervisor-wiring.test.ts` (6 static-shape guards: composes ChildWorkerSupervisor not legacy names, `--max-rss 2048` in argv, `maxCrashes: 5` literal, shutdown-via-callback, no workerProc reference). tick body invokes `runNightlyQualityProbe` when `cfg.autopilot.nightly_quality_probe.enabled === true` (default OFF — opt-in to protect API spend). NO scheduler-side rate-limit check — `runNightlyQualityProbe`'s internal `shouldRunNightly` (reading the audit JSONL) is the single source of truth. Probe call wrapped in try/catch that logs via `logError` and does NOT bump `consecutiveErrors` (probe failure is informational, never crashes the loop). Default `max_usd` cap = 5. Pinned by `test/autopilot-nightly-probe-wiring.test.ts`. per-source `extract_atoms` auto-drain. Postgres-only block after the freshness fan-out: gated on `autopilot.auto_drain.enabled` (default true) AND `!packDeclaresPhase(engine,'extract_atoms')` (the silent-backlog condition) AND per-source `countExtractAtomsBacklog > threshold` (default 25) AND a daily cap `floor(max_usd_per_day / ~$0.30)`. Enumerates `loadAllSources`. Submits the PROTECTED `extract-atoms-drain` job (`{allowProtectedSubmit:true}`) with a UTC-day time-sloted idempotency key `autopilot-extract-atoms-drain:<src.id>:<utcDay>` (a static key would block the source after the first job completed). `src/core/minions/protected-names.ts` lists `extract-atoms-drain`; `src/commands/jobs.ts` registers the handler (thin wrapper over `runExtractAtomsDrainForSource`, `LockUnavailableError` → `{deferred:true}`; a `provider_failure` result throws `formatDrainProviderFailure(result)` — batches/remaining plus the drain's sanitized `last_error` — so the dead-lettered job's `error_text` names the cause, e.g. a missing provider key); `src/core/config.ts` carries the `autopilot.auto_drain.*` config keys + the `autopilot.` key prefix. Pinned by `test/extract-atoms-drain-handler.test.ts`, `test/autopilot-auto-drain-wiring.test.ts`. federated-brain co-existence + launchd hygiene. (1) `LOCK_PATH` resolves via `gbrainPath('autopilot.lock')` so it honors `GBRAIN_HOME` (two brains can run autopilot simultaneously without lock-stealing); lock file stores PID; `src/core/autopilot-lock.ts` checks liveness and the process command before takeover. `looksLikeGbrainAutopilotCommand` recognizes quoted or unquoted `cli.ts` / `cli.js` / `cli.mjs` paths, including spaces and normalized Windows separators, so a live matching autopilot retains even an old lock. Synthetic command-line and lock-decision cases are pinned by `test/autopilot-lock.test.ts`; they are not native Windows process-probe validation. (2) exported `classifyReconnectError(err)` returns `'recoverable' | 'unrecoverable'`; unrecoverable causes `process.exit(0)` so launchd backs off instead of looping `config.database_url undefined`. (3) exported pure `generateLaunchdPlist(wrapperPath, home)` sets `ThrottleInterval=300` so launchd respects the exit-0 backoff. Pinned by `test/autopilot-lock-path.test.ts` + `test/autopilot-reconnect-classifier.test.ts`. targeted-submit loop instead of blanket `autopilot-cycle` dispatch. Each tick: cheap `engine.getHealth()` (single SQL count) + `computeRecommendations()`, then route by shape — `score >= 95 AND no plan AND <60min since last full` → sleep; `score >= 95 AND >=60min` → submit `autopilot-cycle` (60-min floor exercises phase-coupling invariants on healthy brains); `plan <= 3 steps AND est <5min` → submit individual handlers; `plan large OR score < 70` → submit full `autopilot-cycle`. The `gbrain-cycle` lock ensures targeted submissions and the full cycle can't run concurrently. `maxWaiting: 1` per submit closes the queue-fan-out vector. daemon env lane: `writeWrapperScript` additively sources `<gbrainDir>/env` (honors `GBRAIN_HOME`) after the shell profiles with a `set -a` wrap so dotenv-style `KEY=value` lines export too, and creates a fully-commented 0600 template on install (never overwritten, never chmod'd, never removed by uninstall; template excludes `GBRAIN_HOME` — the wrapper bakes it AFTER sourcing). Exported pure `chatBootWarning(chatAvailable, gbrainDir)` derives both remediation paths from the passed dir and prints via `console.log` at daemon boot (stdout is the autopilot.log sink on all four targets; stderr lands in the unsurfaced autopilot.err) using the bare global-model `isAvailable('chat')` probe on purpose (mirrors the bare-gated phases; facts extraction is model-aware and doctor owns it). Install is reload-safe so the warning's re-run-`--install` remediation is true: launchd unloads before load (bare load errors on a loaded agent), systemd `try-restart`s after `enable --now`, cron/container print a residual-process notice instead of auto-killing. Pinned by `test/autopilot-install.test.ts` (16 cases incl. real-bash wrapper execution). Once processing is configuration-blocked, `guardAutopilotEngine` refuses new engine calls (except disconnect), guards transaction callback engines, and rolls back a transaction whose callback finishes after the block; already committed work is not revoked. Pinned by `test/autopilot-transaction-fence.test.ts`. #5195: install, status and uninstall act on one brain's job, named by `resolveAutopilotJob()` in `src/core/autopilot-paths.ts` (default brain: the shared names; any other brain: `<name>-<suffix>` from the random install id in `<brain>/.gbrain/autopilot-install-id`, with move/copy semantics); crontab lines carry `# gbrain-autopilot:<suffix>`; every log sink writes under the brain's home; a pre-#5195 shared job that runs this brain is replaced on install and reported by `--status` as `needs_reinstall: legacy_shared_job`; replacing or removing a job whose wrapper runs another live brain is refused (`autopilot_job_owned_by_other_brain`). Job-definition reads, legacy replacement and the `--status` job report live in `src/commands/autopilot/jobs.ts`. Pinned by `test/autopilot-install-id.test.ts` and `test/e2e/autopilot-multi-brain.serial.test.ts`.
Size ceiling: `scripts/module-size-limits.tsv` (per-change raise history: `git log -p` on that file). The ceiling covers launchd/systemd/cron/container install and reload paths, the wrapper script with its env-file lane and exec guard, status and the self-upgrade channel. `runAutopilot` is a mode table (`AUTOPILOT_MODES`: --install, --uninstall, --status, --pause/--resume; first match wins) that otherwise lazily imports the daemon: `autopilot-daemon.ts` (`runAutopilotDaemon`: boot, lock, managed worker, shutdown and the tick loop over an explicit `AutopilotDaemonState`; steps `probeDatabaseOrReconnect`, `probeNoWorkerPeer`, `runInlineCycle`, `adaptiveInterval`), `autopilot-dispatch.ts` (`dispatchAutopilotTick`: freshness syncs, extract_atoms auto-drain, remediation plan, full-cycle fan-out or targeted submits) and `autopilot-probes.ts` (nightly quality and conversation-parser probes). No injectable single-tick function exists yet (TODOS: testable autopilot tick), so the wiring guards read these modules as source.
- `src/commands/backup.ts` — trusted local `gbrain backup status|check`: status may reuse a recent warning; check forces a bounded remote readback sweep. Enabled missing/locked/degraded evidence does not return an all-clear. Quiet and disabled modes retain explicit zero-exit behavior. JSON separates configured repos from fresh verified recoverable repos and describes committed-file-only recovery. Remote MCP doctor never invokes this local Git path; see `docs/operations/backup-check.md` and `test/backup-cli.serial.test.ts`.
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
new file mode 100644
index 0000000000..c7c948ad00
--- /dev/null
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -0,0 +1,14 @@
+# Key files: Commands (2/6, continued)
+
+[Subsystem index](../KEY_FILES.md) · [Previous entries](commands-2.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+
+- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).
+
+- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter.
+
+- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
+
+- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
+
+- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed. #5183: the page-embedding worker count comes from `resolveEmbedConcurrency` in `src/core/embed-concurrency.ts` (GBRAIN_EMBED_CONCURRENCY, a paced cap, and on Postgres never above the client pool; one warning when an explicit setting is lowered).
diff --git a/docs/architecture/key-files/commands-2.md b/docs/architecture/key-files/commands-2.md
index 5503266a3a..6046fc9bea 100644
--- a/docs/architecture/key-files/commands-2.md
+++ b/docs/architecture/key-files/commands-2.md
@@ -8,11 +8,13 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/persistence-requests.ts` — two wave checks (OPS, registered in `wave-checks.ts`). `persistence_request_indexes` (#5762) reports each managed sync request index missing, INVALID or still building (with progress) and names `gbrain repair request-indexes --apply`. `persistence_request_growth` reports the request-table row count (a `reltuples` estimate on Postgres), each scope's admission rate over the last 7 days (the newest 10,000 admissions per scope, one bounded index read), lifetime IDs against `persistence.limits.*` and the projected exhaustion date within ten years; it warns under 90 days with the `oneYearCapacity` `gbrain config set` value and the doctor re-check. Tests: `test/persistence-request-indexes.test.ts`, `test/e2e/persistence-request-indexes-postgres.test.ts`.
- `src/commands/doctor/checks/{persistence-capacity,parked-effects}.ts` — `persistence_capacity` (OPS) warns when a principal or the brain reaches 80% of permanent request IDs or receipt bytes (via `capacityDiagnostics`) and prints one `gbrain config set <key> <value>` per brain-wide key, using the largest value any scope needs for about one more year; transient caps never warn. `parked_effects` (BRAIN) reads the partial parked-effect index, counts exactly, samples 20, and names each parked page with its `retry-effects ... --dry-run` command. Both report `exact`/`inspected`/`truncated` details; an unreadable state is warn, never clean. Tests: `test/persistence-capacity.test.ts`, `test/persistence-effect-parking.test.ts`.
- `src/commands/doctor/checks/unbound-source.ts` — `unbound_source` (#5254) counts live pages with `pages.database_only_reason='unbound_source'` per source. While the source is unbound the count is ok and the message carries the filled `sources writer status`/`writer claim` bind command (database-only is the chosen mode); once the source has a binding it warns, because binding never materializes those pages into canonical files. Unreadable state warns. Registered on the `persistence_capacity` line in `doctor.ts`. Test: `test/e2e/unbound-source-postgres.test.ts`.
+- `src/commands/doctor/checks/extractor-facts.ts` — `extractor_facts_expired` (#5731): counts conversation-extractor facts the pre-v0.60.11.0 projection expired, by class (`evidenced`, `ambiguous`; `excluded` reported but never a finding) through `classifyExtractorFacts`, and names `gbrain repair extractor-facts` (explicit-only, so the remediation plan and banner list it with its preview). Read-only; health unknown when the query fails.
- `src/commands/doctor/wave-checks.ts` — `WAVE_CHECKS`, the table of managed-persistence wave checks (stable id, `resolution` `repair`/`operator`/`unsupported`, count-free remote `impact`, operator `instruction`, `count` for banners, `registration` inline-in-doctor.ts or from this table). `runWaveChecks` turns a throwing check into an `unknown` finding; `checkHealthUnknown` reads `details.health === 'unknown'`. `remoteWaveHandoff` returns one line per remotely offered check with `details.host_action` {`check_id`, `state` ok/action_required/unknown, `preview_command`} and no paths, rows, SQL, emails or installation ids. Consumers: doctor.ts, `report-remote.ts`, `remediate.ts`, `upgrade-banner.ts`. Tests: `test/recovery-layer.test.ts`, `test/e2e/recovery-layer.test.ts`.
- `src/commands/doctor/remediate.ts` — the `--remediation-plan` / `--remediate` CLI shell (re-exported from doctor.ts): per-step `command` (`gbrain jobs submit …` for job steps, `gbrain repair <kind> --apply` for repair steps), `combinedRemediateCommand`, `REMEDIATE_HELP`, `--include-repairs`/`--no-embed`/`--resume` handling, the resume command after budget exhaustion (repeats the recorded cap and consent), `classifyWaveFindings` (cleared / pending / consent_required / operator_required / unsupported, from wave checks run before and after) and `remediationExitStatus` (0 when no repairable finding remains and no step failed; 1 otherwise or on budget exhaustion; 2 when the target is unreachable with no repair step, or a resume is refused), set through `setCliExitVerdict`.
+- `src/commands/doctor/checks/legacy-job-authority.ts` — `legacy_job_authority` (#5157): the claim gate's population (`UNREVIEWED_LIVE_JOBS_WHERE`), split into authorizable SQL NULL and unsupported rows; terminal keyed SQL NULL rows are reported as `ok`. Live rows `fail` with the filled recovery. `legacyJobAuthorityBannerNote` feeds the banner. Test: `test/doctor-legacy-job-authority.test.ts`.
- `src/commands/doctor/upgrade-banner.ts` — `postUpgradeRecoveryBanner`: runs the wave checks once and returns one `[AGENT] Relay this to your operator` block (brain, per-finding count and resolution, the read-only `gbrain doctor --remediation-plan`, ask before applying), never an applying command; empty for a clean brain. `POST_UPGRADE_NOTES` lets other subsystems add lines. Test: `test/post-upgrade-banner.test.ts`.
- `src/commands/doctor/checks/{safe-index,self-capture,stale-embedding-effects}.ts` — `safe_index_pending` (BRAIN: re-sealable pages below the safe-chunk fence, names `gbrain repair safe-chunks`; kept code/image pages are informational), `self_capture` (BRAIN, #5413: corpus `.txt` files whose session id matches a gbrain claude-cli scratch transcript are classified, ones with no harness transcript left are unclassifiable; details carry a capped sample and copy-paste quarantine commands into `<corpus>.quarantine`; never moves or deletes), `stale_embedding_effects` (OPS, #5629: committed writes with a queued embedding effect untouched for an hour; names each effect with its inspect command; reported as unsupported). Unreadable state is warn with `details.health: 'unknown'`. `writer_version` (`checks/writer-version.ts`, owned by the persistence entry) is registered in the same table as operator-required. Tests: `test/doctor-self-capture.test.ts`, `test/recovery-layer.test.ts`.
@@ -37,13 +39,3 @@ Doctor's embedding-dimension warning treats existing chunks as existing data eve
- `src/commands/doctor/checks/routing-federation.ts` — `checkOauthClientScopeHealth` (`oauth_client_scope_health`, re-exported by the doctor.ts façade) has three warn arms: (a) dangling federated read grants, (b) orphaned empty `<name>-workspace` sources, (c) privileged self-registered clients — active `oauth_clients` rows whose scope word-matches `DCR_PRIVILEGED_SCOPES` — the DERIVED complement `ALLOWED_SCOPES_LIST \ DCR_REGISTRABLE_SCOPES` (exported; bound as a `$1` regex parameter, never interpolated) — and the `(read/write)` / `--scopes read,write` copy is built from `DCR_REGISTRABLE_SCOPES`; pinned by the set-equality + per-scope loop in `test/doctor-oauth-client-scope-health.test.ts`; rows with `grant_revision = 0` and no `oauth_grant_audit` row with `action = 'register'` (every operator path writes one; the anonymous DCR insert does not). Arm (c) is advisory (the signature also matches operator clients that predate the grant audit log) and carries the `gbrain auth rescope-client <client_id> --scopes read,write` / `gbrain auth revoke-client <client_id>` remedy; when the audit table or `grant_revision` column is absent it fails OPEN and the ok message states the self-registered-client audit was skipped (unknown). Pinned by `test/doctor-oauth-client-scope-health.test.ts`.
- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkChatFallbackChainInert` returns one warning when either the effective file/environment config or the DB plane has a non-empty `chat_fallback_chain`; it returns `null` when both are empty, so clean doctor reports add no line. The local and remote doctor registries both consume the check. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.
-
-- `src/commands/dream-retriage.ts` — `gbrain dream retriage`: re-scores the corpus via the shared `runTriagePass` (with `maxMs: 0` — operator sweeps run to completion; `--limit` slices the discovered list caller-side) and reconciles the queued private-queue backlog: synth-v2 rows verdict-gated, plus any row stranded in a provably-dead `dream-inline-*` queue regardless of key family (patterns children, legacy grammars) — doctor's orphaned_private_queue check points here, so the repair selects everything the check can flag. Liveness uses ownership correlation (mirrors the doctor check): a live `gbrain_cycle_locks` row suppresses conversion only for queues born at/after its `acquired_at`; an older crashed cycle's queue stays repairable while a new cycle runs (unknown birth/acquisition stays fail-safe possibly-live). Spend-gated: upfront estimate via `canonicalLookup` on the resolved triage model, confirmation above `SPEND_CONFIRM_USD` ($5, in `dream-retriage-constants.ts`; unpriced models gate on `UNPRICED_CONFIRM_FILES`=500) unless `--yes` (`--json` non-interactive requires `--yes` above the gate); `--max-usd` soft-stops via the pass's `shouldStop` seam (estimate-based). `--reconcile-queue` (opt-in — cancels queued work): selects waiting/delayed/paused `dream:synth-v2:%` jobs across ALL queues, parses keys with `parseSynthV2Key`, then per row, reading THE shared gate (`passesTriageGate` from `triage-rescue.ts` — threshold pass OR the verified-segment rescue; a hand-rolled `score >= threshold` here would cancel exactly the jobs the rescue admitted): matched below the gate → cancel; matched above the gate but `waiting` in a stale `dream-inline-*` queue → cancel as `converted_for_resubmit` (the backlog conversion — cancelled rows release their idempotency slot so the next cycle re-adds into a live drain); matched above the gate in a live queue → keep; matched-but-unscored → keep (never cancel on missing data); unmatched → keep unless `--cancel-unmatched`; key-source vs `data.source_id` disagreement → skip + `source_mismatch`; status re-checked immediately before each cancel (rows turned `active` are skipped; residual race matches cancelJob's best-effort contract). Legacy `dream:synth:` keys are excluded at the SQL LIKE filter — never candidates. `--source` scopes cancels (`other_source` counted); `--threshold`/`--since`/`--force`/`--dry-run` (zero judge calls, zero cancels — cached scores only, uncached files report `needs_triage`). `--audit-rejects <n>` re-judges N stride-sampled files that the gate actually REJECTED (below threshold AND not rescued — auditing a rescued file as a rejection would misreport the disagreement rate) with the SYNTHESIS model and reports that rate — the operator calibration loop. Reports carry `rescued`/`verified_segments` so a rescued file reads as accepted everywhere the command renders. Exit 0 success (even when nothing cancelled), 1 no engine/corpus, 2 usage or declined spend gate. Pinned by `test/dream-retriage.test.ts`. With System One S7 on, cached decide verdicts (cache identity from `resolveTriageDecide`) count as valid, the slot threshold joins every gate read, `runTriagePass` gets `decide`, and the spend estimate prices Jev windows (`estimateTriageDecideUsd`).
-
-- `src/commands/dream-reset-key.ts` — `gbrain dream reset-key <base-key>` persists a breaker reset for one dream key (deaths finished before it stop counting; survives restarts); `gbrain dream reset-key --list [--json]` lists tripped keys with counts and reset commands. Dispatched from `dream.ts` before cycle flag parsing. The `dream_paid_loop` doctor check (`src/commands/doctor/checks/dream-breaker.ts`) warns on keys at the limit through the same counter.
-
-- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved `--source`'s `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
-
-- `src/commands/dream.ts` — `gbrain dream` CLI; thin alias over `runCycle`. Flags: `--dry-run`, `--json`, `--phase <name>`, `--pull`, `--dir <path>`, `--input <file>` (ad-hoc transcript, implies `--phase synthesize`), `--date YYYY-MM-DD`, `--from <d> --to <d>` (backfill range), `--unsafe-bypass-dream-guard` (plumbed through `runCycle.synthBypassDreamGuard` → `SynthesizePhaseOpts.bypassDreamGuard` → `discoverTranscripts({bypassGuard})` / `readSingleTranscript({bypassGuard})`; loud stderr warning at synthesize-phase entry; never auto-applied for `--input`). Conflict detection: `--input` + `--date` exits 2. ISO date validation. `--dry-run` runs the scored triage pass but skips synthesis (NOT zero LLM calls). Exit 1 on status=failed. Source scope enters the shared 6-tier resolver whenever `--source <id>` is given OR `GBRAIN_SOURCE` is set (a null explicit falls through to tier 2: validated + `assertSourceExists`, so an invalid/unknown env value is a clean exit 1; the `__all__` sentinel is excluded and falls through to the unscoped routing, which already spans every source); an env scope naming the brain's default-like source keeps the full implicit cycle (#4700 semantics), any other keeps the `--source` freshness boundary. `resolveBrainDir` returns `string | null` (order: `--dir` → resolved source's `local_path` → global `sync.repo_path` → null); a checkout-less postgres/Supabase brain runs DB-only phases (incl. `resolve_symbol_edges`) and skips the 6 filesystem phases with `details.reason: 'no_brain_dir'`; `runDream` owns the only hard error (no checkout AND no engine). When `--source` resolves but has no on-disk checkout, returns null (DB-only) rather than borrowing another source's global `sync.repo_path` (would mix scopes). Pinned by `test/dream-postgres.serial.test.ts`. `--drain [--window <seconds>]` for `--phase extract_atoms`: `runDrain()` bypasses the pack-gate and runs the single-hold bounded drain from `src/core/cycle/extract-atoms-drain.ts` under the same `cycleLockIdFor(sourceId)` the routine cycle uses (concurrent autopilot tick defers with `cycle_already_running`), reporting `{extracted, skipped, remaining}`. Exits `EXIT_DRAIN_INCOMPLETE=3` while `remaining > 0`; a null backlog count (count query FAILED) is also exit 3, never a drained success; `LockUnavailableError` → `cycle_already_running` skip (also exit 3). The `extract_atoms_backlog` doctor check (`computeExtractAtomsBacklogCheck`) surfaces the silent pack-gated backlog with the exact `--drain` command; pack-gated cycle skips carry a greppable `pack_gated:true` marker. `dream retriage` dispatches on `args[0] === 'retriage'` BEFORE `parseArgs` (its flag set never collides with cycle flags; `dream retriage --help` prints subcommand help engine-free per the same IRON RULE). `--eval-run` opts the process in to `GBRAIN_DECIDE_SLOTS` (`enableDecideEvalOverride`) for eval harnesses; consent, egress and the daily cap still apply.
-
-- `src/commands/embed.ts` — `gbrain embed [--stale|--all] [--slugs ...]`. Explicit slug/slugs and non-stale all routes require live-source projection snapshots before healing or provider work; unavailable preparation and refused installation are recorded through existing failure results and the CLI nonzero exit verdict. Archived rows are preserved and never knowingly dispatched, while active pages in a mixed run can progress. Dry runs retain their read-only counts, and the global page selectors are unchanged. These routes keep provider calls outside the existing source-before-page guards. Pinned by the explicit archived-admission and actual CLI cases in `test/embedding-recovery.serial.test.ts` (PGLite) and its PostgreSQL wrapper, `test/e2e/embedding-recovery-parity.test.ts`. `--stale` first calls `engine.countChunklessPagesWithContent()` (chunkless-page safety net: a page written directly via `putPage` — e.g. an enrichment-generated stub — that never went through chunking has ZERO `content_chunks` rows, so it has no row to go stale and is otherwise invisible to this command forever; the predicate excludes quarantined/embed_skip pages, both intentionally chunkless). When found, `healChunklessPages` chunks them locally (mirrors `embedPage`'s chunkless branch: same `chunkText` calls over `compiled_truth`/`timeline`) with `embedding = NULL`, folding the new rows into the SAME pass; immediately before writing it reads the live canonical snapshot and re-checks `getChunks`. `installPageProjection` then locks the page, verifies the originating revision and source incarnation, and installs/seals chunks in one transaction. A newer canonical edit prevents installation; the single-page chunkless path uses the same guarded installer. Each page's work is try/caught (a bad chunkless page records a failure via the same `EmbedResult.failures`/`recordFailure` path as every other embed failure and the sweep moves on — it never aborts the whole `--stale` run before the normal stale-chunk pass even starts). `listChunklessPagesWithContent`'s default batch is 50 (not the 2000-row default elsewhere in this file) because each row carries a full page body. It honors the caller's pacer, mirrors `--catch-up` (removes its cap entirely, matching the main loop below), and otherwise shares ONE `GBRAIN_EMBED_TIME_BUDGET_MS` wall-clock budget with the main stale loop (both measure from the same `overallStartedAt`, not two independent 30-minute windows) so a large damaged brain can't run the combined `--stale` pass unbounded; an abort during healing stops the whole function before falling through to `invalidateStaleSignatureEmbeddings`. Pinned by `test/embed-stale-chunkless-pages.serial.test.ts` + `test/e2e/engine-parity.test.ts`. Then `--stale` calls `engine.countStaleChunks()` (single SELECT count(*) WHERE embedding IS NULL, ~50 bytes wire) so a fully-embedded brain short-circuits with no further reads beyond those two counts. When stale chunks exist, `engine.listStaleChunks()` returns just the chunks needing embeddings (slug + chunk_index + chunk_text + metadata, no `vector(1536)` payload); caller groups by slug, captures a guarded projection snapshot, embeds outside the transaction, and installs through `installPageEmbeddings`. The installer checks revision, source incarnation, chunk identities/text and indexing context, then updates vectors and provenance without replacing chunk text or membership. Every re-embed merge carries per-chunk metadata through the ONE shared `carryChunkMetadata(chunk, loaded)` field list in `src/core/embed-stale.ts` — `modality` plus the code fields (`language`, `symbol_name`, `symbol_type`, `start_line`). Keep this shared field list for prepared chunk metadata rather than copying a per-path list. The final guarded embedding installer updates vectors and provenance only, preserving the installed modality, code metadata, text and chunk membership. Pinned by `test/embed-modality-preserved.test.ts`. All `console.log`/`console.error` call sites use `slog`/`serr` from `src/core/console-prefix.ts` so when `runEmbedCore` runs inside a per-source `withSourcePrefix` scope (installed by the `gbrain sync --all` worker pool) every line carries the `[<source-id>] ` prefix; standalone callers see identical output because slog/serr fall through to bare console fns outside the wrap. Successful complete page embeddings stamp `pages.embedding_signature` inside the guarded installation transaction so a later model/dims swap is detectable as stale. The per-slug path (`embedPage`, used by `gbrain embed <slug>` AND sync's post-import embed step) and the full-re-embed path (`embedAll`) stamp per page when every chunk embedded cleanly. The stale path (`embedAllStale`) first calls `invalidateStaleSignatureEmbeddings` on a live run so signature-drifted pages flow through the NULL cursor, then stamps each page through `stampIfPageProvenanceComplete` in `src/core/embed-stale.ts` (shared with the minion `embed-backfill` drain, `embedStaleForSource`): the stamp is judged from DB state — every chunk carries an active-column vector whose `model` and vector width match the signature and whose `embedded_text_hash` matches `md5(chunk_text)` — never from the batch subset, because `listStaleChunks` pages by row with no page alignment, so a page straddling a batch boundary is stamped by whichever batch lands its last chunk (a partially-stale page keeping preserved chunks of another model, or a NULL model/hash, stays unstamped rather than falsely marked current; `embed --all` fully re-embeds + stamps those). dry-run never mutates: it counts signature-drift via the widened `countStaleChunks({signature})` predicate without NULLing anything. `--include-null-signature` lifts the NULL-signature grandfather clause: threads `includeNullSignature: true` into the invalidation + counts so pages that predate the v108 stamp re-embed too after a model swap (both engines' `countStaleChunks`/`sumStaleChunkChars`/`invalidateStaleSignatureEmbeddings` accept the flag; predicate becomes `sig IS NULL OR sig <> current`). Without the flag, a live stale run that just invalidated drifted rows probes for left-behind NULL-signature chunks and emits a loud stderr warning naming the count + the fix — mixed embedding spaces in one index are never silent. Pinned by `test/embedding-migration.test.ts` + `test/e2e/migrate-embeddings-postgres.test.ts`. Embed failures are never silent: all three page paths embed via `embedPageTexts`, which tries the page's chunks in one batch and, on a PERMANENT request-shaped failure (non-429, non-`AITransientError`, non-auth), retries once per chunk so one bad chunk costs one chunk instead of darkening the whole page (failed chunks stay `embedding IS NULL` for the next `--stale` pass; a partially-failed page is never signature-stamped). Rate-limit/outage/auth failures do NOT fan out (cost bounding — `embedBatchWithBackoff` already owns 429 backoff). Failed chunk counts land on `EmbedResult.failures` + capped `failure_samples`, and `src/cli.ts`'s embed case sets a non-zero exit verdict on `failures > 0` (mirror of the `import` errors>0 guard). Pinned by `test/embed-partial-failure-3037.serial.test.ts` + `test/embed-exit-code-3037.serial.test.ts` (real spawned CLI). applies the `embed-skip` filter at all 5 stale-chunk sites: `runEmbedCore --stale`, `runEmbedCore --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks` via `EMBED_SKIP_SQL_FRAGMENT`. A soft-blocked page is queryable by title/slug but its chunks never enter the embed sweep. The shared helper from `src/core/embed-skip.ts` is the single implementation — no per-site ad-hoc filter allowed. Pinned by `test/embed-skip.test.ts`. both inline sliding-pool sites (`embedAll` simple at `:458-467` and `embedAllStale` paginated + AbortSignal at `:586-632`) call `runSlidingPool` from the shared worker-pool helper. Invariant-level contract preserved (counts + cost + AbortSignal propagation + per-batch rate-limit retry via `embedBatchWithBackoff`); byte-equality on progress-event ORDERING is NOT promised. The `GBRAIN_EMBED_CONCURRENCY || 20` default is preserved and embed bypasses `resolveWorkersWithClamp` because the 20-worker default would otherwise silently change every brain's embed hot path. Pinned by `test/embed-default-concurrency.test.ts` (20 page workers on both paths when the env var is unset) and `test/embed-pool-abort.test.ts` (an abort stops both page pools from claiming further pages). wires `--background` as the reference integration for the `maybeBackground()` helper. `gbrain embed --stale --background` submits as a Minion job, prints `job_id=N` to stdout, exits 0. Composable: `JOB=$(gbrain embed --stale --background | grep -oE 'job_id=[0-9]+' | cut -d= -f2); gbrain jobs follow $JOB`. `runEmbedCore` accepts an optional `signal` threaded down both the `--stale` and `--all` paths (`embedAllStale`/`embedAll`/`embedPage`); each composes it with the internal wall-clock budget via `anySignal` and checks `isAborted`/`effectiveSignal.aborted` in every per-slug loop, page-claim pool, and `embedBatch` call, so a worker abort (wall-clock timeout / lock loss / SIGTERM) stops embedding within a batch. Pinned by `test/embed.serial.test.ts`. Keyless brains (`embedding_disabled: true`): the exported pure predicate `isKeylessStaleRefusal(args, embeddingDisabled)` gates a CLEAN refusal at the top of `runEmbed` — a bare stale run prints a stderr hint and returns a zero-failure result (exit 0), because the documented agent-scheduler chain `gbrain sync ... && gbrain embed --stale` must stay green on a keyless install; explicit asks (a slug, a slugs list, the all flag) and dry-run keep exiting 1 via `EmbeddingDisabledError`, mirroring the dispatch precedence where a slugs list wins over stale. Pinned by `test/embed-keyless-guard.test.ts` + `test/agent-scheduler-contract.serial.test.ts`. The stale path's signature invalidation is PROBE-GATED — a drift pre-count (two `countStaleChunks` calls) followed by one live `probeEmbedder` embed call (from `src/core/embed-stale.ts`; validates a real vector whose dims match the signature's trailing `:<dims>`) must succeed before anything is NULLed, so a misresolved config (temp `GBRAIN_HOME` → default model, no key) can never strip vectors it cannot replace; a failed probe warns loudly on stderr and degrades to NULL-only staleness. Every live stale run also calls `engine.invalidateContentDriftEmbeddings` (not probe-gated — blast radius is bounded by real content edits) so chunks whose `embedded_text_hash` no longer matches `md5(chunk_text)` re-embed from their CURRENT text; NULL hash (pre-v133 rows) is grandfathered. Pinned by `test/embed-stale.serial.test.ts` (probe-gate + content-drift blocks). The `--stale` single-flight lock HEARTBEAT (interval `GBRAIN_EMBED_LOCK_HEARTBEAT_MS`, default 5 min — test seam) is refresh-bounded per tick: each `refresh()` races a per-tick timeout (`GBRAIN_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`, default 30s via `DEFAULT_EMBED_LOCK_HEARTBEAT_TIMEOUT_MS`) with its own AbortController, so ONE never-settling refresh call can't silence the heartbeat forever; a slow tick never stacks on the next (`beating` guard), a refresh returning false (stolen/released lock) aborts the drain immediately as `lock_lost`, and 3 CONSECUTIVE tick failures (timeouts or throws) also abort as `lock_lost` rather than running without mutual exclusion. The interval is deliberately NOT unref'd (a lost drain promise stays a LOUD hang instead of a silent exit-0 that leaks the locks) while the per-tick timeout timer IS unref'd. `runEmbedCore --stale` also arms the progress-keyed stall watchdog from `src/core/embed-stall.ts` (`GBRAIN_EMBED_STALL_ABORT_SECONDS`, default 900 — see that entry): on stall it aborts the drain, releases the run's self-acquired locks, flushes the summary, and returns `reason: 'stall_timeout'`. Pinned by `test/embed.serial.test.ts` (heartbeat + stall blocks) + `test/jobs-embed-stall-wiring.serial.test.ts`. Explicit `--stale --facts --source ID` is a read-only NULL-fact preview; `--yes --max-cost-usd N` consents to bounded execution, not automatic/full-brain repair. The selected-brain configuration is forwarded out of band to the resident owner, never reloaded from the host or supplied over the wire; selected and DB off-switches fail closed.
diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.md
index 026437d0de..3ea4cd9b3e 100644
--- a/docs/architecture/key-files/commands-4.md
+++ b/docs/architecture/key-files/commands-4.md
@@ -52,6 +52,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/reindex-aliases.ts` — `gbrain reindex --aliases [--limit N] [--dry-run] [--json] [--source <id>]`: backfills the free-text alias layer for EXISTING pages whose frontmatter `aliases:` predate the alias table (the import-time projection covers new + changed pages). Reads each page's frontmatter `aliases:`, writes via `engine.setPageAliases`. Idempotent + convergent (setPageAliases replaces a page's alias set) so no op-checkpoint needed; walks `listAllPageRefs` (cheap cross-source enumeration), `--source` narrows. Pinned by `test/search/reindex-aliases.test.ts`.
+- `src/commands/projections.ts` + `src/cli/commands/projections.ts` — `gbrain projections drain [--limit <n>] [--json]` (#5401). Trusted-local CLI, not an operation. Rebuilds queued Markdown and code projections in-process in batches of up to 100 until every row queued at the run start has been tried once (it waits for the database clock to pass the run start, so a page that fails in the run is not retried); `--limit` caps pages tried. Exit 0 (nothing tried failed), 1 (a page failed; each failure prints source, slug, reason and next action), 2 (did not run: bad usage, or `projection_owner_resident` when a process holds the selected PGLite brain, checked with `persistenceConfigForBrain` before any engine opens, so a mounted PGLite brain on a Postgres host is refused too). On Postgres it runs beside a resident owner (per-page locks plus the revision recheck). `residentDrainSteps` gives the stop-drain-restart commands for the serve service, autopilot and a manual serve, shared with doctor. Tests: `projection-drain.test.ts` (both engines via `test/e2e/projection-drain-postgres.test.ts`), `projections-drain-cli.serial.test.ts`.
- `src/commands/reindex-code.ts` — `gbrain reindex-code [--source ID] [--dry-run] [--yes] [--json] [--force] [--no-embed]`. Walks live `page_kind = 'code'` pages in source/slug order and rebuilds derived projections without rewriting canonical files, revisions or hashes. `--force` rebuilds already-current projections. Managed brains use a guarded journal receipt; resident PGLite delegates through the authenticated local administration route in `reindex-code-delegate.ts`. Cost-preview model field reads `getEmbeddingModelName()` from the gateway so preview reflects what the gateway will actually embed with. An informational stderr nudge inside `runReindexCode` (so dry-run + execute both surface it): when the configured embedding model isn't code-tuned (allowlist `{'voyage-code-3'}`, case-insensitive bare match), prints a recommendation to switch to `voyage:voyage-code-3`; suppress with `GBRAIN_NO_CODE_MODEL_NUDGE=1`, `--no-embed`, or `--json`. Pure `shouldNudgeCodeModel(bareName)` returns a tagged `NudgeDecision` union (takes the bare model name, emits qualified `voyage:voyage-code-3` for the paste-ready `gbrain config set` line). When `--yes` is absent and the caller is non-TTY or passed `--json`, the cost gate refuses (exit 2, no spend) via the pure exported `buildCostRefusal({json, previewMsg, preview, costUsd, model}): {stdout?, stderr?}` — JSON envelope only when `--json` is explicit, otherwise a human refusal on stderr (the spend guardrail is independent of the output format). `spend.posture=tokenmax` OR an explicit `--max-cost off`/`unlimited` makes the gate informational and proceeds; `--max-cost off` also disables the runtime BudgetTracker cap. Pinned by `test/ai/voyage-code-3-recipe.test.ts`, `test/reindex-code-nudge.serial.test.ts`, `test/reindex-code-model-source.serial.test.ts` (IRON-RULE guard for the cost-preview model source), `test/reindex-cost-refusal.test.ts`. Resident-delegated embedding requires explicit --yes; --no-embed is the keyless repair path. Missing vectors remain available to the normal embed-stale workflow.
- `src/commands/reindex-frontmatter.ts` — `gbrain reindex-frontmatter`. `reindexFrontmatterCli(engine, args)` takes the ALREADY-CONNECTED engine from cli.ts's dispatch; it must never build/connect its own engine — a second connect on the same PGLite data dir self-deadlocks on the data-dir lock (this process already holds it). Same rule applies to `runBackfillCommand(engine, args)` in `src/commands/backfill.ts` and any future command dispatched from cli.ts's engine-connected switch. Pinned by `test/reindex-frontmatter-connect.test.ts` (library path) and `test/reindex-frontmatter-pglite-spawn.serial.test.ts` (CLI dispatch seam, both commands).
diff --git a/docs/architecture/key-files/commands-5.md b/docs/architecture/key-files/commands-5.md
index 7c0d642523..401a28fa8a 100644
--- a/docs/architecture/key-files/commands-5.md
+++ b/docs/architecture/key-files/commands-5.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/serve-http-grants.ts` + `admin/src/components/ClientGrant.tsx` — typed admin grant request validation and shared profile/advanced permission editor. Register/rescope/TTL routes in `serve-http-registration.ts`, `serve-http-grants.ts`, and `serve-http-admin-api.ts` use canonical grant validation and audit; legacy response shapes remain available. Registration and permission-edit failures add safe classifications, stage, outcome and inspection remedies; an unacknowledged mutation stays outcome-unknown, while read/preview failures and known refusals remain failed. New UI creation defaults to memory-writer and requires a preview, while edits carry the displayed revision and require a fresh preview after any field change or conflict. Detail/catalog endpoints expose non-secret grants and the shared harness registry. Operation authority snapshots, source sets, delegated tools/namespaces, spend, concurrency, and future TTL are independently reviewable; profile regrant is explicit. `admin/src/pages/Agents.tsx` previews machine/public PKCE/confidential PKCE registration and current permissions, and exposes versioned lifecycle actions. Explicit downloads select machine `HarnessCredentials` or native `OAuthClientSetup`; mixed clients require a flow choice. Loading errors preserve stale rows with Retry and disable creation when required source metadata is missing. Browser downloads and native connection evidence remain distinct. Rebuild committed `admin/dist` and `src/admin-embedded.ts` after SPA edits.
- `src/commands/serve-http.ts` — Express 5 HTTP MCP server with OAuth 2.1, admin dashboard, and SSE live activity feed. The legacy `POST /ingest` queue refuses operation-snapshot clients; they use approved MCP writes so execution stays inside the shared grant contract. Started via `gbrain serve --http [--port N] [--token-ttl N] [--enable-dcr] [--public-url URL] [--bind HOST] [--log-full-params]`. OAuth discovery's `scopes_supported` (RFC 8414 AS metadata and both RFC 9728 protected-resource documents, one value through the SDK router) comes from `scopesSupportedForDiscovery({ enableDcr })` in `src/core/scope.ts`: with `--enable-dcr` it is exactly the self-registration ceiling (`read write`), so a client that copies discovery into its `/register` request succeeds; without DCR it is every scope except operator-only `agent`. The DCR ceiling still rejects an explicit privileged request, and operator-registered clients are never narrowed by the advertisement. Combines MCP SDK's `mcpAuthRouter` (authorize/token/register/revoke), a custom `client_credentials` handler running BEFORE the router (SDK's token endpoint throws `UnsupportedGrantTypeError` for CC; custom handler falls through for `auth_code` / `refresh_token`), `requireBearerAuth` middleware for `/mcp` with scope enforcement + `localOnly` rejection before op dispatch, and per-IP `express-rate-limit` buckets: the MCP SDK's defaults on `/authorize` (100 / 15 min), `/register` (20 / hour) and `/token` (50 / 15 min) because `authRouterOptions` passes no `rateLimit: false`, the custom `client_credentials` handler's `ccRateLimiter`, and independent owner limits: 60 total authentication requests/min/IP, 10 failed authentications/min/IP (verified authority, independent of response status), and 60 consent requests/min/authenticated session in `serve-http-admin-limits.ts`. Admin no-store, no-referrer and framing headers precede login/link handlers. Explicit pending IDs survive fresh-browser links; invalid or restarted requests require native authorization to restart. Serves the built admin SPA from `admin/dist/` with SPA fallback. `/admin/events` SSE broadcasts every MCP request. `cookie-parser` wired (Express 5 has no built-in). Startup logging prints port, engine, issuer URL (honors `--public-url`), client count, DCR status, and the admin bootstrap token line — but the generated token's raw value only prints when stderr is an interactive TTY (`shouldSuppressBootstrapPrint`): a non-TTY (containerized/piped) start hides it so the secret never lands in centralized log storage, env-sourced tokens (`$GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) are always hidden, `--print-admin-token` forces the raw value on a trusted terminal, and `--suppress-bootstrap-token` hides everything. The `/mcp` request handler's OperationContext literal sets `remote: true` explicitly (without it `submit_job`'s protected-name guard would see a falsy undefined and a `read+write`-scoped OAuth token could submit `shell` jobs). `summarizeMcpParams` from `src/mcp/dispatch.ts` feeds both `mcp_request_log` writes and the SSE feed by default (raw via `--log-full-params`). Cookie `Secure` flag set behind HTTPS or a public-URL proxy; magic-link nonce store LRU-bounded; DCR disable routes through the `GBrainOAuthProvider` `dcrDisabled` constructor option (not a router monkey-patch); `transport.handleRequest` wrapped in try/catch to return a JSON-RPC 500 envelope; OperationError + unexpected exceptions unified through `buildError` / `serializeError` so `/mcp` always returns the same envelope. `/health` is liveness-only via `probeLiveness(engine, engineName, version, timeoutMs)` racing `engine.executeRaw('SELECT 1', undefined, { signal })` against the exported `HEALTH_TIMEOUT_MS = 3000`; when the timeout wins, an `AbortController` cancels the Postgres query (PGLite can only discard its eventual result) before the same tagged `ProbeHealthResult` 503 envelope is returned (single timer-cleanup site); body shape `{status, version, engine}` only. Full stats live at admin-only `/admin/api/full-stats` (gated by `requireAdmin`, calls `probeHealth(engine, ...)`) — keeps `getStats()`'s 6× count(*) off the public route so a saturated pool doesn't trigger orchestrator restart cascades. OAuth/admin/audit SQL outside the abortable liveness probe routes through `sqlQueryForEngine(engine)` from `src/core/sql-query.ts` so it works against PGLite; the four `mcp_request_log.params` INSERT sites (success / auth_failed / scope_denied / server-error) go through `executeRawJsonb(engine, ...)` so the column stores real objects (`params->>'op'` returns `search`, not the quoted string). `--bind HOST` defaults `127.0.0.1` (self-hosters pass `--bind 0.0.0.0`); a stderr WARN fires when `--public-url` is set without `--bind`; the banner prints a `Bind:` line. `AuthInfo.sourceId` + `AuthInfo.allowedSources` + `AuthInfo.takesHoldersAllowList` are the typed source of truth, populated by `oauth-provider.ts:verifyAccessToken` (source scope from the `oauth_clients` row; takes-holders from `access_tokens.permissions.takes_holders` for legacy bearer tokens). The `/mcp` dispatch site reads `authInfo.takesHoldersAllowList ?? ['world']` — absent grants (OAuth-client tokens, pre-v29 brains) fail closed to world-only takes visibility, while an explicit `[]` grant is preserved as deny-all; pinned end-to-end by `test/e2e/serve-http-takes-holders.test.ts`. The HTTP MCP `tools/list` handler at `:837-849` uses `paramDefToSchema(v)` from `src/mcp/tool-defs.ts` so array params keep `items` (strict-mode OAuth clients otherwise reject the whole tool list). `POST /ingest` enforces the slug-prefix write fence at the ROUTE, not the op layer: the route hands its payload to the `ingest_capture` minion handler, which deliberately bypasses `put_page`, so no `OperationContext` exists and `enforceClientSlugFence` never runs — a slug-bound client must therefore supply `X-Gbrain-Slug` and it must satisfy `slugUnderBoundPrefixes`, else 403 (without the check a bound client could overwrite any page inside its granted source). The write source is resolved server-side as `authInfo.sourceId ?? 'default'` and travels on the job as `job.data.sourceId`; the caller-supplied `X-Gbrain-Source-Id` header routes nothing and only names the emitter (`webhook-<clientId>`), which is what the event's `source_id` and the 202's back-compat `source_id` field carry. The 202 additionally reports the routed destination as `write_source_id`, and the resolved write source joins the queue idempotency key so a rescoped client lands a new capture instead of deduping against its old job. confidential revoke: a pre-router `/revoke` handler validates the RFC 7009 body, verifies hash-only secrets for both `client_secret_post` and `client_secret_basic`, rejects mixed authentication, preserves the SDK path for public clients, and separates opaque client-auth failures from retryable/backend failures. OAuth metadata advertises both confidential methods. Pinned by `test/e2e/serve-http-oauth.test.ts`. three admin routes: `/admin/api/calibration/profile`, `/admin/api/calibration/charts/:type` (image/svg+xml; type in {brier-trend, domain-bars, pattern-statements, abandoned-threads}), `/admin/api/calibration/pattern/:id` (drill-down). The manual mint route `/admin/api/register-client` in `serve-http-registration.ts` accepts optional `source` + `federatedRead` bindings mirroring the CLI's `--source`/`--federated-read` (validated via `normalizeSourceInput`/`normalizeFederatedReadInput` from `src/core/source-id.ts`; omitting both preserves the default binding `source_id='default'` / `federated_read=[source_id]`, invalid values return a structured 400 `invalid_source`), so an admin SPA or provisioning proxy can mint a source-confined client over HTTP. The route mirrors the CLI lane end to end: structured 400s for `unknown_source` / `archived_source` (one batched `ANY($1::text[])` existence check), `invalid_token_ttl` (shared `TOKEN_TTL_MIN/MAX_SECONDS` bounds, integer-validated BEFORE the tx), and `brain_too_old` (column pre-flight OUTSIDE the tx — a pre-scoped-clients brain refuses up front instead of aborting mid-transaction); the duplicate-name pre-check + INSERT run in ONE transaction under the SAME name-scoped advisory lock the CLI takes (`registerClientNameLockKey`), returning 409 `duplicate_name` with the existing `client_id`; the INSERT composes `registerScopedClient` (the CLI's registration core) so the two paths cannot drift; any post-commit failure includes the created `client_id` so the operator can revoke (never a false "nothing was created"). Pinned by `test/register-client-source-normalize.test.ts`. The `/mcp` tools/list is the honest catalog: per-request filters (token scope incl. the `agentCallable` carve-out, bound-client fence via `opAllowedForBoundClient`, publish gates via `disabledOpsForPublishGates`) over the surface-filtered op set, schemas via `buildToolDefs` (strict emission when `mcp.strict_params` resolves reject); the tools/list `mcp_request_log` row records the listed size as `params.tool_count`. Call-time op-level denials the list should have prevented — the inline scope deny, publish-gate backstop (`config_key=...`), fence op-level deny (`fence=op`, classified via `isListLevelDenialEnvelope`) — log `status='denied_after_list'` instead of `'error'` (the trend-to-zero honest-catalog metric, see docs/operations/mcp-surface-runbook.md) — every tools/call row's status resolves through `requestLogStatusForResult` (dispatch.ts) on BOTH transports. The admin health-indicators error rate counts `status NOT IN ('success','success_with_warnings')` and excludes `operation='surface_change'` audit rows from numerator AND denominator (audit rows record operator/self actions, not traffic). Per-request surface resolution lives in `resolveEffectiveSurface`: a `verbs` ceiling skips the default-surface config read, and a failed read applies the last successfully read default per process (fail-closed — a transient config outage cannot widen a NULL-surface client). OAuth protected-resource metadata (RFC 9728) names `/mcp` as the resource (`resourceServerUrl`), so the SDK mounts the PRM at `/.well-known/oauth-protected-resource/mcp` and the 401 `resource_metadata` URL is derived from the same value; the bare root path is kept as an alias by rewriting `req.url` onto the SDK's handler (same document, same CORS). Shutdown: `waitForHttpServerLifecycle` tracks accepted sockets weakly (`trackServerSockets`; Bun never emits socket `close`, so a strong set leaked one per request), severs the still-reachable ones right after `server.close()`, and bounds the close wait at `CLOSE_TIMEOUT_MS` (5s) — a collected keep-alive wrapper whose native handle keeps `close()` from returning gets one stderr line and shutdown proceeds instead of hanging. DCR startup copy: the SECURITY WARNING states self-registered clients are limited to read/write (read-only for `client_credentials` under `--enable-dcr-insecure`) and that every authorization_code connection needs owner approval in the admin UI; banner `DCR:` values are `enabled (consent; DCR max read write)` / `enabled (INSECURE: read-only M2M)` / `disabled`.
- Layout: `buildServeHttpApp` builds one shared `ServeHttpContext` (sessions, nonce stores, limiters, `requireAdmin`, SSE fan-out, OAuth provider, resource verifier, non-`localOnly` op list) and mounts in registration order `serve-http-oauth.ts` (CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent), `serve-http-metrics.ts` (`/health`, `/metrics`, probes), `serve-http-admin-api.ts` (`requireAdmin`, `/admin/login`, `/admin/api/*`, `/admin/events`), `serve-http-spa.ts`, `serve-http-mcp.ts` (`/mcp`) and `serve-http-webhooks.ts` (`/ingest`, `/webhooks/github`); `runServeHttp` keeps listen, banner, resolve-IPC binding and shutdown, and the façade re-exports moved symbols. Order is pinned by `test/serve-http-route-golden.test.ts` (AST) and `test/serve-http-route-runtime-golden.test.ts` (router stack). Size ceiling: `scripts/module-size-limits.tsv`.
+ Layout: `buildServeHttpApp` builds one shared `ServeHttpContext` (sessions, nonce stores, limiters, `requireAdmin`, SSE fan-out, OAuth provider, resource verifier, non-`localOnly` op list) and mounts in registration order `serve-http-oauth.ts` (CORS gates, DCR TTL hook, confidential credentials, SDK router, discovery, owner login links, consent), `serve-http-metrics.ts` (`/health`, `/metrics`, probes), `serve-http-admin-api.ts` (`requireAdmin`, `/admin/login`, `/admin/api/*`, `/admin/events`), `serve-http-spa.ts`, `serve-http-mcp.ts` (`/mcp`) and `serve-http-webhooks.ts` (`/ingest`, which maps a legacy-authority `permission_denied` from submission to 409 `{error, message, hint, docs_url}` (`test/serve-http-ingest-legacy.test.ts`) and every other submission error to 500, `/webhooks/github`); `runServeHttp` keeps listen, banner, resolve-IPC binding and shutdown, and the façade re-exports moved symbols. Order is pinned by `test/serve-http-route-golden.test.ts` (AST) and `test/serve-http-route-runtime-golden.test.ts` (router stack). Size ceiling: `scripts/module-size-limits.tsv`.
- `src/commands/serve.ts` — `gbrain serve` stdio MCP entrypoint with idempotent shutdown across every parent-disconnect signal. Stdio EOF, SIGTERM, SIGINT, SIGHUP, and parent-process death (every reparent case — PID 1, launchd subreaper, systemd, tmux, or a parent shell with `PR_SET_CHILD_SUBREAPER`) all funnel into one `cleanup(reason)` that first awaits `shutdownDelegatedSync()` (idempotent shared promise; a running delegated sync is aborted and settles its checkpoint against the live engine, with the cleanup deadline extended by `GBRAIN_SERVE_SYNC_SETTLE_MS` only while a job runs) and then releases the engine and the PGLite write-lock dir within 5 seconds (otherwise the lock is held indefinitely after Claude Desktop / Cursor / launchd-managed gateways disconnect, forcing a 5-minute stale-lock wait on next start). Watchdog reparent check is `getParentPid() !== initialParentPid` (the `=== 1` check missed the subreaper case under launchd/systemd). Bun's `process.ppid` cache is stale across reparenting ([oven-sh/bun#30305](https://github.com/oven-sh/bun/issues/30305)) so `getParentPid()` runs `spawnSync('ps', ['-o', 'ppid=', '-p', PID])` per tick. Startup probe verifies `ps` is on PATH; if not (stripped containers, busybox), the watchdog skips installing AND emits a loud `[gbrain serve] watchdog disabled: ps unavailable ...` stderr line so operators see the degraded mode. The idle maintenance sweep skips ticks while a delegated sync runs and drains deferred embeds afterwards (`maybeDrainDeferredEmbeds`); it targets the source `resolveMcpStdioSourceScope` resolves (GBRAIN_SOURCE > `.gbrain-source` dotfile > local_path > `sources.default` > …) — the SAME ladder as stdio dispatch and the startup sweep, so dotfile/local_path-scoped serves reconcile their in-session MCP writes (pinned by `test/serve-idle-sweep-source.serial.test.ts`). Both stdin activity listeners (the default-on idle sweep and the opt-in `--stdio-idle-timeout`) attach only AFTER the MCP SDK transport's own stdin listener — the sweep on its first interval tick, the idle timeout through the activator `installStdioLifecycle` returns, which `runServe` invokes once `startMcpServer` resolves (and which re-arms the countdown so boot time does not eat into the idle window) — so neither can flip stdin into flowing mode and consume a fast client's initialize frame before the SDK sees it. Pinned by `test/serve-stdio-lifecycle.test.ts` (22 cases).
diff --git a/docs/architecture/key-files/core-ai.md b/docs/architecture/key-files/core-ai.md
index 6566ec5a3a..210b9de498 100644
--- a/docs/architecture/key-files/core-ai.md
+++ b/docs/architecture/key-files/core-ai.md
@@ -22,7 +22,9 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/ai/openrouter-families.ts` — single source of truth for which OpenRouter model families may drive the subagent (tool) loop: `OPENROUTER_SUBAGENT_FAMILIES` (currently `anthropic/` + `deepseek/`, each backed by a live abort/retry replay pin under `test/e2e/`) + `openrouterModelSupportsSubagentLoop(modelId)` (takes the bare OpenRouter id, no `openrouter:` prefix). Shared by the openrouter recipe's predicate and the subagent handler's auto-route so the two can never disagree; a new family gets its own live pin before joining the list.
-- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift.
+- `src/core/ai/provider-env.ts` — `mergedProviderEnv(cfg, env)`: THE canonical provider-key/env fold. Maps file-plane config keys (openai/anthropic/openrouter/voyage/dashscope/deepseek/litellm/together/google/azure_openai + azure endpoint/deployment/entra) to the env names recipes read, merges env on top (env wins ONLY for keys carrying a real value — '' and undefined dropped), then applies the `GEMINI_API_KEY → GOOGLE_GENERATIVE_AI_API_KEY` alias (canonical env name > alias > config fallback). Three consumers: `buildGatewayConfig` (gateway env), `detectCapabilities` (capability probe), `resolveTierDefault`/`resolveEffectiveChatModel` (key-aware model resolution) — so gateway env and the capability probe cannot drift. #5137: the fold reads the `CONFIG_API_KEY_ENV` table; `providerKeyShadows(fileCfg, env)` (pure, names only) lists env values that override a different config-plane key, and `providerKeySource` names where a recipe's key comes from. Both take the FILE-only config (`loadConfigFileOnly`), because `loadConfig` already folds OPENAI/ANTHROPIC/OPENROUTER env values into the config fields. TypeSafe has no config key, so its env alias never shadows. Tests: `embedding-key-source.test.ts`, `embedding-key-source-cli.serial.test.ts`.
+- `src/core/ai/key-warnings.ts` — #5137 print seam with one replaceable sink and two once-per-process latches: `warnShadowedProviderKeys` (called from `src/cli.ts` for every command except `gbrain hook`; `gbrain serve` starts through the same path) names the variable, the config key, that env is in effect, and both fixes (remove the variable from that process's environment and restart it, or `gbrain config unset <key>`, which also silences it); `reportEmbeddingAuthFailure` prints `embedding_auth_failed` (catalogue entry) on the first embedding 401/403, naming the key source in effect and the fix plus `gbrain embed --stale`. Never prints a key or fragment. Doctor `embedding_key_source` (`src/commands/doctor/checks/embedding-health.ts`, engine-free filesystem-lane entry `embeddingKeySourceEntry`) reports the same shadows and the embedding key's source, and says it sees only the environment doctor runs in.
+- `src/core/ai/key-redact.ts` — `redactProviderKeys(text, env)`: scrubs every `*_API_KEY`/`*_TOKEN`/`*_SECRET`/`*_PASSWORD` value in the gateway env, masked echoes (`sk-...****abcd`) and 8+ character key fragments from upstream error text. The gateway passes it to `normalizeAIError` (which also scrubs the wrapped error's cause chain in place, keeping status and headers for `.cause` walkers) on embed, multimodal, expand and chat errors, and applies it to multimodal response bodies.
- `src/core/ai/providers/claude-cli-language-model.ts` (+ recipe `src/core/ai/recipes/claude-cli.ts`) — ai-sdk LanguageModel adapter that shells out to the locally-installed `claude` CLI in print mode (OAuth-subscription lane, no API key; `claude-cli:<model>` is config-portable with `anthropic:<model>`). Tool use is system-prompt-instructed JSON emission: the recipe teaches the model the `<use_tools>[{name,input}]</use_tools>` format and the adapter parses those blocks back into ai-sdk `tool-call` parts. An entry that carries its arguments flat beside `name` (no `input` wrapper, the Anthropic tool_use shape with the wrapper dropped) is accepted: every key other than `name`/`input` and the Anthropic tool_use leftovers (`type: "tool_use"`, a `toolu_*` `id`) becomes the input — any other `type`/`id` value is a real argument (e.g. `list_pages`' `type` filter) and stays — and a present `input` wins verbatim over stray sibling keys. Tool-call ids are ALWAYS gbrain-minted (`toolu_claude_cli_<uuidv7>`) — never model-authored: each doGenerate is a fresh subprocess replayed from an id-stripped transcript, so the model structurally cannot keep ids unique across turns (a model-authored id echoes the prompt's example entropy-free and collides); the prompt does not ask for an id, and a stray `id` field is deliberately ignored (nothing round-trips it — the loop pairs results in-memory within one turn). doStream not implemented; callers (gateway.toolLoop) use doGenerate. The recipe declares `chat` + `expansion` touchpoints (no embedding; the expansion list leads with the cheap haiku id and carries the same 30s `default_timeout_ms` as chat for the subprocess cold start); `gateway.expand()` routes `claude-cli` through the schemaless `viaText` path because the adapter ignores `responseFormat` (generateObject would throw NoObjectGeneratedError on the fenced-JSON text). Pinned by `test/claude-cli-recipe.test.ts` + `test/ai/claude-cli-expansion.test.ts`.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index ad43417579..d9cd78cfb0 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -19,7 +19,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-drain.ts` — pure single-hold bounded drain for the silent lens-phase backlog. `runExtractAtomsDrain(deps, opts)` over injected deps (`withLock`, `runBatch`, `countRemaining`, `now`, optional `onBatch`) loops bounded batches under ONE continuous lock hold, **rediscovering eligibility each batch** (idempotent NOT-EXISTS-on-`source_hash`, so content mutated by a concurrent process simply doesn't match — no cross-window stale cursor), until the backlog is empty OR the time window elapses. Returns `{phase, status, extracted, skipped, remaining, batches, stopped}`. Backs `gbrain dream --phase extract_atoms --drain`. Takes the SAME `cycleLockIdFor(sourceId)` the routine cycle takes (a concurrent autopilot tick genuinely defers with `cycle_already_running`); NO release/reacquire-between-windows primitive. The shared wiring helper `runExtractAtomsDrainForSource(engine, {sourceId, windowSeconds, brainDir?, maxBatches?, onBatch?})` owns the lock+batch+count+defer wiring (dynamic imports of db-lock/cycle/extract-atoms keep the pure loop cheap to unit-test) and is the ONE drain path for three callers — `gbrain dream --drain` (which calls it), the `extract-atoms-drain` Minion handler, and autopilot auto-drain — so lock id / window / defer-on-busy can't drift. `sourceId: undefined` → legacy `gbrain-cycle` lock + `'default'` extraction; a real id → `gbrain-cycle:<id>`. `LockUnavailableError` propagates to the caller (each reports the busy case its own way). Pinned by `test/extract-atoms-drain.test.ts`. The summary's `last_error` always passes through `sanitizeFailureText` (secret/DSN redaction, whitespace collapse, bounded): typed failure records use the source/reason caps, and the count-only `firstError` compatibility path is sanitized to the combined bound, so a provider payload cannot ride either path into `--json` output. `formatDrainProviderFailure(result)` renders the Minion handler's `provider_failure` throw (batches/remaining + `last_error`), so the dead-lettered job's `error_text` names the cause.
-- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce, so LLM-chosen titles that drift between extractions don't pile up. Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
+- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes, `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce.
+ Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
+ Both paths prevent LLM-chosen titles that drift between extractions from piling up.
+ Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (migration `extract_atoms_transcript_state_table`; keyed `(source_id, file_path, content_hash)` with the 16-char hash prefix, so an edit is a new row and re-eligibilizes): `recordItemFailureCount` counts a transcript's malformed output toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (the same zero-yield policy as pages), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. Tests: `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-1.md b/docs/architecture/key-files/core-minions-1.md
index f14a2621f4..e9d8051dc6 100644
--- a/docs/architecture/key-files/core-minions-1.md
+++ b/docs/architecture/key-files/core-minions-1.md
@@ -60,10 +60,16 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/handlers/supervisor-audit.ts` — supervisor lifecycle JSONL audit at `~/.gbrain/audit/supervisor-YYYY-Www.jsonl` (ISO-week rotation; shares `computeIsoWeekName()` with `shell-audit.ts`). `writeSupervisorEvent(emission, supervisorPid)` appends one line per event (`started`, `worker_spawned`, `worker_exited`, `backoff`, `health_warn`, `health_error`, `max_crashes_exceeded`, `shutting_down`, `stopped`, `worker_spawn_failed`). `readSupervisorEvents({sinceMs})` is the readback for `gbrain doctor`. Exports `isCrashExit(event)`, `summarizeCrashes(events)`, `CrashSummary` type, and `CLEAN_EXIT_CAUSES` denylist (`'clean_exit' | 'graceful_shutdown' | 'wedge_restart' | 'configuration_blocked'`). Single shared point — both `gbrain doctor` (supervisor check) and `gbrain jobs supervisor status` import from here so the two surfaces can't drift. `isCrashExit` classifies a single `worker_exited` against the denylist: clean/graceful, deliberate wedge restarts and configuration blocks are NON-crashes; everything else (incl. any future `likely_cause` from `child-worker-supervisor.ts`) is a crash; audit lines lacking `likely_cause` fall back to `code !== 0`. `summarizeCrashes` returns `{total, by_cause: {runtime_error, oom_or_external_kill, unknown, legacy}, clean_exits}` — the `legacy` bucket catches both old fallback entries AND unrecognized future causes (fail-loud, not silent underreport); denylist-over-allowlist is deliberate. Pinned by `test/supervisor-audit.test.ts` (14 cases) and 4 source-grep wiring assertions in `test/doctor.test.ts`.
+- `src/core/minions/idempotency-coalesce.ts` — the idempotency-key halves of `MinionQueue.add`: `coalesceOnIdempotencyKey` (fast path) and `insertOrCoalesce` (insert race: re-read the winner, release a dead or cancelled key with a CAS update that rechecks key, status and SQL NULL authority, retry the insert once). Both apply `coalesceDecision` from `submission-authority.ts`. Tests: `test/minions-legacy-coalesce.test.ts`.
+
- `src/core/minions/job-context.ts` — shared `buildJobContext(engine, queue, job, lockToken, signal, shutdownSignal)` (extracted verbatim from executeJob) so inline mode and the run-child child wire identical token-fenced DB callbacks.
- `src/core/minions/job-isolation.ts` — per-job process-isolation protocol: atomic outcome-file codec (`writeChildOutcomeFile` tmp+rename, `decodeChildOutcomeFile` with a 32MiB cap that throws `UnrecoverableError` — oversize results die loudly on attempt 1, decode errors report byte counts never content), `encodeHandlerError`/`reconstructHandlerError` preserving `UnrecoverableError`, `RateLeaseUnavailableError`, and allowlisted `LocalConfigurationError` reason codes; configuration messages are reconstructed locally rather than trusting child text, the child argv/env contract (`CHILD_ENV`, `buildChildArgs`), `resolveChildCliInvocation` (explicit `GBRAIN_JOB_CHILD_CLI` override → current worker entrypoint/compiled executable → PATH fallback → null for fail-fast), and the bounded selected-runtime handshake in `child-readiness.ts` (protocol/features plus version-skew reporting; 20s deadline and combined 64KiB stdout/stderr cap; only complete allowlisted replies prove configuration failure). `killProcessGroup(pid, sig)` — children are spawned detached (own group) because SIGKILL on a tini pid alone orphans the handler grandchild, and Bun rejects negative pids in process.kill (oven-sh/bun#15791) so group signaling falls back to POSIX /bin/kill. Pinned by `test/job-isolation-protocol.test.ts` (incl. real-process grandchild-death). `buildChildArgs(jobId, env = process.env)` appends `--allow-shell-jobs` when `env.GBRAIN_ALLOW_SHELL_JOBS === '1'` (child-job-runner passes its spawning env), because the per-job child re-runs the cwd-.env preflight in the worker's cwd and would otherwise lose the opt-in; `jobs run-child` re-asserts the env from that flag. Pinned by `test/job-isolation-allow-shell-jobs.test.ts`. `child-job-runner.ts` passes `opts.env ?? process.env` as the base env, so `GBRAIN_ALLOW_SHELL_JOBS === '1'` in it appends `--allow-shell-jobs` (any other value does not); pinned by the pass-through case in `test/child-job-runner.test.ts`.
+- `src/core/minions/legacy-cancel.ts` — `gbrain jobs cancel --select` (DX-T2, ENG-O5): selects live rows with SQL NULL or unsupported authority, hashes the full `cancelJobs` closure (selected rows plus parents that return from waiting-children to waiting), refuses a selection that would cascade to a descendant outside it (`legacy_job_selection_invalid`, E-T4), and applies under a table lock through `cancelJobs` in one transaction after re-hashing (`preview_changed` on drift). Tests: `test/jobs-cancel-select.test.ts`.
+
+- `src/core/minions/legacy-selection.ts` — the `--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"` grammar shared by `gbrain jobs authorize-legacy --select` and `gbrain jobs cancel --select` (`parseLegacyJobSelection` refuses with `legacy_job_selection_invalid`), the filled preview/apply commands (`selectCommand`), the recovery hint every legacy refusal names (`legacyRecoveryHint`), the `legacy_jobs_active` precondition listing up to 10 `gbrain jobs cancel <id>` commands, and the DX-O3(d) summary. Both commands are CLI-only (no operation). Tests: `test/jobs-authorize-legacy-select.test.ts`.
+
- `src/core/minions/lock-renewal-tick.ts` — Pure function behind `MinionWorker.launchJob`'s setInterval body, structured so a renewal failure can never surface as an unhandledRejection, carrying the verify-before-evict doctrine. Exports `runLockRenewalTick(deps, state) → Promise<TickResult>` + `resolveLockRenewalKnobs(env, lockDuration, intervalMs?) → LockRenewalKnobs` + `RenewalCallTimeoutError` + `LockRenewalTelemetryCtx`. Doctrine: a thrown/timed-out renewal is NOT evidence of loss — when the NEXT tick would land past the soft deadline (`lease - safetyMargin`, cadence-aware: `sinceLastSuccess + intervalMs >= deadline`), the tick runs ONE bounded fenced VERIFY renewal. Fenced-true → starved-but-ours, lease re-extended, counter reset (audit `success_after_failure` with `via: 'verify'`); fenced-false → CERTAIN loss → `lock_lost` (the only certain signal); verify unreachable → defer + reconnect-once (audit `failure` with `deadline_deferred: true`), aborting only past `hardEvictMs` — a LOCAL decision under uncertainty bounding blind external side effects during a total outage. Four env knobs, positive-int parsed with stderr-warn-once + default fallback, then RELATIONALLY validated (margin < lease/2, callTimeout ≤ cadence, hardEvict ≥ soft deadline — warn-once clamps): `GBRAIN_LOCK_RENEWAL_MAX_FAILURES` (default 3, audit-labeling only), `GBRAIN_LOCK_RENEWAL_CALL_TIMEOUT_MS` (default `min(lease/3, 15s)`), `GBRAIN_LOCK_RENEWAL_SAFETY_MARGIN_MS` (default `min(lease/6, 30s)`), `GBRAIN_LOCK_RENEWAL_HARD_EVICT_MS` (default `2×lease`, floored to the soft deadline; setting it TO the deadline approximates abort-at-deadline). Telemetry: tick lateness (`now - lastTickFiredAt - intervalMs`, the primary local-starvation signal — interval callbacks COALESCE under a blocked loop so missed-tick counters can't measure starvation), `overlapSkips` (tickInFlight re-entrancy skips only), failure-cause classification via the named `RenewalCallTimeoutError` (`call-timeout` | `refused` | `fenced-lost`), optional `deps.loadSnapshot` (try/caught — telemetry must never throw into control flow) and `deps.onRenewalSuccess` (worker resets its event-loop-delay histogram). Elapsed-time arithmetic runs on the injected `deps.now`, which production binds to `performance.now()` (monotonic) — the local clock only schedules WHEN to verify, never WHETHER to evict. The race timeout also aborts the in-flight call via AbortSignal threaded to `renewLock` (best-effort — the fence is the correctness authority). The tick checks `state.cancelled()` at every await boundary (entry, post-resolve, post-throw, post-verify). Result is a tagged union: `should_abort` carries `{cause, latenessMs, sinceLastSuccessMs, overlapSkips, load1?, cores?}` and `lock_lost` carries `{cause: 'fenced-lost', via: 'renewal'|'verify'}`; the worker stashes the result as per-launch `abortMeta` so the grace-evict log (30s later) reports the classified cause. The in-tick verify is reconciled in-code with queue.ts's no-background-retry rationale: it is synchronous, cancelled()-guarded, and callTimeoutMs-bounded — both UPDATEs are same-token idempotent lease extensions, so a fenced row cannot gain two holders. Pinned by `test/worker-lock-renewal.test.ts` (hermetic state-machine suite incl. a fake-time starvation replay, the cadence-quantization pin, hard-backstop timelines, relational-clamp cases) + `test/e2e/worker-lock-renewal-starvation.test.ts` (real-PG foundations). `LockRenewalDeps.renewLock` carries an optional per-call `{signal}`; the timeout race aborts it so the losing UPDATE releases its slot.
- `src/core/minions/niceness.ts` — OS scheduling-priority (niceness) primitives for the `--nice` flag. `parseNiceValue(raw)` whole-string parses + range-validates to POSIX `[-20, 19]` (rejects `"3.5"`/`"10abc"` that `parseInt` would silently truncate). `applyNiceness(nice, setPriority?, getPriority?)` calls `os.setPriority(0, n)` and ALWAYS re-reads `os.getPriority(0)` afterwards — in both the success and the catch paths — so a denied renice (EPERM) or an `RLIMIT_NICE` clamp records the real effective value (e.g. `0`), not null; returns `{applied, requested, effective, error?}`. `getEffectiveNiceness(pid, getPriority?)` reads an arbitrary pid's niceness (null on dead/unreadable). `formatNice(n)` → `+10`/`0`/`-5`. Applied only at the CLI layer (jobs.ts) so worker.ts/supervisor.ts stay embeddable. Pinned by `test/niceness.test.ts`.
diff --git a/docs/architecture/key-files/core-minions-2.md b/docs/architecture/key-files/core-minions-2.md
index c768623b88..1c4df7a9a5 100644
--- a/docs/architecture/key-files/core-minions-2.md
+++ b/docs/architecture/key-files/core-minions-2.md
@@ -7,7 +7,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/minions/spawn-helpers.ts` — pure `detectTini()` + `buildSpawnInvocation()` consumed by both `supervisor.ts` and `autopilot.ts` (one implementation for both spawn sites; tini wrapping is testable without `mock.module()`, rule R2 of `scripts/check-test-isolation.sh`). `detectTini()` calls `execFileSync('which', ['tini'])` with explicit `env: process.env` so Bun sees runtime PATH mutations. `buildSpawnInvocation(tiniPath, cmd, args)` returns `{cmd, args}` with `tini -s --` prepended when present, or the bare invocation otherwise. Subreaper mode also serves job children; it does not imply PID 1 or containment of descendants that escape the process group. Pinned by `test/spawn-helpers.test.ts` (5) and `test/supervisor-tini.test.ts` (4).
-- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows. `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.
+- `src/core/minions/submission-authority.ts` — versioned authority kept outside caller job data. Submission normalization and worker revalidation bind remote jobs to immutable principal/grant/source/payload ceilings; application authority preserves trusted internal work. `coalesceDecision(rawRow, authority)` is the one coalesce rule for all five `MinionQueue.add` coalesce paths (idempotency fast path, param coalescing, pending and waiting caps, insert race); rows are read with `LEGACY_AUTHORITY_COLUMN` so only SQL NULL authority gets the legacy rule (dead/cancelled keys released by a CAS update, completed/failed coalesce for application callers only, live rows refused with the `legacy_job_authority` catalogue error); `UNREVIEWED_LIVE_JOBS_WHERE` is the claim gate's predicate, shared with doctor `legacy_job_authority`. Tests: `test/minions-legacy-coalesce.test.ts` (PGLite) and `test/e2e/minions-legacy-coalesce-postgres.test.ts`, both over `test/helpers/legacy-coalesce-matrix.ts`. `src/core/minions/authorize-legacy.ts` provides explicit local preview and transactional snapshot comparison for selected historical rows: `--ids`, or `--select <filter>` whose preview saves the exact id set under a hash of the filter and the snapshot digest with `saveApprovedSet` (preview-approval helper) so `--expect <hash> --yes` authorizes exactly that set; every refusal is a catalogue error (`legacy_job_selection_invalid`, `legacy_jobs_active`, `preview_changed`). `src/core/minions/source-filesystem.ts` provides reentrant canonical root/worktree locking and descriptor-based confined reads/writes. Both worker modes enforce the same authority gate. Upgrade protocol: `docs/guides/authorization-upgrade.md`.
- `src/core/minions/supervisor-pid.ts` — `readSupervisorPid(pidFile) → {pid, running}`: the shared `existsSync → readFileSync → parseInt → process.kill(pid,0)` PID-file + liveness reader shared by `jobs.ts` (supervisor status), `jobs.ts` (stats), and `doctor.ts`. EPERM from the liveness probe counts as running. Pinned by `test/supervisor-pid.test.ts`.
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.md
index f23c85c0b1..4c541e33f9 100644
--- a/docs/architecture/key-files/core-persistence.md
+++ b/docs/architecture/key-files/core-persistence.md
@@ -13,8 +13,12 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/onboarding.ts` + `legacy-locks.ts` + `physical-root-recovery.ts` — read-only source onboarding states; exact same-host dead-lock cleanup under explicit activation opt-in; and state-bound same-owner root repair using a durable manifest and token-verified temporary stamp. `physical-root.ts` `restampPhysicalRoot` handles a filesystem device id that changed while the owner token, brain, worktree, root, inode and a non-zero birth time still match (macOS can renumber `st_dev` across reboots): under the caller's outside-root native lock, one transaction verifies owner host, brain and host binding and rewrites the recorded self-transfer copies and retained topology staging identities (each only while it still names the old device); after commit the stamp and the reservation's initial device are rewritten and the event is logged, so an interruption between the two leaves a device-only change the next locked acquisition finishes. Ownership markers inside a retained topology clone stage are not re-stamped; an interrupted clone recovery that spans a device renumbering still needs source recovery. `assertPhysicalRoot` stays read-only; zero birth time or any other difference keeps the refusal. `--self-transfer` prepare/accept requires separate fresh reviewed state, preserves original reservation owner evidence and refuses uncertain records. Tests: `test/persistence-onboarding.test.ts`, `test/persistence-admin-recovery.test.ts`, `test/persistence-container-preflight.test.ts`.
-- `src/core/persistence/{atom-maintenance,atom-retry,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation. Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.
-- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links) `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
+- `src/core/persistence/{atom-maintenance,atom-retry,page-prepare,facts-maintenance,facts-prepare,prepared-maintenance}.ts` — resident dispatch for durable atom publication/completion, explicit atom retry, authorized multi-entity fact-fence/backstop append and local synthesize/patterns/consolidation.
+ Atom completion admits replacement and revision-pinned stale-atom deletion children together.
+ Each retirement stamps `retired_by`/`retired_at` into the tombstone in the same publication; `publishManagedAtoms` restores a retired atom of the same origin when an extraction produces it again, and a user-deleted atom stays deleted. Each committed retirement bumps the origin page's regeneration generation (`op_checkpoints` op `managed-atoms-generation`, part of the drain's run key only above 0, never of the explicit retry identity; the content whose extraction retired keeps the generation its accepted batch used, so that batch stays resumable) and clears that page's older `extract_atoms_page_state` rows and completed `managed-atoms` checkpoints in the same publication, so an A→B→A edit, even after a partly failed batch, re-extracts instead of replaying a retained receipt. Retirements are admitted in slug order.
+ Derived atom pages may regenerate or retire when their canonical file is already absent, while ordinary page writes retain missing-file refusal.
+ Accepted output replays provider-free after restart; page/take preparers recheck original/current grants, source incarnation and revisions. Unresolved facts remain DB-only without phantom pages. Retired takes skip; semantic fact snapshots exclude derived vector/cache fields and journal quotas reject overlarge retained intent. Managed consolidation retains the explicit chronological `valid_until` writeback from the legacy consolidation phase, scoped to the accepted source/fact IDs and revalidated semantic snapshots; contradiction probes never gain supersession authority. `submitMaintenanceIntent` admits a maintenance request with its own intent kind keyed by the intent; `prepareMaintenanceMutation` also handles `managed_maintenance_phantom_merge` and `managed_maintenance_phantom_delete` (both delegated to `cycle/phantom-redirect-managed.ts`). `publishMaintenancePage` accepts an optional `eventProjection` (Life Chronicle): the event page and its depth-page timeline row commit in the same publication with the depth page key locked. Remote maintenance remains refused.
+- `src/core/persistence/derived-facts.ts` — database-only fact rows derived from page text (fence reconcile, conversation facts): `managedDerivedFactsPreflight` (managed check, accepting persistence, local writer, active source; before provider spend), `withDerivedFactsWrite` (one transaction holding the coordinator source capability and the page keys, like derived links), `writeDerivedFacts` (that on a managed brain, the caller's own engine call otherwise) and `replaceDerivedFactsForPage` (inside that transaction: the caller's current-page recheck, then the page's prior rows for one writer prefix are deleted and the replacement batch inserted, so a failed or raced extraction keeps the prior batch; `test/managed-facts-writers.test.ts`). No persistence request is admitted per row. Tests: `test/managed-extract-atoms.test.ts`, `test/managed-facts-backstop.test.ts`, `test/managed-maintenance.test.ts`.
- `src/core/persistence/canonical-projections.ts` — installs the facts, takes and timeline projections of a canonical page body inside its publication transaction. Rows written by the conversation fact extractor (`cli:extract-conversation-facts*`) share the page coordinate without a fence and are never expired as rows that left it (#1928 parity with the extract_facts reconcile), so republishing a conversation keeps its extracted facts until their own replay replaces them. Preparation takes the caller's prior snapshot and writer class and pins the stored timeline rows and take row numbers. Writer classes: `editing` (revision-bound `put_page`, reconcile with an approved body decision), `preserving` (`put_page` without a revision, reconcile, connectors), `file` (managed sync of file edits and managed import) and `immutable` (company-brain imports). One pure decision table (`timelineRowAction`) maps each row state (`in_body`, `drifted`, `removed`, `removed_marked`, `database_only`) to `refresh_detail`, `delete`, `keep` or `materialize`: database-only rows are materialized by `editing` and `preserving` writers and kept by the others; a materialized bullet the new body drops is deleted by `editing`/`file`, rendered again by `preserving` and kept DB-side by `immutable`. `materializeTimeline` runs during preparation, before the body is imported, digested and rendered, and appends each round-trippable row after existing bullets in date-then-id order as a marked bullet (`timeline-marker.ts`); `renderMaterializedBullet` requires render-then-extract to return exactly the tuple and normalized detail, so backlink receipts, empty or delimiter-bearing sources are kept and never rendered. `pendingTimelineRows` counts materializable and kept rows for the repair and doctor. Deletes and detail refreshes match the pinned id, tuple and detail, so rows changed after preparation are untouched. A new fence row whose number belongs to a database-only take refuses with `take_row_collision`. `compileCanonicalProjections` is the validation-only entry. `unrecordedCanonicalTimeline` returns the body's canonical tuples with no stored row under the normalized key (managed `extract --stale` inserts only these), and `materializedHistoryRanges` locates marker lines whose hash matches the bullet after it, plus that bullet's indented detail (the dream verifier's history exemption). Tests: `test/canonical-projection-history.test.ts`, `test/timeline-materialize.test.ts` (PGLite and Postgres).
@@ -33,7 +37,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/accepted-pending.ts` — `acceptedPendingReceipt(error)`: the shared test for an accepted, not yet committed write, used by managed atom publication, extract_atoms, managed import and the connector budget.
- `src/core/persistence/connector-checkpoint-migration.ts` — migration 176 and orphan cleanup. The newest committed checkpoint receipt per source incarnation (found by slug, so a compacted one is still seen and re-walks) is copied to the stable key with `INSERT … ON CONFLICT DO NOTHING`; state rows are seeded; the cutoff is stored in `op_checkpoints` (`op=managed-connector-migration`, fingerprint `v2-cutoff`, excluded from the checkpoint purge). `orphanConnectorCheckpoints` keeps rows touched after the start, rows any registered source (archived included) can load, and rows referenced by a non-terminal request or a pending set; timestamps bind as text. `gbrain repair connector-checkpoints` (`src/core/repair/connector-checkpoints.ts`) and the `connector_checkpoints` doctor check reuse it with a 7-day floor. `connector-reset.ts` guards `gbrain sync --reset-checkpoint` to connector sources.
-- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
+- `src/core/persistence/consumer.ts` — resident canonical-write consumer with retained wake-ups, root-scoped retry backoff and locked-row-skipping expired-claim sweeps. A full tick fans out to every worker; when idle, each tick instead runs one work probe (a single statement mirroring the claim, recovery, expired-claim, effect, projection and topology predicates, excluding rows those workers would skip, including topology recoveries that failed to finish within the last 30 s) and the poll interval doubles from 250 ms to a 5 s cap (`idleMaxMs`), resetting on work. `wake()` runs a full tick immediately; `waitForWrite` calls it after a same-process admission commits, so cross-process writes wait at most 5 s plus one probe and no LISTEN is used. A probe failure is reported once and the next tick runs the full fan-out. On Postgres pools of three or more with no connection checked out, idle probes share one reserved connection (acquired and queried under the phase deadline; a timed-out lane returns to the pool once its query settles) so the rest of the pool drains through the 20 s `idle_timeout` (postgres.js reuses idle connections first-in-first-out); root refresh and receipt compaction run every 5 minutes while idle. Root refresh, recovery scan, sweep and capacity-marking SQL use cooperative five-second cancellation; failure never admits work under stale confinement. Cold direct initialization and queued transactions remain observed and awaited through shutdown. Recognized cancellation owned by the consumer's stop reason is not reported as a storage failure; deadline-first cancellation and unrelated storage errors remain visible. Ordinary put-page/remember preparation has a cooperative 30-second deadline; abort-ignoring work remains tracked, and late preparation cannot publish. Publication and shutdown retain the token/native-lock/recovery barriers. Trusted status exposes sampled process-local phases and attempts, not durable progress. A tick woken by a completed publication or a local admission claims the next write at once and runs root refresh plus recovery, expiry and topology scans at most once per poll interval; explicit, timer and idle-probe ticks always scan. Effects drain in batches of 20 without waiting for the next tick while full batches keep arriving; within a batch, git effects wait for their asynchronous durability probe (one per worktree root) after the other effects, and a single-file git effect in a repository without the durability hook acquires the worktree lock only to prove its root and records its outcome after releasing it. Each projection-worker invocation (`runResidentProjectionInvocation`, #5401) rebuilds up to 100 pages and starts no new page once 250 ms have passed since it began; when `hasClaimableWrite` (the `CLAIMABLE_WRITE_SQL` predicate `claimNextWrite` claims with, in `journal.ts`) finds a claimable write at its start it takes 2 pages, and its selector skips failed rows for 30 s through the same `PROJECTION_RETRY_READY_SQL` fragment as the idle probe (measured PGLite rebuild cost on a 1,000-page fixture: mean ~9.5 ms, p99 ~18 ms per page). On PGLite, which has no autovacuum, the maintenance worker also runs `vacuumPersistenceQueues` (VACUUM ANALYZE of the queue tables) every minute or after 50 + 20% of the request table's rows in publications. Tests: `persistence-consumer-scheduling.test.ts`, `persistence-consumer-idle.test.ts`, `projection-drain.test.ts` (injected clock and per-page cost), `persistence-root-refresh.test.ts`, `test/e2e/persistence-phase-liveness.test.ts`, `test/e2e/persistence-idle-pool.test.ts`.
- `src/core/persistence/health.ts` — pure advisory age/reason/action policy shared by receipts and trusted diagnostics. The nested public contract is optional, validated and explicitly allowlisted; thresholds are 30/120 seconds and polls 1/5/30 seconds. The journal batches at most 100 authorized receipts into one projected root query with a 500ms caller budget, retaining one in-flight query per engine until settlement. Database-only pending lookups use a partial source-incarnation/sequence index shared by both engines. Synchronous service reads coalesce only for the same request ID, retain at most four unresolved reads per engine until settlement, and permit cancellation only by the read's initiating waiter or shutdown. No health observation changes authority or durable state. Real authenticated legacy/OAuth recovery and the synthetic three-client import live in `test/e2e/persistence-http-liveness.test.ts`.
@@ -47,11 +51,11 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/params.ts` — runtime-leaf mutation parameter and receipt schemas shared with the frozen verb registry. Its operation-contract import is type-only; runtime validators live in separate modules to avoid a registry initialization cycle. `preconditions.ts` validates UUID/revision/force syntax. `purge-params.ts` validates local-only purge shape/trust before admission and publication, keeping purge diagnostics out of generic precondition imports and unrelated command flag scans. `test/persistence-cold-import.test.ts` loads each validator/contract/registry entry in a fresh process and preserves schema and typed-error identity.
-- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
+- `src/core/persistence/{effect-schema,effect-model,effect-journal,effect-recovery,effect-git,effects}.ts` — bounded postcommit outbox (migration 155). Canonical publication atomically queues Git and embedding work; withdrawals queue three versioned, bounded exact-page manifests with durable slug cursors. `effect-targets.ts` converts legacy source scans with complete bounded discovery keyed on the request's own forgotten fact (falling back to the whole source ledger only when that fact row is gone) while retaining each cursor; ambiguous or over-capacity legacy intent stays pending. Older workers must be quiesced before rollout. Independent mirror recovery reserves capacity before file effects, finishes forward without changing revision or receipt, and blocks only its worktree until reconciled. Git holds the native root lock, disables hooks, uses literal pathspecs and target-only commits, and pushes without pull/rebase. A claimed single-file Git effect brings up to 99 more ready single-file Git effects of its worktree (`claimCoalescedGitEffects`, same readiness, recovery and withdrawal-mirror ordering predicates, `SKIP LOCKED`); the runner validates each path under the worktree lock, makes one `commit --only` per group (`commitGitTargets`: one `ls-files`, `status`, `add` and `diff` for the group; untracked absent or ignored targets take the per-target refusal path) and pushes each root once at the end of the pass (`pushGitRoot`). A group shorter than 100 yields to publications still queued or running for its worktree (`retryEffect` with `publication_pending`, 250 ms apart) for at most 20 claims, so a serial producer publishes ahead and its Git work lands as one group; the v0.13.1 grandfather step admits a 50-page window (`admitCanonicalGrandfather`) before waiting for it. A path failure fails only its effect; a push failure leaves the group queued with `git_push_unavailable`, and the next pass finds nothing to commit and pushes once (#5530; tests: `persistence-git-coalescing-5530.slow.test.ts` + Postgres wrapper). A Git effect for a declared db_only page completes as skipped (`reason: db_only`), keeping its gitignored cache file out of Git. A Git or withdrawal target parks after five consecutive execution failures (`data.target_failures` for `data.failing_target`, reset when the target advances or a different target fails; shutdown cancellation, contention, dependency waits (including recovery-capacity waits) and transient database failures do not count): a scan records it in `data.parked` and moves on, a single-target effect or a failure outside any target parks the whole effect, and an effect with parked targets finishes as `failed`/`targets_parked`, never committed. A mirror or Git scan never parks on a sync-skip metafile page (`RESOLVER.md` carries the managed durability block by design) or on a file whose bytes hold an uncoordinated local edit (`file_database_drift`): the mirror materializes the withdrawal in the database without touching the file, both scans record the page in `data.skipped` (at most 100) and advance, so the request's Git and embedding effects are no longer gated behind a parked mirror (#5396). Migration 170 indexes parked effects for the `parked_effects` doctor check. `retryParkedEffects` (the `retry-effects` admin path) previews parked targets or authorizes one more attempt per target (`data.retry_slugs`, visited before the cursor); tests: `persistence-effect-parking.test.ts`. Old targets resolve under the same hash/confinement checks without changing frozen data; ambiguous absent spellings refuse after scoped staged/unstaged deletion checks. Embedding runs outside transactions/OS locks and installs with projection CAS. Receipt helpers return only public effect state/reason/push. Consumer shutdown aborts providers and awaits workers; receipt compaction is bounded. Tests: `persistence-effects.test.ts`, `persistence-git-publication.test.ts`, `persistence-publication-native.serial.test.ts`. Embedding completion checks active column/vector, embedded stamp, text hash, model and page signature; partial work sends only stale chunks and preserves valid siblings. A partial synopsis rebuild completes before title demotion. Provider timeouts use the gateway budget, five durable page claims/backoff, execution-token CAS after provider work and atomic vector/stamp/effect completion. Keyless work skips cleanly. `retry-effects` is an explicit one-shot failed-effect allowance; current vectors reconcile provider-free without changing canonical receipts. A git refusal on an index lock (git's own message names the lock, so linked worktrees resolve) is `git_index_locked` contention (retried, not counted toward parking) while the lock is younger than 10 minutes, and `git_index_stale` (counted, naming the lock) when older or future-dated; the lock is never removed, because no timestamp proves its holder is gone.
-- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.
+- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct. #5032: `isWindowsColonTarget(rel)` and `colonSlugWindowsRefusal(slug, sourceId)` name the one Windows-only refusal (`colon_slug_windows_write_through`: `:` names an NTFS alternate data stream); `submitPageMutation` raises it before admission when this host publishes the file, `prepareFileTarget` at publication, and managed (`fileRefusals`) and unmanaged (`failedFiles`) sync skip each such path by name (`test/colon-slug-windows-5032.test.ts`).
-- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.
+- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.serial.test.ts`. A credential-free, read-only `projection_status` request (like `capabilities`) returns the resident's projection backlog counts (`PersistenceProjectionStatus`, no identifiers) so doctor's `text_projection_readiness` can report it while the resident holds a PGLite datastore (#5401, `test/projection-resident-doctor.test.ts`).
- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`.
@@ -59,7 +63,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](
- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.
-- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.
+- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres.
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/manual-links.ts` — `coordinatedManualLinkWrite` makes `add_link` / `remove_link` coordinated database-only writes on a managed brain: it checks the caller's durable write authority for the `from` page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits the edge inside `withCoordinatedWrite` holding both endpoint page keys. Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`.
diff --git a/docs/architecture/key-files/core-services-1.md b/docs/architecture/key-files/core-services-1.md
index 0c84c7c7d9..72aacbea87 100644
--- a/docs/architecture/key-files/core-services-1.md
+++ b/docs/architecture/key-files/core-services-1.md
@@ -41,6 +41,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/connectors/` (directory) — the LIVE chat-history connector layer (front-end to the transcripts pipeline). `types.ts`: the `ChatHistoryProvider` contract (mirror of `TranscriptAdapter` — leaf module per provider; `spoolFormat` names the adapter that parses its output; dated `HostSpecTarget`). `credentials.ts`: file-plane store at `~/.gbrain/connectors/<provider>.json` (0600, dir 0700, atomic tmp+rename), env-above-file `resolveCredential` returning `{cred, source}`; credentials NEVER touch the DB / `sources.config` / config planes / op payloads. `classify.ts`: the pure §2A/§2B response classifier — distinguishes a Cloudflare-fingerprint 403 (`forbidden_fingerprint`, dead-end) from an auth-expired 403 (`auth_required`, re-auth) and flags a parses-but-no-`items` body as `drift`. `client.ts`: `ConnectorClient` modeled on `GitHubClient` (plain fetch against a hardcoded ORIGIN + off-origin guard so the cookie/bearer never leaks, browser UA, refresh-once-on-401, Retry-After backoff; `fetchImpl`/`sleep`/`now` injectable — NOT `fetchWithSSRFGuard`, which breaks SNI on Cloudflare hosts). `providers/chatgpt.ts` + `providers/claude.ts` (registry in `registry.ts`; Perplexity deliberately absent — no adapter): offset/updated pagination with a per-pass 500-page cap and a `stopBefore` watermark break, epoch/ISO normalization, ChatGPT's `is_archived` second pass, Claude's `chat_conversations` paged with `limit`/`offset` across every chat-capable org (conversations fetched from the org that listed them; timestamps normalized with ChatGPT's `toIso`), a ChatGPT walk that steps back when `total` shrinks mid-walk (a removal shifts later items to lower offsets) and yields each id once across both passes, content-block text assembly for Claude, and a `refreshAccessToken` (ChatGPT re-mints from the cookie via `/api/auth/session`; Claude's cookie is terminal). `spool.ts`: writes fetched conversations in native-export shape (0600, batched, pruned in the orchestrator `finally`). `sync.ts`: `runConnectorSync` — resolve credential → probe → read the **per-(provider, source) config-scalar watermark** `connectors.<p>.source.<id>.watermark_iso` (NOT op_checkpoint, whose 7-day GC would wipe it → full re-fetch) → list to `watermark − windowDays` → skip stubs whose `updatedAt` the source's `synced` ledger already holds and stubs quarantined in its `failed` ledger (after `QUARANTINE_ATTEMPTS` = 3 fetch OR ingest failures at one `updatedAt`; ingest outcomes are attributed per conversation by session id, a spool-file-level failure fails the batch; an edit or `--full` retries) BEFORE the `--limit` cap, so capped runs progress → fetch → spool → `runTranscriptsIngest` → record each successfully ingested conversation as synced → advance the watermark ONLY on a clean run (quarantined ids no longer block it; ledger entries older than the next list window are pruned) → `logIngest` receipt → stamp per-source `last_sync_at` → engine-branched embed kickoff (`maybeKickoffEmbed`: Postgres `submitEmbedBackfill`, PGLite `runEmbedCore` inline — NEVER `submitEmbedBackfill`, which refuses `no_worker_surface`). `config-keys.ts`: the `connectors.` key builders (sync progress keyed by `(provider, source)`; `auth_error_at` stays per provider because it describes the shared credential), `readConnectorState`/`writeConnectorState` (a legacy per-provider `watermark_iso`/`last_sync_at` is honored only for the scheduled `connectors.source_id` source until that source writes its own key, which retires it), and the pure `isConnectorSyncStale(last, now, floor)` dispatch gate. Status, doctor and the autopilot gate read the scheduled source's state. `oauth-pkce.ts`: dependency-free S256 PKCE loopback (`Bun.serve`, timing-safe state) — best-effort `--try-oauth` only. Surfaces: the `connectors_status`/`connector_sync` ops (`src/core/ops/connectors.ts`, both `localOnly`), the `gbrain connectors` command family (`src/commands/connectors/` peeled dir), the `connector-sync` minion handler (`src/core/minions/handlers/connector-sync.ts`, single-flight lock), the autopilot `maybeDispatchConnectorSyncs` gate, and the `connectors` doctor check. Pinned by `test/connectors-*.test.ts` + `test/e2e/connectors-sync-checkpoints-pglite.test.ts` (per-source watermark, `--limit` progress, quarantine, retitle) + `test/e2e/connectors-sync-pglite.test.ts` (full pipeline against a `Bun.serve` fixture backend, keyless) + `test/e2e/connector-sync-handler-pglite.test.ts` + `test/e2e/doctor-connectors-pglite.test.ts`.
-- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.
+- `src/core/context/` — Retrieval Reflex (Layer 1). `entity-salience.ts`: pure, zero-LLM, precision-biased `extractCandidates(text)` (capitalized runs + `@handles`, STOPWORDS + soft COMMON_WORDS + sentence-start guard, deterministic, capped; a lowercase weak pass additionally emits `weak: true` candidates — lowercase words ≥3 chars on a separate `MAX_WEAK_CANDIDATES=32` budget that never evicts strong candidates — which downstream may resolve through the alias arm ONLY) + `extractCandidatesFromWindow(turns)` (merges per-turn extraction across the last N turns by normalizeAlias form with occurrence/newest-turn/user-mention metadata; salience-ordered — recency > frequency > user-role — so the cap drops stale assistant chatter first). `retrieval-reflex.ts`: `resolveEntitiesToPointers(engine, sourceId, candidates, opts)` — alias arm (`resolveAliases`, caught per-arm for pre-v110 brains) + exact title/slug-suffix arm (real slugs are namespaced `people/x` but `slugify` drops the prefix) + two lexical identity arms behind `opts.lexicalArms` (kill switch: config `retrieval_reflex_lexical_arms` / env `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`, default on): weak lowercase candidates probe the ALIAS arm ONLY (never title/slug-suffix, where ordinary lowercase words would fabricate pointers) and require GLOBAL uniqueness across all sources in play; the surname arm resolves a strong single capitalized token ≥3 chars via a `lower(title) LIKE '% <token>'` predicate on the same query, with exact-arm precedence and ambiguity counted over ALL person rows carrying the surname — ambiguity in either arm injects nothing; pointers carry `source_id`/`arm`/`confidence`/`matchedNorm` (`ARM_CONFIDENCE` alias 0.9 / title 0.8 / title-surname 0.72 (deliberately above the volunteer layer's 0.70 gate, below title) / slug-suffix 0.6 lives next to the arm definitions; arm-2 provenance classified in JS since the combined OR can't report which predicate matched); opts: `sourceIds?` federated scope (alias arm loops per source, arm 2 uses `source_id = ANY`), `suppression?` ('slug-and-title' default; 'slug-only' REQUIRED under windowing — the title rule would suppress every entity merely mentioned in a prior window turn), ambient-channel event logging is DELIVERY-side, not in-resolver — `logDeliveredReflexPointers(engine, pointers)` fires only once a block is actually handed to the consumer (serve's resolve-IPC `onDelivered` hook post-write; `buildReflexAddition` post-timeout on the direct rung), so abandoned/timed-out blocks never pollute the volunteered-vs-used stats; its event write is registered synchronously before return so the CLI background-work drain cannot miss it; synopsis runs through `stripTakesFence`/`stripFactsFence` (the same privacy boundary `get_page` applies) so private facts never reach the prompt; `visibility: private` (and derived-private) pages never resolve on any arm unless the caller passes `excludePrivate: false` (default true, the remote-search predicate `privatePagesFilterFragment`; only `volunteer_context` widens, via `resolveExcludePrivatePages` for a trusted local caller — gbrain-evals N8-1/N8-2, pinned by `test/reflex-private-visibility.test.ts`); capped at `MAX_POINTERS`. `reflex.ts`: the orchestrator + engine-aware resolver ladder (host `resolveEntities` → PGLite serve IPC → Postgres cached process-singleton → disabled), zero-candidate fast path, fail-open + timeout, heartbeat write for the doctor check, `reflexEnabled(cfg)` (file/env gate, default ON; DB-plane does NOT gate — `assemble()` is sync); windowed extraction when `windowTurns` present and `retrieval_reflex_window_turns` (default 4; 1 = single-turn behavior) > 1 — switches suppression to slug-only; accept-side reflex-channel logging fires after the per-turn timeout admits the block (direct-Postgres rung only — IPC logs server-side at delivery; host-injected resolvers are a documented gap). `resolve-ipc.ts`: local unix-socket resolve protocol (client + server) so PGLite resolves through the single connection `gbrain serve` holds (a second opener would hit the exclusive lock; a subprocess would force-steal it past the 5-min staleness window and crash). Wired into both serve transports via `src/mcp/resolve-ipc-binding.ts` (engine-uniform; socket + secret keyed off `hash12(database_url)` under `~/.gbrain/run`, cleaned up on shutdown). Doctor surface: `retrieval_reflex_health` in `src/commands/doctor/checks/verbs-reflex.ts` (reads the heartbeat for truthful runtime status; categorized in `doctor-categories.ts`) + `volunteer_channels` (engine-aware sibling: groups `context_volunteer_events` by channel over 7 days so operators see which push channels — reflex/op/watch/claude-code/codex — actually fire; info-only; the LOCAL doctor runs it brain-wide while the remote report path threads the caller's source scope, so a source-bound token never sees other sources' activity counts/timestamps; counts are reconciled against the hook heartbeat over the same 7-day window — a mostly-degraded week gets a CAUTION note, since a server-side delivery count isn't proof of injection; quiet-channel guidance is engine-aware — Postgres brains are told the hook lane is quiet by design rather than to chase registration — and walks both quiet classes (installed-but-unregistered vs registered-but-quiet; the check can't inspect registration itself); pre-v117 tolerant, and transient DB errors are reported as such, never as an old schema; pinned by `test/doctor-volunteer-channels.test.ts`). Config: `retrieval_reflex` + `retrieval_reflex_max_pointers` + `retrieval_reflex_window_turns` + `retrieval_reflex_lexical_arms` in `src/core/config.ts` (env `GBRAIN_RETRIEVAL_REFLEX_WINDOW_TURNS`, `GBRAIN_RETRIEVAL_REFLEX_LEXICAL_ARMS`). `volunteer.ts`: `parseWindow` (lenient `user:`/`assistant:` prefixes, unprefixed → one user turn), `volunteerContext` (extract → resolve → +0.05 multi-turn/newest-turn boost → `min_confidence` 0.7 gate → cap 3/5; deterministic rationale strings, never raw conversation text; slug-only suppression), `volunteerUsageStats` (per-arm/channel precision from the `pages.last_retrieved_at > volunteered_at` join — APPROXIMATE: the 5-min last-retrieved throttle causes false negatives, unrelated reads false positives). `volunteer-events.ts`: `insertVolunteerEvents` (ONE multi-row parameterized INSERT), `logVolunteerEventsFireAndForget` + bounded drain registered as the `volunteer-events` background-work sink (order 4), `purgeStaleVolunteerEvents` (90-day GC, called from the dream cycle's purge phase). Policy layer ships as the `retrieval-reflex` recipe (`recipes/retrieval-reflex/`). Pinned by `test/context/entity-salience.test.ts`, `test/retrieval-reflex.test.ts`, `test/retrieval-reflex-pre-v110.test.ts`, `test/context/resolve-ipc.test.ts`, `test/doctor-retrieval-reflex.test.ts`, `test/volunteer-context.test.ts`, `test/e2e/volunteer-context-postgres.test.ts`. Checkpoint-compaction modules in this dir: `corpus-segments.ts` — engine-free content-addressed compaction segments (`<session>.seg-<hash24>.txt`, idempotent by name; parsers accept 12–64 hex), the hash-keyed per-session ledger (atomic tmp+rename, fail-open, entry order = the only ordinal), `sliceBoundaryWindow`/`splitByBoundaries`, the redacted `renderSegmentText` (a segment is NEVER written unscanned — unlike the session-end full write, which degrades-and-writes), exact-set `coverageComplete`/`decideCorpusMode` (count equality can be fooled by a duplicated boundary), the compact-time `bankCompactSegment` step (per-step deadline degrades, segment-then-ledger crash order), the openclaw tail boundary reader (`readOpenclawBoundaryTail`, delegates mapping to the adapter's exported `mapOpenclawLine`; also returns turn-stamped `toolCalls`/`toolCallTurnIndexes` for the Memorable receipt — name-only v1, `input: null` by design until an observation run characterizes OpenClaw's args field), and orphan-sidecar/aged-ledger GC — pinned by `test/corpus-segments.test.ts`. `checkpoint-harvest.ts` — the serve-side prompt harvest of a segment: bounded FIFO (cap 8, 60s abort), sweep-shared claim fencing, capability-then-kill-switch gates, `signal.aborted` POST-check (the pipeline returns partials on abort; an aborted run writes nothing and stays retryable), receipt sidecar before idempotent manifest publish (source-scoped `getPage` verification — a link that resolves to nothing is never banked), `.ingested` last, explicit `shutdownCheckpointHarvest()` called by serve BEFORE `engine.disconnect()` (the background-work drain is CLI-exit-only by contract) — pinned by `test/checkpoint-harvest.serial.test.ts`. `hook-heartbeat.ts` — the hooks telemetry JSONL extracted from hook.ts (hook.ts re-exports; serve-side writers never import the command module); allowlist carries the checkpoint `segment`/`inserted`/`duplicate`/`links` count-only fields. `session-state.ts` also carries the v132 `checkpoint_manifest` helpers (`getCheckpointManifest`/`appendCheckpointManifest`: newest-first, dedup-by-slug, cap 20, seg-hash completion key, fail-open on pre-v132 schema) — pinned by `test/checkpoint-manifest.test.ts`. `sensitivity-scan.ts` + `compile-view.ts` — the compile-context stack: composed detector (secret-scan + ordered `PII_PATTERNS` + path/blocklist families + operator pattern file; uniform `.gbrain-scan-allow` fingerprint escape hatch; CONTENT hits drop an entry, CONFIG/loader failures THROW so the caller aborts without writing) and the deterministic compiled-view builder (recency decay anchored to the newest candidate `updated_at`, never wall-clock; total-order (score desc, slug asc); source-scoped listPages/getPage reads that skip op-layer write-backs and pass `excludePrivate: true` on every arm, so private pages never reach the compiled file; whole-file `packToBudget` math that never passes a <=0 budget) — pinned by `test/sensitivity-scan.test.ts` + `test/compile-view.test.ts` + `test/e2e/compile-context-pglite.test.ts`; the CLI shell is `src/commands/compile-context.ts` (targets claude-code|codex|openclaw, AGENTS.md managed-marker splice that throws on damaged markers, atomic writes, `--check` recompile-and-compare exit codes; the guide is `docs/guides/checkpoint-compaction.md`). It also owns the whole Memorable seam's engine-free plumbing: the session-receipt JSONL (`session-receipts.jsonl`, `appendSessionReceipt` — dedup by post-redaction `content_hash` so a resumed session neither duplicates its receipt nor re-fires the relay; tail-rewrite compaction triggered by the 32 MB byte ceiling alone — the read fires exactly when the pass will act, with the 2000-line budget enforced inside the pass — and a `skipCompaction` seam the openclaw compact() lane sets unconditionally: the hook lane is the ONE receipts compactor, so two processes can never race the read-filter-rename rewrite); ONE bounded adaptive `readJsonlTail` reader shared by `lastReceiptMatches`, `lastRelayResult` and `readSessionReceiptsTail` (a receipt line can exceed the 1 MB window — the window doubles rather than reading "empty"); `maybeTrimRelayResults` (BOTH capture lanes trim the child-appended `memorable-relay.jsonl` — an openclaw-only host has no hook lane, and converging newest-keeping trims make concurrent trims safe: mtime-stale preferred, hard 8 MB force backstop, line-boundary cut keeping the newest lines — the child appends open-by-path, so the residual loss window is one in-flight write); the CONSENT STAMP (`memorable-consent.json`, 0600, written ONLY by config-set's disclosure flow — deliberately outside config.json, which the external CLI full-file-rewrites; scope-bound to the disclosure sha256 + `MEMORABLE_CAPTURE_HARNESSES`, so widening the capture surface invalidates old stamps); `memorableGateAllowed(cfg)` ({allowed, reason: kill_switch|disabled|disclosure_missing} — one reason vocabulary for hook, context-engine and doctor); `memorableConsentEvidence()` (the CLI-side opt-in read fail-closed from ~/.memorable/config.json, dated provisional spec note, GBRAIN_MEMORABLE_CONFIG test seam); `redactedToolCallsJson` (the security-load-bearing span-filter + highEntropy redaction, ONE implementation for both capture lanes; string LEAVES are redacted raw before serialization — scanning the serialized JSON would let quoted secrets through via \" escaping — with a post-serialization re-scan as belt-and-braces); `recordAndRelayReceipt` (per-receipt harness scope-binding first — a harness outside `MEMORABLE_CAPTURE_HARNESSES` is refused with `memorable_harness_undisclosed` → receipt → prior-run outcome surfacing with the child's reason clamped via the shared `clampRelayCause` (32 chars, so the 16-char prefix keeps composites inside the 48-char reason bound) and appended LAST → consent evidence → `resolveMemorableBin` → detached spawn; never throws; `spawnFn` test seam); and `priorRelayFailure`, which surfaces the PREVIOUS relay run's self-reported exit status so a relay that records nothing is never reported healthy. `resolveMemorableBin` does the pre-spawn PATH/`MEMORABLE_BIN` resolution so a missing CLI is a named heartbeat reason rather than a silent async ENOENT.
- `src/core/context/ipc-path.ts` — engine-free local socket discovery and private Unix fallback when the complete role-specific address exceeds 103 UTF8 bytes. Hashes the physical parent plus basename under a fixed OS temporary root, verifies ownership/0700 directory/0600 client socket without following fallback symlinks, and retains a native binding claim through actual server close. Existing Unix socket accessibility is rechecked even when a runtime reports ENOENT; permission/resource probe failures never authorize stale takeover; Windows named pipes retain a native Global mutex through actual close; `windows-ipc.ts` normalizes namespace prefixes while native Windows Unicode casing defines the mutex identity. `test/local-ipc-path.test.ts` covers concurrent real processes, SIGKILL recovery, active-connection shutdown, aliases and unsafe paths. The published CLI smoke also uses a long Unicode datastore path.
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 6e91b02c4c..3742d48f65 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -17,14 +17,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`.
-- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.
-- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
+- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.
+- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_versions` filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read).
-- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`.
+- `src/core/ops/context.ts` (source-id confinement helpers) — `assertSourceInCallerScope(ctx, id)` is the READ-scope confinement for an explicitly named source id (`sources_status`): untrusted callers may only name an id inside the `sourceScopeOpts` ladder. `assertSourceInCallerWriteScope(ctx, id)` is its WRITE-authority twin for destructive source ops (`sources_remove`): federation (`ctx.auth.allowedSources`) is read authority and confers no removal right, so a bound untrusted caller (write source `ctx.auth.sourceId ?? ctx.sourceId`, and/or any federated grant) may name only its own write source; a bound caller with no write source (or the `__all__` sentinel) may name nothing; an unbound untrusted caller keeps full authority; trusted local passes. Both answer `OperationError('not_found', 'Unknown source: <id>')`. `resolveRequestedScope(ctx, sourceId, allSources, explicitReads?)` takes an optional explicit-read admission set (#5081) that only `federatedSearchScope` passes: a granted token admits nothing extra, a stdio connection bound by `GBRAIN_SOURCE`/`.gbrain-source` admits `ctx.explicitReadBinding.sourceIds`, and an unbound connection admits its own `localFederatedSourceIds`; its denial hint names why (token grant, binding, opted-out source) with `docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection`. Image, loops and code-intel pass nothing and keep the original denial (`test/explicit-read-admission-5081.test.ts`, `test/serve-stdio-bound-explicit-read.test.ts`).
- `src/core/ops/insights.ts` — stored contradiction reports load only for explicitly trusted, unscoped local callers. Other callers receive the fixed availability note and an empty contradictions list before any report storage access. Expert search threads page and holder policy and performs final authorized-page admission after enrichment.
@@ -42,7 +42,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; callers lock sources before authority/request/fact rows. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.
-- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics.
+- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply.
Embedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index 49f13ab076..9598536295 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -30,6 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.
- `src/core/errors.ts` — `StructuredAgentError` + `buildError` + `serializeError`. Every agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches the `CycleReport.PhaseResult.error` shape.
+- `src/core/error-catalogue.ts` — fix wave 5 refusal catalogue (DX-O2): `ERROR_CATALOGUE` maps each refusal name to its stable wire code and its `docs/guides/repair.md` or `write-refusals.md` anchor; `catalogueError` builds the `OperationError` (hint as `suggestion`, anchor as `docs`), `catalogueStructuredError` the `StructuredError` envelope (`hint`, `docs_url`). `test/error-catalogue.test.ts` resolves every anchor against the guides' headings and `<a id>` tags.
- `src/core/eval-capture-scrub.ts` — zero-deps PII scrubber: emails, phones, SSN, Luhn-verified credit cards, JWT-shaped tokens, bearer tokens.
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.md
index 7e83226594..9a27ccc6c4 100644
--- a/docs/architecture/key-files/core-utilities-2.md
+++ b/docs/architecture/key-files/core-utilities-2.md
@@ -3,8 +3,10 @@
[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
-- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. `safeChunkUpgradeAdvisory` formats a pending-count line (the post-upgrade recovery banner reports `safe_index_pending` instead). `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.
+- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — and the doctor `checks` it clears), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use; a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Only explicit-only kinds accept `--expect <hash>` and `--include-ambiguous`, passed to `plan` as `RepairPlanOptions`; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`.
- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.
+- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.
+- `src/core/persistence/mirror-read-only.ts` and `src/commands/sources-mirror.ts` — #5409 read-only mirror sources. `sourceMirrorReadOnly(engine, sourceId)` reads `sources.config.mirror_read_only` (default false). When true, `prepareFileTarget` (`page-prepare.ts`) returns no file for any coordinated page write into the source (receipt `write_through.skipped: 'mirror_read_only'`, `storage: 'database_only'`, set in `coordinator.ts`), and managed sync (`sync-prepare.ts`) imports an overlay (canonical form differs from the file bytes) database-only: no `file`, no newer-working-tree refusal, and `contentUnchanged` ignores the overlay. A page created that way with no recorded file is stamped `pages.database_only_reason='mirror_read_only'` (`classifyMirrorPage`, in the publication) and stays database-only after the flag is cleared; the coordinator refuses (`source_changed`) a file target prepared before the flag was set (rechecked under the publication with the source row `FOR SHARE`); `gitPage` (`effects.ts`) completes a mirror source's Git effects as skipped. `gbrain sources mirror-readonly|mirror-writable <id>` set and clear the key like `federate`/`unfederate`; `sources list --json` reports `mirror_read_only`.
- `src/core/runtime-version.ts` — Bun 1.4.0 minimum (`MINIMUM_BUN_VERSION`; the lowest 1.4 release, carrying the Linux child-exit fix oven-sh/bun#30301). `unsupportedBunMessage` names the found and required versions and the fix (`bun upgrade`, restart, `gbrain post-upgrade` for an interrupted upgrade). `exitOnUnsupportedBun` is the CLI entrypoint gate: every command below the floor exits 1 before dispatch (`--version` still prints, exit 0, so an older gbrain's upgrade can verify the swap; `autopilot` also writes the refusal to stdout, its service log); `scripts/postinstall.ts` prints it when an install lands on an older Bun; the guarded HTTP transport asserts it; doctor reports it as `bun_runtime`. Package engines, runtime checks and the CI minimum-version lanes share the same floor (`test/scripts/ci-pr-scope.test.ts`).
diff --git a/docs/architecture/key-files/files-and-sync-1.md b/docs/architecture/key-files/files-and-sync-1.md
index 7a8fe494fd..09294273c3 100644
--- a/docs/architecture/key-files/files-and-sync-1.md
+++ b/docs/architecture/key-files/files-and-sync-1.md
@@ -43,7 +43,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/source-id.ts` — single canonical source_id validation, dependency-free by design (imported by both engines, cycle, source-resolver, sources-ops). `SOURCE_ID_RE` (strict: 1-32 lowercase alnum, interior hyphens only, no edge hyphens); `isValidSourceId` (boolean — for tiers that silently fall back: dotfile, brain_default) vs `assertValidSourceId` (throws — for tiers that must reject loudly: explicit `--source`, `GBRAIN_SOURCE`, `cycleLockIdFor`); `ALL_SOURCES = '__all__'` sentinel (deliberately NOT a valid id so it can never collide with a real source or leak into lock ids/path joins; `sourceScopeOpts` translates it to an unscoped read for trusted local callers and keeps it unsatisfiable for remote callers, fail-closed). `normalizeSourceInput`/`normalizeFederatedReadInput` normalize the `/admin/api/register-client` HTTP body, mirroring the CLI's `--source`/`--federated-read` flags: omitted `source` → `'default'`; omitted `federatedRead` → `undefined` so `registerClientManual` applies its own `[sourceId]` default; present-but-invalid values throw so the route returns a structured 400 (`invalid_source`) instead of failing at INSERT time. Pinned by `test/register-client-source-normalize.test.ts`.
-- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.
+- `src/core/source-resolver.ts` — 6-tier source resolution. `resolveSourceWithTier(engine, explicit, cwd)` returns `{ source_id, tier: SourceTier, detail? }` alongside `resolveSourceId()` (unchanged). `SOURCE_TIER_NAMES = ['flag', 'env', 'dotfile', 'local_path', 'sole_non_default', 'brain_default', 'seed_default']` (7 entries; order matches priority). Tier `sole_non_default` slots between `local_path` and `brain_default`: when NO `sources.default` config is set AND exactly one registered source has `local_path` AND isn't `'default'` AND the `'default'` source holds no active pages (the emptiness guard — the tier's charter is rescuing brains whose `'default'` is empty; when `'default'` carries an established corpus, auto-routing would hijack every bare write into the side-source, so the resolver falls through to `seed_default` and prints a one-line stderr notice naming both sides so the suppressed flip is diagnosable, same `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1` suppression knob as the routing nudge; a failed pages probe on an exotic/legacy schema keeps the auto-route), auto-route to it; archived sources excluded (try/catch for pre-v34 brains); private `pickSoleNonDefaultSource(engine)` shared by both resolver entry points so they cannot drift. Exported `formatSoleNonDefaultNudge(sourceId): string | null` builds the user-facing stderr nudge (null when `GBRAIN_NO_SOLE_NON_DEFAULT_NUDGE=1`). `resolveCliSyncSource` in `src/commands/sync/run.ts` calls `resolveSourceWithTier` unconditionally so the tier fires; `src/commands/import.ts:96-128` mirrors with the tier-gated nudge. Consumed by `gbrain sources current`, `import --source-id`, `extract --source-id`, and the `source_routing_health` doctor check. Pinned by `test/source-resolver-with-tier.test.ts` (`withEnv()` per test-isolation lint), `test/source-resolver-sole-non-default.test.ts` (20 cases incl. both-ways emptiness-guard + probe-failure fallback), `test/sync-sole-non-default-routing.test.ts` (3 PGLite cases driving real `runSync`), `test/pages-source-scoping-4329.test.ts` (real-engine both-ways guard coverage). Also exports `noGrantFederatedScope(engine, hasSourceGrant, sourceId)`, the widening decision transports share: returns `localFederatedSourceIds(..., 'seed_default')` ONLY when `hasSourceGrant === false` (the legacy-bearer no-grant floor), `undefined` for a granted token, for an OAuth client (flag `undefined` — a falsy gate here would widen every OAuth client), and when the resolver throws (best-effort; the scalar scope stands rather than failing the request). Called by `src/commands/serve-http.ts`; pinned by `test/no-grant-federated-scope.test.ts` (6 cases). `explicitReadBinding(engine, sourceId, tier)` (#5081) is the explicit-tier twin used by the stdio transport for `GBRAIN_SOURCE` (`env`) and `.gbrain-source` (`dotfile`) bindings: `{ sourceId, via, sourceIds, optedOut }`, where `sourceIds` is the same set `localFederatedSourceIds` computes (shared `federatedSetFor`, so an isolated anchor admits only itself) and `optedOut` lists `federated === false` sources for the denial hint; `undefined` for every other tier. Pinned by `test/explicit-read-admission-5081.test.ts`. Unscoped default-write guard family (the `seed_default` tier is the only one that actually lands a write in `'default'`): `assessDefaultWriteGuard(engine)` → `DefaultWriteAssessment { shouldGuard, defaultPages, nonDefaultPages, nonDefaultSources, failed? }` — an unindexed full-`pages` aggregate; `shouldGuard` when ≥1 non-default source holds pages AND non-default pages outnumber default's; a query failure returns the fail-open no-guard verdict stamped `failed: true`, which cachers/latchers must not treat as settled. `assessDefaultWriteGuardOnce(engine)` is the per-engine WeakMap memo (arms on the first SUCCESSFUL assessment whatever its verdict, forgets a failed attempt so the next caller retries, coalesces concurrent callers; `__resetDefaultWriteGuardMemo` is the test seam). `assessUnscopedDefaultWrite(engine, tier, mutating)` → `{ warning, assessed }` (`assessed: false` only when the aggregate failed); `formatDefaultWriteWarning(a, sourceFlag?)` / `formatDefaultWriteRefusal(cmd, a)` render the two surfaces; `defaultWriteAllowedByEnv()` is the `GBRAIN_ALLOW_DEFAULT_WRITE=1` escape hatch. Consumers: `sync` refuses (dry-run warns), `import` warns via the memo, MCP stdio's `createDefaultWriteAdvisory` prints once. Also exports `isResolverUserError(e)` — the ONE predicate for this module's user-facing throws (`Source "…" not found.` / `not found or is archived.`, `Invalid --source value`, `Invalid GBRAIN_SOURCE value`), consumed by dream.ts, agent.ts and code-scope.ts so a CLI command turns an unknown/archived source into a clean stderr line + exit 1 while anything else keeps propagating.
- `src/core/source-delete.ts` — `deleteSourceRow`: every unmanaged source delete (`sources remove`, `sources purge`, the `sources_remove` op, expired-archive purge) deletes the `sources` row and that incarnation's `persistence_source_bindings` row in one statement; bindings have no FK to `sources`. Bindings of other incarnations are left to `gbrain repair orphan-bindings` (`src/core/persistence/orphan-bindings.ts`, doctor `orphan_persistence_bindings`). The unmanaged claim check (`sync-authority.ts`) and doctor `unbound_source` count only a binding of the source's current incarnation.
- `src/core/sources-ops.ts` — Multi-source registration + clone-lifecycle ops (`addSource`, `recloneIfMissing`, `defaultCloneDir`, `isOwnedClone`, `unownedHint`). **Reclone-ownership invariant (must-never-violate): gbrain may only delete/re-clone a clone it created, NEVER a user working tree.** `recloneIfMissing` deletes `local_path`, so it gates on `isOwnedClone(src)` and throws a `SourceOpError('unmanaged_path', ...)` BEFORE any filesystem op when ownership is unprovable — fail-closed. Ownership is proven by `config.managed_clone === true` (written by `addSource`'s `--url` path, covering default-location and `--clone-dir` clones) OR `local_path === defaultCloneDir(id)` (back-compat for pre-marker clones, via exact normalized-path equality, symlink-free). A row with `remote_url` + an unowned `local_path` (a user-registered working tree, e.g. `sources add --path`) is refused untouched; re-add with `--url` to regain auto-reclone. The reclone is EXDEV-safe: clone into a SIBLING temp of `local_path` (not the shared `clones/.tmp`, which may sit on a different mount than a `--clone-dir` target), then swap (move old aside → move new in → drop old) so `local_path` is never left missing-and-unrecoverable; on swap failure the original is restored, and if restore fails the error names the `aside` path so it's never reflexively deleted. A TOCTOU re-check re-confirms ownership immediately before the destructive move and rejects a symlink leaf swapped in after the entry check (`symlink_escape`). `unownedHint(src, state)` is the shared recovery message used by both the core error and the `gbrain sync --source` CLI error; `gbrain sources restore` special-cases `unmanaged_path` to print "DB row restored; gbrain syncs this path read-only" instead of the misleading "try sync to recover" guidance. `SourceOpErrorCode` includes `unmanaged_path`. Pinned by `test/sources-ops.test.ts`, `test/sources-resync-recovery.test.ts`. `assertNoOverlappingPath(engine, id, path)` is the ONE overlapping-path guard shared by every surface that binds a `local_path` (`addSource`, `gbrain sources set-path`): a path equal to, nested inside, or enclosing another source's `local_path` throws `SourceOpError('overlapping_path')` — overlapping trees make sync/write-through attribute files to the wrong source, so no add or repair path may skip it. The guard compares by spelling AND by realpath (both the candidate and each sibling `local_path` are `realpathSync`'d when they exist, fail-open to the spelling otherwise), so a symlink resolving into or over another source's tree cannot slip past it; the stored pointer and the error message keep the operator's spelling.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 827c38cec7..bf51486e41 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -15,7 +15,7 @@
- `src/core/persistence/diagnostics.ts` — trusted administrator counts for owners/epochs, queued bytes/age, outbox recovery, configured quota usage and actionable capacity warnings; bigint values are transport-safe strings and diagnostics exclude intent, credentials and private paths.
-- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity.
+- **`src/core/persistence/sync-discovery.ts`** + **`sync-origin.ts`** — managed owner-only Git discovery with source-relative exclusions and one-statement page identity/revision snapshots. Nested full discovery filters source scope before slicing paths. Windows separator aliases retain their page identity; ambiguous aliases refuse, while POSIX backslashes/case remain exact. Under `source-root` mode a stored `<scope>/<path>` origin (the Git-root form older write-through minted from the slug, recognized because `<path>` names the page slug) is accepted as `<path>` at discovery, freeze, preparation and the page-origin query, and an import rewrites it in place; when both readings name existing files the stored origin refuses with `detail: ambiguous_source_path`. A genuine origin mismatch refuses with `detail: sync_origin_mismatch` and the filled paths. Deletions must be absent from the pinned Git target or their explicitly selected working tree. Existing cursors reuse their accepted manifests, with unknown old deletion provenance refused rather than rewritten. Imports whose origin has no page claim their slug together: a live page whose own file is still in the tree keeps the slug, otherwise the file named like the slug (else the first path) wins, and the losers leave the manifest and are reported as `slugCollisions` (the library path's `slug_collision` skip) instead of failing the run. A winner whose slug is held by a page with a vanished or deleted origin takes that page over (`renameFrom`, same slug). A Git-detected rename to an unoccupied slug becomes one import carrying `renameFrom` in place of a delete plus a create. Origins for one slug that differ only by case or separator spelling refuse, except a case-only respelling whose old file the same sync removes. Code files keep exact per-origin identity. On Windows a path containing `:` is reported in `SyncDiscovery.fileRefusals` (code `colon_slug_windows_write_through`, with its filled `gbrain sync --source <id> --no-pull` hint) and kept out of the run and its origin checks, so one such file no longer fails the whole sync (#5032).
- **`src/core/persistence/sync-run.ts`** + **`sync-authority.ts`** — one immutable request at a time, bounded fairness and pinned-target resumption. Cursors and requests freeze `noEmbed`, `noExtract` and `noSchemaPack`. A resume adopts the stored options for every option the caller did not set explicitly (`SyncOpts.explicitProcessing`: CLI flags, wire flags, job params; autopilot and the cycle set none); an explicit conflict refuses with `detail: cursor_processing_options_conflict`, the stored options and the exact resume command. Callers that omit `explicitProcessing` stay strict. Explicit idle ordinary-source retry creates fresh discovery/admission and retains terminal receipts; company consent retry retains its approved manifest/run. Active work blocks replacement. Claimed/inactive sync, including connector/company dispatch, remains refused: existing leases and native locks do not fence already-running engine-only legacy writers. No automatic activation or new transition protocol. `freezeEntry` checks a rename's source page (id, revision, origin) as well as its target slug, and a committed rename counts in `renamed`. #5522: a new-file entry (`pageId: null`) whose origin another cursor of the source has since imported is re-frozen against that page when it is live, holds exactly that origin at the entry's slug in the cursor's incarnation, and the sync preparer finds its content unchanged; otherwise the origin refusal stands, and the manifest is never rewritten. #5751: the working-tree screen passes the kernel waivers for working-tree entries and counts them into `legacySkips` (printed by `sync-diagnostics.ts` with `gbrain repair contextual-mode`). A terminal `checkpoint_validation_timeout` receipt gets its hint from `checkpoint-validation.ts`. After the checkpoint commits (and unless `noExtract`), the owner derives links for the source's stale pages through `links-maintenance.ts`, so a PGLite-delegated sync and a Postgres sync take the same path; the result carries `links`, and an extraction failure leaves pages stale without failing the committed sync.
- **`src/core/persistence/sync-prepare.ts`** — guarded raw fingerprint/revision, source root and active coordinator checks before preparation and at locked publication. Old imports/checkpoints without durable processing consent refuse under their original IDs; old deletions require their immutable origin manifest and a still-matching page origin. `noEmbed` suppresses the effect itself; `noSchemaPack` bypasses pack loading; optional extraction stays disabled, but mandatory provider-free canonical projections remain. CRLF equivalence never weakens raw CAS. No uncoordinated filesystem writes. The checkpoint validates receipts through `checkpoint-validation.ts` and, for a run whose entries another cursor imported (`overtaken`, #5522), also commits when that cursor already checkpointed the same target. Tests: `persistence-sync-origin-native.serial.test.ts`, `persistence-sync-options.serial.test.ts`, `persistence-sync-company.serial.test.ts`. A same-slug `renameFrom` accepts the page's recorded old origin. A different-slug rename prepares against the page where it stands, locks the old slug as an additional page key, and at publication moves the page with `updateSlug` (same id, inbound links and history, `old -> new` in `slug_aliases`, withdrawn claims follow), re-infers an implicit type from the new path, then re-prepares and applies the file content at the new slug, so the move never writes back to the file. Tests: `persistence-managed-lifecycle.test.ts`.
- **`src/core/persistence/links-maintenance.ts`** — `extractManagedStaleLinks` derives links for pages whose extraction watermark is stale with `prepareAutomaticLinks` (put_page's replace contract; other producers' edges stay) and adds the coordinator's unrecorded canonical timeline tuples (insert-only) and each page's watermark in the same `withCoordinatedWrite` transaction, bound to the revision it read; an edited page or unresolved attendance stays stale. A page skipped for unresolved attendance is marked attendance-blocked at that revision (`pages.links_attendance_blocked_revision` / `_at`, written by `markPagesAttendanceBlocked` in `engine-sql/pages.ts` only while the revision still matches, cleared by `markPagesExtractedBatch` with the watermark); it is still reconsidered every run, and the `links_extraction_lag` doctor check counts it apart from lag while the marker equals the page's current revision. It is the one managed extraction path: managed sync, `extractStaleFromDB` on a managed brain, and the owner delegation all run it. `runManagedStaleExtraction` backs `gbrain extract --stale` on managed brains, locally or through the `writer_extract_stale` administration operation inside a PGLite owner (`src/commands/extract-stale-delegate.ts`, trusted CLI registration only). `links-preparation.ts` retargets a link written against a renamed page's old slug to the live canonical page through `slug_aliases`, as `get_page` does. Tests: `persistence-managed-lifecycle.test.ts`, `persistence-sync-stdio-owner.serial.test.ts`.
diff --git a/docs/architecture/key-files/google-and-loops.md b/docs/architecture/key-files/google-and-loops.md
index c1edd7c7b7..0cc393fa63 100644
--- a/docs/architecture/key-files/google-and-loops.md
+++ b/docs/architecture/key-files/google-and-loops.md
@@ -24,7 +24,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/google/google-clients.ts` — hand-rolled Gmail/Calendar/People REST clients (house style, no googleapis dependency): auth via any `GoogleAccessProvider` (vault-backed `GoogleTokenProvider` by default), 401 → forceRefresh + single retry, Retry-After honored (delta-seconds AND http-date), 403 accessNotConfigured → `api_not_enabled` carrying the exact enable deep link (project number extracted from the client id), uniform pageToken pagination with a safety cap, `fetchImpl` injectable for tests. `extractCalendarMethod(part)` walks the MIME tree for a `text/calendar`/`application/ics` part and reads the iCalendar `method=` parameter from the PART's own `Content-Type` header (`headers[]` on nested parts with `format=full` — Gmail's `MessagePart.mimeType` is the BARE media type, so a mimeType-only parse would read '' for every real invite and silently downgrade the structural signal to the subject fallback); a mimeType that still carries params is the fallback parse; a bare `.ics` filename with a non-calendar MIME type claims nothing. `CalendarClient.listEvents({calendarId})` sweeps one calendar (default `DEFAULT_CALENDAR_ID`). A People request with a nonempty `syncToken` maps HTTP 400 to `GoogleCursorExpiredError` only for typed `google.rpc.ErrorInfo` reason `EXPIRED_SYNC_TOKEN` or a message beginning `Sync token [is] expired`; unrelated 400s, initial-list requests, and other APIs remain upstream failures. The contacts sweep uses its existing bounded full re-list recovery without restarting Gmail. Pinned by injected-response tests in `test/google-clients.test.ts` and `test/google-source-reconcile.test.ts`, not live-provider validation.
- `src/core/google/google-render.ts` — pure render functions (`{relPath, markdown}` out; no I/O, no engine): thread pages under `emails/YYYY/MM/` (type email), events under `calendar/YYYY/MM/` (type meeting), contacts under `people/` (type person). Gmail deep links are code-generated via the typed `emailCitation` scaffold, never LLM-composed. The noise/signature rules `recipes/email-to-brain.md` specifies as prose for agent-authored collectors are implemented here — keep the recipe and this module in sync. `isCalendarSystemMail({calendarMethod, subject})` gates BOTH loop detectors: the PRIMARY signal is a `calendarMethod` in the `CALENDAR_METHODS` allowlist (RFC 5546 — REQUEST, REPLY, CANCEL, PUBLISH, COUNTER, DECLINECOUNTER, REFRESH, ADD; case-insensitive); an empty or unrecognised method is NOT a stamp and falls to the subject fallback, which is anchored to the start of the subject, refuses any Re:/Fwd: prefix, and matches only Calendar's OWN localised headers (`Invitation:`, `Updated invitation:`, `Accepted:`, `Declined:`, `Tentative:`, `Canceled event:` + localised equivalents) — a generic word like `Notification:` is a human/vendor subject and never matches. `renderThreadPage` stamps `participants:` (every address on the thread) AND `senders:` (sorted unique message AUTHORS only — the list `loops mute sender` gates on, so muting one person cannot silence a whole group thread). Pinned by `test/google-render.test.ts`.
- `src/core/google/google-source.ts` — the Google API source sweep. Unmanaged mode materializes Markdown under the source directory and imports through the standard chunks/aliases/links pipeline; managed mode uses journaled connector admission. Sweep order contacts → calendar → gmail: alias rows must exist before the loop detector resolves counterparties. Per-service independent cursors: contacts/calendar syncToken commits only after that service's fully-successful sweep (410 GONE drops the token and re-runs windowed); gmail delta rides history.list with an expired-history windowed fallback; the INITIAL backfill drains newest→oldest with a batch-committed floor cursor so a killed 50k-message backfill resumes at the floor instead of restarting, and the historyId anchor is captured BEFORE the backfill so the delta lane takes over with zero gap (overlap re-renders are idempotent). Emits the `sync.google_materialize` progress phase (docs/progress-events.md). Access resolves per source config: the vault (default), a token-printing command (`g_access: command` — gog/gcloud/gateway; identity entry synthesized, scope preflight trusts the configured services, send-as aliases fetched live best-effort), or a named env var (`g_access: env`). Secrets never land in `sources.config` (the command/env NAME is config; tokens are not). Honesty invariants: `last_sync_at` is gated on the GMAIL sweep's success (it feeds `gbrain waiting`'s trust-critical staleness gate, which protects loop freshness — a gmail sweep with real thread failures must not advance it); contacts/calendar failures mark the run `partial` but do not block the stamp, and a source without gmail in its services stamps unconditionally. A thread whose fetch fails on consecutive sweeps lands in the poison ledger and is skipped (steady-state runs honor the ledger; `--full` retries with a fresh one), so one bad thread can't wedge the sync while a poison-skip alone doesn't count as failure. Contact reconcile resolves by contact resourceName (DB lookup by contact id FIRST): deletion tombstones carry only `resourceName + deleted` (no names — slug derivation yields null) and a renamed contact derives a DIFFERENT slug, so both must land on the existing page by id, never by slug. The calendar sweep binds its sync token to its calendar: `sweepCalendar` compares `state.calendar_id` (legacy state without it is treated as primary's) with the configured `calendarId`; on a mismatch it logs `[google] calendar changed (<old> → <new>)`, discards the token and takes the windowed first-sync path (no `syncToken` on the wire), and a freshly banked token stores the calendar id beside it — pairing a re-pointed source with the previous calendar's cursor would import a foreign delta. Pages from the previous calendar are not reconciled on the switch (logged; a filed follow-up). `enqueueLoopsExtraction` enqueues EVERY eligible thread (newest first) under a waiting-depth budget `LOOPS_EXTRACT_ENQUEUE_CEILING − waiting` that counts only THIS source's waiting `loops_extract` jobs (`data->>'sourceId'`), so one account's stalled backlog cannot pin another source's budget at 0; overflow is a logged deferral (a deferred thread re-candidates when it changes) and a failed probe fails open. The budget probe counts PENDING rows — `status IN ('waiting','delayed','active')` — so a retry backlog parked in `delayed` during a flapping provider cannot stack past the ceiling. With no chat provider available (`isAvailable('chat')` false) the enqueue is skipped entirely and one stderr line per sweep names the reason and the count; pages still import and the threads re-candidate on their next touch or a `--full` sweep. Managed Google API sync uses journaled connector checkpoints; an unbound source is explicitly `connector_database`, while a bound source publishes canonical files. Identity-query storage failures do not become successful absence or advance the checkpoint. Unsupported Git/dry-run flags refuse before credentials/network; legacy materialization remains the unmanaged path.
-- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound`; a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.
+- `src/core/google/loop-detect.ts` — the zero-LLM thread-state machine: last substantive message inbound + user in To: + unanswered ≥24h → `unanswered_inbound`; last outbound + contains a question + unanswered ≥72h → `unanswered_outbound` (both grace windows measured from the oldest owed message in the trailing run since the last turn flip, so a nudge or follow-up never restarts the clock — gbrain-evals N7-1); a reply closes the loop (`closed_by: reply_detected`). Precision IS the product: noise senders, list mail (List-Unsubscribe), CC-only delivery, FYI/forwards without a question, self-threads, and muted senders/threads never open loops — pinned by the labeled fixture corpus in `test/google-loop-detect.test.ts` (every false-positive class gets a fixture before its fix). Pure verdict function + a thin apply step called per touched thread from the sync; the apply step must never fail the sync.
- `src/core/google/loops-extract.ts` — the LLM half of the open-loop engine: ONE extractor per recent thread page projects each commitment into THREE substrates in the same pass — the `open_loops` row (dedup `commit:<sha8>`), a facts row via writeSingleFact (kind=commitment, fence-first, deduped; its id lands on `open_loops.fact_id` so entity cards / recall / context_pack see the commitment through existing read paths with zero new read code), and a typed edge thread-page → person-page (`owes_to` / `awaiting_reply_from`) for relational search. `extract_facts` never runs separately on google-source email pages. Guardrails: injection-hardened input, ALL-or-nothing parse barrier (a malformed model response writes NOTHING), a structural eligibility gate (`loopExtractionEligibility` — Gmail labels, `List-Unsubscribe`, calendar part, who wrote the message; no vendor lists) plus the per-source waiting-depth enqueue budget (`LOOPS_EXTRACT_ENQUEUE_CEILING`, a spend backstop — see `google-source.ts`), only the last `LOOPS_EXTRACT_WINDOW_DAYS` (30) of mail (the deep backfill is never extracted), kill switch `loops.extraction_enabled` (default ON for google sources). Suppressions gate the lane before any model/facts/edge write: a muted thread id, or a muted SENDER — `fm.from` ∪ `fm.senders`, every address that AUTHORED a message, so a muted counterparty who wrote earlier in the thread still suppresses — returns `reason: 'suppressed'`; recipients/CC never count (muting one person must not hide everyone else's commitments in a group thread, and an outside sender must not be able to dodge extraction by CC'ing a muted address). Pages without a `senders:` field fall back to `fm.from` alone until their next re-render. Eligibility computes the substantive (non-noise, non-calendar) message set FIRST and `owner_participated` requires the owner to have written a SUBSTANTIVE message — a pure-calendar thread the owner RSVP'd to stays `no_substantive_messages`. When the chat provider is unavailable, `runLoopsExtract` throws `LoopsExtractRetryableError` (reason `llm_unavailable`) rather than returning a skipped result: a completed no-work row would hold the revision-keyed idempotency slot forever, while a retried-then-dead row frees it so the same revision re-enqueues on the next sweep. On a managed brain `managedFactWritePreflight` checks the managed fact authority and canonical owner before chat (an unaccepted writer refuses with `writer_coordinator_required`), and the commitment fact publishes through writeSingleFact's coordinator path; disabled, missing-page and suppressed cases retain their existing no-work outcomes.
- `src/core/loops/loops-store.ts` — SQL accessors for the `open_loops` + `loop_suppressions` tables over `engine.executeRaw` with IDENTICAL SQL text on both engines (parity by construction, the sources-ops.ts pattern — no per-engine method twins). JSONB discipline: evidence binds through `$N::text::jsonb`, never a bare `::jsonb` cast over JSON.stringify. Loops close by state transition, never delete: reply-driven auto-close flips status to `done` and stamps `closed_by`, keeping the audit trail. The upsert's DO UPDATE carries a manual-close guard in its WHERE: a closed row (done/dropped/stale) only reopens on GENUINELY newer activity, so a routine sweep re-seeing the same thread never resurrects a hand-closed loop, and the staleness auto-close (`closed_by: 'staleness'`) is likewise guarded against the upsert's reopen. `removeSuppression(engine, sourceId, kind, value)` is the exact inverse of the mute write — deletes the one `(source_id, kind, value)` row with the same lower-casing, returns `{removed: boolean}` (false = was not muted, callers treat it as a no-op success), and never reopens loops: suppressions gate NEW detection only.
- `src/core/ops/loops.ts` — the op surface: `open_loops` (read), `loops_close` (write), `loops_mute` (write). `open_loops` is deliberately NOT localOnly (hosted serves it over HTTP to the authenticated owner); instead it applies fail-closed evidence redaction for `ctx.remote !== false` — counts, counterparty, summary, due date only; verbatim quotes, Gmail deep links, and the injectable `text` digest are trusted-local only. The result carries the google sources' last-successful-sync ages + a `stale` flag (>24h) so callers can refuse stale-but-confident output on a trust-critical surface. Per-call scope params `source_id`/`all_sources` resolve through `resolveRequestedScope` (an MCP client bound to another source can reach the google source's loops; remote callers stay in-grant, out-of-grant `source_id` is denied); a scope with NO google source returns `no_google_sources: true` and the digest says the engine has nothing to read instead of a false "You are clean". Scope is fail-closed too: an UNSCOPED remote `open_loops` read is refused outright (the op must not rely on transports to enforce it — an unscoped remote read would span every source), and the write ops (`loops_close`, `loops_mute`, `loops_unmute`) require a single-source remote scope that matches the caller's grants — trusting a caller-supplied `source_id` for a remote write would let any remote client plant (or lift) suppression rows cross-source; `loops_unmute` reverses a suppression via `removeSuppression` and reports `{removed}` honestly.
@@ -41,7 +41,7 @@ Historical Gmail repair selects explicit nested MIME metadata fields, excluding
- `src/core/harness/oauth-setup.ts` + `client-setup.ts` — explicit client metadata projection, flow selection, native OAuth setup/private-file validation, and live-row-locked secret delivery recovery. Public PKCE needs no journal; confidential exports validate the retained secret against current registration, and machine exports discard cached tokens. Unknown/mixed flows refuse until an explicit supported flow is selected.
- `src/core/harness/capabilities.ts` + `src/mcp/capabilities.ts` — Shared effective-grant orientation for OAuth whoami and authenticated `gbrain://capabilities`. The resource preserves the exact seven-tool surface; source, operation, scope, fence and server-gate restrictions remain enforced at dispatch. No worker probe or per-tool database query during discovery. Shared administration guidance explains separate owner authority, links the MCP admin runbook, and exposes an admin URL only for a configured credential-free HTTP MCP endpoint. Stdio never infers an HTTP address.
-- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.
+- `src/commands/mcp.ts` + `mcp-provision.ts` + `harness-connect.ts` — Host-side grant/preview/CAS and recoverable private delivery, followed by installation inside the intended harness. Codex, Claude Code and opencode installs (`src/core/harness/install.ts`) store the bearer token inline in the harness config; `inlineTokenReceipt` adds `token_storage`, `config_path`, `renew_command`, `if_exposed` (invalidate-tokens preview/apply, renew, reload; `renew_command` carries `--fresh-token` for renewable handoffs so it always exchanges a new token) and a `token_warning` when a Git working tree would commit the file, and `harness-connect.ts` repeats them on stderr in human mode without printing the token (#5775; `test/harness-token-receipt.test.ts`). Running PGLite hosts are administered through their authenticated API, never by opening a second database process. CLI status uses the delivery-aware exit verdict. `mcp-admin.ts` and `mcp-admin-http.ts` provide engine-free owner commands with explicit-file/env credential precedence, in-memory sessions, private native exports, versioned lifecycle previews, and safe stage/outcome/remedy receipts. Unknown mutation outcomes require inspection instead of automatic repetition. `runMcp` also dispatches `gbrain mcp expose` to `runMcpExpose` (dynamic import of `./mcp-expose.ts`; HELP carries the expose lines so the flag registry harvests them) and sets the CLI exit verdict from its returned code. `mcpNeedsEngine(args)` is true only for `grant` without an owner credential (`--admin-token-file` or `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`) and outside help; `admin`, `expose`, and `verify` never open the database.
- `src/commands/mcp-expose.ts` — `gbrain mcp expose [--port N] [--funnel] [--surface] [--enable-dcr] [--no-tailscale] [--no-service] [--no-install] [--force] [--dry-run] [--yes] [--json]` / `--status` / `--remove`: publishes `gbrain serve --http` on the user's Tailscale tailnet (Serve by default, Funnel only with the explicit flag) and keeps it running as a user service. `runMcpExpose(args, deps?)` returns the exit code (0 done, 1 failed, 2 needs `--yes`, the prompt was declined, or a step is pending — a tailnet feature to enable, Tailscale login, tailnet certificate). Arg validation via `validateHarnessArguments` (exclusive pairs `--status`/`--remove`, `--funnel`/`--no-tailscale`, `--dry-run`/`--status`); the help text names every flag and the `verify.local` / `verify.tailnet` checks. Ordered named checks — `plan` (platform, execution environment, engine kind from `loadConfig()`; thin clients are refused with "run on the brain host"; `engine === 'unknown'` — no config or an unreadable one — without `--no-service` is refused as `no_brain_config` / exit 1 with next action `gbrain init` BEFORE consent, because a service around a missing brain only crash-loops, while `--dry-run` still prints the plan with the refusal marked and exits 0; on a PGLite engine `deps.pgliteHolder` (default `probeLivePgliteHolder` from `src/core/bootstrap/uninstall.ts`, a read-only lock-file probe) is consulted with `cfg.database_path`, and a live holder that is not our own managed service — receipt present with `service.state` `running`/`loaded` — adds a `Lock` plan line plus a `pglite_lock` check with status `warn` (never a stop); `--no-tailscale` over an existing receipt whose `tailscale.dns_name` is set (a live Serve/Funnel mapping) is refused BEFORE consent as `tailscale_receipt_present` / exit 1 with next actions `gbrain mcp expose --remove --yes` and the re-run without the flag — `--dry-run` marks it `WOULD BE REFUSED`; then probes `127.0.0.1:<port>` with `probeOccupied(d, port, url)` — occupied when EITHER the injectable `deps.tcpProbe` (default `defaultTcpProbe`, one `node:net` connect, socket destroyed on every outcome; true on connect, false on refusal / timeout / throw) accepts a TCP connect OR the `/health` fetch RESOLVES with ANY status (2xx, 404, 500), so a non-HTTP listener counts too; only both rejecting is free — and refuses a foreign listener with no receipt claiming that port as `foreign_listener` BEFORE anything is published unless `--no-service`; the message names the interrupted-run escape hatch `gbrain mcp expose --remove --yes`; `probeHealth` (`res.ok`) stays the bar for `verify.local` / `verify.tailnet` / `--status`), `consent` (shared `confirmOrFinish` for publish and `--remove`: one stderr y/N prompt on a TTY; declining is `pending` / exit 2 / `declined` with "Nothing changed. Re-run with --yes to confirm."; non-interactive without `--yes` prints the plan and exits 2 / `confirmation_required`; every re-run hint is rendered by `rerunCommand(opts)` — the user's publish flags + `--yes`), `tailscale.binary` (install plan: brew cask on macOS — then `open -a Tailscale` and a bounded poll of `tailscale status --json`, up to 20 attempts 1s apart, breaking as soon as the app's daemon answers and otherwise falling through to the login step's daemon-not-running handling — official installer on Linux, `--no-install` → exit 1), `tailscale.login` (Linux `sudo tailscale set --operator=<user>` non-fatal then flagless `sudo tailscale up` — `sudo` is put in front of the binary ONLY when `isSystemTailscaleBinary(binary)` holds (one of `TAILSCALE_BINARY_CANDIDATES`, literally or via `realpathSync`); a user-writable `tailscale` found on PATH stops the step as `pending` / exit 2 / `tailscale_login_manual` with the message "tailscale at <path> is not a system install, so gbrain will not run it with sudo. If you trust that binary, sign in yourself (this runs it as root): `sudo <path> set --operator=$USER && sudo <path> up`, then re-run: <rerun>" — the command is `tailscaleManualLoginCommand(binary)`, naming the discovered path shell-quoted, because a binary outside sudo's `secure_path` is exactly this case — and never spawns `sudo`; macOS `tailscale up`; bounded wait via `GBRAIN_TAILSCALE_LOGIN_TIMEOUT_MS`), `tailscale.identity` (MagicDNS name → `public_url`; pre-checks so `tailscale serve`/`funnel` — which wait interactively instead of failing when a feature is off — are never started blind: empty `CertDomains` → `pending` / exit 2 / `tailscale_https_not_enabled` with `TAILSCALE_ADMIN_DNS_URL`; `--funnel` with `funnelCapable === false` → `tailscale_funnel_not_enabled` with the ACL admin + Funnel KB URLs; `funnelCapable === null` proceeds), `tailscale.publish` (reads the serve config through `readServeView`, which FAILS CLOSED — it returns `{ view: ServeStatusView | null, stderr, status }` with `view: null` when `tailscale serve status --json` exits non-zero / is killed (`status: null`) or when stdout is not a JSON object per `parseServeStatusStrict`; an empty document / `{}` / `null` from exit 0 is the legitimately empty view — a null view before `--bg` is described once by `describeServeReadFailure` (`{ kind, detail, fix }` from one `classifyTailscaleError` call), records `tailscale.publish` = fail and returns exit 1 with reason `tailscale_<kind>` without publishing; a null view after `--bg` is `tailscale_publish_unconfirmed` naming the read failure; refuses a `/` handler proxying a different port, a foreground session or a raw TCP forward without `--force` as `foreign_serve_config` — `next_actions` says `tailscale serve status`, only `message` explains `--force`; `PUBLISH_TIMEOUT_MS` (60s) bounds `--bg`, `SERVE_OFF_TIMEOUT_MS` (30s) every `--https=443 --set-path=/ off` and `STATUS_READ_TIMEOUT_MS` (15s) both status reads; a `status: null` timeout is `unknown` with a run-by-hand hint; stderr classified by `classifyTailscaleError` as the second line of defense; switching our own handler's shape pre-clears ONLY in the funnel → tailnet direction (`funnel --https=443 --set-path=/ off` before `serve --bg`, because `serve --bg` over a Funnel mount keeps `AllowFunnel`; tailnet → funnel is one atomic `funnel --bg`), and when that pre-off was followed by a failed publish (non-zero, timeout, or unconfirmed) `restorePrevious` best-effort re-publishes the previous shape with `tailscaleServeArgv(port, { funnel: true })`, re-reads the view, and appends to the `tailscale.publish` detail whether "the previous funnel handler was restored" or "could NOT be restored"; the existing receipt is never touched on those paths), `admin_token` (ensure the 0600 token file, never printed), `service` (launchd / systemd user unit / `manual` fallback with the exact foreground and `nohup` commands; a `--no-service` re-run carries the existing receipt's service block unchanged and does not rewrite the wrapper; `service_install_failed` still writes the receipt with `service.state: 'stopped'` before exit 1 so `--status`/`--remove` can clean up the published handler; the receipt is ALSO written right after a successful service step — service state as probed at that moment — before verify runs, so a kill during verify always leaves `--status`/`--remove` something to find), `verify.local` (wall-clock `/health` polling up to 20s, timeout → `warn`, exit 2, `verify.tailnet` skipped), `verify.tailnet` (up to 30s, `pending` is exit 2 — EXCEPT when the last probe's rejection was a name-resolution failure per `mcp-expose-probe.ts`: Bun's `fetch` rejects an unresolvable host and a refused connection with the same "Unable to connect. Is the computer able to access the url?" / `ConnectionRefused`, so after a rejected fetch the URL's hostname (never an IP literal or `localhost`) is handed to `deps.lookup` — default `dns.promises.lookup`, bounded by the probe timeout — and a rejection with code `ENOTFOUND` / `EAI_AGAIN` / `EAI_NONAME` / `EAI_NODATA` / `DNS_ENOTFOUND` (or a message naming one) is the verdict, the fetch-message regex staying a secondary hint; a name that resolves but does not answer stays `pending`: then the check is `warn` with `unresolvedDetail(dnsName)` — "this host cannot resolve <name> (MagicDNS may be off here: `tailscale set --accept-dns=true`); devices that do resolve it may already reach the server" — and the run exits 0, since this host's resolver says nothing about the server), `receipt` (rewrites the early receipt with the settled state — the supervisor is re-probed once verify.local ran — keeping `created_at`). The admin-token, service and verify steps run inside one try: a THROW there after this run's `--bg` succeeded but BEFORE the early receipt is rolled back by `rollbackAfterThrow(d, s, opts, published, error, receiptWritten)` — the fresh handler is turned off again with `tailscaleServeOffArgv({ funnel })` only when no `/` handler for our port existed before the run (a pre-existing one is left in place), a `rollback` check records what happened — "turned off again" is claimed only when a re-read of the serve view after an exit-0 `off` no longer shows our port; an exit-0 `off` whose re-read still shows it is a `warn` "NOT turned off (… the handler is still present)", an unreadable re-read is a `warn` "state unknown", and an `off` that exits non-zero or throws is a `warn` whose message says the handler was NOT turned off — no receipt is written, and the error is re-thrown so the outer catch reports `mcp_expose_failed` with a message naming the handler state; once the early receipt is on disk (`receiptWritten`, checked first) a throw tears nothing down (`rollback` = skipped pointing at `--status` / `--remove --yes`), because the receipt makes everything findable (the non-throwing `service_install_failed` path keeps its partial receipt). Success banner and `next_actions` gate the local-agent line on the engine: Postgres → `gbrain bootstrap harness --yes --port N`; PGLite → pre-mint (`gbrain auth create … --scopes read,write` before the service runs) + `--token`, or the scoped `mcp grant … --url http://127.0.0.1:N/mcp --admin-token-file …` + `gbrain connect … --install` path, and "host-side commands fail with `live_serve` — administer through the running server". `--json` emits one stdout document `{ status, receipt, checks[], next_actions, reason?, message? }` with prose on stderr; every `inherit` subprocess redirects its stdout to stderr under `--json`. `--status` and `--remove` read the receipt through `readExposeReceipt`'s shape guard (a partial receipt is `not_exposed` / "nothing to remove", never a crash) and execute the tailscale binary from `resolveReceiptBinary`: the receipt's recorded path is honored only when it still exists AND is either what `findTailscaleBinary` finds now or one of `TAILSCALE_BINARY_CANDIDATES`, otherwise discovery wins — a path in a receipt is data, never a licence to run it. the probes — `probeHealth` (`res.ok`), `probeOccupied` (any response, or an accepted TCP connect), the bounded never-throwing `tryFetch` → `FetchOutcome { res, unresolved }`, `pollHealth` → `{ ok, unresolved }` with the LAST probe's resolution verdict, `unresolvedDetail`, `defaultTcpProbe`, `defaultLookup` — live in `src/commands/mcp-expose-probe.ts` and take the narrow `ProbeDeps` slice of the resolved deps (`fetch`, `tcpProbe`, `lookup`, `now`, `sleep`, `healthIntervalMs`); `defaultTcpProbe` is re-exported here so its import site never moved; `isLiveService(state)` is the one definition of "the supervisor reports our service" (`running` or `loaded`) used by the lock-holder exemption, the service check, `--status` and both `--remove` paths; `serviceLabel` builds on `serviceKindLabel` (`launchd <label>` / `systemd (user) <unit>`). `--status` runs its four independent probes (serve config, supervisor state, local and tailnet `/health`) concurrently with `Promise.all` and still reports the checks in the fixed order `receipt`, `tailscale.publish`, `service`, `verify.local`, `verify.tailnet`; an unreadable serve config (null view) is a FAILED `tailscale.publish` check / exit 1, never "handler present"; a tailnet `/health` rejected for name resolution is `verify.tailnet` = warn (same `unresolvedDetail`), not `pending`, and does not by itself make the exit non-zero. `--status` with NO receipt is `runStatusWithoutReceipt`: it runs the read-only `probeLeftovers(d, opts.port)` (`--port` is honored) and, when the wrapper, the plist / unit or a live service, or a `/` handler on `:443` proxying the port is found, emits one `warn` check per artifact (`receipt`, `service`, `tailscale.publish`, `files`), pushes `recoveryCommand(port, force)` (`gbrain mcp expose --remove --yes`, `--force` only when a handler stands alone with no wrapper / service corroborating it, `--port N` when non-default) to `next_actions`, and finishes `error` / exit 1 / `leftovers_without_receipt` (also under `--json`); an unreadable serve status alone is a caveat warn, not a leftover; nothing found keeps the `not_exposed` answer (exit 0, `--json` exit 2). `--remove` (consent; decline is `pending` / exit 2) probes the supervisor and removes a service that exists even when the receipt says skipped — `recordServiceUninstall` prints the uninstall notes, and when `launchdBootoutFailed(result)` (a `launchctl bootout failed: …` / `unload failed: …` note, i.e. a non-"not loaded" failure) the `service` check is `warn` pointing at `launchctl print gui/$(id -u)/com.gbrain.serve` and "the launchd job (bootout failed)" is added to "Left in place"; it returns the one-line service summary quoted below — then clears only gbrain's own serve/funnel handler through `turnOffOurHandler` (Funnel off first; every `off` is `--https=443 --set-path=/ off`, scoped to our `/` mount; the serve config is re-read only after an `off` command ran, otherwise the view already read is reused; a failed re-read is reported as `unknown` — a warn, never "gone"; a foreign port on `:443` gets "nothing to turn off"). `--remove` never reports success while our handler survives: when `turnOffOurHandler` returns `remaining` as a handler (`tailscale.publish` = fail) or `'unknown'` (= warn), `finishHandlerNotRemoved` keeps the receipt AND the wrapper (mirroring the unreadable-status branch), records `receipt` = skipped "kept: …", pushes `tailscale serve status` + the re-run to `next_actions`, says which service outcome already happened, and exits 1 with reason `handler_not_removed`; `--remove` never runs `tailscale serve reset`, never uninstalls or logs out, keeps the admin token unless `--force` (deleted through the same `unlinkQuietly` as the wrapper and receipt), and unlinks the wrapper / receipt / token ONLY when the path's directory is the serve directory — a receipt path elsewhere is left untouched and named in "Left in place" (also in the plan). The receipt's recorded `plist_path` / `unit_path` are data, never a licence: `uninstallServeService` is always handed the computed `d.plistPath` / `d.unitPath` (home + the fixed label / unit name), and a recorded path that differs is not touched and is named in "Left in place" as "recorded in the receipt but not the expected location". A null serve view during `--remove` fails closed: `tailscale.publish` = fail "could not read tailscale serve status; handler left as is", reason `tailscale_serve_status_unreadable`, exit 1, and the receipt AND wrapper are kept so a re-run finishes the job. With NO receipt, `runRemoveWithoutReceipt` recovers from what is on disk through the same `probeLeftovers` `--status` uses (`wrapperPath(serveDir)`, the launchd plist / systemd unit or a `running`/`loaded` service, a `/` handler on `:443` proxying `opts.port` — `--port` may accompany `--remove`, default 3131); inside it the supervisor chain (`probeServiceTarget` → `serveServiceState`) and the `readServeView` read run concurrently under `Promise.all` (the binary is resolved synchronously first) and the plan / checks are emitted in the fixed order afterwards; the re-run hints come from `recoveryCommand`. The handler is turned off only with corroborating gbrain evidence — the wrapper present, our unit/plist present, or the supervisor reporting our service live — or with `--force`, because another tool may proxy `:443` to the same port: a handler standing alone is reported (`tailscale.publish` = warn naming the proxy target and `--force`, next action `gbrain mcp expose --remove --yes --force`) and left in place on the "not exposed — nothing to remove" exit-0 path; with `--force` the plan line says so. Otherwise it prints a "Recovering without a receipt" plan (`receipt` check = warn), takes consent as usual, removes exactly those artifacts (service via the supervisor — the same `recordServiceUninstall` bootout-failure warn applies — wrapper, the handler — funnel off first when `AllowFunnel` lists the host), leaves the admin token file, and finishes `removed` with reason `recovered_without_receipt`; a handler that survives the `off` is `handler_not_removed` / exit 1 here too, with the wrapper deliberately KEPT as the corroboration the re-run needs (`files` = skipped "kept: the wrapper"; the re-run hint carries `--force` when no wrapper is left); an unreadable serve status on this path (gbrain evidence present, `serveUnreadable` set) fails closed exactly like the receipt path — the service, when found, is still uninstalled, the plan says the handler cannot be checked and the wrapper is kept, `tailscale.publish` = fail "…; handler state unknown", `files` = skipped "kept: the wrapper" (or "nothing (no wrapper was found)"), `next_actions` = `tailscale serve status --json` + the recovery command (`--force` when no wrapper is left), exit 1 with reason `tailscale_serve_status_unreadable` and message "could not read tailscale serve status; handler state unknown"; when nothing of ours is found the answer stays "not exposed — nothing to remove", exit 0 (an unreadable serve status is then only the caveat warn — there is nothing to keep and a handler alone would not be touched anyway). Every filesystem/exec effect goes through injectable deps so tests run against a fake runner in a tmpdir. Success guidance separates owner login, native OAuth registration, and machine grant/install. It uses the expose-managed owner file only when installing or keeping that service; publication with `--no-service` and no managed service instead requires the existing server's independently configured owner credential. Publishing receipts and health checks do not certify client authorization or native activation.
[Continue this subsystem](google-and-loops-continued.md).
diff --git a/docs/architecture/key-files/runtime.md b/docs/architecture/key-files/runtime.md
index 9e274b3918..e8e651848f 100644
--- a/docs/architecture/key-files/runtime.md
+++ b/docs/architecture/key-files/runtime.md
@@ -19,9 +19,10 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/mcp-client.ts` — the thin-client transport (trust boundary). `callRemoteTool(config, toolName, args, opts)` with `CallRemoteToolOptions {timeoutMs, signal}`; `buildAbortController` composes an external signal with the timeout, and `buildMcpRequestOptions` forwards `timeoutMs` as the SDK request deadline (otherwise its own 60s default wins); an SDK `RequestTimeout` classifies as `network`/`timeout`, never unreachable. All transport errors normalize to `RemoteMcpError` via the `toRemoteMcpError` funnel: stable `RemoteMcpErrorReason` union, `RemoteMcpErrorDetail.kind` (`'timeout' | 'aborted' | 'unreachable'`) sub-tag, `RemoteMcpErrorDetail.code` carrying server-supplied error codes (e.g. `missing_scope`). `extractToolErrorCode` parses the operation `{error: string, message}` shape as well as legacy envelopes. Mutation arguments retain one request UUID before the first transport attempt, across OAuth refresh and caller retries. Mutation errors retain that UUID and distinguish unknown delivery from requests never submitted; the shared CLI renderer emits same-ID retry guidance without fabricating a receipt. Received pending or terminal error receipts and frozen verb metadata survive deadlines during client cleanup, including the refreshed attempt. Only the locked SDK’s typed `StreamableHTTPError` with numeric code 401 triggers one refresh and reconstructed client; application error text never causes authentication replay. The outer abort signal reaches discovery, minting, initialization, fetch and tool calls, with per-request limits retained and clients closed after failed initialization or abort. `unpackToolResult<T>(res)` parses tool-call JSON content. `_clearMcpClientTokenCache()` test escape. The CLI routing seam that consumes this lives in `src/cli.ts` (`runThinClientRouted`); see `docs/architecture/thin-client.md`.
-- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
+- `src/core/op-checkpoint.ts` — DB-backed checkpoint primitive for long-running ops. Migration v67 introduces `op_checkpoints (op TEXT, fingerprint TEXT, completed_keys JSONB, updated_at TIMESTAMPTZ, PK(op, fingerprint))`. Per-op fingerprint helpers (`embedFingerprint`, `extractFingerprint`, `reindexFingerprint`, `integrityFingerprint`, `purgeFingerprint`) compute `sha8(canonical-JSON(relevant-params))` so re-running with the same params resumes from `completed_keys` and re-running with different params (e.g. `--limit 100` vs `--limit 200`) starts fresh. Cross-worker safe on Postgres (DB row, no file-lock race); PGLite degrades gracefully. The 7-day TTL GC runs in the cycle's `purge` phase. All writes (`recordCompleted`, `clearOpCheckpoint`) route through `engine.executeRawDirect` + `withRetry(BULK_RETRY_OPTS)` so they survive Supavisor pool exhaustion, and `recordCompleted` returns `boolean` (banked vs failed-after-retries) — the 9 non-sync consumers keep its REPLACE-into-`completed_keys` semantics. Resumable sync uses the additive `appendCompleted(key, deltaKeys)` / `appendCompletedOnce` (the latter no-retry for the SIGTERM path) which INSERT a delta into the `op_checkpoint_paths` child table (migration v115: `(op, fingerprint, path)` PK, FK to `op_checkpoints` ON DELETE CASCADE) via a single writable-CTE `unnest($3::text[])` write — O(delta), never an O(N²) full-set rewrite. `loadOpCheckpoint` returns the `UNION ALL` of legacy `completed_keys` + child-table paths (deduped in JS), so an in-flight upgrade loses nothing. The legacy arm is gated on `jsonb_typeof(completed_keys) = 'array'` so a non-array (scalar) parent row can't make `jsonb_array_elements_text` throw "cannot extract elements from a scalar" and take down the whole union (which would discard the valid child rows and lose all banked progress for the key); a third union arm flags the corruption so the loader logs it once and keeps the child rows. Migration v119 adds the `op_checkpoints_completed_keys_array` CHECK (`jsonb_typeof(completed_keys) = 'array'`) — a DB-enforced, always-on guard that makes the scalar-corruption class structurally impossible going forward; the migration repairs any pre-existing scalar to `'[]'` under `LOCK TABLE ... IN SHARE ROW EXCLUSIVE MODE` and `src/core/schema-embedded.generated.ts` + `src/core/pglite-schema.ts` ship the same CHECK on fresh installs (a loader hit implies schema drift, a disabled constraint, or an out-of-band writer). `recordCompleted` binds its array through `$3::text::jsonb` (NOT a bare `$3::jsonb`) so postgres.js `.unsafe()` doesn't double-encode `JSON.stringify(sorted)` into the scalar string that CHECK rejects (PGLite parses it silently, so only real Postgres surfaces the bug). A DATABASE_URL-gated `test/e2e/op-checkpoint-jsonb-parity.test.ts` (its own CI job) asserts the array shape on real Postgres. `syncFingerprint({sourceId, lastCommit})` keys the sync rows. Pinned by `test/op-checkpoint.test.ts` (incl. delta-append, union read, cascade clear, durable-write boolean, and the scalar-parent guard). `import-checkpoint.ts` stays a separate file-backed checkpoint — both systems coexist without conflict (unifying them would mean async-propagating the four sync call sites in `src/commands/import.ts`; deferred). TTL cleanup preserves unresolved managed cursors, their manifests and failure observations; a completed full cursor does not hide a different failed incremental cursor. Unfinished `managed-atoms` and `managed-atoms-generation` checkpoints survive ordinary seven-day GC so accepted output/retry state is not silently forgotten.
+- `src/core/persistence/preview-approval.ts` — preview-bound approval shared by `jobs authorize-legacy --select`, `jobs cancel --select`, `repair stale-atoms` and `repair extractor-facts` (fix wave 5, ENG-O1). `previewHash(parts)` is SHA-256 over key-sorted JSON, byte-identical to `authorityDigest`; `saveApprovedSet` / `loadApprovedSet` / `clearApprovedSet` keep the approved items in `op_checkpoints` (`op='repair-approval'`, fingerprint `<command>:<hash>`). A missing, foreign, malformed or older-than-`APPROVAL_MAX_AGE_DAYS` (7, the purge TTL) set refuses whole with `preview_changed`. Tests: `test/preview-approval.test.ts` (PGLite; Postgres via `test/e2e/preview-approval-postgres.test.ts`).
-- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`).
+- `src/core/process-cleanup.ts` — cleanup registry + abnormal-termination handlers (SIGTERM/SIGHUP/SIGPIPE, uncaughtException/unhandledRejection, EPIPE-on-stdout) that release locks before exit. `registerCleanup(name, fn)` returns a deregister handle; `tryAcquireDbLock` auto-registers. `installSignalHandlers()` is idempotent and called from INSIDE cli.ts's `import.meta.main` seam (first statement before `main()`), NOT at module load — installing at import time would leak a process-wide SIGTERM→`process.exit(143)` handler into any process that merely imports cli.ts (a bun test runner would die mid-suite when a test emits a synthetic SIGTERM, misreading rc=143 as an external kill). Spawned/compiled CLI processes are entrypoints, so they still install. Every attached listener ref is recorded so `_resetForTests()` DETACHES them (clearing flags alone would leave the exit(143) listener live on the shared runner). Tests that must emit synthetic signals strip foreign listeners around the emit (see `test/run-child-entry.test.ts`). #5079: `serve --http` (detected by `isHttpServeInvocation` in `src/core/serve-invocation.ts`) installs it with `keepServingOnLogEpipe`, so a closed stdout/stderr pipe (SIGPIPE under Bun, or an EPIPE stream error) drops the log write instead of exiting; stdio `serve` and every other command still exit. Pinned by `test/serve-http-log-epipe.test.ts`.
- `src/core/process-watchdog.ts` — out-of-band hard-deadline killer for `gbrain sync`. A spinning sync (synchronous catastrophic-regex / ReDoS in pack link-inference) STARVES the main event loop, so the existing SIGTERM handler (`process-cleanup.ts`), `--timeout` `setTimeout`, and abort-flag checks can't fire — the process becomes unkillable-by-SIGTERM and, under cron, orphans pile up for 24h+. `installProcessWatchdog({deadlineMs, graceMs?, label?, heartbeatMs?, onWarn?}): WatchdogHandle` spawns a Bun `worker_threads` Worker via `new Worker(code, {eval: true, workerData})` — its own OS thread + event loop fires even while main is in an unyielding sync loop. At `deadlineMs` it `process.kill(process.pid, 'SIGTERM')` (clean-shutdown chance if responsive); at `deadlineMs+graceMs` `process.kill(process.pid, 'SIGKILL')` (uncatchable — guaranteed death under starvation). Signaling SELF has NO PID-reuse footgun (current PID never reused while alive — the reason the detached-child-watches-parent design was rejected). `eval: true` bakes the worker body into the `bun build --compile` binary with no separate-file embedding. Empirically validated on Bun 1.3.13 (worker timer + SIGKILL killed a `while(true){}`-starved process). `handle.dispose()` (clean-exit `finally`) `worker.terminate()`s it; `unref()`'d so it never keeps the process alive. Pure `watchdogDecision(elapsedMs, deadlineMs, graceMs) → 'wait'|'sigterm'|'sigkill'` extracted for unit tests, and pure exported `clampWatchdogTimers(deadlineMs, graceMs)` + `MAX_WATCHDOG_TIMER_MS` clamp BOTH worker timers so the deadline AND the `deadline+grace` SUM stay ≤ 2^31−1 — `setTimeout` overflow-fires above that at ~1ms, which for the sum timer would be an instant SIGKILL of a healthy process (unit-tested as pure arithmetic only; never arm a real max-deadline worker in-suite — its firing SIGTERMs the test runner itself). Optional `heartbeatMs` emits periodic `[<label>] parent alive Ns, hard-kill in ~Ms` lines (visible in cron logs even under starvation — the diagnosis surface). Fallback: if `new Worker` throws, degrades to an in-process timer with a loud warning that it can't fire under starvation. Two adopters: `gbrain sync` (below) and the opt-in PGLite disconnect watchdog (`pglite-engine.ts` entry above); autopilot/cycle are follow-up candidates. Pinned by `test/process-watchdog.test.ts` (pure decision matrix + clamp arithmetic + handle contract) + `test/process-watchdog.serial.test.ts` (Bun-pinned spawn integration: a starved harness process IS killed ~deadline+grace, a no-watchdog control does NOT self-exit, clean dispose never kills). Wired into `src/cli.ts` sync dispatch BEFORE `connectEngine` (so a connect-phase hang is bounded too); deadline resolved by `resolveSyncHardDeadline` in `sync.ts` (precedence: `--no-hard-deadline` > `--hard-deadline` > `--timeout`(non-`--all`) > `GBRAIN_SYNC_MAX_RUNTIME_SECONDS` env > non-TTY default 3600s > none).
diff --git a/docs/architecture/topologies.md b/docs/architecture/topologies.md
index 88215f8596..66d4a407e0 100644
--- a/docs/architecture/topologies.md
+++ b/docs/architecture/topologies.md
@@ -558,11 +558,14 @@ dry run first."*
recovery, `gbrain repair embedding-effects --source <id>` for a stuck
embedding effect, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`
for a failed Git or withdrawal effect, and `gbrain sources writer unlock` for
- the writer admin lock. A held Google or GitHub item is resolved first:
- `gbrain sources status <id>` names its error; fix the cause, then run
- `gbrain sources retry-held <id>` and `gbrain sync --source <id>` (a
- successful re-attempt clears the hold), because classic mode does not read
- managed holds. A live connector or maintenance
+ the writer admin lock. Held Google or GitHub items do not block: deactivate
+ copies each source's managed holds into its classic state file
+ (`.google-source.json` or `.github-source.json`), so they stay held, retried
+ and reported in classic mode; the dry run lists them as `carried_holds`. Only
+ a source with no state directory, or with a classic state file that does not
+ parse, blocks; its exit is to move that file aside, or to resolve the holds
+ (`gbrain sources status <id>`, fix the cause, `gbrain sources retry-held <id>`,
+ `gbrain sync --source <id>`). A live connector or maintenance
lease means waiting for that run. A clean dry run prints `apply_command`,
the deactivate command bound to the state it reviewed.
4. Deactivate: run the printed `apply_command`, or `gbrain sources writer status --json`
diff --git a/docs/guides/authorization-upgrade.md b/docs/guides/authorization-upgrade.md
index ccf3abdf59..c81e18f219 100644
--- a/docs/guides/authorization-upgrade.md
+++ b/docs/guides/authorization-upgrade.md
@@ -147,10 +147,31 @@ no tools; only an absent trusted-local binding uses the default registry.
A changed snapshot or dependency graph refuses approval; preview and review
again. Only selected SQL-NULL rows receive application authority. IDs, schedules, attempts, and
dependencies remain intact. Dependencies require their own explicit review.
+
+ For many rows, select by status and job name instead of typing ids. The
+ preview lists counts by job name and status, the first 20 ids, marks job
+ names whose handlers make paid provider calls, and prints a preview hash;
+ the apply authorizes exactly the previewed set:
+
+ ```sh
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize"
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize" --expect <hash> --yes
+ ```
+
+ Live rows you do not want to run (including unsupported non-NULL ones)
+ cancel the same way with `gbrain jobs cancel --select "<filter>"` and its
+ printed `--expect <hash> --yes`; a selection that would also cancel a job
+ outside it refuses and names that job. Active jobs are cancelled one at a
+ time with `gbrain jobs cancel <id>` before either preview runs.
+ `gbrain doctor` (`legacy_job_authority`) prints these commands filled in
+ for your brain.
5. Explicitly authorize or cancel every nonterminal legacy job before restarting
services. Worker startup refuses unresolved work. Historical terminal rows
- remain unchanged; review them explicitly before a later local replay.
- Remote replay cannot authorize legacy rows.
+ remain unchanged and need no step for local producers: a resubmission over a
+ completed or failed legacy key reuses that row, and a dead or cancelled key
+ is released for a fresh job. A remote caller is refused over a terminal
+ legacy key; it resubmits with a new key. Review terminal rows explicitly
+ before a later local replay. Remote replay cannot authorize legacy rows.
6. Start the matching application, producers, and workers and inspect job
diagnostics for bounded authorization denials. Resume normal post-upgrade
setup and automatic-upgrade schedules only after the queue review is complete
diff --git a/docs/guides/bootstrap.md b/docs/guides/bootstrap.md
index 459afd8a8b..f61d4186f4 100644
--- a/docs/guides/bootstrap.md
+++ b/docs/guides/bootstrap.md
@@ -39,6 +39,20 @@ follows is `BOOTSTRAP_FOR_AGENTS.md` at the repo root, fetched at the
| Private GitHub repo | your account, created by `bootstrap repo` (or an empty repo you made yourself, adopted) | privacy verified via API |
| Machine receipt | `~/.gbrain/bootstrap/receipt.json` | uninstall is keyed to it |
+**What session start shows:** the SessionStart hook prints your
+allowlisted MEMORY.md sections, push status and hook health, plus a warm
+context pack. It never shows another session's activity. Releases before
+v0.60.28.0 printed a `Last session activity` line from the newest session
+buffer on the machine, whichever agent or session wrote it (#5558). That line
+and the stop-hook buffer behind it are gone, and there is deliberately no
+opt-in to bring them back. Buffers an older release left in
+`~/.gbrain/transcripts/live/` are deleted by the stop hook once they are 7
+days old; you can delete them now. If you set `GBRAIN_HOOKS=0` as a
+workaround, remove it from the environment the harness starts from (shell
+profile or service) after upgrading the `gbrain` the harness runs, then
+restart the harness: `GBRAIN_HOOKS=0` also turns off capture, session
+persistence and crash recovery.
+
**What does NOT run:** anything while the harness is closed. Session-triggered
schedules fire at turn/session boundaries only. True 24/7 operation is what a
hosted brain provides — this is the honest desktop contract.
diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.md
index cbebae8705..321370c939 100644
--- a/docs/guides/concurrent-writes.md
+++ b/docs/guides/concurrent-writes.md
@@ -311,6 +311,15 @@ bytes, revisions, chunks and embedding signatures remain unchanged. Managed
withdrawals retain a versioned target manifest for the mirror, Git and embedding
workers; each worker checkpoints one affected page at a time.
+A withdrawal mirror or Git scan no longer parks on a page whose file is a
+sync-skip metafile (`RESOLVER.md`, which carries the managed durability block
+by design) or whose file holds an uncoordinated local edit (#5396): the
+withdrawal is recorded in the database, the page is listed in the effect's
+`data.skipped` with reason `metafile` or `file_database_drift`, and the
+request's Git and embedding effects proceed. Reconcile a `file_database_drift`
+page as described in
+[Repair a file/database disagreement](#repair-a-filedatabase-disagreement).
+
Stop older mutation workers before upgrading the owner and restarting work. Older
binaries do not understand the target manifest and must not share the brain with
the upgraded worker. This is a quiesced upgrade, not a mixed-version rollout.
@@ -620,6 +629,20 @@ source; a stale remote is never accepted as recovery. Incomplete directory
replacement blocks that root until its recorded recovery finishes. Neither
recovery nor lifecycle administration reverses a committed fact withdrawal.
+Large worktrees have no file-count bound. The stored manifest records the
+content digest and `file_count`, not a per-file map, so `sources add`, `claim`,
+`rebind`, `archive`, `remove`, clone, reclone and writer transfer work the same
+at 50,000 files as at 50. Rows written by older releases, which also carry a
+per-file map, stay valid and are compacted on their next rewrite. Every command
+still hashes each file once while holding the root's native lock and before it
+opens a database transaction; in human output it reports `files hashed of total`
+on stderr for worktrees above 5,000 files. Measured on a 4-vCPU cloud machine
+with a 50,000-file, 3.4 MB worktree: `sources add`, `claim` and transfer
+prepare and accept each took under one second on PGLite and Postgres, with
+peak RSS growth of about 100 MB on Postgres and 325 MB on PGLite
+(`test/e2e/persistence-large-manifest-50k.test.ts`). Hashing time grows with
+total bytes, not only file count.
+
Physical checkout identity lives in private durable markers in and beside the
root. Copies, replaced directories, and competing homes cannot claim that same
path as separate worktrees. Keep those markers: removing them does not grant
diff --git a/docs/guides/hosted-harness-access.md b/docs/guides/hosted-harness-access.md
index d7f061899a..189b8b5521 100644
--- a/docs/guides/hosted-harness-access.md
+++ b/docs/guides/hosted-harness-access.md
@@ -134,7 +134,7 @@ gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex \
For Grok Bot, Muse, or another supported thin CLI adapter, also supply `--root /absolute/verified/persistent-root`. Grok Bot's recommended root is `/workspace/gbrain`. Discover and verify Muse's durable location before choosing a root. Use the generated **absolute launcher** for every later GBrain call; it pins routing and isolates inherited configuration.
-The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
+The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration (mode 0600) with the bearer token stored **inline** in that file: `~/.codex/config.toml`, Claude Code's user MCP config, or opencode's global config. The receipt names it with `token_storage: "inline"` and `config_path`, gives the `renew_command` that exchanges and writes a fresh token (`--install --fresh-token`), and lists `if_exposed`: preview and apply `gbrain mcp admin invalidate-tokens <client_id>` on the brain host ([invalidate tokens](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete)), run the renew command, which exchanges a new token instead of reusing the cached invalidated one (a handoff without a client secret needs a new handoff from the owner), then reload the harness. Neither the receipt nor the output prints the token. Treat that config file as a secret: when it sits in a Git working tree that does not ignore it, the receipt adds `token_warning`; add the file to the repository's `.gitignore` or move it, and follow `if_exposed` if it was already committed. Rotating the client secret does not invalidate issued access tokens. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
A configured server is only one step. Follow the adapter's reload instructions and enable the GBrain standing instruction through the harness's actual controls. Thin CLI installations write that instruction to `<ROOT>/GBRAIN-INSTRUCTIONS.md`. Grok Bot/Muse native skill activation remains a separate, visible step until observed in that harness. Generated files alone do not activate a skill.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index ac37ae5a4f..fa452c619e 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -261,6 +261,38 @@ vars — incident-time escape hatches, not everyday knobs.
reads only the filesystem — no database connection — so it keeps working
during the exact outages it exists to diagnose.
+## Several brains on one host
+
+Each brain gets its own autopilot job. The default brain (`~/.gbrain`, that
+is `GBRAIN_HOME` unset or set to your home directory) keeps the shared names:
+launchd label `com.gbrain.autopilot`, systemd unit `gbrain-autopilot.service`,
+start script `~/.gbrain/start-autopilot.sh`, and an unmarked crontab line.
+Any other brain gets names with a suffix: `com.gbrain.autopilot.<suffix>`,
+`gbrain-autopilot-<suffix>.service`, `<brain>/.gbrain/start-autopilot-<suffix>.sh`,
+and a crontab line ending in `# gbrain-autopilot:<suffix>`. The suffix is the
+first 8 hex characters of a random id that `--install` records in
+`<brain>/.gbrain/autopilot-install-id`. Every brain logs to its own
+`<brain>/.gbrain/autopilot.log`.
+
+`gbrain autopilot --status [--json]` prints the brain's job name, suffix,
+install-id path, wrapper path and log path (`job` in `--json`). `--status`
+and `--uninstall` act only on that brain's job.
+
+- **Moving a brain** keeps its id and job. `--status` reports
+ `needs_reinstall: wrapper_missing` until you run
+ `GBRAIN_HOME=<new parent> gbrain autopilot --install`, which repoints the
+ same job.
+- **Copying a brain** (`cp -r`) gives the copy a new id on its first
+ `--install`, so the original brain keeps its job.
+- **Upgrading from an older gbrain**: a non-default brain installed before
+ per-brain names ran under the shared names. `--status` reports
+ `needs_reinstall: legacy_shared_job`; `GBRAIN_HOME=<parent> gbrain autopilot --install`
+ replaces that shared job with the brain's own job and says so.
+- **`autopilot_job_owned_by_other_brain`**: installing the default brain
+ refuses when the shared job still runs another brain. Run the printed
+ `GBRAIN_HOME=<parent> gbrain autopilot --install` for that brain first, then
+ install the default brain again.
+
---
*Part of the [GBrain Skillpack](../GBRAIN_SKILLPACK.md).*
diff --git a/docs/guides/minions-fix.md b/docs/guides/minions-fix.md
index 658c62f57f..44e00697d5 100644
--- a/docs/guides/minions-fix.md
+++ b/docs/guides/minions-fix.md
@@ -27,7 +27,10 @@ existing launch options throughout the repair.
| Autopilot under user systemd | `gbrain autopilot --status --json`; `systemctl --user status gbrain-autopilot.service` | `systemctl --user stop gbrain-autopilot.service` | `systemctl --user start gbrain-autopilot.service` |
| Autopilot under launchd | `gbrain autopilot --status --json`; `launchctl print "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootout "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.gbrain.autopilot.plist"` |
-These are the default user-service names. If the installation uses a different
+These are the default brain's user-service names. A brain under any other
+`GBRAIN_HOME` uses its own suffixed names; `gbrain autopilot --status --json`
+prints them under `job` ([several brains on one host](live-sync.md#several-brains-on-one-host)).
+If the installation uses a different
service definition, use its actual name and recorded launcher. For a foreground
autopilot or a container/cron owner, stop and restart that owner through its
existing launcher; do not start a competing standalone supervisor. A timed-out
diff --git a/docs/guides/multi-source-brains.md b/docs/guides/multi-source-brains.md
index 52538b6401..197c7d0371 100644
--- a/docs/guides/multi-source-brains.md
+++ b/docs/guides/multi-source-brains.md
@@ -115,6 +115,27 @@ behave as you'd expect — every page appears in search.
Flip later with `gbrain sources federate <id>` / `unfederate <id>`.
+### Explicit reads from a bound agent connection
+
+An agent connection started with `GBRAIN_SOURCE=<id>` (or inside a
+directory pinned by `.gbrain-source`) is bound to that source. Its
+unqualified reads stay on the bound source. It may still name another
+source in an explicit `source_id` read (`search`, `query`, `get_page`,
+`list_pages`, `resolve_slugs`, `recall`) when that source is
+`federated=true`; the result holds only the named source's rows. Writes
+still go to the bound source only.
+
+| Refusal hint | Why | Fix (on the brain host) |
+|--------------|-----|-------------------------|
+| `<id> is not federated` | The named source is not federated. | `gbrain sources federate <id>`, or start the connection without the binding. |
+| `<id> opted out of federation` | The named source was unfederated. | `gbrain sources federate <id>` if it should be readable from other sources. |
+| `<bound> opted out of federation …, so it reads no other source` | The bound source itself is isolated (`federated=false`), so it never reads another source. | `gbrain sources federate <bound>`, or start the connection without the binding. |
+| `Your token is not granted <id>` | An HTTP token or OAuth client whose grant does not include the source. | `gbrain auth rescope-client <client_id> --federated-read <ids>` for an OAuth client. |
+
+`search_by_image`, `open_loops` and the code-intel tools keep their stricter
+rule: an explicit `source_id` must be inside the connection's own source or
+grant.
+
## Commands
The most-used subcommands (run `gbrain sources --help` for the full,
@@ -148,8 +169,31 @@ gbrain sources attach <id> Write .gbrain-source in CWD (like kubectl context
gbrain sources detach Remove .gbrain-source from CWD.
gbrain sources federate <id>
gbrain sources unfederate <id>
+gbrain sources mirror-readonly <id>
+gbrain sources mirror-writable <id>
```
+### Read-only mirror sources
+
+A source whose Git remote is the source of truth (a code or docs repository
+you keep current with `git pull --ff-only`) can be marked a read-only mirror:
+
+```bash
+gbrain sources mirror-readonly <id>
+```
+
+On a managed brain, sync then imports canonical metadata (a default title,
+type, tags kept in the brain) into the database only and never writes a file
+back into that checkout, so `git status` stays clean and the next fast-forward
+pull succeeds. A page write into the source (`put_page`, a timeline entry, a
+maintenance write) is stored database-only too; its receipt says
+`storage: "database_only"` with `write_through.skipped: "mirror_read_only"`.
+`gbrain sources list --json` shows `mirror_read_only` per source. Undo it with
+`gbrain sources mirror-writable <id>`; files are written again from the next
+write on, except for pages created while the source was a mirror: those have
+no file in the checkout and stay database-only. Git effects of a mirror's
+writes (for example a `forget`) complete as skipped. The flag is off by default.
+
## The git requirement for --path sources
Every `--path` source must be a git repository (or live inside one — a
diff --git a/docs/guides/open-loops.md b/docs/guides/open-loops.md
index 2ac87cfae6..82889baaa5 100644
--- a/docs/guides/open-loops.md
+++ b/docs/guides/open-loops.md
@@ -24,6 +24,10 @@ zero LLM, free, always on). For every synced Gmail thread:
≥72h → `unanswered_outbound` — *you are waiting on them*.
- a reply lands → the loop **closes itself** (`closed_by: reply_detected`).
Loops close by state transition, never delete — the audit trail stays.
+- "unanswered" is measured from the oldest unanswered message since the
+ last turn flip (the first one addressed to you, or your first question),
+ so a nudge or follow-up never restarts the clock — a request that waited
+ 40h and got a "bumping this" 5h ago opens on the first sync.
Precision rules (pinned by a labeled fixture corpus in
`test/google-loop-detect.test.ts` — every false-positive class gets a
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 62160df746..f0ae7f4f7d 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -6,6 +6,8 @@ visibility, pages indexed before the safe-chunk fence, pages imported
without a contextual retrieval mode, and connector checkpoint rows no source
can load. `gbrain repair` fixes those five kinds. Every run is a preview
unless you pass `--apply`.
+Two explicit-only kinds, `stale-atoms` and `extractor-facts`, run only when
+you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs` runs them under a budget
(see [Run repairs through doctor](#run-repairs-through-doctor)).
@@ -18,7 +20,7 @@ agent runs `gbrain repair` to preview and, after you agree,
## Preview first
```bash
-gbrain repair # preview every kind
+gbrain repair # preview every automatic kind
gbrain repair timeline # preview one kind
gbrain repair --json # machine-readable preview
```
@@ -60,7 +62,7 @@ gbrain repair safe-chunks --apply
gbrain repair safe-chunks --apply --no-embed # re-seal text now, embed later
gbrain repair contextual-mode --apply
gbrain repair request-indexes --apply
-gbrain repair --all --apply # every kind in order
+gbrain repair --all --apply # every automatic kind in order
```
`--apply` writes without a prompt, so review the preview first. With
@@ -70,12 +72,22 @@ refused run changes nothing. To cap paid embedding work, run the repairs
through `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. `--all`
runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, then `request-indexes`, then `connector-fences`, then `orphan-bindings`, then `embedding-effects`, and stops at the
first kind that stops.
+The explicit-only kinds (`stale-atoms`, `extractor-facts`) never run under
+`--all`; it lists each with its preview command and still exits 0 when they
+are the only findings left. `gbrain repair` with no kind does the same for a
+preview. With `--json` the list is `explicit_kinds[]` (`kind`, `code:
+"explicit_kind_required"`, `preview_command`, `docs`).
Each item is re-checked against the page's current state just before it is
written, and the write is bound to the revision it just read, so an edit made
after planning is kept and repaired too. An item that no longer needs the
repair, or whose page changes during the write, is counted as `skipped` and
-left for the next run. Nothing is deleted.
+left for the next run. No kind deletes data except `stale-atoms`, which
+soft-deletes the atoms it retires (they stay recoverable through the
+`restore_page` operation for 72 hours, and a later extraction that produces
+a retired atom again restores it). See [Stale atoms](#stale-atoms).
+`extractor-facts` only restores previewed facts (it clears `expired_at` and
+gives each a fresh row number); it never deletes or rewrites a page.
| Option | Effect |
| --- | --- |
@@ -83,8 +95,10 @@ left for the next run. Nothing is deleted.
| `--source <id>` | Limit the run to one active source. The default is every active (non-archived) source. An unknown or archived id is refused. |
| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. |
| `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. |
-| `--all` | Run every kind in order. |
-| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`. |
+| `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |
+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms` and `extractor-facts`. |
+| `--include-ambiguous` | `extractor-facts` only: widen the hashed set to `ambiguous` facts. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts). |
+| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`, plus `explicit_kinds[]` when the run skipped explicit-only kinds. |
The command exits 1 when a run stops early (capacity, a pending write, or a
held writer). A `--limit` batch that leaves work behind exits 0, so scripts
@@ -103,6 +117,8 @@ should also check `results[].complete`.
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |
| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |
+| `stale-atoms` (explicit-only) | `atom_provenance_drift` | Retires, by soft delete, live page-bound atoms whose source page is gone (`origin_gone`), or whose source page was edited and its current text already extracted (`origin_changed`). Preview-bound: `--apply --expect <hash>` retires exactly the previewed set. See [Stale atoms](#stale-atoms). | Atoms with `imported_from`, transcript (file-bound) atoms, and atoms of an edited page that was not extracted again yet (the `extract_atoms` backlog). |
+| `extractor-facts` (explicit-only) | `extractor_facts_expired` | Restores conversation-extractor facts the pre-v0.60.11.0 canonical projection expired (#5731). Restores `evidenced` facts by default, `ambiguous` ones only with `--include-ambiguous`; database-only. See [Extractor facts](#extractor-facts). | `excluded:<reason>` facts: page missing or deleted, superseded, withdrawn, an active duplicate, or a duplicate candidate. |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
@@ -203,6 +219,63 @@ one more year, the same value `persistence_capacity` prints) and the check to
re-run. Request IDs are permanent, so raising the limit is the intervention;
nothing is evicted.
+<a id="projection-drain"></a>
+### Drain queued text projections
+
+After an upgrade that re-queues text projections (for example the 0.51
+protocol activation), search and code results stay incomplete until every
+queued Markdown and code page is rebuilt (#5401). Doctor
+`text_projection_readiness` warns while any visible page is pending.
+
+The upgraded resident owner (`gbrain serve` or autopilot) drains the queue on
+its own: each pass rebuilds up to 100 pages and starts no new page after
+250 ms, and takes 2 pages while writes are waiting. A page whose rebuild fails
+is retried after 30 seconds.
+
+To drain now:
+
+```bash
+gbrain projections drain # until every page queued at the start was tried once
+gbrain projections drain --limit 5000
+gbrain projections drain --json # {rebuilt, superseded, failed: [{source_id, slug, reason}], remaining}
+```
+
+| Exit | Meaning |
+| --- | --- |
+| 0 | Nothing tried failed. "The projection backlog is empty." appears only when `remaining` is 0. |
+| 1 | Some pages failed. Each prints `failed: <source>/<slug>: <reason>` and a `next:` action; the pages stay queued. |
+| 2 | Did not run: bad usage (`invalid_params`), or [`projection_owner_resident`](#projection-owner-resident). |
+
+On Postgres the drain is safe while `gbrain serve` runs: each page is rebuilt
+under its page lock with a revision recheck, so a page is rebuilt once whichever
+process gets there first. On PGLite a resident process holds the datastore, so
+the drain refuses before opening it (also for a mounted PGLite brain selected
+with `--brain`).
+
+Verify: `gbrain doctor` shows `text_projection_readiness` ok.
+
+<a id="embedding-key-source"></a>
+### Provider key source
+
+An exported provider key (for example `OPENAI_API_KEY`) wins over the matching
+config key (`openai_api_key` in `~/.gbrain/config.json`) (#5137). When both are
+set and differ, every gbrain command except `gbrain hook` prints one warning
+per process naming the variable, the config key and which one is in effect.
+No key or part of one is ever printed.
+
+- To use the config key: remove the variable from the environment of the
+ process that printed the warning (shell profile, `~/.gbrain/.env`, or for a
+ daemon its service definition) and restart that process.
+- If the environment key is intended: `gbrain config unset openai_api_key`
+ (or the matching key), which also stops the warning.
+
+Doctor `embedding_key_source` reports the same plus where the embedding key in
+effect comes from. It sees only the environment `gbrain doctor` runs in: a
+daemon has its own and reports a mismatch in its log, with the startup warning
+or `embedding_auth_failed` on the first rejected embedding
+([write refusals](write-refusals.md#embedding_auth_failed)). After fixing a
+rejected key, `gbrain embed --stale` embeds what was saved meanwhile.
+
<a id="connector-held-items"></a>
### Connector held items
@@ -238,6 +311,90 @@ Do not delete binding rows by hand: the repair rechecks, in the same
statement, that the binding is still orphaned and that no pending write
request uses it.
+### Stale atoms
+
+`gbrain repair stale-atoms` (explicit-only, #5770) retires atoms that drifted
+before managed re-extraction learned to retire them. It lists live atoms bound
+to a source page (`source_slug`) in two classes:
+
+- `origin_gone`: the source page is missing or deleted;
+- `origin_changed`: the source page was edited, and its current text has
+ already been extracted (a managed brain records a completed extraction at
+ the page's current hash; an unmanaged brain has an atom carrying it). Atoms
+ of an edited page that was not extracted again yet are the extract_atoms
+ backlog, not stale, and are not listed.
+
+It never lists an atom with `imported_from` or a transcript (file-bound)
+atom.
+
+```bash
+gbrain repair stale-atoms --source <id> # preview: every atom with its class, and a hash
+gbrain repair stale-atoms --source <id> --apply --expect <hash>
+```
+
+The apply retires exactly the previewed set. Each atom is checked again first;
+one whose revision, class, source page or completion evidence changed since
+the preview reports `changed_since_preview` and is kept. Retiring is a soft
+delete stamped with `retired_by: stale-atoms`: on a managed brain each atom is
+one coordinated request (its file is removed through the page deletion path),
+on an unmanaged brain a direct soft delete. Retiring also marks the source
+page for extraction again, so restoring a deleted page and running
+`extract_atoms` brings its atoms back. `--apply` without `--expect` refuses
+with the preview and apply commands; a stale hash refuses with
+[`preview_changed`](#preview-changed). An apply under a different `--source`
+than the preview also refuses with `preview_changed`. Doctor
+`atom_provenance_drift` names this command when drift crosses its warn
+threshold.
+
+### Extractor facts
+
+Before v0.60.11.0, every managed write to a conversation page without a
+Facts fence expired all of that page's conversation-extractor facts
+(`expired_at` set, `row_num` cleared), and recall stopped returning them.
+`gbrain repair extractor-facts` (#5731) restores them. It is explicit-only and
+preview-bound.
+
+```bash
+gbrain doctor # extractor_facts_expired
+gbrain repair extractor-facts # preview: every candidate with its class
+gbrain repair extractor-facts --apply --expect <hash>
+gbrain doctor
+```
+
+Each candidate gets one class:
+
+| Class | Meaning | Restored |
+| --- | --- | --- |
+| `evidenced` | A committed write of the page completed in the same transaction that expired the fact (`completed_at = expired_at`), and its consumer was older than v0.60.11.0 (no version stamp, or an older one). | By `--apply --expect <hash>` |
+| `ambiguous` | Unmanaged brain (no receipts); no committed write at the exact expiry instant; the expiring write came from a fixed consumer (a fence row may legitimately have taken the fact's position); or the page has carried fence facts. | Only with `--include-ambiguous` and that preview's hash |
+| `excluded:<reason>` | Page missing or deleted, superseded (`superseded_by`), withdrawn (`forget`), an active fact with the same text and entity already on the page, or an earlier candidate with the same text and entity. | Never |
+
+Ambiguous rows are restored as the hashed set; `--limit` is the only
+narrowing. Run `gbrain repair extractor-facts --include-ambiguous`, review
+the list, then `gbrain repair extractor-facts --include-ambiguous --apply
+--expect <hash>`.
+
+The apply restores exactly the previewed set. A fact that changed since the
+preview (edited, withdrawn, superseded, its page deleted or recreated)
+reports `changed_since_preview` and stays expired; `preview_changed` means
+the hash names no saved preview, the preview is older than 7 days, or the
+apply's `--source` / `--include-ambiguous` differs from the preview's.
+Restored facts get a fresh row number above the page's rows. Nothing is
+written to any page or file. On a managed brain each page publishes one
+database-only `managed_maintenance_restore_extractor_facts` request; a
+rerun after a crash replays it and restores no new candidate.
+
+Receipts are retained (compaction keeps `completed_at`), so a history older
+than the 30-day receipt retention is still evidenced. Not recoverable
+automatically: facts whose extractor batch was since replaced by a
+re-extraction (the old rows are gone), and facts on unmanaged brains without
+`--include-ambiguous`. On PGLite the same-transaction rule holds only to the
+millisecond (PGLite's clock resolution).
+
+The preview warns, naming the host, when a consumer older than this release
+published writes after `writer_version_cutoff`: an old consumer expires
+restored facts again. Upgrade and restart it first.
+
## Resume
Runs are resumable. After each page commits, the position is saved under the
@@ -320,6 +477,13 @@ Apply everything after the user agrees: gbrain doctor --remediate --yes --includ
Ask the user before applying any repair step.
```
+The plan never includes an explicit-only kind as a repair step. It prints them
+in an `Explicit-only repairs` block instead, one line per kind with its
+read-only preview command (`stale-atoms: gbrain repair stale-atoms`), and
+`--json` lists them as `explicit_repairs[]` (`kind`, `code:
+"explicit_kind_required"`, `preview_command`, `docs`). Run each by name after
+the user agrees (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
+
`gbrain doctor --remediate --yes` runs job steps only. Repair steps run only
when you also pass `--include-repairs`, which records the user's agreement;
without it they are listed as `N repair steps skipped (user agreement required):
@@ -370,11 +534,12 @@ With `--json`, the result adds `repairs[]` (one entry per repair step, with
| `pending` | A repairable finding remains: its step stopped, was refused by the budget, left items behind, or the check could not run. |
| `consent_required` | A repairable finding whose step was skipped for lack of `--include-repairs`; `command` applies it. |
| `operator_required` | Needs a named manual action on the brain host (`instruction`), for example raising a journal limit, retrying a parked effect, or quarantining self-captures. |
+| `explicit_kind_required` | Only an explicit-only kind clears it (for example `atom_provenance_drift` and `stale-atoms`); `command` is that kind's read-only preview. It never runs under `--remediate` and does not fail the exit status. |
| `unsupported` | No command can clear it yet; it is reported so it is never hidden (a stale queued embedding effect). |
Exit status: `0` when no automatically repairable finding remains and no step
-failed, even if operator-required or unsupported findings remain (they are
-listed); `1` when a repairable finding remains, a step failed, or the budget
+failed, even if operator-required, explicit-only or unsupported findings
+remain (they are listed); `1` when a repairable finding remains, a step failed, or the budget
ran out; `2` when the score target is unreachable and there was no repair step
to run, or a resume was refused. `healthy` is true only when every wave check
is clean; `repairs_completed` counts the repair steps that finished.
@@ -412,7 +577,69 @@ as one line each, for example
A line that says `Unknown:` means the check could not run; it is not a clean
result. Ask the brain host's operator to run the steps above.
-### Symptoms from the lifecycle fixes in this release
+<a id="fix-wave-5"></a>
+### Upgrading to v0.60.28.0 (fix wave 5)
+
+**Say to your agent:** *"We upgraded gbrain to v0.60.28.0. Restart everything
+that runs it, then walk me through what doctor finds, in order, before
+changing anything."*
+
+Most wave 5 fixes take effect only in a process that runs the new binary, so
+restart first. `gbrain sources writer status --json` lists, in
+`writer_versions[]`, the latest version each host and principal was seen
+writing with in the retained requests. That is history, not proof: an idle
+older `gbrain serve` never shows up there. Restart in this order:
+
+1. Stop autopilot and workers (`gbrain autopilot --status` names the job;
+ `gbrain jobs work` or your supervisor for workers).
+2. Stop each resident `gbrain serve`: HTTP services through their service
+ manager, and harness-owned stdio servers by quitting the harness.
+3. Upgrade each host: `gbrain upgrade`.
+4. Run `gbrain --version` through each launcher's own binary path (the path in
+ the service definition, the harness MCP command, the hook commands) and
+ confirm it prints `0.60.28.0`.
+5. Restart services, harnesses, workers and autopilot.
+6. Make one write from each host, then confirm a fresh `last_seen` for that
+ host in `gbrain sources writer status --json` (`writer_versions[]`).
+
+Then recover what doctor names, in this order (skip a step whose check is ok):
+
+1. `gbrain doctor`.
+2. Legacy jobs (`legacy_job_authority`): see
+ [Legacy job authority](#legacy-job-authority).
+3. Projections (`text_projection_readiness`): `gbrain projections drain`
+ (Postgres, or PGLite with no resident); on PGLite with a resident, let it
+ drain or stop, drain and restart it. See
+ [Drain queued text projections](#projection-drain).
+4. Stale atoms (`atom_provenance_drift`): `gbrain repair stale-atoms --source <id>`,
+ then after the user agrees `gbrain repair stale-atoms --source <id> --apply --expect <hash>`.
+5. Extractor facts (`extractor_facts_expired`): `gbrain repair extractor-facts`,
+ then after the user agrees `gbrain repair extractor-facts --apply --expect <hash>`
+ (add `--include-ambiguous` to both for ambiguous facts). See
+ [Extractor facts](#extractor-facts).
+6. `gbrain doctor` again, then `gbrain doctor --remediation-plan` for the
+ automatic kinds.
+
+| Symptom | Check or code | Issue | Preview | Apply | Verify |
+| --- | --- | --- | --- | --- | --- |
+| synthesize fails every run; `POST /ingest` 409 (was 500); workers refuse to start with "legacy jobs have missing or unsupported authority" | `legacy_job_authority` / `permission_denied` ([legacy job authority](#legacy-job-authority)) | #5157, #5114 | stop `gbrain serve`, autopilot and workers; `gbrain jobs cancel <active id>`; `gbrain jobs authorize-legacy --select "status=waiting\|delayed\|waiting-children\|paused"` | `gbrain jobs authorize-legacy --select "<same filter>" --expect <hash> --yes`, then restart | `gbrain doctor` shows `legacy_job_authority` ok; `/ingest` returns 202 |
+| Search returns atoms quoting text a page no longer has, or atoms of deleted pages | doctor `atom_provenance_drift` | #5770 | `gbrain repair stale-atoms --source <id>` | `gbrain repair stale-atoms --source <id> --apply --expect <hash>` | `gbrain doctor` (`atom_provenance_drift` drops by the retired count) |
+| `sources add`, `claim`, `rebind`, `archive`, `remove`, clone, reclone or `sources writer transfer` on a repo with more than ~10k files fails with "The verified source manifest exceeds the 1 MiB administration metadata bound" | `request_too_large` | #5790 | none: upgrade and restart every writer host and resident `gbrain serve` | Re-run the failed command (with the same `--request-id` if you kept it) | `gbrain sources writer status --json` shows the source bound, and its `manifest_digest` is set |
+| A stdio agent bound with `GBRAIN_SOURCE` (or `.gbrain-source`) gets `permission_denied` naming the binding when it passes `source_id` | `permission_denied` (hint starts "This connection is bound to source …") | #5081 | `gbrain sources list` (the source must show `federated`, not `isolated` or `unset`) | `gbrain sources federate <id>` on the brain host | Repeat the read with `source_id: "<id>"`; it returns only that source's rows. See [explicit reads from a bound agent connection](multi-source-brains.md#explicit-reads-from-a-bound-agent-connection) |
+| A new session's start-up context showed another session's text (`Last session activity: …`) | none | #5558 | none | Upgrade the `gbrain` each harness runs its hooks with and restart the harness. If you set `GBRAIN_HOOKS=0` as a workaround, remove it from the environment the harness starts from (shell profile or service) and restart the harness again | A new session shows no `Last session activity` line, and `gbrain doctor` reports `bootstrap_hooks_heartbeat` again after a few turns (capture and session persistence are back) |
+| `connect --harness codex\|claude-code\|opencode --install` stored the bearer token inline in the harness config without telling you | receipt `token_storage: "inline"` | #5775 | On the brain host: `gbrain mcp admin invalidate-tokens <client_id> --url <mcp_url> --admin-token-file <owner-admin-token-file> --json` (only if the config file was exposed) | `gbrain mcp admin invalidate-tokens <client_id> --yes --if-version <revision> --url <mcp_url> --admin-token-file <owner-admin-token-file> --json`, then `gbrain connect <mcp_url> --harness <harness> --credentials-file <handoff> --install --fresh-token`, then reload the harness | The new receipt prints `token_storage`, `config_path`, `renew_command` and `if_exposed`, and the harness answers a memory round trip |
+| A second brain's autopilot replaced the first one's job, logs interleave in `~/.gbrain/autopilot.log`, or `gbrain autopilot --status --json` shows `job.needs_reinstall: "legacy_shared_job"` (or `"wrapper_missing"` after moving a brain); install refuses with `autopilot_job_owned_by_other_brain` | `gbrain autopilot --status --json` (`job.*`) / `autopilot_job_owned_by_other_brain` | #5195 | `GBRAIN_HOME=<brain parent> gbrain autopilot --status --json` | `GBRAIN_HOME=<brain parent> gbrain autopilot --install` (every non-default brain first, then the default brain) | `GBRAIN_HOME=<brain parent> gbrain autopilot --status --json` shows `job.needs_reinstall: null` and the brain's own `launchd_label` / `systemd_unit`. See [several brains on one host](live-sync.md#several-brains-on-one-host) |
+| `gbrain serve` started in a `.gbrain-mount` project: CLI writes fail `owner_unavailable` and MCP writes stay `queued` | `owner_unavailable` | #5237 | none | Upgrade and restart the resident `gbrain serve` (the harness that spawns it) | `gbrain sources writer status --probe --json` from the project answers |
+| Backup coverage reports `remote evidence: unavailable` for a private remote that is pushed | doctor `backup_coverage` | #5794 | none | Upgrade, then `gbrain backup check` | `gbrain backup status --json` shows `verification.state: "verified"`; see [remote unavailable](../operations/backup-check.md#remote-unavailable) |
+| On Windows, a write or `gbrain sync` refuses a colon slug such as `calendar:abc` | [`colon_slug_windows_write_through`](write-refusals.md#colon_slug_windows_write_through) | #5032 | none | Use a slug without `:`, or write the page from a macOS or Linux host that owns the source | The write succeeds, or `gbrain sync` no longer lists the file |
+| Search empty or incomplete after upgrading; doctor `text_projection_readiness` warns | `text_projection_readiness` | #5401 | `gbrain doctor` (pending count, also while a PGLite resident runs) | `gbrain projections drain` (Postgres, or PGLite with no resident); on PGLite with a resident, wait or stop, drain and restart per [projection owner resident](#projection-owner-resident) | `gbrain doctor` shows `text_projection_readiness` ok |
+| `Error [projection_owner_resident]` from `gbrain projections drain` (exit 2) | [`projection_owner_resident`](#projection-owner-resident) | #5401 | `gbrain doctor` | the printed stop, drain and restart commands | `gbrain doctor` |
+| `[gbrain] warning: OPENAI_API_KEY in this process's environment differs from openai_api_key …`; doctor `embedding_key_source` warns | `embedding_key_source` ([provider key source](#embedding-key-source)) | #5137 | `gbrain doctor` (`embedding_key_source`) | remove the variable and restart that process, or `gbrain config unset openai_api_key` | the warning no longer prints; `gbrain doctor` shows `embedding_key_source` ok |
+| `The OpenAI embedding provider rejected its key (HTTP 401)` | [`embedding_auth_failed`](write-refusals.md#embedding_auth_failed) | #5137 | `gbrain doctor` (`embedding_key_source`, `embedding_provider`) | the printed fix for the key source in effect, then `gbrain embed --stale` | `gbrain doctor` shows `embedding_provider` ok |
+| Conversation facts missing from recall after managed writes | `extractor_facts_expired` | #5731 | `gbrain repair extractor-facts` | `gbrain repair extractor-facts --apply --expect <hash>` (ambiguous: add `--include-ambiguous` to both) | `gbrain doctor` |
+
+
+### Symptoms from the lifecycle fixes in v0.60.20.0
| Symptom or error text | Issue | Preview | Apply | Verify |
| --- | --- | --- | --- | --- |
@@ -491,6 +718,122 @@ covers the whole retry budget each grant authorizes. A resumed run replays the
grant it already made instead of granting another cycle. A signature-mismatched
vector is never reconciled; it is re-embedded.
+## Wave 5 refusal codes
+
+Each heading below is the `docs` anchor a refusal carries.
+
+### Explicit-only repair kinds
+
+`stale-atoms` and `extractor-facts` run only when named:
+`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply --expect <hash>`
+applies exactly the previewed set. They are excluded everywhere else:
+
+- `gbrain repair --all` (and `gbrain repair` with no kind) lists each with its
+ preview command (`--json`: `explicit_kinds[]`) and never runs it. A
+ `--all --apply` run exits 0 when only explicit-only kinds remain.
+- `gbrain doctor --remediation-plan` prints them in an `Explicit-only repairs`
+ block (`--json`: `explicit_repairs[]`, each `{kind, code:
+ "explicit_kind_required", preview_command, docs}`), never as a repair step.
+- `gbrain doctor --remediate --include-repairs` classifies a finding only an
+ explicit-only kind clears as `explicit_kind_required`, with the preview as
+ its `command`. That class does not fail the exit status.
+- The `gbrain post-upgrade` banner prints such a finding as
+ `<check>: N (explicit_kind_required; preview with: gbrain repair <kind>)`.
+
+A remediation step or any other runner that reaches an explicit-only kind
+without its name refuses with `explicit_kind_required`. A build that does not
+implement the kind refuses with `unavailable`.
+
+### Preview changed
+
+`preview_changed`: the hash passed with `--expect` names no saved preview, the
+saved preview is older than 7 days, or the selection no longer matches it (for
+`stale-atoms`, a different `--source`). Nothing was applied. The message reads
+"The preview changed since <hash>; re-run <preview command> and use the new
+hash." Re-run the printed preview command and apply with the new hash. It
+applies to `gbrain jobs authorize-legacy --select`, `gbrain jobs cancel
+--select`, `gbrain repair stale-atoms` and `gbrain repair extractor-facts`.
+
+### Legacy job authority
+
+`permission_denied` with this anchor means a queued job row has SQL NULL
+`submission_authority`, left by an upgrade across v0.50 (#5157, #5114).
+
+- A resubmission over a **dead or cancelled** legacy key releases the key and
+ queues a fresh job. No step needed.
+- A **completed or failed** legacy row is reused by local producers (synthesize,
+ autopilot, `POST /ingest`). No step needed. A remote `submit_job` caller is
+ refused and resubmits with a new idempotency key.
+- A **live** legacy row (waiting, delayed, waiting-children, paused, active)
+ blocks every worker, so nothing reuses it. `POST /ingest` returns 409
+ `{error, message, hint, docs_url}`, never 500.
+
+`gbrain doctor` (`legacy_job_authority`) counts exactly the rows that block workers,
+split into authorizable (SQL NULL) and unsupported (non-NULL) rows, and prints the
+filled commands. Recovery, in order:
+
+1. Stop producers and workers: the resident `gbrain serve`, `gbrain autopilot`,
+ `gbrain jobs work` / supervisor.
+2. Cancel each active job the hint or doctor names: `gbrain jobs cancel <id>`.
+ (Stall and timeout sweeps are behind the same gate, so an orphaned active row
+ never finishes on its own.)
+3. Preview: `gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"`
+ (narrow with `,name=<job>|<job>`). It lists counts by job name and status, the
+ first 20 ids, marks paid-provider job names, and prints a hash. `--json` has the full rows.
+4. Apply exactly that set with the printed command:
+ `gbrain jobs authorize-legacy --select "<same filter>" --expect <hash> --yes`.
+ To drop work instead, `gbrain jobs cancel --select "<filter>"` previews and its
+ printed `--expect <hash> --yes` cancels exactly the previewed set.
+5. Unsupported non-NULL rows cannot be authorized: run matching application and
+ database versions, or cancel them (`gbrain jobs cancel <id>`, as doctor lists).
+6. Restart producers and workers. Verify: `gbrain doctor` shows
+ `legacy_job_authority` ok; `POST /ingest` returns 202.
+
+### Legacy jobs active
+
+`legacy_jobs_active`: `authorize-legacy --select`/`--ids` or `jobs cancel --select`
+found active jobs. Legacy review needs nothing active. Stop producers
+(`gbrain serve`, `gbrain autopilot`) and workers, cancel the listed jobs
+(`gbrain jobs cancel <id>`; the refusal lists up to 10, the rest with
+`gbrain jobs list --status active`), then re-run the preview it names.
+
+### Legacy job selection invalid
+
+`legacy_job_selection_invalid`: `--select` named an unknown key or value, a
+flag combination was wrong (`--ids` with `--select`; apply without both
+`--expect <hash>` and `--yes`), a selected row no longer exists or is not SQL
+NULL, or a `jobs cancel --select` selection would also cancel a job outside it
+(the message names those ids; cancel them on purpose or widen the filter). The
+grammar is `--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"`; the
+message lists the valid statuses, and the hint is a complete example.
+
+### Projection owner resident
+
+`projection_owner_resident` (exit 2): `gbrain projections drain` did not run
+because a gbrain process (named with its pid) holds this PGLite brain. Nothing
+changed. The upgraded resident drains the queue itself; re-run `gbrain doctor`
+to watch the pending count in `text_projection_readiness` (doctor asks the
+resident over its local socket, so the count shows while the resident runs; a
+resident that does not answer may predate this release and should be restarted
+on the upgraded gbrain).
+
+To drain faster, stop the owner, drain, then restart it. The restart runs
+whether or not the drain failed:
+
+| Owner | Stop, drain, restart |
+| --- | --- |
+| `gbrain serve` service, launchd | `launchctl bootout gui/$(id -u)/com.gbrain.serve && { gbrain projections drain; launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.gbrain.serve.plist; }` |
+| `gbrain serve` service, systemd | `systemctl --user stop gbrain-serve.service && { gbrain projections drain; systemctl --user start gbrain-serve.service; }` |
+| autopilot, launchd | `launchctl bootout gui/$(id -u)/com.gbrain.autopilot && { gbrain projections drain; launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.gbrain.autopilot.plist; }` |
+| autopilot, systemd | `systemctl --user stop gbrain-autopilot.service && { gbrain projections drain; systemctl --user start gbrain-autopilot.service; }` |
+| a manual `gbrain serve` | stop it (`kill <pid>`), run `gbrain projections drain`, then start `gbrain serve` again |
+
+The rows above show the default brain's names. The refusal prints these
+commands filled in: with `--brain <id>` for a mounted brain, and with this
+brain's own autopilot job (or the shared job an older install still runs it
+from) for a brain under another `GBRAIN_HOME`. The autopilot launchd label
+follows `GBRAIN_AUTOPILOT_LABEL` when set.
+
## Related
- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery command
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 1b10b09aa2..49e2b09b89 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -60,6 +60,8 @@ of making a duplicate.
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
+| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
+| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
### Other error codes
diff --git a/docs/mcp/CLAUDE_CODE.md b/docs/mcp/CLAUDE_CODE.md
index 8bf00f4c0a..1517391394 100644
--- a/docs/mcp/CLAUDE_CODE.md
+++ b/docs/mcp/CLAUDE_CODE.md
@@ -180,7 +180,10 @@ sub-second, world-visibility by default, and available on `--surface verbs`.
installer wires `SessionStart` (injects a warm pack; also fires on
post-compaction re-entry, `source=compact`) and `PreCompact` (banks the
window's standing entities so that rehydration pack is warm) into
- `.claude/settings.local.json`. Nothing to call; `GBRAIN_HOOKS=0` disables.
+ `.claude/settings.local.json`. Nothing to call; `GBRAIN_HOOKS=0` disables
+ every hook event, including capture. Session start never shows another
+ session's activity: the `Last session activity` line older releases printed
+ was removed in v0.60.28.0 (#5558), with deliberately no opt-in to restore it.
- **Manual (any brain, incl. remote/Postgres):** call the verbs yourself at
boundaries — `context_pack(entities, budget_tokens)` at session start /
after compaction, `delta(session_id, budget_tokens)` on wakes. See
diff --git a/docs/mcp/CODEX.md b/docs/mcp/CODEX.md
index d3ff7f82f4..04671d01cc 100644
--- a/docs/mcp/CODEX.md
+++ b/docs/mcp/CODEX.md
@@ -89,12 +89,29 @@ binary the launcher resolves.
Recent versions of the Codex CLI (`@openai/codex`) support remote
streamable-HTTP MCP servers with a bearer token read from an environment
-variable. On THIS page's `gbrain connect` path the token lives in your shell
-env, not in Codex's config file. The exception is `gbrain bootstrap harness`
-(local agent-framework boxes): framework-spawned codex inherits no shell
-profile, so that lane writes the token INLINE into a managed, 0600
-`[mcp_servers.gbrain]` block in the codex config — stated in its consent
-block, removable with `gbrain bootstrap harness --remove`.
+variable. Where the token lives depends on the path:
+
+| Path | Where the bearer token lives |
+| --- | --- |
+| `gbrain connect <url> --token <token> --agent codex [--install]` (this page) | Your shell environment (`GBRAIN_REMOTE_TOKEN`); Codex's config stores only the variable name. |
+| `gbrain connect <url> --harness codex --credentials-file <handoff> --install` (the [machine handoff](../guides/hosted-harness-access.md)) | **Inline** in a managed, 0600 `[mcp_servers.<name>]` block in `~/.codex/config.toml`. |
+| `gbrain bootstrap harness` (local agent-framework boxes) | **Inline** in the same managed block; stated in its consent block, removable with `gbrain bootstrap harness --remove`. |
+
+The inline paths exist because framework-spawned Codex inherits no shell
+profile. Anything that reads or prints that config file (support bundles,
+config diffs, agents inspecting MCP entries) can see a live token. The
+`--harness codex --install` receipt says so: `token_storage: "inline"`,
+`config_path`, the `renew_command` that writes a fresh token (with
+`--fresh-token`, so it exchanges a new token instead of reinstalling an
+unexpired cached one), and `if_exposed`, which lists the
+[token invalidation](ADMIN.md#invalidate-tokens-revoke-or-delete) preview and
+apply commands for the brain host, then the renew command (a handoff without a
+client secret needs a new handoff from the owner instead), then the Codex
+reload. When the config file sits in a Git working tree that does not
+ignore it, the receipt adds `token_warning`: add the file to that repository's
+`.gitignore` or move the config, and follow `if_exposed` if it was already
+committed. Rotating a client secret does not invalidate access tokens already
+issued, so it is not the fix for an exposed token.
## Fastest path: `gbrain connect`
diff --git a/docs/operations/backup-check.md b/docs/operations/backup-check.md
index be553cd3a5..be23e929b7 100644
--- a/docs/operations/backup-check.md
+++ b/docs/operations/backup-check.md
@@ -114,6 +114,29 @@ a clean tree. Roots beyond the budget report `budget_exhausted`; successive
sweeps can cover them. Background and stdio refreshes use local probes only;
remote MCP doctor reads aggregate cache only, with no engine or Git access.
+### Remote verification and your Git configuration
+
+The probe runs `git` with an allowlist of your environment, so it reads your own
+`~/.gitconfig`, credential helpers and `url.<base>.insteadOf` rewrites:
+`HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`,
+`HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY` (upper and lower case), plus
+`USERPROFILE`, `APPDATA` and `SystemRoot` on Windows. It never passes `GIT_DIR`,
+`GIT_WORK_TREE` or any other variable, and it always disables prompts.
+
+A deploy key works through `~/.ssh/config` (`Host` with `IdentityFile`). The
+probe sets its own `GIT_SSH_COMMAND` (`ssh -oBatchMode=yes
+-oStrictHostKeyChecking=yes -oConnectTimeout=2`), so a `GIT_SSH_COMMAND` you
+export is not used, and the remote's host key must already be in `known_hosts`.
+
+| `verification.state` | Meaning | What to do |
+|---|---|---|
+| `verified` | The remote branch HEAD matches a clean local HEAD. | Nothing. |
+| `missing_ref` | The remote answered but has no such branch. | `git push -u origin <branch>`, then `gbrain backup check`. |
+| `mismatch` | The remote HEAD differs from the local HEAD, or the tree changed during the probe. | Push or pull until they match, then `gbrain backup check`. |
+| <a id="remote-unavailable"></a>`unavailable` | `git ls-remote` failed: no network, authentication refused, or an unknown host key. The probe passes only `HOME`, `PATH`, `XDG_CONFIG_HOME`, `SSH_AUTH_SOCK`, `GIT_CONFIG_GLOBAL`, `HTTPS_PROXY`/`https_proxy`, `HTTP_PROXY`/`http_proxy`, `NO_PROXY`/`no_proxy` (and `USERPROFILE`, `APPDATA`, `SystemRoot` on Windows). | Run `git -C <root> ls-remote origin` in the same shell; credentials must come from your Git config, a credential helper, `~/.ssh/config` or the SSH agent, not from a prompt or `GIT_SSH_COMMAND`. |
+| `budget_exhausted` | The sweep's eight-probe or eight-second budget ran out first. | Run `gbrain backup check` again. |
+| `stale`, `not_checked` | Earlier evidence expired or no probe ran yet. | `gbrain backup check`. |
+
When does the compute actually run? On any of: `gbrain backup check`, a stale
cache at `backup status`/doctor/advisor time, `gbrain sync` completion, the
serve process (stdio only) when the cache is stale or a warn verdict is >24h
diff --git a/llms-full.txt b/llms-full.txt
index 2024d108fd..3d8c85bc44 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -1428,7 +1428,7 @@ gbrain connect https://your-machine.your-tailnet.ts.net/mcp --harness codex \
For Grok Bot, Muse, or another supported thin CLI adapter, also supply `--root /absolute/verified/persistent-root`. Grok Bot's recommended root is `/workspace/gbrain`. Discover and verify Muse's durable location before choosing a root. Use the generated **absolute launcher** for every later GBrain call; it pins routing and isolates inherited configuration.
-The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
+The installer preserves unrelated configuration and refuses an unowned or edited connection. Codex, Claude Code, and opencode receive private managed configuration (mode 0600) with the bearer token stored **inline** in that file: `~/.codex/config.toml`, Claude Code's user MCP config, or opencode's global config. The receipt names it with `token_storage: "inline"` and `config_path`, gives the `renew_command` that exchanges and writes a fresh token (`--install --fresh-token`), and lists `if_exposed`: preview and apply `gbrain mcp admin invalidate-tokens <client_id>` on the brain host ([invalidate tokens](../mcp/ADMIN.md#invalidate-tokens-revoke-or-delete)), run the renew command, which exchanges a new token instead of reusing the cached invalidated one (a handoff without a client secret needs a new handoff from the owner), then reload the harness. Neither the receipt nor the output prints the token. Treat that config file as a secret: when it sits in a Git working tree that does not ignore it, the receipt adds `token_warning`; add the file to the repository's `.gitignore` or move it, and follow `if_exposed` if it was already committed. Rotating the client secret does not invalidate issued access tokens. Generic adapters supply endpoint/authentication guidance; there is no universal configuration file. [Adapter reference](harness-adapters.md) lists supported mechanisms and reload steps.
A configured server is only one step. Follow the adapter's reload instructions and enable the GBrain standing instruction through the harness's actual controls. Thin CLI installations write that instruction to `<ROOT>/GBRAIN-INSTRUCTIONS.md`. Grok Bot/Muse native skill activation remains a separate, visible step until observed in that harness. Generated files alone do not activate a skill.
@@ -1763,7 +1763,7 @@ writing or reviewing an operation, consult `src/core/operations.ts` for the cont
cumulative across `--resume`; a paid step that would exceed it is not
started while free steps still run. Without `--include-repairs`, repair
steps are listed as skipped. `--json` classifies each finding `cleared`,
- `pending`, `consent_required`, `operator_required` or `unsupported`.
+ `pending`, `consent_required`, `operator_required`, `explicit_kind_required` or `unsupported`.
Stale extraction uses source-scoped database pages, including DB-only
pages; it does not require a repository sync first. Empty brains (no
entity pages) or unconfigured embedding keys hit a `max_reachable_score`
@@ -5013,6 +5013,38 @@ vars — incident-time escape hatches, not everyday knobs.
reads only the filesystem — no database connection — so it keeps working
during the exact outages it exists to diagnose.
+## Several brains on one host
+
+Each brain gets its own autopilot job. The default brain (`~/.gbrain`, that
+is `GBRAIN_HOME` unset or set to your home directory) keeps the shared names:
+launchd label `com.gbrain.autopilot`, systemd unit `gbrain-autopilot.service`,
+start script `~/.gbrain/start-autopilot.sh`, and an unmarked crontab line.
+Any other brain gets names with a suffix: `com.gbrain.autopilot.<suffix>`,
+`gbrain-autopilot-<suffix>.service`, `<brain>/.gbrain/start-autopilot-<suffix>.sh`,
+and a crontab line ending in `# gbrain-autopilot:<suffix>`. The suffix is the
+first 8 hex characters of a random id that `--install` records in
+`<brain>/.gbrain/autopilot-install-id`. Every brain logs to its own
+`<brain>/.gbrain/autopilot.log`.
+
+`gbrain autopilot --status [--json]` prints the brain's job name, suffix,
+install-id path, wrapper path and log path (`job` in `--json`). `--status`
+and `--uninstall` act only on that brain's job.
+
+- **Moving a brain** keeps its id and job. `--status` reports
+ `needs_reinstall: wrapper_missing` until you run
+ `GBRAIN_HOME=<new parent> gbrain autopilot --install`, which repoints the
+ same job.
+- **Copying a brain** (`cp -r`) gives the copy a new id on its first
+ `--install`, so the original brain keeps its job.
+- **Upgrading from an older gbrain**: a non-default brain installed before
+ per-brain names ran under the shared names. `--status` reports
+ `needs_reinstall: legacy_shared_job`; `GBRAIN_HOME=<parent> gbrain autopilot --install`
+ replaces that shared job with the brain's own job and says so.
+- **`autopilot_job_owned_by_other_brain`**: installing the default brain
+ refuses when the shared job still runs another brain. Run the printed
+ `GBRAIN_HOME=<parent> gbrain autopilot --install` for that brain first, then
+ install the default brain again.
+
---
*Part of the [GBrain Skillpack](../GBRAIN_SKILLPACK.md).*
@@ -8053,7 +8085,10 @@ existing launch options throughout the repair.
| Autopilot under user systemd | `gbrain autopilot --status --json`; `systemctl --user status gbrain-autopilot.service` | `systemctl --user stop gbrain-autopilot.service` | `systemctl --user start gbrain-autopilot.service` |
| Autopilot under launchd | `gbrain autopilot --status --json`; `launchctl print "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootout "gui/$(id -u)/com.gbrain.autopilot"` | `launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.gbrain.autopilot.plist"` |
-These are the default user-service names. If the installation uses a different
+These are the default brain's user-service names. A brain under any other
+`GBRAIN_HOME` uses its own suffixed names; `gbrain autopilot --status --json`
+prints them under `job` ([several brains on one host](live-sync.md#several-brains-on-one-host)).
+If the installation uses a different
service definition, use its actual name and recorded launcher. For a foreground
autopilot or a container/cron owner, stop and restart that owner through its
existing launcher; do not start a competing standalone supervisor. A timed-out
@@ -8582,6 +8617,8 @@ visibility, pages indexed before the safe-chunk fence, pages imported
without a contextual retrieval mode, and connector checkpoint rows no source
can load. `gbrain repair` fixes those five kinds. Every run is a preview
unless you pass `--apply`.
+Two explicit-only kinds, `stale-atoms` and `extractor-facts`, run only when
+you name them (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
`gbrain doctor --remediation-plan` lists the same kinds as repair steps, and
`gbrain doctor --remediate --yes --include-repairs` runs them under a budget
(see [Run repairs through doctor](#run-repairs-through-doctor)).
@@ -8594,7 +8631,7 @@ agent runs `gbrain repair` to preview and, after you agree,
## Preview first
```bash
-gbrain repair # preview every kind
+gbrain repair # preview every automatic kind
gbrain repair timeline # preview one kind
gbrain repair --json # machine-readable preview
```
@@ -8636,7 +8673,7 @@ gbrain repair safe-chunks --apply
gbrain repair safe-chunks --apply --no-embed # re-seal text now, embed later
gbrain repair contextual-mode --apply
gbrain repair request-indexes --apply
-gbrain repair --all --apply # every kind in order
+gbrain repair --all --apply # every automatic kind in order
```
`--apply` writes without a prompt, so review the preview first. With
@@ -8646,12 +8683,22 @@ refused run changes nothing. To cap paid embedding work, run the repairs
through `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. `--all`
runs `timeline`, then `visibility`, then `safe-chunks`, then `contextual-mode`, then `connector-checkpoints`, then `request-indexes`, then `connector-fences`, then `orphan-bindings`, then `embedding-effects`, and stops at the
first kind that stops.
+The explicit-only kinds (`stale-atoms`, `extractor-facts`) never run under
+`--all`; it lists each with its preview command and still exits 0 when they
+are the only findings left. `gbrain repair` with no kind does the same for a
+preview. With `--json` the list is `explicit_kinds[]` (`kind`, `code:
+"explicit_kind_required"`, `preview_command`, `docs`).
Each item is re-checked against the page's current state just before it is
written, and the write is bound to the revision it just read, so an edit made
after planning is kept and repaired too. An item that no longer needs the
repair, or whose page changes during the write, is counted as `skipped` and
-left for the next run. Nothing is deleted.
+left for the next run. No kind deletes data except `stale-atoms`, which
+soft-deletes the atoms it retires (they stay recoverable through the
+`restore_page` operation for 72 hours, and a later extraction that produces
+a retired atom again restores it). See [Stale atoms](#stale-atoms).
+`extractor-facts` only restores previewed facts (it clears `expired_at` and
+gives each a fresh row number); it never deletes or rewrites a page.
| Option | Effect |
| --- | --- |
@@ -8659,8 +8706,10 @@ left for the next run. Nothing is deleted.
| `--source <id>` | Limit the run to one active source. The default is every active (non-archived) source. An unknown or archived id is refused. |
| `--limit <n>` | Repair at most `n` items per kind in this run (a positive integer; with `--all`, up to `n` for each kind). Rerun the same command to continue. |
| `--no-embed` | `safe-chunks` and `contextual-mode`: skip the embedding provider. Run `gbrain embed --stale` later. `timeline` and `visibility` pages are re-embedded by their publication either way. |
-| `--all` | Run every kind in order. |
-| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`. |
+| `--all` | Run every automatic kind in order. Explicit-only kinds are listed with their preview command, never run. |
+| `--expect <hash>` | Explicit-only kinds: apply exactly the set the preview printed under this hash. Required with `--apply` for `stale-atoms` and `extractor-facts`. |
+| `--include-ambiguous` | `extractor-facts` only: widen the hashed set to `ambiguous` facts. Pass it to both the preview and the apply. See [Extractor facts](#extractor-facts). |
+| `--json` | Print `{ scope, mode, results[], paid_kinds }`, one result per kind with `paid`, `affected`, `sample`, `residuals`, `cost`, `capacity`, `resumed_from`, `applied`, `skipped`, `complete`, `stopped` and `apply_command`, plus `explicit_kinds[]` when the run skipped explicit-only kinds. |
The command exits 1 when a run stops early (capacity, a pending write, or a
held writer). A `--limit` batch that leaves work behind exits 0, so scripts
@@ -8679,6 +8728,8 @@ should also check `results[].complete`.
| `embedding-effects` | `stale_embedding_effects` | Settles stale queued and failed embedding effects of committed writes, which block receipt compaction and activation: `reconciled` when current vectors pass the effect verifier, `superseded` when the page was deleted or a newer revision owns its own effect, `retry_queued` for the owner (paid; a used-up retry allowance gets one new bounded cycle per explicit apply). See [stale queued embedding effects](#stale-queued-embedding-effects). | `blocked` effects, counted by reason (`owner_unavailable`, `embedding_disabled`, `embedding_unconfigured`, `projection_pending`, `no_replacement_obligation`). |
| `safe-chunks` | `safe_index_pending` (also `contextual_retrieval_coverage`, `details.unsealed_pages`) | Rebuilds the chunks of markdown and code pages indexed before the safe-chunk fence, which remote and MCP search withhold. It rebuilds projections only: no page write, no new page version and no request ID. Vectors whose embedding input did not change are kept; the rest are embedded unless you pass `--no-embed` or no embedding model is configured. | `code_without_source_path`: code pages with no recorded file to re-chunk. `unsupported_page_kind`: other page kinds, such as images. Their importer re-seals them. |
| `contextual-mode` | `contextual_retrieval_coverage` (pages with no recorded mode) | Stamps the contextual retrieval mode on markdown pages imported without one (for example by a large `--no-embed` sync or a connector source before this release), exactly as a fresh import of the page would: the page, source and brain settings decide, and the per-chunk synopsis tier lands at the free title tier. It rebuilds projections only: no page write, no new page version and no request ID. A page whose stored vectors already match the stamped convention keeps them and queues no re-embedding; a page whose embedding input changes has only those vectors cleared and is re-embedded once, unless you pass `--no-embed`. | `unsealed_projection`: pages whose chunks lag their text; `gbrain embed --stale` or `safe-chunks` seals them first, and the next run stamps them. `embed_skip`: pages marked to skip embedding keep their stored vectors and are not stamped. |
+| `stale-atoms` (explicit-only) | `atom_provenance_drift` | Retires, by soft delete, live page-bound atoms whose source page is gone (`origin_gone`), or whose source page was edited and its current text already extracted (`origin_changed`). Preview-bound: `--apply --expect <hash>` retires exactly the previewed set. See [Stale atoms](#stale-atoms). | Atoms with `imported_from`, transcript (file-bound) atoms, and atoms of an edited page that was not extracted again yet (the `extract_atoms` backlog). |
+| `extractor-facts` (explicit-only) | `extractor_facts_expired` | Restores conversation-extractor facts the pre-v0.60.11.0 canonical projection expired (#5731). Restores `evidenced` facts by default, `ambiguous` ones only with `--include-ambiguous`; database-only. See [Extractor facts](#extractor-facts). | `excluded:<reason>` facts: page missing or deleted, superseded, withdrawn, an active duplicate, or a duplicate candidate. |
Timeline rows that an earlier version of a page produced and its current text
no longer has are removals, not history, so `timeline` neither counts nor
@@ -8779,6 +8830,63 @@ one more year, the same value `persistence_capacity` prints) and the check to
re-run. Request IDs are permanent, so raising the limit is the intervention;
nothing is evicted.
+<a id="projection-drain"></a>
+### Drain queued text projections
+
+After an upgrade that re-queues text projections (for example the 0.51
+protocol activation), search and code results stay incomplete until every
+queued Markdown and code page is rebuilt (#5401). Doctor
+`text_projection_readiness` warns while any visible page is pending.
+
+The upgraded resident owner (`gbrain serve` or autopilot) drains the queue on
+its own: each pass rebuilds up to 100 pages and starts no new page after
+250 ms, and takes 2 pages while writes are waiting. A page whose rebuild fails
+is retried after 30 seconds.
+
+To drain now:
+
+```bash
+gbrain projections drain # until every page queued at the start was tried once
+gbrain projections drain --limit 5000
+gbrain projections drain --json # {rebuilt, superseded, failed: [{source_id, slug, reason}], remaining}
+```
+
+| Exit | Meaning |
+| --- | --- |
+| 0 | Nothing tried failed. "The projection backlog is empty." appears only when `remaining` is 0. |
+| 1 | Some pages failed. Each prints `failed: <source>/<slug>: <reason>` and a `next:` action; the pages stay queued. |
+| 2 | Did not run: bad usage (`invalid_params`), or [`projection_owner_resident`](#projection-owner-resident). |
+
+On Postgres the drain is safe while `gbrain serve` runs: each page is rebuilt
+under its page lock with a revision recheck, so a page is rebuilt once whichever
+process gets there first. On PGLite a resident process holds the datastore, so
+the drain refuses before opening it (also for a mounted PGLite brain selected
+with `--brain`).
+
+Verify: `gbrain doctor` shows `text_projection_readiness` ok.
+
+<a id="embedding-key-source"></a>
+### Provider key source
+
+An exported provider key (for example `OPENAI_API_KEY`) wins over the matching
+config key (`openai_api_key` in `~/.gbrain/config.json`) (#5137). When both are
+set and differ, every gbrain command except `gbrain hook` prints one warning
+per process naming the variable, the config key and which one is in effect.
+No key or part of one is ever printed.
+
+- To use the config key: remove the variable from the environment of the
+ process that printed the warning (shell profile, `~/.gbrain/.env`, or for a
+ daemon its service definition) and restart that process.
+- If the environment key is intended: `gbrain config unset openai_api_key`
+ (or the matching key), which also stops the warning.
+
+Doctor `embedding_key_source` reports the same plus where the embedding key in
+effect comes from. It sees only the environment `gbrain doctor` runs in: a
+daemon has its own and reports a mismatch in its log, with the startup warning
+or `embedding_auth_failed` on the first rejected embedding
+([write refusals](write-refusals.md#embedding_auth_failed)). After fixing a
+rejected key, `gbrain embed --stale` embeds what was saved meanwhile.
+
<a id="connector-held-items"></a>
### Connector held items
@@ -8814,6 +8922,90 @@ Do not delete binding rows by hand: the repair rechecks, in the same
statement, that the binding is still orphaned and that no pending write
request uses it.
+### Stale atoms
+
+`gbrain repair stale-atoms` (explicit-only, #5770) retires atoms that drifted
+before managed re-extraction learned to retire them. It lists live atoms bound
+to a source page (`source_slug`) in two classes:
+
+- `origin_gone`: the source page is missing or deleted;
+- `origin_changed`: the source page was edited, and its current text has
+ already been extracted (a managed brain records a completed extraction at
+ the page's current hash; an unmanaged brain has an atom carrying it). Atoms
+ of an edited page that was not extracted again yet are the extract_atoms
+ backlog, not stale, and are not listed.
+
+It never lists an atom with `imported_from` or a transcript (file-bound)
+atom.
+
+```bash
+gbrain repair stale-atoms --source <id> # preview: every atom with its class, and a hash
+gbrain repair stale-atoms --source <id> --apply --expect <hash>
+```
+
+The apply retires exactly the previewed set. Each atom is checked again first;
+one whose revision, class, source page or completion evidence changed since
+the preview reports `changed_since_preview` and is kept. Retiring is a soft
+delete stamped with `retired_by: stale-atoms`: on a managed brain each atom is
+one coordinated request (its file is removed through the page deletion path),
+on an unmanaged brain a direct soft delete. Retiring also marks the source
+page for extraction again, so restoring a deleted page and running
+`extract_atoms` brings its atoms back. `--apply` without `--expect` refuses
+with the preview and apply commands; a stale hash refuses with
+[`preview_changed`](#preview-changed). An apply under a different `--source`
+than the preview also refuses with `preview_changed`. Doctor
+`atom_provenance_drift` names this command when drift crosses its warn
+threshold.
+
+### Extractor facts
+
+Before v0.60.11.0, every managed write to a conversation page without a
+Facts fence expired all of that page's conversation-extractor facts
+(`expired_at` set, `row_num` cleared), and recall stopped returning them.
+`gbrain repair extractor-facts` (#5731) restores them. It is explicit-only and
+preview-bound.
+
+```bash
+gbrain doctor # extractor_facts_expired
+gbrain repair extractor-facts # preview: every candidate with its class
+gbrain repair extractor-facts --apply --expect <hash>
+gbrain doctor
+```
+
+Each candidate gets one class:
+
+| Class | Meaning | Restored |
+| --- | --- | --- |
+| `evidenced` | A committed write of the page completed in the same transaction that expired the fact (`completed_at = expired_at`), and its consumer was older than v0.60.11.0 (no version stamp, or an older one). | By `--apply --expect <hash>` |
+| `ambiguous` | Unmanaged brain (no receipts); no committed write at the exact expiry instant; the expiring write came from a fixed consumer (a fence row may legitimately have taken the fact's position); or the page has carried fence facts. | Only with `--include-ambiguous` and that preview's hash |
+| `excluded:<reason>` | Page missing or deleted, superseded (`superseded_by`), withdrawn (`forget`), an active fact with the same text and entity already on the page, or an earlier candidate with the same text and entity. | Never |
+
+Ambiguous rows are restored as the hashed set; `--limit` is the only
+narrowing. Run `gbrain repair extractor-facts --include-ambiguous`, review
+the list, then `gbrain repair extractor-facts --include-ambiguous --apply
+--expect <hash>`.
+
+The apply restores exactly the previewed set. A fact that changed since the
+preview (edited, withdrawn, superseded, its page deleted or recreated)
+reports `changed_since_preview` and stays expired; `preview_changed` means
+the hash names no saved preview, the preview is older than 7 days, or the
+apply's `--source` / `--include-ambiguous` differs from the preview's.
+Restored facts get a fresh row number above the page's rows. Nothing is
+written to any page or file. On a managed brain each page publishes one
+database-only `managed_maintenance_restore_extractor_facts` request; a
+rerun after a crash replays it and restores no new candidate.
+
+Receipts are retained (compaction keeps `completed_at`), so a history older
+than the 30-day receipt retention is still evidenced. Not recoverable
+automatically: facts whose extractor batch was since replaced by a
+re-extraction (the old rows are gone), and facts on unmanaged brains without
+`--include-ambiguous`. On PGLite the same-transaction rule holds only to the
+millisecond (PGLite's clock resolution).
+
+The preview warns, naming the host, when a consumer older than this release
+published writes after `writer_version_cutoff`: an old consumer expires
+restored facts again. Upgrade and restart it first.
+
## Resume
Runs are resumable. After each page commits, the position is saved under the
@@ -8896,6 +9088,13 @@ Apply everything after the user agrees: gbrain doctor --remediate --yes --includ
Ask the user before applying any repair step.
```
+The plan never includes an explicit-only kind as a repair step. It prints them
+in an `Explicit-only repairs` block instead, one line per kind with its
+read-only preview command (`stale-atoms: gbrain repair stale-atoms`), and
+`--json` lists them as `explicit_repairs[]` (`kind`, `code:
+"explicit_kind_required"`, `preview_command`, `docs`). Run each by name after
+the user agrees (see [Explicit-only repair kinds](#explicit-only-repair-kinds)).
+
`gbrain doctor --remediate --yes` runs job steps only. Repair steps run only
when you also pass `--include-repairs`, which records the user's agreement;
without it they are listed as `N repair steps skipped (user agreement required):
@@ -8946,11 +9145,12 @@ With `--json`, the result adds `repairs[]` (one entry per repair step, with
| `pending` | A repairable finding remains: its step stopped, was refused by the budget, left items behind, or the check could not run. |
| `consent_required` | A repairable finding whose step was skipped for lack of `--include-repairs`; `command` applies it. |
| `operator_required` | Needs a named manual action on the brain host (`instruction`), for example raising a journal limit, retrying a parked effect, or quarantining self-captures. |
+| `explicit_kind_required` | Only an explicit-only kind clears it (for example `atom_provenance_drift` and `stale-atoms`); `command` is that kind's read-only preview. It never runs under `--remediate` and does not fail the exit status. |
| `unsupported` | No command can clear it yet; it is reported so it is never hidden (a stale queued embedding effect). |
Exit status: `0` when no automatically repairable finding remains and no step
-failed, even if operator-required or unsupported findings remain (they are
-listed); `1` when a repairable finding remains, a step failed, or the budget
+failed, even if operator-required, explicit-only or unsupported findings
+remain (they are listed); `1` when a repairable finding remains, a step failed, or the budget
ran out; `2` when the score target is unreachable and there was no repair step
to run, or a resume was refused. `healthy` is true only when every wave check
is clean; `repairs_completed` counts the repair steps that finished.
@@ -8988,7 +9188,69 @@ as one line each, for example
A line that says `Unknown:` means the check could not run; it is not a clean
result. Ask the brain host's operator to run the steps above.
-### Symptoms from the lifecycle fixes in this release
+<a id="fix-wave-5"></a>
+### Upgrading to v0.60.28.0 (fix wave 5)
+
+**Say to your agent:** *"We upgraded gbrain to v0.60.28.0. Restart everything
+that runs it, then walk me through what doctor finds, in order, before
+changing anything."*
+
+Most wave 5 fixes take effect only in a process that runs the new binary, so
+restart first. `gbrain sources writer status --json` lists, in
+`writer_versions[]`, the latest version each host and principal was seen
+writing with in the retained requests. That is history, not proof: an idle
+older `gbrain serve` never shows up there. Restart in this order:
+
+1. Stop autopilot and workers (`gbrain autopilot --status` names the job;
+ `gbrain jobs work` or your supervisor for workers).
+2. Stop each resident `gbrain serve`: HTTP services through their service
+ manager, and harness-owned stdio servers by quitting the harness.
+3. Upgrade each host: `gbrain upgrade`.
+4. Run `gbrain --version` through each launcher's own binary path (the path in
+ the service definition, the harness MCP command, the hook commands) and
+ confirm it prints `0.60.28.0`.
+5. Restart services, harnesses, workers and autopilot.
+6. Make one write from each host, then confirm a fresh `last_seen` for that
+ host in `gbrain sources writer status --json` (`writer_versions[]`).
+
+Then recover what doctor names, in this order (skip a step whose check is ok):
+
+1. `gbrain doctor`.
+2. Legacy jobs (`legacy_job_authority`): see
+ [Legacy job authority](#legacy-job-authority).
+3. Projections (`text_projection_readiness`): `gbrain projections drain`
+ (Postgres, or PGLite with no resident); on PGLite with a resident, let it
+ drain or stop, drain and restart it. See
+ [Drain queued text projections](#projection-drain).
+4. Stale atoms (`atom_provenance_drift`): `gbrain repair stale-atoms --source <id>`,
+ then after the user agrees `gbrain repair stale-atoms --source <id> --apply --expect <hash>`.
+5. Extractor facts (`extractor_facts_expired`): `gbrain repair extractor-facts`,
+ then after the user agrees `gbrain repair extractor-facts --apply --expect <hash>`
+ (add `--include-ambiguous` to both for ambiguous facts). See
+ [Extractor facts](#extractor-facts).
+6. `gbrain doctor` again, then `gbrain doctor --remediation-plan` for the
+ automatic kinds.
+
+| Symptom | Check or code | Issue | Preview | Apply | Verify |
+| --- | --- | --- | --- | --- | --- |
+| synthesize fails every run; `POST /ingest` 409 (was 500); workers refuse to start with "legacy jobs have missing or unsupported authority" | `legacy_job_authority` / `permission_denied` ([legacy job authority](#legacy-job-authority)) | #5157, #5114 | stop `gbrain serve`, autopilot and workers; `gbrain jobs cancel <active id>`; `gbrain jobs authorize-legacy --select "status=waiting\|delayed\|waiting-children\|paused"` | `gbrain jobs authorize-legacy --select "<same filter>" --expect <hash> --yes`, then restart | `gbrain doctor` shows `legacy_job_authority` ok; `/ingest` returns 202 |
+| Search returns atoms quoting text a page no longer has, or atoms of deleted pages | doctor `atom_provenance_drift` | #5770 | `gbrain repair stale-atoms --source <id>` | `gbrain repair stale-atoms --source <id> --apply --expect <hash>` | `gbrain doctor` (`atom_provenance_drift` drops by the retired count) |
+| `sources add`, `claim`, `rebind`, `archive`, `remove`, clone, reclone or `sources writer transfer` on a repo with more than ~10k files fails with "The verified source manifest exceeds the 1 MiB administration metadata bound" | `request_too_large` | #5790 | none: upgrade and restart every writer host and resident `gbrain serve` | Re-run the failed command (with the same `--request-id` if you kept it) | `gbrain sources writer status --json` shows the source bound, and its `manifest_digest` is set |
+| A stdio agent bound with `GBRAIN_SOURCE` (or `.gbrain-source`) gets `permission_denied` naming the binding when it passes `source_id` | `permission_denied` (hint starts "This connection is bound to source …") | #5081 | `gbrain sources list` (the source must show `federated`, not `isolated` or `unset`) | `gbrain sources federate <id>` on the brain host | Repeat the read with `source_id: "<id>"`; it returns only that source's rows. See [explicit reads from a bound agent connection](multi-source-brains.md#explicit-reads-from-a-bound-agent-connection) |
+| A new session's start-up context showed another session's text (`Last session activity: …`) | none | #5558 | none | Upgrade the `gbrain` each harness runs its hooks with and restart the harness. If you set `GBRAIN_HOOKS=0` as a workaround, remove it from the environment the harness starts from (shell profile or service) and restart the harness again | A new session shows no `Last session activity` line, and `gbrain doctor` reports `bootstrap_hooks_heartbeat` again after a few turns (capture and session persistence are back) |
+| `connect --harness codex\|claude-code\|opencode --install` stored the bearer token inline in the harness config without telling you | receipt `token_storage: "inline"` | #5775 | On the brain host: `gbrain mcp admin invalidate-tokens <client_id> --url <mcp_url> --admin-token-file <owner-admin-token-file> --json` (only if the config file was exposed) | `gbrain mcp admin invalidate-tokens <client_id> --yes --if-version <revision> --url <mcp_url> --admin-token-file <owner-admin-token-file> --json`, then `gbrain connect <mcp_url> --harness <harness> --credentials-file <handoff> --install --fresh-token`, then reload the harness | The new receipt prints `token_storage`, `config_path`, `renew_command` and `if_exposed`, and the harness answers a memory round trip |
+| A second brain's autopilot replaced the first one's job, logs interleave in `~/.gbrain/autopilot.log`, or `gbrain autopilot --status --json` shows `job.needs_reinstall: "legacy_shared_job"` (or `"wrapper_missing"` after moving a brain); install refuses with `autopilot_job_owned_by_other_brain` | `gbrain autopilot --status --json` (`job.*`) / `autopilot_job_owned_by_other_brain` | #5195 | `GBRAIN_HOME=<brain parent> gbrain autopilot --status --json` | `GBRAIN_HOME=<brain parent> gbrain autopilot --install` (every non-default brain first, then the default brain) | `GBRAIN_HOME=<brain parent> gbrain autopilot --status --json` shows `job.needs_reinstall: null` and the brain's own `launchd_label` / `systemd_unit`. See [several brains on one host](live-sync.md#several-brains-on-one-host) |
+| `gbrain serve` started in a `.gbrain-mount` project: CLI writes fail `owner_unavailable` and MCP writes stay `queued` | `owner_unavailable` | #5237 | none | Upgrade and restart the resident `gbrain serve` (the harness that spawns it) | `gbrain sources writer status --probe --json` from the project answers |
+| Backup coverage reports `remote evidence: unavailable` for a private remote that is pushed | doctor `backup_coverage` | #5794 | none | Upgrade, then `gbrain backup check` | `gbrain backup status --json` shows `verification.state: "verified"`; see [remote unavailable](../operations/backup-check.md#remote-unavailable) |
+| On Windows, a write or `gbrain sync` refuses a colon slug such as `calendar:abc` | [`colon_slug_windows_write_through`](write-refusals.md#colon_slug_windows_write_through) | #5032 | none | Use a slug without `:`, or write the page from a macOS or Linux host that owns the source | The write succeeds, or `gbrain sync` no longer lists the file |
+| Search empty or incomplete after upgrading; doctor `text_projection_readiness` warns | `text_projection_readiness` | #5401 | `gbrain doctor` (pending count, also while a PGLite resident runs) | `gbrain projections drain` (Postgres, or PGLite with no resident); on PGLite with a resident, wait or stop, drain and restart per [projection owner resident](#projection-owner-resident) | `gbrain doctor` shows `text_projection_readiness` ok |
+| `Error [projection_owner_resident]` from `gbrain projections drain` (exit 2) | [`projection_owner_resident`](#projection-owner-resident) | #5401 | `gbrain doctor` | the printed stop, drain and restart commands | `gbrain doctor` |
+| `[gbrain] warning: OPENAI_API_KEY in this process's environment differs from openai_api_key …`; doctor `embedding_key_source` warns | `embedding_key_source` ([provider key source](#embedding-key-source)) | #5137 | `gbrain doctor` (`embedding_key_source`) | remove the variable and restart that process, or `gbrain config unset openai_api_key` | the warning no longer prints; `gbrain doctor` shows `embedding_key_source` ok |
+| `The OpenAI embedding provider rejected its key (HTTP 401)` | [`embedding_auth_failed`](write-refusals.md#embedding_auth_failed) | #5137 | `gbrain doctor` (`embedding_key_source`, `embedding_provider`) | the printed fix for the key source in effect, then `gbrain embed --stale` | `gbrain doctor` shows `embedding_provider` ok |
+| Conversation facts missing from recall after managed writes | `extractor_facts_expired` | #5731 | `gbrain repair extractor-facts` | `gbrain repair extractor-facts --apply --expect <hash>` (ambiguous: add `--include-ambiguous` to both) | `gbrain doctor` |
+
+
+### Symptoms from the lifecycle fixes in v0.60.20.0
| Symptom or error text | Issue | Preview | Apply | Verify |
| --- | --- | --- | --- | --- |
@@ -9067,6 +9329,122 @@ covers the whole retry budget each grant authorizes. A resumed run replays the
grant it already made instead of granting another cycle. A signature-mismatched
vector is never reconciled; it is re-embedded.
+## Wave 5 refusal codes
+
+Each heading below is the `docs` anchor a refusal carries.
+
+### Explicit-only repair kinds
+
+`stale-atoms` and `extractor-facts` run only when named:
+`gbrain repair <kind>` previews, and `gbrain repair <kind> --apply --expect <hash>`
+applies exactly the previewed set. They are excluded everywhere else:
+
+- `gbrain repair --all` (and `gbrain repair` with no kind) lists each with its
+ preview command (`--json`: `explicit_kinds[]`) and never runs it. A
+ `--all --apply` run exits 0 when only explicit-only kinds remain.
+- `gbrain doctor --remediation-plan` prints them in an `Explicit-only repairs`
+ block (`--json`: `explicit_repairs[]`, each `{kind, code:
+ "explicit_kind_required", preview_command, docs}`), never as a repair step.
+- `gbrain doctor --remediate --include-repairs` classifies a finding only an
+ explicit-only kind clears as `explicit_kind_required`, with the preview as
+ its `command`. That class does not fail the exit status.
+- The `gbrain post-upgrade` banner prints such a finding as
+ `<check>: N (explicit_kind_required; preview with: gbrain repair <kind>)`.
+
+A remediation step or any other runner that reaches an explicit-only kind
+without its name refuses with `explicit_kind_required`. A build that does not
+implement the kind refuses with `unavailable`.
+
+### Preview changed
+
+`preview_changed`: the hash passed with `--expect` names no saved preview, the
+saved preview is older than 7 days, or the selection no longer matches it (for
+`stale-atoms`, a different `--source`). Nothing was applied. The message reads
+"The preview changed since <hash>; re-run <preview command> and use the new
+hash." Re-run the printed preview command and apply with the new hash. It
+applies to `gbrain jobs authorize-legacy --select`, `gbrain jobs cancel
+--select`, `gbrain repair stale-atoms` and `gbrain repair extractor-facts`.
+
+### Legacy job authority
+
+`permission_denied` with this anchor means a queued job row has SQL NULL
+`submission_authority`, left by an upgrade across v0.50 (#5157, #5114).
+
+- A resubmission over a **dead or cancelled** legacy key releases the key and
+ queues a fresh job. No step needed.
+- A **completed or failed** legacy row is reused by local producers (synthesize,
+ autopilot, `POST /ingest`). No step needed. A remote `submit_job` caller is
+ refused and resubmits with a new idempotency key.
+- A **live** legacy row (waiting, delayed, waiting-children, paused, active)
+ blocks every worker, so nothing reuses it. `POST /ingest` returns 409
+ `{error, message, hint, docs_url}`, never 500.
+
+`gbrain doctor` (`legacy_job_authority`) counts exactly the rows that block workers,
+split into authorizable (SQL NULL) and unsupported (non-NULL) rows, and prints the
+filled commands. Recovery, in order:
+
+1. Stop producers and workers: the resident `gbrain serve`, `gbrain autopilot`,
+ `gbrain jobs work` / supervisor.
+2. Cancel each active job the hint or doctor names: `gbrain jobs cancel <id>`.
+ (Stall and timeout sweeps are behind the same gate, so an orphaned active row
+ never finishes on its own.)
+3. Preview: `gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"`
+ (narrow with `,name=<job>|<job>`). It lists counts by job name and status, the
+ first 20 ids, marks paid-provider job names, and prints a hash. `--json` has the full rows.
+4. Apply exactly that set with the printed command:
+ `gbrain jobs authorize-legacy --select "<same filter>" --expect <hash> --yes`.
+ To drop work instead, `gbrain jobs cancel --select "<filter>"` previews and its
+ printed `--expect <hash> --yes` cancels exactly the previewed set.
+5. Unsupported non-NULL rows cannot be authorized: run matching application and
+ database versions, or cancel them (`gbrain jobs cancel <id>`, as doctor lists).
+6. Restart producers and workers. Verify: `gbrain doctor` shows
+ `legacy_job_authority` ok; `POST /ingest` returns 202.
+
+### Legacy jobs active
+
+`legacy_jobs_active`: `authorize-legacy --select`/`--ids` or `jobs cancel --select`
+found active jobs. Legacy review needs nothing active. Stop producers
+(`gbrain serve`, `gbrain autopilot`) and workers, cancel the listed jobs
+(`gbrain jobs cancel <id>`; the refusal lists up to 10, the rest with
+`gbrain jobs list --status active`), then re-run the preview it names.
+
+### Legacy job selection invalid
+
+`legacy_job_selection_invalid`: `--select` named an unknown key or value, a
+flag combination was wrong (`--ids` with `--select`; apply without both
+`--expect <hash>` and `--yes`), a selected row no longer exists or is not SQL
+NULL, or a `jobs cancel --select` selection would also cancel a job outside it
+(the message names those ids; cancel them on purpose or widen the filter). The
+grammar is `--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"`; the
+message lists the valid statuses, and the hint is a complete example.
+
+### Projection owner resident
+
+`projection_owner_resident` (exit 2): `gbrain projections drain` did not run
+because a gbrain process (named with its pid) holds this PGLite brain. Nothing
+changed. The upgraded resident drains the queue itself; re-run `gbrain doctor`
+to watch the pending count in `text_projection_readiness` (doctor asks the
+resident over its local socket, so the count shows while the resident runs; a
+resident that does not answer may predate this release and should be restarted
+on the upgraded gbrain).
+
+To drain faster, stop the owner, drain, then restart it. The restart runs
+whether or not the drain failed:
+
+| Owner | Stop, drain, restart |
+| --- | --- |
+| `gbrain serve` service, launchd | `launchctl bootout gui/$(id -u)/com.gbrain.serve && { gbrain projections drain; launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.gbrain.serve.plist; }` |
+| `gbrain serve` service, systemd | `systemctl --user stop gbrain-serve.service && { gbrain projections drain; systemctl --user start gbrain-serve.service; }` |
+| autopilot, launchd | `launchctl bootout gui/$(id -u)/com.gbrain.autopilot && { gbrain projections drain; launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.gbrain.autopilot.plist; }` |
+| autopilot, systemd | `systemctl --user stop gbrain-autopilot.service && { gbrain projections drain; systemctl --user start gbrain-autopilot.service; }` |
+| a manual `gbrain serve` | stop it (`kill <pid>`), run `gbrain projections drain`, then start `gbrain serve` again |
+
+The rows above show the default brain's names. The refusal prints these
+commands filled in: with `--brain <id>` for a mounted brain, and with this
+brain's own autopilot job (or the shared job an older install still runs it
+from) for a brain under another `GBRAIN_HOME`. The autopilot launchd label
+follows `GBRAIN_AUTOPILOT_LABEL` when set.
+
## Related
- [Write refusal reasons](write-refusals.md) — what a refused write means and the recovery command
@@ -9142,6 +9520,8 @@ of making a duplicate.
| <a id="migrations_running"></a>`migrations_running` | `migrations_running` (exit 75) | `gbrain apply-migrations` (or the post-upgrade step of `gbrain upgrade`) found another runner holding the brain's orchestration lock and stopped before touching the migration ledger, so migrations never run twice in parallel. The message names the holder's host and pid. A holder that died is taken over automatically on the next run. `gbrain upgrade` reports this as `Migrations: running`, not as a failed upgrade. | Wait for the other run to finish; `gbrain doctor` shows migration progress. Then `gbrain apply-migrations --yes` confirms everything is applied. |
| <a id="writer_deactivate"></a>`writer_deactivate` blockers | `writer_not_quiesced`, `writer_admin_locked`, `writer_admin_state_changed`, `writer_lock_unavailable` | `gbrain sources writer deactivate` found pending work (a queued, running or recovering write, a topology change or effect that is not settled, a held connector item, or a live connector or maintenance lease), the writer admin lock, a changed admin state, or a local process holding a worktree lock. Nothing changed. The suggestion names each blocker and its exit. | Run `gbrain sources writer deactivate --dry-run` for the full list, run each named exit (`gbrain cancel-write-request <request_id>`, `gbrain sync --source <id> --no-pull --retry-failed`, `gbrain repair embedding-effects --source <id>`, `gbrain sources writer retry-effects <source> --request-id <id> --dry-run`, `gbrain sources writer unlock`, `gbrain sources retry-held <id>`), then deactivate again with a fresh `--expected-state` from `gbrain sources writer status --json`. See the [deactivate runbook](../architecture/topologies.md#deactivate-runbook). |
| unknown option (repair) | `invalid_params` | `gbrain repair` refuses any option it does not list, so a mistyped flag or `--max-usd` never runs a repair silently without it. | Fix the option (`gbrain repair --help`). To cap paid repair work, run `gbrain doctor --remediate --yes --include-repairs --max-usd <n>`. |
+| <a id="colon_slug_windows_write_through"></a>`colon_slug_windows_write_through` | `colon_slug_windows_write_through` | A page slug such as `calendar:abc` is valid, but its canonical file name would contain `:`, which Windows cannot store (it names an alternate data stream). On Windows, a write that would publish that file is refused before admission, and `gbrain sync` skips each such file with this reason instead of failing the run. Database-only writes of the same slug (no repo configured, `sync.write_through` off, an unbound source, or a [read-only mirror](multi-source-brains.md#read-only-mirror-sources) source and pages created while it was one) still succeed, and macOS and Linux are unchanged. | Use a slug without `:` (the suggestion names one), or write the page from a macOS or Linux host that owns the source. For a skipped sync file, rename it without `:` on a macOS or Linux checkout, commit, then run `gbrain sync --source <source> --no-pull` on the Windows host. |
+| <a id="embedding_auth_failed"></a>`embedding_auth_failed` | `embedding_auth_failed` | The embedding provider rejected the configured key (HTTP 401 or 403). Printed once per process on stderr, naming the key source in effect: an environment variable (for example `OPENAI_API_KEY`, which wins over the config key) or the config key in `~/.gbrain/config.json`. No key or part of one is printed. | Environment key in effect but the config key is right: remove the variable from the environment of the process that reported it (shell profile, `~/.gbrain/.env`, or a daemon's service definition) and restart that process. Environment key intended: replace it with a valid key, restart, and run `gbrain config unset openai_api_key` (or the matching key). Config key in effect: `gbrain config set openai_api_key <valid key>`. Then `gbrain embed --stale` embeds what was saved meanwhile. `gbrain doctor` (`embedding_key_source`) shows the key source in doctor's own environment. |
### Other error codes
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 654531841d..b290781cf0 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 84398a877b..8d49c826c2 100644
--- a/package.json
+++ b/package.json
@@ -204,7 +204,7 @@
"bun": ">=1.4.0"
},
"license": "MIT",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.33",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 5c3bb914cc..79bf4ec563 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 123ba5239b..05ee40de00 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 1b0f815ce8..5844df0f79 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.27.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.28.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 4566b7eccc..00f123b45a 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 01f5f304fa..ec52d80904 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.27.0",
+ "version": "0.60.28.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 46e4aefd15..696a707bc8 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.27.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.28.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index b9d60822e6..5f38a69fc5 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.27.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.28.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/plugin/skills/brain-pdf/SKILL.md b/plugin/skills/brain-pdf/SKILL.md
index f18f9eb8c5..a63f73a36c 100644
--- a/plugin/skills/brain-pdf/SKILL.md
+++ b/plugin/skills/brain-pdf/SKILL.md
@@ -83,10 +83,13 @@ else
gbrain get "$SLUG" > "$RAW" # prints the page as markdown with frontmatter
fi
-# 3. Strip YAML frontmatter — sed: skip the opening '---' through the
-# closing '---' (lines 1..N), then keep everything after.
+# 3. Strip the leading YAML frontmatter block only: line 1 '---' through
+# the next '---'. A later '---' (a horizontal rule) and a page without
+# frontmatter are kept as written. Plain awk, so it behaves the same with
+# BSD (macOS) and GNU tools. Stop if nothing is left to render.
CLEAN=$(mktemp /tmp/brain-page-clean-XXXXXX.md)
-sed '1{/^---$/!q}; /^---$/,/^---$/d' "$RAW" > "$CLEAN"
+awk 'NR==1 && /^---[[:space:]]*$/ {f=1; next} f==1 && /^---[[:space:]]*$/ {f=2; next} f!=1' "$RAW" > "$CLEAN"
+[ -s "$CLEAN" ] || { echo "brain-pdf: nothing to render for $SLUG after removing frontmatter" >&2; exit 1; }
# 4. Render. NO --cover, NO --toc by default — they look corporate
# and waste space. Add them only if explicitly requested.
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index b81fd33413..f853f42803 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -29,6 +29,25 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/migration-orchestration-lock.ts": ["test/e2e/apply-migrations-orchestration-lock.test.ts"],
"src/core/source-delete.ts": ["test/e2e/sources-remove-bindings.test.ts"],
"src/core/persistence/orphan-bindings.ts": ["test/e2e/sources-remove-bindings.test.ts"],
+ // Fix wave 5 shared commit: preview-bound approved sets in op_checkpoints.
+ "src/core/persistence/preview-approval.ts": ["test/e2e/preview-approval-postgres.test.ts", "test/e2e/minions-legacy-journey-postgres.test.ts"],
+ // #5157: the legacy recovery commands and doctor check.
+ "src/commands/jobs/authorize-legacy.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
+ "src/commands/jobs/cancel.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
+ "src/commands/doctor/checks/legacy-job-authority.ts": ["test/e2e/minions-legacy-journey-postgres.test.ts"],
+ // Fix wave 5 #5401: projection drain CLI and the budgeted resident drain.
+ "src/commands/projections.ts": ["test/e2e/projection-drain-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
+ "src/core/persistence/consumer.ts": ["test/e2e/projection-drain-postgres.test.ts"],
+ "src/core/persistence/journal.ts": ["test/e2e/projection-drain-postgres.test.ts"],
+ // Fix wave 5 (#5731): the extractor-facts restore and its doctor check.
+ "src/core/repair/extractor-facts.ts": ["test/e2e/repair-extractor-facts-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
+ "src/commands/doctor/checks/extractor-facts.ts": ["test/e2e/repair-extractor-facts-postgres.test.ts"],
+ // Fix wave 5: managed writeSingleFact keeps an absent entity's fallback slug (attribute_fallback).
+ "src/core/facts/write-single.ts": ["test/e2e/managed-write-single-attribution-postgres.test.ts", "test/e2e/managed-facts-writers.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
+ "src/core/facts/managed-fact-write.ts": ["test/e2e/managed-write-single-attribution-postgres.test.ts", "test/e2e/managed-facts-writers.test.ts"],
+ // Fix wave 5 (#5409): read-only mirror sources.
+ "src/core/persistence/mirror-read-only.ts": ["test/e2e/sources-mirror-read-only-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
+ "src/commands/sources-mirror.ts": ["test/e2e/sources-mirror-read-only-postgres.test.ts"],
"src/core/persistence/deactivation.ts": ["test/e2e/persistence-deactivate-race.test.ts", "test/e2e/fix-wave-4-integration.test.ts"],
// SkillOpt orchestrator, outcome/resume, models plan + strict mode, spend ledger.
"src/core/skillopt/**": [
@@ -101,7 +120,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/search-exclude.test.ts",
"test/e2e/search-swamp.test.ts",
],
- "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-readiness-currency.test.ts", "test/e2e/projection-embedding-input-hash.test.ts", "test/e2e/safe-chunk-reseal.test.ts", ...MIGRATION_WAVE_TESTS],
+ "src/core/page-state/**": ["test/e2e/projection-recovery-parity.test.ts", "test/e2e/projection-drain-postgres.test.ts", "test/e2e/projection-readiness-currency.test.ts", "test/e2e/projection-embedding-input-hash.test.ts", "test/e2e/safe-chunk-reseal.test.ts", ...MIGRATION_WAVE_TESTS],
"src/core/embedding-input-hash.ts": ["test/e2e/projection-embedding-input-hash.test.ts"],
// Evidence delivery (return_unit): the release-gate leak canaries and the
// engine / product-path parity suite.
@@ -190,6 +209,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
],
// Any minions queue/worker/handler change exercises all minion E2E.
"src/core/minions/**": [
+ "test/e2e/minions-legacy-coalesce-postgres.test.ts",
+ "test/e2e/minions-legacy-journey-postgres.test.ts",
"test/e2e/worker-readiness-cli.test.ts",
"test/e2e/worker-configuration-release.test.ts",
"test/e2e/delegated-grants-withdrawal.test.ts",
@@ -244,6 +265,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/managed-extract-atoms.test.ts",
"test/e2e/managed-atom-regressions.test.ts",
"test/e2e/managed-atom-compaction.test.ts",
+ "test/e2e/repair-stale-atoms-postgres.test.ts",
+ "test/e2e/journey-atoms-sync-race-postgres.test.ts",
"test/e2e/managed-maintenance.test.ts",
"test/e2e/managed-writers-w3.test.ts",
"test/e2e/managed-facts-writers.test.ts",
@@ -266,6 +289,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"test/e2e/derived-visibility-repair.test.ts",
"test/e2e/repair-command.test.ts",
"test/e2e/w5-persistence-postgres.test.ts",
+ "test/e2e/persistence-large-manifest-postgres.test.ts",
+ "test/e2e/persistence-large-manifest-50k.test.ts",
],
"src/core/brain-score-recommendations.ts": ["test/e2e/w5-persistence-postgres.test.ts"],
"src/core/repair/**": ["test/e2e/repair-command.test.ts", "test/e2e/derived-visibility-repair.test.ts", "test/e2e/safe-chunk-reseal.test.ts", "test/e2e/recovery-layer.test.ts", "test/e2e/repair-contextual-mode-5621-postgres.test.ts", "test/e2e/fix-wave-3-integration.test.ts"],
@@ -382,7 +407,10 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
// stays in its engine module dir); both key the cross-engine read-parity
// suite directly. (The ** globs match these files too; the selector unions
// the entries.)
- "src/core/engine-sql/code-edges.ts": ["test/e2e/code-edges-read-parity.test.ts"],
+ "src/core/engine-sql/code-edges.ts": ["test/e2e/code-edges-read-parity.test.ts", "test/e2e/code-intel-n13-postgres.test.ts"],
+ // Eval-category wave lane A (folded into fix wave 5): N13 code-intel walk and N8 private-page reflex filter.
+ "src/core/code-intel/recursive-walk.ts": ["test/e2e/code-intel-n13-postgres.test.ts"],
+ "src/core/context/retrieval-reflex.ts": ["test/e2e/reflex-private-visibility-postgres.test.ts"],
"src/core/pglite-engine/code-edges.ts": ["test/e2e/code-edges-read-parity.test.ts"],
// D7 parity batch: chronicle ontology merge (mergeOntologyFact helpers in
// chronicle/ontology.ts) + event projection (only production caller:
@@ -449,7 +477,9 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
],
// Autopilot linux install/uninstall lifecycle (PATH-shimmed crontab +
// systemctl; the ubuntu CI runner's only behavioral pin on those arms).
- "src/commands/autopilot.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],
+ "src/commands/autopilot.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/autopilot-multi-brain.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],
+ "src/commands/autopilot/jobs.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/autopilot-multi-brain.serial.test.ts"],
+ "src/core/autopilot-paths.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/autopilot-multi-brain.serial.test.ts"],
"src/commands/autopilot-daemon.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],
"src/commands/autopilot-dispatch.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],
"src/commands/autopilot-probes.ts": ["test/e2e/autopilot-linux-lifecycle.serial.test.ts", "test/e2e/worker-readiness-cli.test.ts"],
@@ -463,7 +493,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/derived-links.ts": ["test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/attendance-repair-postgres.test.ts"],
"src/core/link-reconciliation.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],
"src/core/persistence/links-preparation.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],
- "src/core/sweep.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],
+ "src/core/sweep.ts": ["test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
// v0.38 ingestion substrate. POST /ingest lives inside serve-http.ts
// (per the plan-eng-review E1 decision); the daemon + built-in sources
// + ingest_capture Minion handler all feed the in-process roundtrip
@@ -482,7 +512,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/commands/serve-http-admin-api.ts": ["test/e2e/serve-http-consent.test.ts", "test/e2e/serve-http-oauth.test.ts"],
"src/commands/serve-http-metrics.ts": ["test/e2e/serve-http-oauth.test.ts"],
"src/commands/serve-http-spa.ts": ["test/e2e/serve-http-consent.test.ts"],
- "src/commands/serve-http-webhooks.ts": ["test/e2e/serve-http-ingest-webhook.test.ts"],
+ "src/commands/serve-http-webhooks.ts": ["test/e2e/serve-http-ingest-webhook.test.ts", "test/e2e/minions-legacy-journey-postgres.test.ts"],
"src/commands/serve-http-mcp.ts": [
"test/e2e/serve-http-oauth.test.ts",
"test/e2e/harness-access.test.ts",
@@ -524,6 +554,8 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"src/core/connectors/connector-text.ts": ["test/e2e/connector-holds.test.ts"],
"src/commands/sources-retry-held.ts": ["test/e2e/connector-holds.test.ts"],
"src/core/repair/connector-fences.ts": ["test/e2e/connector-holds.test.ts"],
+ // Fix wave 5 (#5770): stale-atoms repair and its #5777 cross-lane journey.
+ "src/core/repair/stale-atoms.ts": ["test/e2e/repair-stale-atoms-postgres.test.ts", "test/e2e/journey-atoms-sync-race-postgres.test.ts", "test/e2e/managed-extract-atoms.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],
// Fix wave 3 lane A: connector identity, account pin, no-op kernel, pending set and migration 176.
"src/core/take-proposals.ts": ["test/e2e/takes-propose-accept-managed.test.ts"],
"src/core/persistence/connector-sync.ts": ["test/e2e/connector-wave3.test.ts", "test/e2e/connector-holds.test.ts"],
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index dee1654df5..2ea539adb5 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -3,16 +3,16 @@
# 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.ts 3158 ratchet +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)
-src/commands/autopilot.ts 1633 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
+src/cli.ts 3162 ratchet +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)
+src/commands/autopilot.ts 1635 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)
src/commands/doctor.ts 653 ratchet refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.ts
src/commands/embed.ts 2187 ratchet 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
src/commands/extract-conversation-facts.ts 2146 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts)
src/commands/extract.ts 2621 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked
-src/commands/jobs.ts 635 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts
+src/commands/jobs.ts 658 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2)
src/commands/serve-http.ts 915 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts
-src/core/ai/gateway.ts 4358 ratchet +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)
-src/commands/sync.ts 472 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary)
+src/core/ai/gateway.ts 4365 ratchet +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state)
+src/commands/sync.ts 473 ratchet refactor wave 1 split target (W4 sync); ceiling rationale: docs/architecture/key-files/commands-6.md entry for src/commands/sync.ts; +2 for the #5751 SyncResult.legacySkips interface field (fix wave 4); +2 fix wave 4 lane B: SyncResult.connectorHolds interface field (held counts for the sync summary); +1 fix wave 5 (#5032): SyncResult.fileRefusals interface field (named per-file Windows colon refusals)
src/core/cycle.ts 3221 ratchet +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge
src/core/cycle/synthesize.ts 3291 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge
src/core/cycle/extract-atoms.ts 1802 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts)
@@ -30,12 +30,12 @@ src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 conne
src/core/minions/handlers/subagent.ts 1918 ratchet merged: master v131 settle rework + dream-wave C5 peel + C6 accounting + C7 lease heartbeats/lost-lease aborts + C9 oneshot dispatch + adversarial fix batches; grown by #4078 subagent-loop capability fix; +6 lines (reasoning-item replay: adaptContentBlocksToChatBlocks handles 'reasoning' blocks); +3 wave G #4514: Anthropic-via-OpenRouter allowed on the subagent loop; +36 lines (code review, same PR): isPromptTooLongError walks a bounded .cause chain so it still matches post-normalizeAIError() wrapping, plus extractPromptTooLongDetail so the dead-lettered job's error carries the matched provider detail instead of the generic normalizeAIError() wrapper text; master integration: harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; #5105: +13 call-site wiring to shared tool-write-identity helper across fresh and replay dispatch
src/commands/bootstrap.ts 2115 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics
src/core/minions/worker.ts 1764 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry
-src/commands/sources.ts 2007 ratchet grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
+src/commands/sources.ts 2013 ratchet +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts)
src/core/link-extraction.ts 2133 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note
src/core/embedding-migration.ts 1525 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed
src/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refresh
src/commands/hook.ts 1903 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read
-src/core/chunkers/code.ts 1582 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES
+src/core/chunkers/code.ts 1588 ratchet new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (decorated-python defs #3821, version-gate + timeout chunker fixes); grown wave-g (#4511): named defs never folded into merged chunks; grown #4669: skip WASM parse for languages without TOP_LEVEL_TYPES; +6 N13-1: CodeChunkMetadata.definesFunction field + merge-guard stamp (predicate lives in def-types.ts)
src/core/config.ts 1806 ratchet +1 System One v1: decide.* key prefix (validated by ai/decide/config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave (spend-controls hint #3703, config-set validation); +3 wave G #3974: sync.include_working_tree key; grown wave-g (#4540 #4494 #4415): extractor caps + intent-pattern config keys; +1 chat-connectors: connectors. config prefix; wave-k: config-table snapshot serving the DB-plane reads (#3980 + #2119 merge); +8: loadConfig hook for ~/.gbrain/.env, loader lives in gbrain-env-file.ts (#3893); +17: litellm/together key-fold slots (#3904 reimpl: two GBrainConfig fields + KNOWN_CONFIG_KEYS rows); +1: link_resolution.cross_source key (#3908); +4 v0.47 gmail-loops: loops.extraction_enabled key; +1: pricing.overrides key (#4633 adoption); +7 #4667 adoption: sync.exclude key registration; +4: eval fix wave keys (quote_verify + 3 rescue knobs); +memorable file-plane key registration (integrations.memorable.enabled + consent-event doc); +33 ambient-writeback: memory.* + brain.audience key registration + GBrainConfig.memory mirror slot (resolvers live in facts/writeback-config.ts); +38 2026-08 wave: retrieval_reflex_volunteer key + env mapping (volunteer-arm kill switch) + E5a registration of the 10 adaptive_return*/autocut*/crag_* search (incl. adversarial batch isEnvDisabled dedup); ambient-writeback (master merge): facts/writeback-config.ts); new row: crossed the 1500 unlisted cap in v0.46.26.0 megawave; prior growth: sync/intent/chat-connectors/litellm/pricing/loops key folds; +34: #4702 content_sanity.disabled_patterns (type + DB-plane parse/merge + key registration); composition true-up (fix-wave multi-train) | merged v0.48.1.0: master #4788 writeback keys + wave #4702/#4748 keys; master: | merged v0.48.1.0 true-up; ranker wave v0.48.4.0: +4 KNOWN_CONFIG_KEYS rows (+8); +5 #4895: CWD_DOTENV_FILES gains the per-NODE_ENV .local variants Bun auto-loads; +2 #5003: sync.include_hidden key registration; +57 #4605: search.* registry reconciled to the keys mode.ts reads (+20 knob rows, +4 direct-read singletons) + GBrainConfig.search slot + adaptive_return* DB-plane merge; +2 pre-landing review: fts.reindex_in_progress key registration (#4795 marker escape hatch); +4 #4987: auto_timeline key registration (the documented off switch was rejected as unknown); lowered to 1793: GHSA wave v0.50.5.0 moved CWD_DOTENV_FILES + dotenvValuesForKey into core/env-trust.ts (-49, re-exported); re-summed to the merged line count after merging master v0.50.2.0 (#5122) with the v0.50.5.0 security wave; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; evidence delivery: 5 registered config keys + comment (+7); +2 #5691: embedding_query_prefix key registration; evidence delivery auto v2: search.return_budget_conversation key row (+1)
src/core/bootstrap/harness.ts 2674 ratchet +29 live-PGLite-serve lane: LIVE_SERVE refusal ahead of source resolution + unpinned --token hooks (CI e2e fix); +46 wave review: resolveHookSource dep (serve-parity resolver + federated grant), --source shape validation, loud SOURCE_UNRESOLVED instead of a silent 'default'; +10: #4574 parseCodexBlockBearer http_headers shape + legacy bearer_token fallback; +4 at megawave/wave-k merge; +codex hooks lane: step-7 codex hooks.json + config.toml trust pair, removeHarness arm; +234 ambient-writeback WP3: kind:'instructions' targets (plan/apply/converge-off/remove/status probes, OV-A4 override pre-check) — splice/render mechanics live in instructions-block.ts; +59 adversarial fix wave: registrar-mode block suppression, converge-failure receipt tracking, MCP-confirmed guard before block install; +26 round-3 fixes: codex-lane MCP-confirmed guard + smoke-rollback block strip; master: | merged v0.48.1.0 true-up; +41 #4897 resolveImplicitSource dep + defaultResolveImplicitSource: hooks/token/receipt bind to the serve's implicit default source when --source is omitted; +23 #4586 statusHarness live claude-code mcp verdict (URL mismatch or same-scope non-HTTP registration reads failed, receipt untouched); shared-skills integration on company-ingestion base; +18 #5671: logAmbientPostureNotes helper (registrar note moved out of applyHarness + pre-consent warning when an explicit private facts default meets the HTTP harness; text shared with doctor in facts/writeback-config.ts)
src/core/oauth-provider.ts 1236 ratchet new row: crossed the 1500 unlisted cap absorbing #3819 (DCR 400 invalid_client_metadata + scope filtering + custom-scheme redirect_uris + pseudo-scheme guard); merged v0.49: transactional grant enforcement shared with hosted grant policies; +1 #5222 resourceUrl option
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index df1966eb10..1073797c11 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -95,7 +95,7 @@ test/destructive-guard.test.ts purgeExpiredSources — clone cleanup containment
test/detached-stderr.test.ts jobs.ts detach branch (source pin, #4418) 2 source-surface-helper
test/docs-mcp-deploy.test.ts DEPLOY.md documents the owner magic-link flow (#5007) 1 readFileSync,source-surface-helper
test/docs-navigation.test.ts primary documentation navigation 1 readFileSync
-test/doctor-atom-provenance-drift.test.ts computeAtomProvenanceDriftCheck 18 doctor-source-helper
+test/doctor-atom-provenance-drift.test.ts computeAtomProvenanceDriftCheck 19 doctor-source-helper
test/doctor-embedding-env-override.test.ts cross-surface parity (source-grep regression guard) 1 doctor-source-helper
test/doctor-fix.test.ts gbrain doctor --fix CLI integration 3 readFileSync
test/doctor-frontmatter-partial.test.ts doctor frontmatter_integrity — load-bearing render strings 5 doctor-source-helper
@@ -126,6 +126,7 @@ test/e2e/codex-plugin-install-real.serial.test.ts (file-level) 2 readFileSync
test/e2e/migration-flow.test.ts (file-level) 4 readFileSync
test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (W1 + W2 + W3) 8 readFileSync
test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
+test/embed-concurrency-pool-clamp.test.ts #5183 embed concurrency never exceeds the Postgres pool 4 readFileSync
test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
test/embedding-dim-check-facts.test.ts postgres-engine fact insert cast (T6, codex #20) 1 source-surface-helper
test/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync
@@ -204,11 +205,12 @@ test/migrate.test.ts resolveSessionTimeouts — env var overrides 5 source-surfa
test/migrate.test.ts v117 — context_volunteer_events_table 5 readFileSync,source-surface-helper
test/migration-resume.test.ts Bug 3 — orchestrator no longer writes the ledger directly 6 bun-file
test/migrations-v0_11_0.test.ts AGENTS.md marker injection 6 readFileSync
+test/migrations-v0_11_0.test.ts GBRAIN_HOME resolution (#5549) 2 readFileSync
test/migrations-v0_11_0.test.ts cron manifest rewrite — gbrain builtins only 8 readFileSync
test/migrations-v0_14_0.test.ts Bug 5 + Bug 8 — v0_14_0 module shape 3 bun-file
test/migrations-v0_14_0.test.ts Bug 5 — Phase B host-work entry dedup 2 readFileSync
test/migrations-v0_14_0.test.ts Bug 8 — max_stalled default bumped in schema files 3 bun-file
-test/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 9 readFileSync
+test/migrations-v0_22_4.test.ts v0.22.4 migration (B11) 10 readFileSync
test/model-pricing.test.ts DRIFT GUARD — derived views stay equal to canonical (re-hardcode trip-wire) 4 readFileSync
test/model-pricing.test.ts no heavy import (cycle guard) 1 readFileSync
test/ocr-run-budget.test.ts doctor ocr_health surfaces the budget-skip counter (#3973) 1 doctor-source-helper
@@ -318,6 +320,7 @@ test/template-repo-generator.test.ts generateTemplateTree 0 readFileSync
test/template-repo-generator.test.ts renderTemplateReadme 5 readFileSync
test/think-embed-question-wiring.serial.test.ts #3734 — CRAG think escalation wires embedQuestion (source pin) 1 readFileSync
test/think-embed-question-wiring.serial.test.ts #3734 — synthesize verb wires embedQuestion into runThink 1 readFileSync
+test/think-save-source.test.ts #5426 think --save persists into the think source 5 readFileSync
test/timing-safe.test.ts extraction contract 1 source-surface-helper
test/title-fuzzy-index.test.ts findByTitleFuzzy indexed threshold 2 source-surface-helper
test/transcription-injection.test.ts transcription — command injection (#245) 2 readFileSync
diff --git a/skills/brain-pdf/SKILL.md b/skills/brain-pdf/SKILL.md
index f18f9eb8c5..a63f73a36c 100644
--- a/skills/brain-pdf/SKILL.md
+++ b/skills/brain-pdf/SKILL.md
@@ -83,10 +83,13 @@ else
gbrain get "$SLUG" > "$RAW" # prints the page as markdown with frontmatter
fi
-# 3. Strip YAML frontmatter — sed: skip the opening '---' through the
-# closing '---' (lines 1..N), then keep everything after.
+# 3. Strip the leading YAML frontmatter block only: line 1 '---' through
+# the next '---'. A later '---' (a horizontal rule) and a page without
+# frontmatter are kept as written. Plain awk, so it behaves the same with
+# BSD (macOS) and GNU tools. Stop if nothing is left to render.
CLEAN=$(mktemp /tmp/brain-page-clean-XXXXXX.md)
-sed '1{/^---$/!q}; /^---$/,/^---$/d' "$RAW" > "$CLEAN"
+awk 'NR==1 && /^---[[:space:]]*$/ {f=1; next} f==1 && /^---[[:space:]]*$/ {f=2; next} f!=1' "$RAW" > "$CLEAN"
+[ -s "$CLEAN" ] || { echo "brain-pdf: nothing to render for $SLUG after removing frontmatter" >&2; exit 1; }
# 4. Render. NO --cover, NO --toc by default — they look corporate
# and waste space. Add them only if explicitly requested.
diff --git a/skills/migrations/v0.60.28.0.md b/skills/migrations/v0.60.28.0.md
new file mode 100644
index 0000000000..70be3f0296
--- /dev/null
+++ b/skills/migrations/v0.60.28.0.md
@@ -0,0 +1,97 @@
+# Upgrade to v0.60.28.0: fix wave 5
+
+Fix wave 5 removes the session-start line that could show another session's
+text, lets repos over ~10,000 files onboard, unblocks jobs queued before
+v0.50, adds two preview-bound cleanups (`gbrain repair stale-atoms` and
+`gbrain repair extractor-facts`) and a projection drain, and fixes more
+than a dozen smaller bugs. There is no schema migration. Never apply a repair,
+authorize or cancel jobs, or change a key on the user's behalf without asking.
+
+## What the user will notice
+
+- Session start no longer shows a `Last session activity` line. It was taken
+ from whichever session on the machine wrote last (#5558). Nothing restores
+ it, by design.
+- Ambient recall (`volunteer_context` for remote callers, the per-turn hook
+ block) and `gbrain compile-context` no longer show private pages.
+- Code pages re-chunk once (`CHUNKER_VERSION` 7 → 8) on the next sync or
+ `gbrain embed --stale`.
+- `gbrain doctor` may report `legacy_job_authority`,
+ `text_projection_readiness`, `atom_provenance_drift`,
+ `extractor_facts_expired` or `embedding_key_source`.
+- `gbrain repair --all` and `gbrain doctor --remediate` list `stale-atoms`
+ and `extractor-facts` with a preview command (`explicit_kind_required`)
+ instead of running them.
+- A non-default brain's autopilot job gets its own name and logs to
+ `<brain>/.gbrain/autopilot.log`.
+- A command may print one warning that an exported provider key (for example
+ `OPENAI_API_KEY`) differs from the config key. The environment key is still
+ the one in effect.
+
+## Step 1: restart everything that runs gbrain
+
+Most fixes apply only in a process running the new binary. Tell the user,
+then, with their agreement and in this order:
+
+1. Stop autopilot and workers.
+2. Stop each resident `gbrain serve`: HTTP services through their service
+ manager, stdio servers by quitting the harness that started them.
+3. Run `gbrain upgrade` on each host.
+4. Run `gbrain --version` through each launcher's own binary path (service
+ definition, harness MCP command, hook commands); each must print
+ `0.60.28.0`.
+5. Restart services, harnesses, workers and autopilot.
+6. Make one write from each host and check that host's `last_seen` in
+ `gbrain sources writer status --json` (`writer_versions[]`). That list is
+ history from retained requests, not proof that every process upgraded.
+
+If the user set `GBRAIN_HOOKS=0` to work around #5558, ask them to remove it
+from the environment the harness starts from (shell profile or service) and
+restart the harness. It also turned off session capture, session persistence
+and crash recovery. Verify: a new session shows no `Last session activity`
+line, and after a few turns `gbrain doctor` reports `bootstrap_hooks_heartbeat`.
+
+## Step 2: run doctor and recover in order
+
+Run `gbrain doctor`, show the user what it names, and handle each finding in
+this order. Preview first and apply only after the user agrees.
+
+1. **Legacy jobs** (`legacy_job_authority`). Stop `gbrain serve`, autopilot
+ and workers. Cancel each active job doctor lists
+ (`gbrain jobs cancel <id>`). Preview with
+ `gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"`,
+ show the user the counts and any paid job names, then apply with the
+ printed `--expect <hash> --yes`. To drop the work instead, use
+ `gbrain jobs cancel --select "<filter>"` and its printed apply command.
+ Restart, then check `legacy_job_authority` is ok.
+2. **Projections** (`text_projection_readiness`). Run
+ `gbrain projections drain` on Postgres, or on PGLite when no resident
+ holds the brain. If it refuses with `projection_owner_resident`, either let
+ the upgraded resident drain it (watch the pending count in doctor) or, with
+ the user's agreement, run the stop, drain and restart commands it prints.
+3. **Stale atoms** (`atom_provenance_drift`). `gbrain repair stale-atoms --source <id>`
+ previews; after the user reviews it,
+ `gbrain repair stale-atoms --source <id> --apply --expect <hash>`. Retired
+ atoms are soft-deleted and recoverable with `restore_page` for 72 hours.
+4. **Extractor facts** (`extractor_facts_expired`). `gbrain repair extractor-facts`
+ previews; after review, `gbrain repair extractor-facts --apply --expect <hash>`.
+ Ambiguous facts restore only if the user asks: add `--include-ambiguous`
+ to both the preview and the apply.
+5. Run `gbrain doctor` again, then `gbrain doctor --remediation-plan` for the
+ automatic repair kinds.
+
+## Step 3: other one-time actions
+
+- **Several brains on one host:** run
+ `GBRAIN_HOME=<brain parent> gbrain autopilot --install` for each non-default
+ brain, then for the default brain. `gbrain autopilot --status --json`
+ should show `job.needs_reinstall: null`.
+- **Key warning:** to use the config key, remove the variable from the
+ environment of the process that printed the warning and restart it; if the
+ environment key is intended, `gbrain config unset <config key>`.
+- **Inline harness token (#5775):** if a harness config file holding an
+ inline token was exposed, follow the receipt's `if_exposed` command on the
+ brain host, then reconnect with `--fresh-token`.
+
+The full symptom table, with preview, apply and verify commands for each
+issue, is in `docs/guides/repair.md#fix-wave-5`.
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 7941f4246a..023b7769bd 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -21,7 +21,7 @@
"brain-link-discipline/SKILL.md": "489268f71a01abb6213df8a8bb5f4d16d587b09dd670ac3c47876a8ed808b5ae",
"brain-link-discipline/routing-eval.jsonl": "0adea4c6d72fdb849c12fe2cad718568b9ab704299b00b093c40c2284faf684c",
"brain-ops/SKILL.md": "075666e81df0b5f8ab23493d4972ef5ba42bc789ae213d3bc03e5d3b9c38a3bf",
- "brain-pdf/SKILL.md": "68eb85679718afe504179be780ced483b1fe5916b7b294bd202dceca2d9c9398",
+ "brain-pdf/SKILL.md": "c24727ade7c222606249bbf690ddede1bebe218122c9cf9060a2baa6b63d3bc8",
"brain-pdf/routing-eval.jsonl": "119e4fa113ea45783cee4499e63a729fdeecb4d9a45d47497754b4f5b21d0734",
"brain-taxonomist/SKILL.md": "dea4557b540868ec2c56bf43ee7f63c5d03a22d4047cd0dfbeaf19adef334f60",
"brain-taxonomist/routing-eval.jsonl": "8b485b3d735aace60be703854f0f2e9d97c52d52564efdaf7334a0c39e8d20ae",
@@ -155,6 +155,7 @@
"migrations/v0.60.20.0.md": "9266863a9f76164c64a72b1be17b8ddb3bb97e1c3c5db9f666b69ebc7a228fdd",
"migrations/v0.60.26.0.md": "30d761ef5a2361bad66053f97b7b659304a591274be33e281f4f6df0d7d5566e",
"migrations/v0.60.27.0.md": "1c3ac6a23ccfce8ad299457799b02958f7d21fcd967c471634f73bdb66f2b603",
+ "migrations/v0.60.28.0.md": "f7fa936066fb188f6f3f54bb6c720f57743792e4371d0b98dd3cb5a57d1bd9c9",
"migrations/v0.60.5.0.md": "0d3ee19359a2740de08ac9ec388ddc15e7c72d663afe33832e1e54170528acab",
"migrations/v0.60.6.0.md": "1cbfca2c899e1348acbd61f0baa4c8e723b5283ff868c710c74e116c0cb6726e",
"migrations/v0.7.0.md": "97c2740445a10b1c5c7123c17dbd625fa27a94095b85d27c2b278da756c4c59a",
diff --git a/src/cli.ts b/src/cli.ts
index 8256406007..0189e60a75 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -4,7 +4,7 @@ import { affectsRecall } from './core/types.ts';
import { deliveryVersionSkewWarning } from './core/search/evidence-delivery.ts';
import { installSigchldHandler } from './core/zombie-reap.ts';
installSigchldHandler();
-import { installSignalHandlers as installCleanupSignalHandlers } from './core/process-cleanup.ts';
+import { installCleanupSignalHandlers } from './core/serve-invocation.ts';
import { readFileSync, existsSync, unlinkSync, fstatSync } from 'fs';
import { spawn } from 'child_process';
@@ -330,6 +330,8 @@ async function main() {
const { maybeEmitBackupNag } = await import('./core/backup/status-file.ts');
maybeEmitBackupNag(command, { quiet: getCliOptions().quiet === true });
}
+ // #5137: once per process, when an env key shadows a different config key; never from hook commands.
+ if (command !== 'hook') (await import('./core/ai/key-warnings.ts')).warnShadowedProviderKeys();
const subArgs = args.slice(1);
@@ -1878,6 +1880,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
search: '`search modes|stats|tune` route to the brain host automatically (search_modes / search_stats / search_tune MCP ops). The modes reset form, modes with the source flag (the reset dry-run), and tune apply mutate or preview host config, and `diagnose` runs live retrieval — run those on the host.',
cache: '`cache stats` routes to the brain host automatically (cache_stats MCP op). clear/prune mutate the host cache — run those on the host.',
repair: 'repair runs on the brain host (it publishes coordinated page writes against the local engine). Run `gbrain repair` on the brain host.',
+ projections: 'projections drain rebuilds text projections against the local engine. Run `gbrain projections drain` on the brain host.',
quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',
};
@@ -2900,6 +2903,7 @@ SETUP
upgrade Self-update
check-update [--json] Check for new versions
repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)
+ projections drain [--limit n] Rebuild queued text projections now [--json]
doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)
integrations [subcommand] Manage integration recipes (senses + reflexes)
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 86fba5fedb..aa7eea42a7 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -182,6 +182,9 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// System One decide: local CLI only (calibrate, receipts and proposals are trusted-local); help and a
// key-only probe answer without a brain, so the module opens its own engine.
{ name: 'decide', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/decide.ts') },
+ // #5401: projections drain refuses a resident-held PGLite brain before any engine opens, so the
+ // module opens its own engine. Trusted local CLI only (not an operation).
+ { name: 'projections', phase: 'pre-connect-own-engine', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/projections.ts') },
// Dispatched by handleCliOnly's explicit deferred-persistence step (never by the table step).
// selfHelp: v0.39.3.0 WARN-5: capture's detailed HELP constant (src/commands/capture.ts:90+) was
diff --git a/src/cli/commands/projections.ts b/src/cli/commands/projections.ts
new file mode 100644
index 0000000000..18fba7f75a
--- /dev/null
+++ b/src/cli/commands/projections.ts
@@ -0,0 +1,74 @@
+/**
+ * `gbrain projections drain`: pre-connect dispatch that opens its own engine,
+ * so the PGLite resident-owner refusal (#5401, exit 2) happens before any
+ * engine opens. The record lives in src/cli/command-table.ts.
+ */
+import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../../core/cli-force-exit.ts';
+import type { CliDispatchContext } from '../command-table.ts';
+
+export async function run(args: string[], ctx: CliDispatchContext): Promise<void> {
+ const projections = await import('../../commands/projections.ts');
+ if (args.length === 0 || args.includes('--help') || args.includes('-h')) {
+ console.log(projections.PROJECTIONS_HELP);
+ return;
+ }
+ const json = args.includes('--json');
+ const { OperationError } = await import('../../core/ops/contract.ts');
+ const { reportPersistenceCliError } = await import('../../commands/persistence-delegate.ts');
+ const refuse = async (error: InstanceType<typeof OperationError>) => {
+ await reportPersistenceCliError(error, json);
+ setCliExitVerdict(2);
+ };
+ const limitAt = args.indexOf('--limit');
+ const limitValue = limitAt === -1 ? undefined : args[limitAt + 1];
+ const known = new Set(['drain', '--json', '--limit', ...(limitValue === undefined ? [] : [limitValue])]);
+ const unknown = args.find(arg => !known.has(arg));
+ if (args[0] !== 'drain' || unknown !== undefined) {
+ await refuse(new OperationError('invalid_params', `Unknown projections argument '${unknown ?? args[0]}'.`,
+ 'Run `gbrain projections drain [--limit <n>] [--json]`.', projections.PROJECTION_DRAIN_DOCS));
+ return;
+ }
+ const limit = limitValue === undefined ? undefined : Number(limitValue);
+ if (limitAt !== -1 && (!Number.isSafeInteger(limit) || limit! < 1)) {
+ await refuse(new OperationError('invalid_params', `--limit needs a positive whole number of pages, not '${limitValue ?? ''}'.`,
+ 'Run `gbrain projections drain --limit 1000`, or omit --limit to drain everything queued.', projections.PROJECTION_DRAIN_DOCS));
+ return;
+ }
+
+ const { loadConfig } = await import('../../core/config.ts');
+ const { getCliOptions } = await import('../../core/cli-options.ts');
+ const { resolveBrainId } = await import('../../core/brain-resolver.ts');
+ const { loadMounts } = await import('../../core/brain-registry.ts');
+ const { persistenceConfigForBrain } = await import('../../core/persistence/local-client.ts');
+ const { inspectLockHolder } = await import('../../core/pglite-lock.ts');
+ const brainId = resolveBrainId(getCliOptions().brain, process.cwd());
+ const config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());
+ if (config?.engine === 'pglite' && config.database_path && !config.database_url) {
+ const holder = inspectLockHolder(config.database_path);
+ if (holder.held) { await refuse(projections.projectionOwnerResidentError(holder, config.database_path, brainId)); return; }
+ }
+
+ const { createProgress } = await import('../../core/progress.ts');
+ const { cliOptsToProgressOptions } = await import('../../core/cli-options.ts');
+ const engine = await ctx.connectEngine();
+ try {
+ const result = await projections.drainProjections(engine, { limit, progress: createProgress(cliOptsToProgressOptions(getCliOptions())) });
+ if (json) {
+ const { limited: _limited, ...payload } = result;
+ await writeStdoutFinal(JSON.stringify(payload) + '\n');
+ } else {
+ for (const failure of result.failed) {
+ console.error(`failed: ${failure.source_id}/${failure.slug}: ${failure.reason}\n next: ${projections.projectionFailureNextAction(failure)}`);
+ }
+ const summary = `projections drain: ${result.rebuilt} rebuilt, ${result.superseded} superseded, ${result.failed.length} failed, ${result.remaining} remaining.`;
+ const tail = result.remaining === 0 ? ' The projection backlog is empty.'
+ : result.limited ? ` Stopped at --limit ${limit}; run \`gbrain projections drain\` again to continue.`
+ : result.failed.length ? ' Failed pages stay queued; fix them as shown above, then run `gbrain projections drain` again.'
+ : ' Rows queued during this run are left for the next run or the resident owner.';
+ await writeStdoutFinal(summary + tail + '\n');
+ }
+ if (result.failed.length) setCliExitVerdict(1);
+ } finally {
+ await finishCliTeardown({ engine });
+ }
+}
diff --git a/src/commands/autopilot.ts b/src/commands/autopilot.ts
index 2e33d2e717..8db039b649 100644
--- a/src/commands/autopilot.ts
+++ b/src/commands/autopilot.ts
@@ -55,7 +55,31 @@ import {
autopilotPauseReason,
autopilotDisableStrikesPath,
autopilotLaunchdLabel,
+ autopilotWrapperOwner,
+ resolveAutopilotJob,
+ DEFAULT_AUTOPILOT_SYSTEMD_UNIT,
+ type AutopilotJob,
} from '../core/autopilot-paths.ts';
+import {
+ BOOTSTRAP_MARKER,
+ brainCommand,
+ cronLineBelongsToBrain,
+ crontabIndicatesAutopilotInstall,
+ autopilotJobStatus,
+ detectOpenClaw,
+ legacyStartScriptPath,
+ plistPath,
+ plistWrapperPath,
+ readIfExists,
+ refuseForeignJob,
+ replaceLegacySharedJob,
+ scriptWrapperPath,
+ shellQuote,
+ stripBootstrapLines,
+ systemdUnitPath,
+ unitWrapperPath,
+} from './autopilot/jobs.ts';
+export { cronLineBelongsToBrain, crontabIndicatesAutopilotInstall, plistWrapperPath, scriptWrapperPath, unitWrapperPath };
export { autopilotLockPath, autopilotDisabledMarkerPath, autopilotPausedMarkerPath, autopilotLaunchdLabel };
export { relativeSourceLocalPathSkipWarning as relativeLocalPathSkipWarning };
@@ -137,7 +161,7 @@ export function logError(phase: string, e: unknown) {
const line = `[${ts}] [${phase}] ERROR: ${msg}`;
console.error(line);
try {
- const logDir = join(process.env.HOME || '', '.gbrain');
+ const logDir = gbrainHomePath();
mkdirSync(logDir, { recursive: true });
appendFileSync(join(logDir, 'autopilot.log'), line + '\n');
} catch { /* best-effort */ }
@@ -615,18 +639,6 @@ export async function runAutopilot(engine: BrainEngine, args: string[]) {
// --- Install/Uninstall ---
-function plistPath(): string {
- return join(process.env.HOME || '', 'Library', 'LaunchAgents', `${autopilotLaunchdLabel()}.plist`);
-}
-
-function systemdUnitPath(): string {
- return join(process.env.HOME || '', '.config', 'systemd', 'user', AUTOPILOT_SYSTEMD_UNIT);
-}
-
-function ephemeralStartScriptPath(): string {
- return join(process.env.HOME || '', '.gbrain', 'start-autopilot.sh');
-}
-
export type InstallTarget = 'macos' | 'linux-systemd' | 'ephemeral-container' | 'linux-cron';
/**
@@ -661,25 +673,10 @@ export function detectInstallTarget(): InstallTarget {
return 'linux-cron';
}
-function detectOpenClaw(): { detected: boolean; bootstrapCandidates: string[] } {
- const home = process.env.HOME || '';
- const candidates = [
- process.env.OPENCLAW_HOME ? join(process.env.OPENCLAW_HOME, 'hooks', 'bootstrap', 'ensure-services.sh') : '',
- join(process.cwd(), 'hooks', 'bootstrap', 'ensure-services.sh'),
- join(home, '.claude', 'hooks', 'bootstrap', 'ensure-services.sh'),
- ].filter(Boolean) as string[];
- const existing = candidates.filter(p => existsSync(p));
- const signal = !!process.env.OPENCLAW_HOME
- || existsSync(join(process.cwd(), 'openclaw.json'))
- || existsSync(join(home, 'openclaw.json'))
- || existing.length > 0;
- return { detected: signal, bootstrapCandidates: existing };
-}
-
/** systemd unit name. The launchd label lives in `autopilotLaunchdLabel()`
* (core/autopilot-paths.ts) so installer, uninstaller, status, and the
* wrapper's self-disable can never name different jobs. */
-export const AUTOPILOT_SYSTEMD_UNIT = 'gbrain-autopilot.service';
+export const AUTOPILOT_SYSTEMD_UNIT = DEFAULT_AUTOPILOT_SYSTEMD_UNIT;
/**
@@ -707,14 +704,14 @@ export const AUTOPILOT_SYSTEMD_UNIT = 'gbrain-autopilot.service';
* Exported pure so tests can assert the emitted shape per target without
* installing a daemon.
*/
-export function generateSelfDisableGuard(repoPath: string, target: InstallTarget): string {
+export function generateSelfDisableGuard(repoPath: string, target: InstallTarget, job: AutopilotJob = resolveAutopilotJob()): string {
const q = (s: string) => s.replace(/'/g, "'\\''");
const marker = autopilotDisabledMarkerPath();
const disableCmd =
target === 'macos'
- ? ` launchctl bootout "gui/$(id -u)/${autopilotLaunchdLabel()}" 2>/dev/null || true\n`
+ ? ` launchctl bootout "gui/$(id -u)/${job.launchdLabel}" 2>/dev/null || true\n`
: target === 'linux-systemd'
- ? ` systemctl --user disable --now ${AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true\n`
+ ? ` systemctl --user disable --now ${job.systemdUnit} 2>/dev/null || true\n`
: '';
const strikes = autopilotDisableStrikesPath();
return `# Self-disable if the captured checkout is gone (rename / relocation / deletion).
@@ -772,7 +769,7 @@ const GBRAIN_ENV_TEMPLATE = `# gbrain daemon environment — sourced by autopilo
# daemon's home from this file's own location.
`;
-export function writeWrapperScript(repoPath: string, target: InstallTarget): string {
+export function writeWrapperScript(repoPath: string, target: InstallTarget, job: AutopilotJob = resolveAutopilotJob()): string {
// gbrainHomePath, not raw $HOME: the daemon writes its lock/markers through
// it and the status command reads through it, so a GBRAIN_HOME install must
// keep its wrapper (and the start-script detection that looks for it) in
@@ -855,7 +852,7 @@ export function writeWrapperScript(repoPath: string, target: InstallTarget): str
# or which init file the OS loaded.
export PATH=${runtimePathPrefix}"$HOME/.bun/bin:$PATH"
${process.env.GBRAIN_HOME ? `# Baked at install: the supervisor does not pass the installer's env, and\n# without this the daemon would read/write a different home than the\n# install that configured it.\nexport GBRAIN_HOME='${(process.env.GBRAIN_HOME).replace(/'/g, "'\\''")}'\n` : ''}
-${generateSelfDisableGuard(repoPath, target)}# #3696: daemon cwd = the repo, so any legacy RELATIVE sources.local_path /
+${generateSelfDisableGuard(repoPath, target, job)}# #3696: daemon cwd = the repo, so any legacy RELATIVE sources.local_path /
# sync.repo_path row resolves against it instead of a phantom path under the
# supervisor's cwd. Done HERE — after the guard has proven the repo exists —
# and NOT via launchd's plist WorkingDirectory: launchd chdir()s before exec,
@@ -917,7 +914,20 @@ async function installDaemon(engine: BrainEngine, args: string[]) {
const injectBootstrap = args.includes('--inject-bootstrap');
const noInject = args.includes('--no-inject');
- const wrapperPath = writeWrapperScript(repoPath, target);
+ // #5195: every name this brain's job uses (minting the install id on a
+ // non-default brain's first install), and a refusal before anything is
+ // written when the job under that name runs another live brain.
+ const job = resolveAutopilotJob({ mint: true });
+ try {
+ if (target === 'macos') refuseForeignJob(job.launchdLabel, plistWrapperPath(readIfExists(plistPath(job.launchdLabel)) ?? ''), job);
+ if (target === 'linux-systemd') refuseForeignJob(job.systemdUnit, unitWrapperPath(readIfExists(systemdUnitPath(job.systemdUnit)) ?? ''), job);
+ if (target === 'ephemeral-container') refuseForeignJob(job.startScriptPath, scriptWrapperPath(readIfExists(job.startScriptPath) ?? ''), job);
+ } catch (e) {
+ console.error(e instanceof Error ? e.message : String(e));
+ process.exit(1);
+ }
+
+ const wrapperPath = writeWrapperScript(repoPath, target, job);
// #2608: tell the operator about the deterministic key channel — launchd/
// systemd don't inherit the login shell env, and rc-file interactive guards
// routinely swallow exports, so "it works in my terminal" keys often never
@@ -936,16 +946,16 @@ async function installDaemon(engine: BrainEngine, args: string[]) {
switch (target) {
case 'macos':
- installLaunchd(wrapperPath, home, repoPath);
+ installLaunchd(wrapperPath, home, repoPath, job);
break;
case 'linux-systemd':
- installSystemd(wrapperPath, repoPath);
+ installSystemd(wrapperPath, repoPath, job);
break;
case 'ephemeral-container':
- installEphemeralContainer(wrapperPath, home, repoPath, { injectBootstrap, noInject });
+ installEphemeralContainer(wrapperPath, home, repoPath, { injectBootstrap, noInject }, job);
break;
case 'linux-cron':
- installCrontab(wrapperPath, home);
+ installCrontab(wrapperPath, home, job);
break;
default: {
console.error(`Unknown --target "${forcedTarget}". Allowed: macos, linux-systemd, ephemeral-container, linux-cron.`);
@@ -988,12 +998,14 @@ export function pgliteDaemonGuardMessage(engineKind: string, force: boolean): st
// proven it exists (writeWrapperScript), which is what makes legacy
// RELATIVE sources.local_path / sync.repo_path rows resolve against the
// repo instead of a phantom path.
-export function generateLaunchdPlist(wrapperPath: string, home: string): string {
+export function generateLaunchdPlist(wrapperPath: string, home: string, job?: AutopilotJob): string {
+ const logPath = job?.logPath ?? `${home}/.gbrain/autopilot.log`;
+ const errPath = job?.errPath ?? `${home}/.gbrain/autopilot.err`;
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(autopilotLaunchdLabel())}</string>
+ <key>Label</key><string>${escapeXml(job?.launchdLabel ?? autopilotLaunchdLabel())}</string>
<key>ProgramArguments</key><array>
<string>${escapeXml(wrapperPath)}</string>
</array>
@@ -1010,36 +1022,39 @@ export function generateLaunchdPlist(wrapperPath: string, home: string): string
floor; launchd would have applied a default of 10s if unset.
-->
<key>ThrottleInterval</key><integer>60</integer>
- <key>StandardOutPath</key><string>${escapeXml(home)}/.gbrain/autopilot.log</string>
- <key>StandardErrorPath</key><string>${escapeXml(home)}/.gbrain/autopilot.err</string>
+ <key>StandardOutPath</key><string>${escapeXml(logPath)}</string>
+ <key>StandardErrorPath</key><string>${escapeXml(errPath)}</string>
</dict>
</plist>`;
}
-function installLaunchd(wrapperPath: string, home: string, repoPath: string) {
- const plist = generateLaunchdPlist(wrapperPath, home);
+function installLaunchd(wrapperPath: string, home: string, repoPath: string, job: AutopilotJob) {
+ const plist = generateLaunchdPlist(wrapperPath, home, job);
try {
const agentsDir = join(home, 'Library', 'LaunchAgents');
mkdirSync(agentsDir, { recursive: true });
- writeFileSync(plistPath(), plist, { mode: 0o644 });
+ replaceLegacySharedJob(job, 'macos');
+ writeFileSync(plistPath(job.launchdLabel), plist, { mode: 0o644 });
// launchd rejects group/world-writable agent plists: bootstrap/load fails
// with the opaque "Bootstrap failed: 5: Input/output error" and the login
// scan skips the file silently. writeFileSync's mode only applies on
// create — a reinstall over an existing plist keeps the old bits (a 0666
// plist written under an umask-0 parent stays 0666 forever) — so
// normalize unconditionally.
- chmodSync(plistPath(), 0o644);
+ chmodSync(plistPath(job.launchdLabel), 0o644);
// Unload-before-load (same pattern as uninstall): bare `launchctl load`
// on an already-loaded agent errors and aborted every reinstall — and a
// running daemon must be relaunched anyway to pick up a regenerated
// wrapper / env file (#2608: the boot warning tells users to re-run
// --install to reload; this line is what makes that true on macOS).
- execSync(`launchctl unload "${plistPath()}" 2>/dev/null || true`, { stdio: 'pipe' });
- execSync(`launchctl load "${plistPath()}"`, { stdio: 'pipe' });
- console.log(`Installed launchd service: ${autopilotLaunchdLabel()}`);
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- launchdLabel comes from autopilotLaunchdLabel(), which rejects anything outside [A-Za-z0-9._-] and '..'; trusted local CLI only
+ execSync(`launchctl unload "${plistPath(job.launchdLabel)}" 2>/dev/null || true`, { stdio: 'pipe' });
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- same grammar-checked label
+ execSync(`launchctl load "${plistPath(job.launchdLabel)}"`, { stdio: 'pipe' });
+ console.log(`Installed launchd service: ${job.launchdLabel}`);
console.log(` Repo: ${repoPath}`);
- console.log(` Log: ~/.gbrain/autopilot.log`);
+ console.log(` Log: ${job.logPath}`);
console.log(' Uninstall: gbrain autopilot --uninstall');
} catch (e: unknown) {
const msg = e instanceof Error ? e.message : String(e);
@@ -1065,7 +1080,9 @@ function installLaunchd(wrapperPath: string, home: string, repoPath: string) {
* Exported so the v0.42 migration can recognize the prior generated shape and
* rewrite existing `on-failure` units in place.
*/
-export function generateSystemdUnit(wrapperPath: string): string {
+export function generateSystemdUnit(wrapperPath: string, job?: AutopilotJob): string {
+ const logPath = job && job.kind !== 'default' ? job.logPath : '%h/.gbrain/autopilot.log';
+ const errPath = job && job.kind !== 'default' ? job.errPath : '%h/.gbrain/autopilot.err';
return `[Unit]
Description=GBrain Autopilot
After=network-online.target
@@ -1077,8 +1094,8 @@ Type=simple
ExecStart=${wrapperPath}
Restart=always
RestartSec=30
-StandardOutput=append:%h/.gbrain/autopilot.log
-StandardError=append:%h/.gbrain/autopilot.err
+StandardOutput=append:${logPath}
+StandardError=append:${errPath}
[Install]
WantedBy=default.target
@@ -1141,27 +1158,30 @@ export function migrateSystemdUnitToRestartAlways(): { rewritten: boolean; reaso
}
}
-function installSystemd(wrapperPath: string, repoPath: string) {
- const unit = generateSystemdUnit(wrapperPath);
+function installSystemd(wrapperPath: string, repoPath: string, job: AutopilotJob) {
+ const unit = generateSystemdUnit(wrapperPath, job);
try {
- const unitPath = systemdUnitPath();
+ const unitPath = systemdUnitPath(job.systemdUnit);
mkdirSync(join(process.env.HOME || '', '.config', 'systemd', 'user'), { recursive: true });
+ replaceLegacySharedJob(job, 'linux-systemd');
writeFileSync(unitPath, unit, { mode: 0o644 });
// Same umask-0 hardening as the launchd path (systemd warns on
// world-writable units); mode only applies on create, so normalize.
chmodSync(unitPath, 0o644);
execSync('systemctl --user daemon-reload', { stdio: 'pipe', timeout: 10_000 });
- execSync(`systemctl --user enable --now ${AUTOPILOT_SYSTEMD_UNIT}`, { stdio: 'pipe', timeout: 15_000 });
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- systemdUnit is a constant or gbrain-autopilot-<8 hex chars>.service from the install id; trusted local CLI only
+ execSync(`systemctl --user enable --now ${job.systemdUnit}`, { stdio: 'pipe', timeout: 15_000 });
// enable --now does NOT restart an already-active unit, so a reinstall
// over a running daemon would keep the old process (and its stale env)
// alive indefinitely (#2608: the boot warning tells users to re-run
// --install to reload; this line is what makes that true on systemd).
// try-restart only bounces a running unit — a fresh install just started
// above is restarted at worst, never left stopped.
- execSync(`systemctl --user try-restart ${AUTOPILOT_SYSTEMD_UNIT}`, { stdio: 'pipe', timeout: 15_000 });
- console.log(`Installed systemd user service: ${AUTOPILOT_SYSTEMD_UNIT}`);
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- same derived unit name
+ execSync(`systemctl --user try-restart ${job.systemdUnit}`, { stdio: 'pipe', timeout: 15_000 });
+ console.log(`Installed systemd user service: ${job.systemdUnit}`);
console.log(` Repo: ${repoPath}`);
- console.log(' Log: ~/.gbrain/autopilot.log');
+ console.log(` Log: ${job.logPath}`);
console.log(' Uninstall: gbrain autopilot --uninstall');
} catch (e: unknown) {
console.error(`Failed to install systemd unit: ${e instanceof Error ? e.message : e}`);
@@ -1175,18 +1195,21 @@ function installEphemeralContainer(
home: string,
repoPath: string,
opts: { injectBootstrap: boolean; noInject: boolean },
+ job: AutopilotJob,
) {
// Write a start script the agent's bootstrap can source on every container start.
- const safeWrapperPath = wrapperPath.replace(/'/g, "'\\''");
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- homeDir is configDir() of the local operator's own brain
+ const pidPath = join(job.homeDir, 'autopilot.pid');
const script = `#!/bin/bash
# Auto-generated by gbrain autopilot --install (ephemeral-container target)
# Ephemeral filesystems lose crontab on every deploy; source this from
# your agent's bootstrap instead.
-nohup '${safeWrapperPath}' > ~/.gbrain/autopilot.log 2>&1 &
-echo \$! > ~/.gbrain/autopilot.pid
+nohup ${shellQuote(wrapperPath)} > ${shellQuote(job.logPath)} 2>&1 &
+echo \$! > ${shellQuote(pidPath)}
`;
- const scriptPath = ephemeralStartScriptPath();
- mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const scriptPath = job.startScriptPath;
+ mkdirSync(job.homeDir, { recursive: true });
+ replaceLegacySharedJob(job, 'ephemeral-container');
writeFileSync(scriptPath, script, { mode: 0o755 });
console.log('Ephemeral container detected (Render / Railway / Fly / Docker).');
@@ -1196,7 +1219,7 @@ echo \$! > ~/.gbrain/autopilot.pid
// from it — that process keeps its old environment until the container
// restarts. Never auto-kill; say how (#2608, same honesty as the cron path).
console.log(' An already-running autopilot keeps its old environment until the container');
- console.log(' restarts (or: kill $(cat ~/.gbrain/autopilot.pid), then re-run the start script).');
+ console.log(` restarts (or: kill $(cat ${shellQuote(pidPath)}), then re-run the start script).`);
console.log('');
console.log('Crontab is unreliable here (wiped on deploy). Add ONE LINE to your');
console.log('agent bootstrap to launch autopilot on every start:');
@@ -1225,8 +1248,8 @@ echo \$! > ~/.gbrain/autopilot.pid
for (const candidate of bootstrapCandidates) {
try {
const existing = readFileSync(candidate, 'utf-8');
- const marker = '# gbrain:autopilot v0.11.0';
- if (existing.includes(marker)) {
+ const marker = BOOTSTRAP_MARKER;
+ if (existing.includes(`${marker}\nbash ${scriptPath}`)) {
console.log(` [skip] ${candidate} already has the gbrain marker`);
continue;
}
@@ -1245,13 +1268,23 @@ echo \$! > ~/.gbrain/autopilot.pid
console.log(' Uninstall: gbrain autopilot --uninstall');
}
-function installCrontab(wrapperPath: string, home: string) {
+function installCrontab(wrapperPath: string, home: string, job: AutopilotJob) {
// Linux/WSL without systemd — crontab runs the wrapper every 5 minutes.
- const safeWrapperPath = wrapperPath.replace(/'/g, "'\\''");
- const cronLine = `*/5 * * * * '${safeWrapperPath}' >> '${home.replace(/'/g, "'\\''")}/.gbrain/autopilot.log' 2>&1`;
+ // #5195: a non-default brain's line carries its marker; the default brain's
+ // line is unchanged.
+ const cronLine = `*/5 * * * * ${shellQuote(wrapperPath)} >> ${shellQuote(job.logPath)} 2>&1${job.cronMarker ? ` ${job.cronMarker}` : ''}`;
try {
- const existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });
- if (existing.includes('gbrain autopilot') || existing.includes('autopilot-run.sh')) {
+ let existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });
+ // A line of this brain is stale when it predates the brain's marker (a
+ // pre-#5195 shared line) or runs a wrapper that is not this brain's
+ // current one (the brain moved): either is replaced, never duplicated.
+ const ownLines = existing.split('\n').filter(l => cronLineBelongsToBrain(l, job));
+ const staleLines = ownLines.filter(l =>
+ (job.cronMarker !== null && !l.includes(job.cronMarker)) || (scriptWrapperPath(l) !== null && scriptWrapperPath(l) !== wrapperPath));
+ if (staleLines.length > 0) {
+ existing = existing.split('\n').filter(l => !staleLines.includes(l)).join('\n');
+ console.log(`Replacing ${staleLines.length} crontab line(s) that ran this brain from an older install with its current line.`);
+ } else if (ownLines.length > 0) {
console.log('Crontab entry already exists. Remove with: gbrain autopilot --uninstall');
// The wrapper (and env template) were regenerated above, but cron
// cannot reload a loop that is already running — it keeps its old
@@ -1263,7 +1296,9 @@ function installCrontab(wrapperPath: string, home: string) {
return;
}
// Use a temp file instead of echo pipe to avoid shell escaping issues (#1)
- const tmpFile = join(home, '.gbrain', 'crontab.tmp');
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- homeDir is configDir() of the local operator's own brain
+ const tmpFile = join(job.homeDir, 'crontab.tmp');
+ mkdirSync(job.homeDir, { recursive: true });
writeFileSync(tmpFile, existing.trimEnd() + '\n' + cronLine + '\n');
execSync(`crontab '${tmpFile.replace(/'/g, "'\\''")}'`, { stdio: 'pipe' });
try { unlinkSync(tmpFile); } catch { /* best-effort */ }
@@ -1294,10 +1329,20 @@ export function runAutopilotStatus(args: string[]): void {
}
export function uninstallDaemon() {
- const home = process.env.HOME || '';
- // Same resolution as writeWrapperScript — a GBRAIN_HOME install must
- // uninstall the wrapper it actually wrote, not a sibling under raw $HOME.
- const wrapperPath = join(gbrainHomePath(), 'autopilot-run.sh');
+ // #5195: only this brain's job is removed — its own named job (checked to
+ // run this brain's wrapper before removal), plus, for a non-default brain,
+ // a pre-#5195 shared-name job whose wrapper names this brain. A shared job
+ // that runs another live brain is left alone and named.
+ const job = resolveAutopilotJob();
+ const wrapperPath = job.wrapperPath;
+ const ownsDefinition = (name: string, wrapper: string | null): boolean => {
+ const owner = autopilotWrapperOwner(wrapper, job.homeDir);
+ if (owner.owner !== 'other') return true;
+ console.log(`Left ${name} in place: it runs the brain at ${owner.home}. To remove it: ${brainCommand(owner.home, '--uninstall')}`);
+ return false;
+ };
+ const legacyOnly = (wrapper: string | null) => autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';
+ const assigned = job.kind !== 'unassigned';
// Always try all four targets — the user might have run `--install` under
// one target earlier and moved hosts (e.g. macOS laptop → Linux server).
@@ -1306,11 +1351,18 @@ export function uninstallDaemon() {
let removed = 0;
// macOS launchd
- if (existsSync(plistPath())) {
+ const labels: Array<{ label: string; legacy: boolean }> = [];
+ if (assigned) labels.push({ label: job.launchdLabel, legacy: false });
+ if (job.kind !== 'default' && (!assigned || autopilotLaunchdLabel(null) !== job.launchdLabel)) labels.push({ label: autopilotLaunchdLabel(null), legacy: true });
+ for (const { label, legacy } of labels) {
+ const path = plistPath(label);
+ if (!existsSync(path)) continue;
+ const wrapper = plistWrapperPath(readIfExists(path) ?? '');
+ if (legacy ? !legacyOnly(wrapper) : !ownsDefinition(label, wrapper)) continue;
try {
- execSync(`launchctl unload "${plistPath()}" 2>/dev/null || true`, { stdio: 'pipe' });
- unlinkSync(plistPath());
- console.log(`Removed launchd service: ${autopilotLaunchdLabel()}`);
+ execSync(`launchctl unload "${path}" 2>/dev/null || true`, { stdio: 'pipe' });
+ unlinkSync(path);
+ console.log(`Removed launchd service: ${label}`);
removed++;
} catch (e) {
console.error(` [warn] launchd: ${e instanceof Error ? e.message : e}`);
@@ -1318,12 +1370,19 @@ export function uninstallDaemon() {
}
// Linux systemd user unit
- if (existsSync(systemdUnitPath())) {
+ const units: Array<{ unit: string; legacy: boolean }> = [];
+ if (assigned) units.push({ unit: job.systemdUnit, legacy: false });
+ if (job.kind !== 'default') units.push({ unit: DEFAULT_AUTOPILOT_SYSTEMD_UNIT, legacy: true });
+ for (const { unit, legacy } of units) {
+ const path = systemdUnitPath(unit);
+ if (!existsSync(path)) continue;
+ const wrapper = unitWrapperPath(readIfExists(path) ?? '');
+ if (legacy ? !legacyOnly(wrapper) : !ownsDefinition(unit, wrapper)) continue;
try {
- execSync(`systemctl --user disable --now ${AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });
- unlinkSync(systemdUnitPath());
+ execSync(`systemctl --user disable --now ${unit} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });
+ unlinkSync(path);
try { execSync('systemctl --user daemon-reload', { stdio: 'pipe', timeout: 5_000 }); } catch { /* best-effort */ }
- console.log('Removed systemd user service: gbrain-autopilot.service');
+ console.log(`Removed systemd user service: ${unit}`);
removed++;
} catch (e) {
console.error(` [warn] systemd: ${e instanceof Error ? e.message : e}`);
@@ -1331,55 +1390,34 @@ export function uninstallDaemon() {
}
// Ephemeral container start script + bootstrap marker injection
- if (existsSync(ephemeralStartScriptPath())) {
+ const scripts: Array<{ path: string; legacy: boolean }> = [];
+ if (assigned) scripts.push({ path: job.startScriptPath, legacy: false });
+ if (job.kind !== 'default') scripts.push({ path: legacyStartScriptPath(), legacy: true });
+ for (const { path, legacy } of scripts) {
+ if (!existsSync(path)) continue;
+ const wrapper = scriptWrapperPath(readIfExists(path) ?? '');
+ if (legacy ? !legacyOnly(wrapper) : !ownsDefinition(path, wrapper)) continue;
try {
- unlinkSync(ephemeralStartScriptPath());
- console.log('Removed ephemeral start script: ~/.gbrain/start-autopilot.sh');
+ unlinkSync(path);
+ console.log(`Removed ephemeral start script: ${path}`);
removed++;
} catch (e) {
console.error(` [warn] start script: ${e instanceof Error ? e.message : e}`);
}
+ // Remove marker-lines from any OpenClaw bootstrap we previously injected.
+ removed += stripBootstrapLines(path);
}
- // Remove marker-line from any OpenClaw bootstrap we previously injected.
- try {
- const { bootstrapCandidates } = detectOpenClaw();
- for (const candidate of bootstrapCandidates) {
- try {
- const content = readFileSync(candidate, 'utf-8');
- if (!content.includes('# gbrain:autopilot v0.11.0')) continue;
- const lines = content.split('\n');
- const cleaned: string[] = [];
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].includes('# gbrain:autopilot v0.11.0')) {
- // Skip this marker line AND the next line (the bash start-script call).
- i++;
- continue;
- }
- cleaned.push(lines[i]);
- }
- // Backup before edit
- const stamp = new Date().toISOString().replace(/[:.]/g, '-');
- writeFileSync(`${candidate}.bak.${stamp}`, content);
- writeFileSync(candidate, cleaned.join('\n'));
- console.log(`Removed bootstrap marker from: ${candidate}`);
- removed++;
- } catch (e) {
- console.error(` [warn] bootstrap ${candidate}: ${e instanceof Error ? e.message : e}`);
- }
- }
- } catch { /* OpenClaw detection best-effort */ }
// Linux crontab (don't gate on platform — the user may have run `--install
// --target linux-cron` on a different machine that now has the crontab).
try {
const existing = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });
- if (existing.includes('gbrain autopilot') || existing.includes('autopilot-run.sh')) {
- const filtered = existing.split('\n').filter(l =>
- !l.includes('gbrain autopilot') && !l.includes('autopilot-run.sh'),
- ).join('\n');
- const tmpFile = join(home, '.gbrain', 'crontab.tmp');
- mkdirSync(join(home, '.gbrain'), { recursive: true });
- writeFileSync(tmpFile, filtered);
+ const lines = existing.split('\n');
+ const filtered = lines.filter(l => !cronLineBelongsToBrain(l, job));
+ if (filtered.length !== lines.length) {
+ const tmpFile = join(job.homeDir, 'crontab.tmp');
+ mkdirSync(job.homeDir, { recursive: true });
+ writeFileSync(tmpFile, filtered.join('\n'));
execSync(`crontab '${tmpFile.replace(/'/g, "'\\''")}' 2>/dev/null || true`, { stdio: 'pipe' });
try { unlinkSync(tmpFile); } catch { /* best-effort */ }
console.log('Removed crontab entry for gbrain autopilot');
@@ -1397,7 +1435,7 @@ export function uninstallDaemon() {
}
if (removed === 0) {
- console.log('No autopilot install found on this host. Nothing to uninstall.');
+ console.log('No autopilot install found for this brain. Nothing to uninstall.');
}
// A deliberate uninstall ends the disabled/paused story: without this, a
@@ -1506,57 +1544,19 @@ export function classifyAutopilotStatus(input: {
};
}
-/**
- * Which supervisor, if any, currently holds an autopilot install.
- *
- * Checks every target `installDaemon` can produce. The prior version grepped
- * crontab ONLY on non-darwin, so systemd-user and ephemeral-container installs
- * read as "not installed" — cosmetic while status always exited 0, but a hard
- * false failure once the exit code became load-bearing.
- */
-function detectInstalledTarget(): InstallTarget | null {
- if (process.platform === 'darwin' && existsSync(plistPath())) return 'macos';
- if (existsSync(systemdUnitPath())) return 'linux-systemd';
- if (existsSync(join(gbrainHomePath(), 'start-autopilot.sh'))) return 'ephemeral-container';
- try {
- const crontab = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });
- if (crontabIndicatesAutopilotInstall(crontab)) {
- return 'linux-cron';
- }
- } catch { /* no crontab */ }
- return null;
-}
-
-/**
- * Does this crontab contain an autopilot INSTALL line? The installed line
- * invokes the generated wrapper (autopilot-run.sh); older installs called
- * `gbrain autopilot` directly — match either. But the docs also recommend
- * cron-ing `gbrain autopilot --status` as a health monitor, and counting THAT
- * line as an install makes a monitor-only machine report installed/never_run
- * with exit 1 forever. Comments never count. Pure and exported for tests.
- */
-export function crontabIndicatesAutopilotInstall(crontab: string): boolean {
- return crontab.split('\n').some((line) => {
- if (line.trimStart().startsWith('#')) return false;
- if (line.includes('autopilot-run.sh')) return true;
- return line.includes('gbrain autopilot') && !line.includes('--status');
- });
-}
-
function showStatus(json: boolean, intervalSeconds: number) {
// gbrainHomePath, not raw HOME: the daemon writes its lock through
// gbrainHomePath() (#1226), so a GBRAIN_HOME install had status reading one
// directory while the daemon wrote another — a permanent false "stale".
- const home = gbrainHomePath();
+ // #5195: every log sink writes under the brain's own home, so the log is
+ // read only there (a raw-$HOME fallback would show another brain's log).
+ const job = resolveAutopilotJob();
let lastLine = '';
- for (const logPath of [join(home, 'autopilot.log'), join(process.env.HOME || '', '.gbrain', 'autopilot.log')]) {
- try {
- const content = readFileSync(logPath, 'utf-8');
- const lines = content.trim().split('\n');
- lastLine = lines[lines.length - 1] || '';
- break;
- } catch { /* try the next home; supervisor log redirects bake raw $HOME */ }
- }
+ try {
+ const content = readFileSync(job.logPath, 'utf-8');
+ const lines = content.trim().split('\n');
+ lastLine = lines[lines.length - 1] || '';
+ } catch { /* no log yet */ }
let disabledReason: string | null = null;
try {
@@ -1571,7 +1571,8 @@ function showStatus(json: boolean, intervalSeconds: number) {
heartbeatAgeSeconds = Math.max(0, Math.floor((Date.now() - mtimeMs) / 1000));
} catch { /* never ran, or already cleaned up */ }
- const installTarget = detectInstalledTarget();
+ const jobStatus = autopilotJobStatus(job);
+ const installTarget = jobStatus.installTarget;
const report = classifyAutopilotStatus({
installed: installTarget !== null,
installTarget,
@@ -1584,7 +1585,7 @@ function showStatus(json: boolean, intervalSeconds: number) {
const processing = readAutopilotProcessingStatus();
if (json) {
- console.log(JSON.stringify({ ...report, ...processing }));
+ console.log(JSON.stringify({ ...report, ...processing, job: jobStatus.report }));
} else {
switch (report.state) {
case 'not_installed':
@@ -1622,6 +1623,7 @@ function showStatus(json: boolean, intervalSeconds: number) {
console.log(`Stage: ${processing.processing_stage}${processing.retry_at ? `; next retry ${processing.retry_at}` : ''}`);
if (processing.processing_state === 'configuration_blocked') console.log('Repair the worker and selected child installation, then explicitly restart autopilot.');
}
+ for (const line of jobStatus.lines) console.log(line);
if (lastLine) console.log(`Last log: ${lastLine}`);
}
diff --git a/src/commands/autopilot/jobs.ts b/src/commands/autopilot/jobs.ts
new file mode 100644
index 0000000000..35a9aa18ec
--- /dev/null
+++ b/src/commands/autopilot/jobs.ts
@@ -0,0 +1,306 @@
+/**
+ * #5195: one brain's autopilot job definitions on every install target.
+ * Reads and replaces the launchd plist, systemd unit, ephemeral start script and
+ * crontab lines that belong to a brain, judged by the job name it resolves
+ * (`resolveAutopilotJob`) and by the wrapper path each definition runs. Split
+ * out of src/commands/autopilot.ts, which installs, uninstalls and reports.
+ */
+import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'fs';
+import { dirname, join, resolve as resolvePath } from 'path';
+import { execSync } from 'child_process';
+import {
+ autopilotLaunchdLabel,
+ autopilotWrapperOwner,
+ DEFAULT_AUTOPILOT_SYSTEMD_UNIT,
+ type AutopilotJob,
+} from '../../core/autopilot-paths.ts';
+import { errorFor } from '../../core/errors.ts';
+import type { InstallTarget } from '../autopilot.ts';
+
+export function plistPath(label: string): string {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- label is grammar-checked by autopilotLaunchdLabel(); HOME is the operator's own
+ return join(process.env.HOME || '', 'Library', 'LaunchAgents', `${label}.plist`);
+}
+
+export function systemdUnitPath(unit: string = DEFAULT_AUTOPILOT_SYSTEMD_UNIT): string {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- unit is a constant or derived from the hex install id
+ return join(process.env.HOME || '', '.config', 'systemd', 'user', unit);
+}
+
+/** The pre-#5195 shared start script, which every brain used to overwrite. */
+export function legacyStartScriptPath(): string {
+ return join(process.env.HOME || '', '.gbrain', 'start-autopilot.sh');
+}
+
+export const shellQuote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;
+export const unshellQuote = (s: string) => s.replace(/'\\''/g, "'");
+
+/** The wrapper a launchd plist runs (its first ProgramArguments entry). */
+export function plistWrapperPath(plist: string): string | null {
+ const m = /<key>ProgramArguments<\/key>\s*<array>\s*<string>([^<]*)<\/string>/.exec(plist);
+ if (!m) return null;
+ return m[1].replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&');
+}
+
+/** The wrapper a systemd unit runs. */
+export function unitWrapperPath(unit: string): string | null {
+ return /^ExecStart=(.+)$/m.exec(unit)?.[1].trim() || null;
+}
+
+/** The autopilot wrapper a crontab line or start script names, if any. */
+export function scriptWrapperPath(text: string): string | null {
+ const quoted = /'((?:[^']|'\\'')*autopilot-run\.sh)'/.exec(text);
+ if (quoted) return unshellQuote(quoted[1]);
+ return /(\S*autopilot-run\.sh)/.exec(text)?.[1] ?? null;
+}
+
+/**
+ * #5195: does this crontab line belong to this brain's job? A marked line
+ * (`# gbrain-autopilot:<suffix>`) belongs to the brain with that suffix. An
+ * unmarked line predates per-brain names: it belongs to the brain whose
+ * wrapper it names, and to the default brain when it names none.
+ */
+export function cronLineBelongsToBrain(line: string, job: AutopilotJob): boolean {
+ if (!crontabIndicatesAutopilotInstall(line)) return false;
+ const marker = /#\s*gbrain-autopilot:([A-Za-z0-9]+)\s*$/.exec(line);
+ if (marker) return job.suffix !== null && marker[1] === job.suffix;
+ const wrapper = scriptWrapperPath(line);
+ if (!wrapper) return job.kind === 'default';
+ return autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';
+}
+
+/** `GBRAIN_HOME=<parent> gbrain autopilot <verb>` for the brain whose home is `brainHome`. */
+export function brainCommand(brainHome: string, verb: string): string {
+ const parent = dirname(brainHome);
+ const defaultHome = join(process.env.HOME || '', '.gbrain');
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- path comparison only, no fs access
+ return resolvePath(brainHome) === resolvePath(defaultHome)
+ ? `gbrain autopilot ${verb}`
+ : `GBRAIN_HOME=${shellQuote(parent)} gbrain autopilot ${verb}`;
+}
+
+/**
+ * ENG-O11: before replacing a job, make sure its wrapper names this brain. A
+ * job whose wrapper belongs to another live brain is that brain's supervision;
+ * replacing it would silently stop it (the #5195 failure).
+ */
+export function refuseForeignJob(jobName: string, wrapperPath: string | null, job: AutopilotJob): void {
+ const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);
+ if (owner.owner !== 'other') return;
+ throw errorFor({
+ class: 'AutopilotJobOwnedByOtherBrain',
+ code: 'autopilot_job_owned_by_other_brain',
+ message: `The autopilot job ${jobName} runs the brain at ${owner.home}, not this brain at ${job.homeDir}.`,
+ hint: `Give that brain its own job first: ${brainCommand(owner.home, '--install')}; then re-run: ${brainCommand(job.homeDir, '--install')}`,
+ docs_url: 'docs/guides/live-sync.md#several-brains-on-one-host',
+ });
+}
+
+export function readIfExists(path: string): string | null {
+ try { return readFileSync(path, 'utf-8'); } catch { return null; }
+}
+
+export function detectOpenClaw(): { detected: boolean; bootstrapCandidates: string[] } {
+ const home = process.env.HOME || '';
+ const candidates = [
+ process.env.OPENCLAW_HOME ? join(process.env.OPENCLAW_HOME, 'hooks', 'bootstrap', 'ensure-services.sh') : '',
+ join(process.cwd(), 'hooks', 'bootstrap', 'ensure-services.sh'),
+ join(home, '.claude', 'hooks', 'bootstrap', 'ensure-services.sh'),
+ ].filter(Boolean) as string[];
+ const existing = candidates.filter(p => existsSync(p));
+ const signal = !!process.env.OPENCLAW_HOME
+ || existsSync(join(process.cwd(), 'openclaw.json'))
+ || existsSync(join(home, 'openclaw.json'))
+ || existing.length > 0;
+ return { detected: signal, bootstrapCandidates: existing };
+}
+
+export const BOOTSTRAP_MARKER = '# gbrain:autopilot v0.11.0';
+
+/**
+ * Remove the bootstrap lines that launch `scriptPath` (the marker line and the
+ * `bash <script>` line after it) from every OpenClaw bootstrap candidate.
+ * Another brain's injected lines name its own script and are left alone.
+ */
+export function stripBootstrapLines(scriptPath: string): number {
+ let removed = 0;
+ try {
+ const { bootstrapCandidates } = detectOpenClaw();
+ for (const candidate of bootstrapCandidates) {
+ try {
+ const content = readFileSync(candidate, 'utf-8');
+ if (!content.includes(`${BOOTSTRAP_MARKER}\nbash ${scriptPath}`)) continue;
+ const lines = content.split('\n');
+ const cleaned: string[] = [];
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].includes(BOOTSTRAP_MARKER) && lines[i + 1] === `bash ${scriptPath}`) {
+ // Skip this marker line AND the next line (the bash start-script call).
+ i++;
+ continue;
+ }
+ cleaned.push(lines[i]);
+ }
+ // Backup before edit
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ writeFileSync(`${candidate}.bak.${stamp}`, content);
+ writeFileSync(candidate, cleaned.join('\n'));
+ console.log(`Removed bootstrap marker from: ${candidate}`);
+ removed++;
+ } catch (e) {
+ console.error(` [warn] bootstrap ${candidate}: ${e instanceof Error ? e.message : e}`);
+ }
+ }
+ } catch { /* OpenClaw detection best-effort */ }
+ return removed;
+}
+
+/**
+ * #5195: a non-default brain installed by an older gbrain ran under the shared
+ * job name. Installing it again on the same target removes that shared job —
+ * only when its wrapper names this brain — before the brain's own job is
+ * written, and says so. Crontab lines are handled by installCrontab.
+ */
+export function replaceLegacySharedJob(job: AutopilotJob, target: InstallTarget): void {
+ if (job.kind === 'default') return;
+ const own = (wrapper: string | null) => autopilotWrapperOwner(wrapper, job.homeDir).owner === 'own';
+ if (target === 'macos') {
+ const legacyLabel = autopilotLaunchdLabel(null);
+ const path = plistPath(legacyLabel);
+ if (legacyLabel === job.launchdLabel || !own(plistWrapperPath(readIfExists(path) ?? ''))) return;
+ execSync(`launchctl unload "${path}" 2>/dev/null || true`, { stdio: 'pipe' });
+ unlinkSync(path);
+ console.log(`Replaced the shared launchd job ${legacyLabel}, which ran this brain, with ${job.launchdLabel}.`);
+ } else if (target === 'linux-systemd') {
+ const path = systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT);
+ if (!own(unitWrapperPath(readIfExists(path) ?? ''))) return;
+ execSync(`systemctl --user disable --now ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT} 2>/dev/null || true`, { stdio: 'pipe', timeout: 10_000 });
+ unlinkSync(path);
+ console.log(`Replaced the shared systemd unit ${DEFAULT_AUTOPILOT_SYSTEMD_UNIT}, which ran this brain, with ${job.systemdUnit}.`);
+ } else if (target === 'ephemeral-container') {
+ const path = legacyStartScriptPath();
+ if (path === job.startScriptPath || !own(scriptWrapperPath(readIfExists(path) ?? ''))) return;
+ unlinkSync(path);
+ stripBootstrapLines(path);
+ console.log(`Replaced the shared start script ${path}, which ran this brain, with ${job.startScriptPath}.`);
+ console.log(` Update any bootstrap line that runs \`bash ${path}\` to run \`bash ${job.startScriptPath}\`.`);
+ }
+}
+
+export interface InstalledJob {
+ target: InstallTarget;
+ /** launchd label, systemd unit, start-script path, or the crontab marker. */
+ name: string;
+ wrapperPath: string | null;
+ /** A pre-#5195 shared-name job that runs this non-default brain. */
+ legacy: boolean;
+}
+
+/**
+ * Which supervisor, if any, currently holds THIS brain's autopilot job (#5195).
+ *
+ * Checks every target `installDaemon` can produce. The prior version grepped
+ * crontab ONLY on non-darwin, so systemd-user and ephemeral-container installs
+ * read as "not installed" — cosmetic while status always exited 0, but a hard
+ * false failure once the exit code became load-bearing. A shared job whose
+ * wrapper runs another live brain is reported separately, never as this
+ * brain's install.
+ */
+export function detectInstalledJob(job: AutopilotJob): { installed: InstalledJob | null; foreign: { name: string; home: string } | null } {
+ let foreign: { name: string; home: string } | null = null;
+ const assigned = job.kind !== 'unassigned';
+ const consider = (target: InstallTarget, name: string, text: string | null, wrapperOf: (t: string) => string | null, legacy: boolean): InstalledJob | null => {
+ if (text === null) return null;
+ const wrapperPath = wrapperOf(text);
+ const owner = autopilotWrapperOwner(wrapperPath, job.homeDir);
+ if (legacy) return owner.owner === 'own' ? { target, name, wrapperPath, legacy } : null;
+ if (owner.owner === 'other') {
+ foreign ??= { name, home: owner.home };
+ return null;
+ }
+ return { target, name, wrapperPath, legacy };
+ };
+ const candidates: Array<() => InstalledJob | null> = [];
+ if (process.platform === 'darwin') {
+ if (assigned) candidates.push(() => consider('macos', job.launchdLabel, readIfExists(plistPath(job.launchdLabel)), plistWrapperPath, false));
+ if (job.kind !== 'default' && (!assigned || autopilotLaunchdLabel(null) !== job.launchdLabel)) {
+ candidates.push(() => consider('macos', autopilotLaunchdLabel(null), readIfExists(plistPath(autopilotLaunchdLabel(null))), plistWrapperPath, true));
+ }
+ }
+ if (assigned) candidates.push(() => consider('linux-systemd', job.systemdUnit, readIfExists(systemdUnitPath(job.systemdUnit)), unitWrapperPath, false));
+ if (job.kind !== 'default') candidates.push(() => consider('linux-systemd', DEFAULT_AUTOPILOT_SYSTEMD_UNIT, readIfExists(systemdUnitPath(DEFAULT_AUTOPILOT_SYSTEMD_UNIT)), unitWrapperPath, true));
+ if (assigned) candidates.push(() => consider('ephemeral-container', job.startScriptPath, readIfExists(job.startScriptPath), scriptWrapperPath, false));
+ if (job.kind !== 'default') candidates.push(() => consider('ephemeral-container', legacyStartScriptPath(), readIfExists(legacyStartScriptPath()), scriptWrapperPath, true));
+ candidates.push(() => {
+ try {
+ const crontab = execSync('crontab -l 2>/dev/null || true', { encoding: 'utf-8' });
+ if (!crontabIndicatesAutopilotInstall(crontab)) return null;
+ const line = crontab.split('\n').find(l => cronLineBelongsToBrain(l, job));
+ if (!line) return null;
+ const legacy = job.cronMarker !== null && !line.includes(job.cronMarker);
+ return { target: 'linux-cron', name: job.cronMarker ?? 'crontab entry', wrapperPath: scriptWrapperPath(line), legacy };
+ } catch { return null; /* no crontab */ }
+ });
+ for (const candidate of candidates) {
+ const installed = candidate();
+ if (installed) return { installed, foreign };
+ }
+ return { installed: null, foreign };
+}
+
+/**
+ * Does this crontab contain an autopilot INSTALL line? The installed line
+ * invokes the generated wrapper (autopilot-run.sh); older installs called
+ * `gbrain autopilot` directly — match either. But the docs also recommend
+ * cron-ing `gbrain autopilot --status` as a health monitor, and counting THAT
+ * line as an install makes a monitor-only machine report installed/never_run
+ * with exit 1 forever. Comments never count. Pure and exported for tests.
+ */
+export function crontabIndicatesAutopilotInstall(crontab: string): boolean {
+ return crontab.split('\n').some((line) => {
+ if (line.trimStart().startsWith('#')) return false;
+ if (line.includes('autopilot-run.sh')) return true;
+ return line.includes('gbrain autopilot') && !line.includes('--status');
+ });
+}
+
+
+/**
+ * DX-O12: this brain's job for `autopilot --status`: the names it resolves to,
+ * the definition actually installed (which may be a pre-#5195 shared-name job,
+ * or one whose wrapper is gone because the brain moved), and the human lines.
+ */
+export function autopilotJobStatus(job: AutopilotJob): { installTarget: InstallTarget | null; report: Record<string, unknown>; lines: string[] } {
+ const { installed, foreign } = detectInstalledJob(job);
+ const wrapperMissing = installed?.wrapperPath ? !existsSync(installed.wrapperPath) : false;
+ const needsReinstall = installed?.legacy ? 'legacy_shared_job' : wrapperMissing ? 'wrapper_missing' : null;
+ const assigned = job.kind !== 'unassigned';
+ const report = {
+ kind: job.kind,
+ suffix: job.suffix,
+ launchd_label: assigned ? job.launchdLabel : null,
+ systemd_unit: assigned ? job.systemdUnit : null,
+ start_script: assigned ? job.startScriptPath : null,
+ cron_marker: job.cronMarker,
+ install_id_path: job.installIdPath,
+ wrapper_path: job.wrapperPath,
+ log_path: job.logPath,
+ installed_definition: installed
+ ? { target: installed.target, name: installed.name, wrapper_path: installed.wrapperPath, wrapper_exists: !wrapperMissing, legacy_shared_name: installed.legacy }
+ : null,
+ needs_reinstall: needsReinstall,
+ shared_job_of_other_brain: foreign,
+ };
+ const lines: string[] = [];
+ const jobName = installed?.name ?? (assigned ? `${job.launchdLabel} (launchd) / ${job.systemdUnit} (systemd)` : null);
+ if (jobName) lines.push(`Job: ${jobName}${job.suffix ? ` (suffix ${job.suffix})` : ''}`);
+ if (job.installIdPath) lines.push(`Install id: ${job.installIdPath}`);
+ lines.push(`Wrapper: ${installed?.wrapperPath ?? job.wrapperPath}`);
+ lines.push(`Log: ${job.logPath}`);
+ if (needsReinstall === 'legacy_shared_job') {
+ lines.push(` This brain runs under the shared job ${installed!.name} from an older gbrain. Give it its own job: ${brainCommand(job.homeDir, '--install')}`);
+ } else if (needsReinstall === 'wrapper_missing') {
+ lines.push(` The job runs ${installed!.wrapperPath}, which no longer exists (the brain moved?). Reinstall: ${brainCommand(job.homeDir, '--install')}`);
+ }
+ if (foreign) lines.push(` ${foreign.name} runs the brain at ${foreign.home}, not this one.`);
+ return { installTarget: installed?.target ?? null, report, lines };
+}
diff --git a/src/commands/doctor/checks/embedding-health.ts b/src/commands/doctor/checks/embedding-health.ts
index e08facceca..68d3ae959d 100644
--- a/src/commands/doctor/checks/embedding-health.ts
+++ b/src/commands/doctor/checks/embedding-health.ts
@@ -9,6 +9,11 @@
import { hnswIndexExpected, hnswMaxDimsForType } from '../../../core/vector-index.ts';
import { checkEmbeddingEnvOverride, checkEmbeddingMigrationState } from './search-eval.ts';
+import type { GBrainConfig } from '../../../core/config.ts';
+import { DEFAULT_EMBEDDING_MODEL } from '../../../core/ai/defaults.ts';
+import { providerKeyShadows, providerKeySource } from '../../../core/ai/provider-env.ts';
+import { credentialEnvName, keyShadowWarning } from '../../../core/ai/key-warnings.ts';
+import { getRecipe } from '../../../core/ai/recipes/index.ts';
import type { Check } from '../../doctor.ts';
import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
@@ -433,3 +438,47 @@ export const embeddingEnvOverrideEntry: DoctorEntry = {
emits: ['embedding_env_override', 'embedding_migration_state'],
run: runEmbeddingEnvOverride,
};
+
+/**
+ * Doctor `embedding_key_source` (#5137, DX-O8): which provider keys come from
+ * the environment and override a different config-plane key, and where the
+ * embedding key in effect comes from. Names only, never key values. It sees
+ * only the environment `gbrain doctor` runs in, not a daemon's. Engine-free
+ * filesystem-lane entry (also under `--fast`).
+ */
+const KEY_SOURCE_DOCS = 'docs/guides/repair.md#embedding-key-source';
+const KEY_SOURCE_SCOPE = 'This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.';
+
+export function embeddingKeySource(fileCfg: GBrainConfig | null, env: Record<string, string | undefined>, file: string): Pick<Check, 'status' | 'message' | 'details'> {
+ const shadows = providerKeyShadows(fileCfg, env);
+ const model = env.GBRAIN_EMBEDDING_MODEL || fileCfg?.embedding_model || DEFAULT_EMBEDDING_MODEL;
+ const variable = credentialEnvName(getRecipe(model.split(':')[0] ?? '')?.auth_env);
+ const source = variable ? providerKeySource(fileCfg, env, variable) : null;
+ const inEffect = !source ? `The embedding model ${model} reads no API key.`
+ : source.kind === 'env' ? `The embedding key in effect is ${source.variable} from this environment.`
+ : source.kind === 'config' ? `The embedding key in effect is ${source.config_key} in ${file}.`
+ : `No embedding key is set here (${source.variable}${source.config_key ? ` or ${source.config_key}` : ''}).`;
+ const details = { shadows: shadows.map(shadow => ({ ...shadow, in_effect: 'env' as const })),
+ embedding_model: model, embedding_key: source ? { kind: source.kind, variable: source.variable, config_key: source.config_key ?? null } : null, docs: KEY_SOURCE_DOCS };
+ if (!shadows.length) return { status: 'ok', message: `${inEffect} No environment variable overrides a different config-plane provider key. ${KEY_SOURCE_SCOPE}`, details };
+ return {
+ status: 'warn',
+ message: `${inEffect} ${shadows.map(shadow => keyShadowWarning(shadow, file).replace('[gbrain] warning: ', '')).join(' ')} ${KEY_SOURCE_SCOPE}`,
+ details,
+ };
+}
+
+async function runEmbeddingKeySource(_ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const { configPath, loadConfigFileOnly } = await import('../../../core/config.ts');
+ let file = 'config.json';
+ try { file = configPath(); } catch { /* invalid GBRAIN_HOME: doctor reports it elsewhere */ }
+ checks.push({ name: 'embedding_key_source', ...embeddingKeySource(loadConfigFileOnly(), process.env, file) });
+ return checks;
+}
+
+export const embeddingKeySourceEntry: DoctorEntry = {
+ name: 'embedding_key_source',
+ emits: ['embedding_key_source'],
+ run: runEmbeddingKeySource,
+};
diff --git a/src/commands/doctor/checks/extraction-sync.ts b/src/commands/doctor/checks/extraction-sync.ts
index 8a75c0cbf2..259c38adcb 100644
--- a/src/commands/doctor/checks/extraction-sync.ts
+++ b/src/commands/doctor/checks/extraction-sync.ts
@@ -840,7 +840,10 @@ export async function computeAtomProvenanceDriftCheck(
// metric omitted, verdict untouched).
`WITH atom AS (
SELECT a.source_id,
- a.frontmatter->>'source_hash' AS sh,
+ -- managed atoms keep their provisional prefix for good (#5770)
+ CASE WHEN a.frontmatter->>'managed_extraction' = 'true'
+ THEN regexp_replace(a.frontmatter->>'source_hash', '^pending:', '')
+ ELSE a.frontmatter->>'source_hash' END AS sh,
-- NULL = slug-unbound: transcript-minted (source_path only) or
-- pre-binding-era. \`ss IS NULL\` is THE predicate for that
-- population everywhere below (#4799 / #4806).
@@ -851,8 +854,8 @@ export async function computeAtomProvenanceDriftCheck(
WHERE a.type = 'atom'
AND a.deleted_at IS NULL
AND a.frontmatter->>'source_hash' IS NOT NULL
- -- in-flight marker written before the extraction commits
- AND a.frontmatter->>'source_hash' NOT LIKE 'pending:%'
+ -- in-flight marker written before an unmanaged extraction commits
+ AND (a.frontmatter->>'source_hash' NOT LIKE 'pending:%' OR a.frontmatter->>'managed_extraction' = 'true')
-- Lookup sets are built ONCE and joined (#4937). A correlated EXISTS in
-- the SELECT list is not rewritten to a semi-join — Postgres re-runs it
-- per atom over substring(content_hash), which no index serves, so the
@@ -888,7 +891,7 @@ export async function computeAtomProvenanceDriftCheck(
[],
);
const r = rows?.[0];
- if (!r) return { name, status: 'warn', message: 'atom provenance query returned no rows' };
+ if (!r) return { name, status: 'warn', message: 'atom provenance query returned no rows', details: { health: 'unknown' } };
const num = (v: string | number | null | undefined) => (v == null ? 0 : Number(v));
const total = num(r.total);
@@ -922,11 +925,9 @@ export async function computeAtomProvenanceDriftCheck(
if (drifted >= MIN_DRIFTED && ratio > WARN_RATIO) {
const fix =
- "review before acting — most drift is an edited source, not a dead one. " +
- "List them with: SELECT slug, frontmatter->>'source_slug' FROM pages a WHERE a.type='atom' " +
- "AND a.deleted_at IS NULL AND NULLIF(a.frontmatter->>'source_slug','') IS NOT NULL " +
- "AND NOT EXISTS (SELECT 1 FROM pages p WHERE p.source_id=a.source_id " +
- "AND p.deleted_at IS NULL AND substring(p.content_hash from 1 for 16)=a.frontmatter->>'source_hash')";
+ "preview the atoms that are safe to retire with gbrain repair stale-atoms (source gone, or source edited and " +
+ "already re-extracted), then apply with the --expect hash it prints. Atoms of an edited page that was not " +
+ "re-extracted yet are the extract_atoms backlog, not stale";
return {
name, status: 'warn',
message:
@@ -944,7 +945,7 @@ export async function computeAtomProvenanceDriftCheck(
details,
};
} catch (err) {
- return { name, status: 'warn', message: `atom_provenance_drift check failed: ${(err as Error).message}` };
+ return { name, status: 'warn', message: `atom_provenance_drift check failed: ${(err as Error).message}`, details: { health: 'unknown' } };
}
}
diff --git a/src/commands/doctor/checks/extractor-facts.ts b/src/commands/doctor/checks/extractor-facts.ts
new file mode 100644
index 0000000000..57cf87f820
--- /dev/null
+++ b/src/commands/doctor/checks/extractor-facts.ts
@@ -0,0 +1,34 @@
+import type { BrainEngine } from '../../../core/engine.ts';
+import type { Check } from '../../doctor.ts';
+import { managedPersistenceEnabled } from '../../../core/persistence/ownership.ts';
+import { classifyExtractorFacts } from '../../../core/repair/extractor-facts.ts';
+
+/**
+ * #5731: conversation-extractor facts the pre-fix canonical projection
+ * expired (expired, row number cleared). Counts the restorable ones by class
+ * (evidenced, ambiguous) and names the explicit-only repair's preview; the
+ * excluded ones (superseded, withdrawn, duplicated, page gone) are reported
+ * but never count as a finding. Read-only.
+ */
+export async function extractorFactsCheck(engine: BrainEngine, sourceIds?: string[]): Promise<Check> {
+ try {
+ const sources = sourceIds ?? (await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE archived IS NOT TRUE ORDER BY id')).map(row => row.id);
+ const facts = await classifyExtractorFacts(engine, sources, { managed: await managedPersistenceEnabled(engine) });
+ const count = (klass: string) => facts.filter(f => f.class === klass).length;
+ const details = { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded'),
+ repair: 'extractor-facts', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' };
+ if (!details.evidenced && !details.ambiguous) {
+ return { name: 'extractor_facts_expired', status: 'ok', details,
+ message: `No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection${details.excluded ? ` (${details.excluded} expired candidate(s) are excluded and stay expired)` : ''}.` };
+ }
+ return { name: 'extractor_facts_expired', status: 'warn', details,
+ message: `${details.evidenced + details.ambiguous} conversation-extractor fact(s) were expired by the pre-v0.60.11.0 canonical projection `
+ + `(${details.evidenced} with receipt evidence, ${details.ambiguous} ambiguous); recall no longer returns them. `
+ + 'Preview the restore on the brain host: gbrain repair extractor-facts — then run the apply command it prints after the user agrees '
+ + '(ambiguous rows only with gbrain repair extractor-facts --include-ambiguous).' };
+ } catch (error) {
+ return { name: 'extractor_facts_expired', status: 'warn',
+ message: `Expired extractor facts could not be inspected: ${error instanceof Error ? error.message : String(error)}. Health is unknown.`,
+ details: { count: 'unknown' } };
+ }
+}
diff --git a/src/commands/doctor/checks/graph-health.ts b/src/commands/doctor/checks/graph-health.ts
index 26acea06dc..ebef87d566 100644
--- a/src/commands/doctor/checks/graph-health.ts
+++ b/src/commands/doctor/checks/graph-health.ts
@@ -274,6 +274,7 @@ export const timelineHistoryEntry: DoctorEntry = {
'writer_version',
'self_capture',
'stale_embedding_effects',
+ 'extractor_facts_expired',
],
run: runTimelineHistory,
};
diff --git a/src/commands/doctor/checks/legacy-job-authority.ts b/src/commands/doctor/checks/legacy-job-authority.ts
new file mode 100644
index 0000000000..92c3a6821a
--- /dev/null
+++ b/src/commands/doctor/checks/legacy-job-authority.ts
@@ -0,0 +1,100 @@
+/**
+ * legacy_job_authority (#5157, DX-O3(a)): the claim gate's population, read
+ * with the gate's own predicate (`UNREVIEWED_LIVE_JOBS_WHERE`) so the two counts
+ * never drift. Live rows whose authority is SQL NULL (authorizable with
+ * `gbrain jobs authorize-legacy --select`) or unsupported non-NULL block
+ * every worker, so the check fails and names the recovery order. Terminal
+ * keyed SQL NULL rows are reported separately: application callers coalesce
+ * onto completed or failed ones and dead or cancelled keys are released on
+ * resubmission, so they need no operator step.
+ */
+import type { BrainEngine } from '../../../core/engine.ts';
+import { ERROR_CATALOGUE } from '../../../core/error-catalogue.ts';
+import { LIVE_LEGACY_PREVIEW, legacyRecoveryHint } from '../../../core/minions/legacy-selection.ts';
+import { UNREVIEWED_LIVE_JOBS_WHERE, parseSubmissionAuthority } from '../../../core/minions/submission-authority.ts';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+export interface LegacyJobAuthorityState {
+ /** Live rows with SQL NULL authority, by status. */
+ authorizable: Record<string, number>;
+ /** Live rows whose non-NULL authority is unsupported (first 10 ids). */
+ unsupported_ids: number[];
+ unsupported: number;
+ /** Every active job (first 10 ids): legacy review needs none. */
+ active_ids: number[];
+ /** Terminal keyed SQL NULL rows, by status. */
+ terminal_keyed: Record<string, number>;
+}
+
+export async function readLegacyJobAuthority(engine: BrainEngine): Promise<LegacyJobAuthorityState> {
+ const live = (await engine.executeRaw<{ id: number; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(
+ `SELECT id, status, submission_authority, submission_authority IS NULL AS legacy_authority_is_null
+ FROM minion_jobs WHERE ${UNREVIEWED_LIVE_JOBS_WHERE} ORDER BY id`))
+ .filter(row => !parseSubmissionAuthority(row.submission_authority));
+ const authorizable: Record<string, number> = {};
+ for (const row of live) if (row.legacy_authority_is_null === true) authorizable[row.status] = (authorizable[row.status] ?? 0) + 1;
+ const unsupported = live.filter(row => row.legacy_authority_is_null !== true);
+ const active = await engine.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status = 'active' ORDER BY id LIMIT 10");
+ const terminal = await engine.executeRaw<{ status: string; count: number | string }>(
+ `SELECT status, count(*) AS count FROM minion_jobs
+ WHERE submission_authority IS NULL AND idempotency_key IS NOT NULL
+ AND status IN ('completed','failed','dead','cancelled')
+ GROUP BY status ORDER BY status`);
+ return {
+ authorizable,
+ unsupported_ids: unsupported.slice(0, 10).map(row => Number(row.id)),
+ unsupported: unsupported.length,
+ active_ids: active.map(row => Number(row.id)),
+ terminal_keyed: Object.fromEntries(terminal.map(row => [row.status, Number(row.count)])),
+ };
+}
+
+const sum = (counts: Record<string, number>) => Object.values(counts).reduce((n, c) => n + c, 0);
+
+export async function legacyJobAuthorityCheck(engine: BrainEngine): Promise<Check> {
+ const state = await readLegacyJobAuthority(engine);
+ const authorizable = sum(state.authorizable);
+ const terminal = sum(state.terminal_keyed);
+ const live = authorizable + state.unsupported;
+ const details = { ...state, live, authorizable_total: authorizable, terminal_keyed_total: terminal, docs: ERROR_CATALOGUE.legacy_job_authority.docs };
+ if (!live) {
+ return {
+ name: 'legacy_job_authority', status: 'ok', details,
+ message: terminal
+ ? `${terminal} finished job row(s) from before the upgrade still hold idempotency keys; resubmissions reuse completed or failed ones and release dead or cancelled ones, so no action is needed.`
+ : 'No queued job predates submission authority.',
+ };
+ }
+ const unsupported = state.unsupported
+ ? ` ${state.unsupported} carry unsupported non-NULL authority: run matching application and database versions, or cancel them (${state.unsupported_ids.map(id => `gbrain jobs cancel ${id}`).join('; ')}).`
+ : '';
+ return {
+ name: 'legacy_job_authority', status: 'fail', details,
+ message: `${live} queued job(s) predate submission authority and block every worker (${authorizable} authorizable with SQL NULL authority, ${state.unsupported} unsupported). `
+ + `${legacyRecoveryHint(state.active_ids)}${unsupported} See ${ERROR_CATALOGUE.legacy_job_authority.docs}.`,
+ };
+}
+
+async function runLegacyJobAuthority(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const { status, message, details } = await legacyJobAuthorityCheck(connectedEngine(ctx));
+ checks.push({ name: 'legacy_job_authority', status, message, details });
+ return checks;
+}
+
+export const legacyJobAuthorityEntry: DoctorEntry = {
+ name: 'legacy_job_authority',
+ emits: ['legacy_job_authority'],
+ run: runLegacyJobAuthority,
+};
+
+/** `gbrain post-upgrade` banner line when live legacy rows block workers (read-only commands only). */
+export async function legacyJobAuthorityBannerNote(engine: BrainEngine): Promise<string | null> {
+ const state = await readLegacyJobAuthority(engine);
+ const authorizable = sum(state.authorizable);
+ if (!authorizable && !state.unsupported) return null;
+ return `legacy_job_authority: ${authorizable + state.unsupported} queued job(s) from before v0.50 block every worker. `
+ + `Stop producers (gbrain serve, gbrain autopilot) and workers, cancel active jobs, then preview with: ${LIVE_LEGACY_PREVIEW}`
+ + `${state.unsupported ? `; ${state.unsupported} unsupported row(s) need matching versions or gbrain jobs cancel <id>` : ''}. Recipe: ${ERROR_CATALOGUE.legacy_job_authority.docs}`;
+}
diff --git a/src/commands/doctor/checks/projection-readiness.ts b/src/commands/doctor/checks/projection-readiness.ts
index 4f24ea02ec..c58a58ea00 100644
--- a/src/commands/doctor/checks/projection-readiness.ts
+++ b/src/commands/doctor/checks/projection-readiness.ts
@@ -1,9 +1,20 @@
import type { BrainEngine } from '../../../core/engine.ts';
import type { PageReadScope } from '../../../core/types.ts';
import { probeProjectionReadiness } from '../../../core/search/projection-readiness.ts';
+import type { PersistenceProjectionStatus } from '../../../core/persistence/ipc.ts';
import type { Check } from '../../doctor.ts';
+import type { DoctorContext, DoctorEntry } from '../context.ts';
-export async function checkProjectionReadiness(engine: BrainEngine, scope: PageReadScope = {}): Promise<Check> {
+const DOCS = 'docs/guides/repair.md#projection-drain';
+const UNCHANGED = 'No repair or embedding was started by this check.';
+const CODE_REPAIR = 'For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path.';
+
+/**
+ * #5401: `resident` is true when the caller runs inside a PGLite resident (the
+ * run_doctor operation on a serving process), where the drain command would
+ * refuse; the resident drains the backlog itself.
+ */
+export async function checkProjectionReadiness(engine: BrainEngine, scope: PageReadScope = {}, opts: { resident?: boolean } = {}): Promise<Check> {
const readiness = await probeProjectionReadiness(engine, scope);
return {
name: 'text_projection_readiness',
@@ -11,8 +22,71 @@ export async function checkProjectionReadiness(engine: BrainEngine, scope: PageR
message: readiness.status === 'ready'
? 'Visible text projections match their canonical revisions.'
: readiness.status === 'projection_pending'
- ? 'Visible pages have missing or stale text projections; search and code results may be incomplete. Restart the upgraded resident `gbrain serve` to drain queued Markdown and code rebuilds. For code metadata repair, run `gbrain reindex-code --force --no-embed`. If work stays pending, inspect the recorded source path. No repair or embedding was started by this check.'
+ ? `Visible pages have missing or stale text projections; search and code results may be incomplete. ${opts.resident
+ ? 'The resident gbrain process that holds this PGLite brain is rebuilding queued Markdown and code projections (up to 100 pages per pass, fewer while writes wait). On the brain host, `gbrain doctor` shows the pending count and how to drain faster.'
+ : 'Run `gbrain projections drain` to rebuild queued Markdown and code projections now; it is safe while `gbrain serve` runs on Postgres.'} ${CODE_REPAIR} ${UNCHANGED}`
: 'Text projection readiness is unknown because its read-only probe failed; index completeness could not be verified.',
details: { readiness: readiness.status, ready: readiness.ready },
};
}
+
+/** The doctor text when a PGLite resident holds the datastore, from its projection_status reply (null: it gave none). */
+export function residentProjectionReadiness(pid: number | undefined, status: PersistenceProjectionStatus | null, steps: string): Pick<Check, 'status' | 'message' | 'details'> {
+ const owner = `The resident gbrain process${pid ? ` (pid ${pid})` : ''} holds this PGLite brain`;
+ if (!status) {
+ return {
+ status: 'warn',
+ message: `${owner} and did not report its projection backlog, so it may predate the faster projection drain. Restart it on the upgraded gbrain so it drains up to 100 pages per pass. ${steps}`,
+ details: { readiness: 'unknown', ready: false, owner_pid: pid ?? null, docs: DOCS },
+ };
+ }
+ const details = { readiness: status.pending ? 'projection_pending' : 'ready', ready: status.pending === 0, owner_pid: pid ?? null, ...status, docs: DOCS };
+ if (status.pending === 0) return { status: 'ok', message: `${owner} and reports no queued text projections.`, details };
+ const age = status.oldest_age_seconds === null ? '' : `; the oldest was queued ${status.oldest_age_seconds}s ago`;
+ const failed = status.failed ? `; ${status.failed} last failed and are retried after 30 seconds` : '';
+ return {
+ status: 'warn',
+ message: `${owner} and is draining ${status.pending} queued text projections${age}${failed}. Search and code results may be incomplete until it finishes; it rebuilds up to 100 pages per pass, fewer while writes wait. Re-run \`gbrain doctor\` to watch the count. ${steps} ${UNCHANGED}`,
+ details,
+ };
+}
+
+async function runProjectionResident(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ if (ctx.engine || ctx.fastMode) return checks;
+ const { loadConfig } = await import('../../../core/config.ts');
+ const { getCliOptions } = await import('../../../core/cli-options.ts');
+ const { resolveBrainId } = await import('../../../core/brain-resolver.ts');
+ const { loadMounts } = await import('../../../core/brain-registry.ts');
+ const { persistenceConfigForBrain } = await import('../../../core/persistence/local-client.ts');
+ const { inspectLockHolder } = await import('../../../core/pglite-lock.ts');
+ const { persistenceSocketPathForConfig, requestPersistenceProjectionStatus } = await import('../../../core/persistence/ipc.ts');
+ const { residentDrainSteps } = await import('../../projections.ts');
+ let config: ReturnType<typeof persistenceConfigForBrain>;
+ let brainId: string;
+ try {
+ brainId = resolveBrainId(getCliOptions().brain, process.cwd());
+ config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());
+ } catch { return checks; }
+ if (config?.engine !== 'pglite' || !config.database_path || config.database_url) return checks;
+ const holder = inspectLockHolder(config.database_path);
+ if (!holder.held) return checks;
+ const socketPath = persistenceSocketPathForConfig(config);
+ let status: PersistenceProjectionStatus | null = null;
+ if (socketPath) {
+ try { status = await requestPersistenceProjectionStatus(socketPath); } catch { /* an older resident, or none listening */ }
+ }
+ checks.push({ name: 'text_projection_readiness', ...residentProjectionReadiness(holder.pid, status, residentDrainSteps(holder.pid, brainId)) });
+ return checks;
+}
+
+/**
+ * Filesystem-lane entry (#5401, E-T1): when the engine did not open because a
+ * PGLite resident holds the datastore, ask that resident for its projection
+ * backlog over the read-only persistence IPC op.
+ */
+export const projectionResidentEntry: DoctorEntry = {
+ name: 'text_projection_readiness',
+ emits: ['text_projection_readiness'],
+ run: runProjectionResident,
+};
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 62c46c1021..69f53a3da9 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -53,7 +53,9 @@ import {
embeddingQueryPrefixEntry,
embeddingColumnRegistryEntry,
embeddingEnvOverrideEntry,
+ embeddingKeySourceEntry,
} from './checks/embedding-health.ts';
+import { projectionResidentEntry } from './checks/projection-readiness.ts';
import {
graphCoverageEntry,
orphanRatioEntry,
@@ -76,6 +78,7 @@ import {
salienceEntry,
} from './checks/knowledge-health.ts';
import { queueHealthEntry, indexAuditEntry, imageAssetsEntry } from './checks/queue-assets.ts';
+import { legacyJobAuthorityEntry } from './checks/legacy-job-authority.ts';
import { syncFreshnessEntry, searchModeEntry } from './checks/sync-search.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
@@ -94,7 +97,9 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
extractionBacklogsEntry,
homeDirInWorktreeEntry,
defaultSourcePathEntry,
+ embeddingKeySourceEntry,
pgliteDataDirEntry,
+ projectionResidentEntry,
offlineConnectionEntry,
dbChecksGateEntry,
connectionEntry,
@@ -127,6 +132,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
effectiveDateEntry,
salienceEntry,
queueHealthEntry,
+ legacyJobAuthorityEntry,
indexAuditEntry,
imageAssetsEntry,
syncFreshnessEntry,
diff --git a/src/commands/doctor/remediate.ts b/src/commands/doctor/remediate.ts
index a18c160691..2366c6ecec 100644
--- a/src/commands/doctor/remediate.ts
+++ b/src/commands/doctor/remediate.ts
@@ -11,10 +11,14 @@
* cap is cumulative across the original run and every `--resume`; the cap,
* consent and step manifest live in the local remediation checkpoint.
*
+ * Explicit-only repair kinds are never steps: the plan lists each with its
+ * read-only preview command (`explicit_kind_required`).
+ *
* After a run, every wave check is classified (cleared, pending,
- * consent_required, operator_required, unsupported). Exit status: 0 when no
- * automatically repairable finding remains and no step failed, even if
- * operator-required or unsupported findings remain (they are listed); 1
+ * consent_required, operator_required, explicit_kind_required, unsupported).
+ * Exit status: 0 when no automatically repairable finding remains and no step
+ * failed, even if operator-required, explicit-kind or unsupported findings
+ * remain (they are listed); 1
* otherwise and on budget exhaustion; 2 when the target is unreachable and
* there is no repair step to run, or a resume is refused.
*/
@@ -22,6 +26,7 @@ import type { BrainEngine } from '../../core/engine.ts';
import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
import type { RemediationPlan, RemediationResult } from '../../core/remediation/types.ts';
import type { RepairPlanStep } from '../../core/remediation/repairs.ts';
+import { repairPreviewCommand, repairSpec, type ExplicitRepairNotice } from '../../core/repair/registry.ts';
import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';
export const REMEDIATE_HELP = `Usage: gbrain doctor --remediation-plan [--target-score <n>] [--no-embed] [--json]
@@ -117,6 +122,7 @@ interface RemediationPlanShape {
est_total_usd_cost: number;
blocked: Array<{ check: string; reason: string }>;
repair_steps?: RepairPlanStep[];
+ explicit_repairs?: ExplicitRepairNotice[];
}
/**
@@ -152,6 +158,10 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetSco
lines.push(` apply: ${step.command}`);
}
}
+ if (plan.explicit_repairs?.length) {
+ lines.push('\nExplicit-only repairs (never run by --remediate or gbrain repair --all; preview each by name on this host):');
+ for (const notice of plan.explicit_repairs) lines.push(` ${notice.kind}: ${notice.preview_command}`);
+ }
if (plan.plan.length > 0 || repairs.length > 0) {
lines.push(`\nApply everything${repairs.length ? ' after the user agrees' : ''}: ${combinedRemediateCommand(plan, targetScore)}`);
if (repairs.length) lines.push('Ask the user before applying any repair step.');
@@ -163,7 +173,7 @@ export function renderRemediationPlanLines(plan: RemediationPlanShape, targetSco
return lines;
}
-export type FindingClass = 'cleared' | 'pending' | 'consent_required' | 'operator_required' | 'unsupported';
+export type FindingClass = 'cleared' | 'pending' | 'consent_required' | 'operator_required' | 'explicit_kind_required' | 'unsupported';
export interface RemediationFinding {
check_id: string;
@@ -197,6 +207,10 @@ export function classifyWaveFindings(before: WaveFinding[], after: WaveFinding[]
// A repairable finding the repair can only report blocked needs the operator first.
const blocked = now.check.details?.operator_instruction;
if (typeof blocked === 'string') { findings.push({ ...base, class: 'operator_required', instruction: blocked, ...(kind ? { repair_kind: kind } : {}) }); continue; }
+ if (kind && repairSpec(kind).explicit_only) {
+ findings.push({ ...base, class: 'explicit_kind_required', repair_kind: kind, command: repairPreviewCommand(kind) });
+ continue;
+ }
const skipped = result.repairs_skipped?.find(step => step.kind === kind);
findings.push({ ...base, class: skipped ? 'consent_required' : 'pending', ...(kind ? { repair_kind: kind } : {}),
...(skipped ? { command: skipped.command } : kind ? { command: `gbrain repair ${kind} --apply` } : {}) });
diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.ts
index 8367b16551..d682e2240e 100644
--- a/src/commands/doctor/report-remote.ts
+++ b/src/commands/doctor/report-remote.ts
@@ -452,7 +452,7 @@ export async function doctorReportRemote(
checks.push(await checkProjectionReadiness(engine, {
sourceIds: opts.sourceIds,
excludePrivate: await resolveExcludePrivatePages(engine, opts.remote),
- }));
+ }, { resident: engine.kind === 'pglite' && opts.remote === true }));
// issue #1777 — hidden_by_search_policy: chunked pages withheld from default
// search by the hard-exclude prefix policy. Pure SQL COUNT, safe on the
diff --git a/src/commands/doctor/upgrade-banner.ts b/src/commands/doctor/upgrade-banner.ts
index 917c4cbadb..c2e0d2eca6 100644
--- a/src/commands/doctor/upgrade-banner.ts
+++ b/src/commands/doctor/upgrade-banner.ts
@@ -5,11 +5,15 @@
* selected brain, the count per finding, the read-only preview command and
* the instruction to ask the user before applying anything. It never prints
* an applying command (`--yes`, `--apply`): applying is the user's decision.
- * A clean brain prints nothing.
+ * A finding cleared by an explicit-only repair kind names that kind's own
+ * read-only preview (`explicit_kind_required`), because the remediation plan
+ * never runs it. A clean brain prints nothing.
*/
import type { BrainEngine } from '../../core/engine.ts';
-import { runWaveChecks } from './wave-checks.ts';
+import { runWaveChecks, waveRepairKind, type WaveFinding } from './wave-checks.ts';
+import { repairPreviewCommand, repairSpec } from '../../core/repair/registry.ts';
import { readConnectorSourceStatuses } from '../../core/persistence/connector-status.ts';
+import { legacyJobAuthorityBannerNote } from './checks/legacy-job-authority.ts';
/** #5686: connector sources that re-walk their window once, or resumed from a pre-upgrade checkpoint. */
async function connectorRewalkNote(engine: BrainEngine): Promise<string | null> {
@@ -26,17 +30,23 @@ async function connectorRewalkNote(engine: BrainEngine): Promise<string | null>
* of connector sources that will re-walk once after a checkpoint migration).
* Each returns null when it has nothing to say.
*/
-export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote];
+export const POST_UPGRADE_NOTES: Array<(engine: BrainEngine) => Promise<string | null>> = [connectorRewalkNote, legacyJobAuthorityBannerNote];
+
+/** One banner line for a non-ok wave finding. */
+export function bannerFindingLine({ spec, check, state }: WaveFinding): string {
+ if (state === 'unknown') return `[AGENT] ${spec.id}: could not be checked (health unknown)`;
+ const kind = waveRepairKind(spec);
+ const how = kind && repairSpec(kind).explicit_only ? `explicit_kind_required; preview with: ${repairPreviewCommand(kind)}`
+ : spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';
+ return `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`;
+}
export async function postUpgradeRecoveryBanner(engine: BrainEngine, brainLabel: string): Promise<string[]> {
const findings = (await runWaveChecks(engine)).filter(f => f.state !== 'ok');
const notes = (await Promise.all(POST_UPGRADE_NOTES.map(note => note(engine).catch(() => null)))).filter((n): n is string => !!n);
if (!findings.length && !notes.length) return [];
const lines = ['', `[AGENT] Relay this to your operator: brain ${brainLabel} has residual state to review after the upgrade.`];
- for (const { spec, check, state } of findings) {
- const how = spec.resolution === 'repair' ? 'repairable after the user agrees' : spec.resolution === 'operator' ? 'needs an operator action' : 'reported only; no command clears it yet';
- lines.push(state === 'unknown' ? `[AGENT] ${spec.id}: could not be checked (health unknown)` : `[AGENT] ${spec.id}: ${spec.count(check.details ?? {})} (${how})`);
- }
+ for (const finding of findings) lines.push(bannerFindingLine(finding));
for (const note of notes) lines.push(`[AGENT] ${note}`);
lines.push('[AGENT] Preview (read-only): gbrain doctor --remediation-plan');
lines.push('[AGENT] Ask the user before applying any repair; the plan prints the exact commands. Recipe: docs/guides/repair.md#recover-after-upgrading-to-this-release');
diff --git a/src/commands/doctor/wave-checks.ts b/src/commands/doctor/wave-checks.ts
index 835ba41297..0622791c93 100644
--- a/src/commands/doctor/wave-checks.ts
+++ b/src/commands/doctor/wave-checks.ts
@@ -148,6 +148,20 @@ export const WAVE_CHECKS: readonly WaveCheckSpec[] = [
impact: 'A committed write still has a stale queued or failed embedding effect that blocks compaction and activation',
run: async (engine, scope) => (await import('./checks/stale-embedding-effects.ts')).staleEmbeddingEffectsCheck(engine, scope.sourceIds),
},
+ {
+ id: 'atom_provenance_drift', resolution: 'repair', registration: 'doctor.ts',
+ hostOnly: 'Retiring stale atoms is a host-side, explicit-only repair.',
+ count: d => Number(d.drifted ?? 0),
+ impact: 'Some atoms reference a source page that is gone or was edited, and still surface in search with a quote no current page contains',
+ run: async engine => (await import('./checks/extraction-sync.ts')).computeAtomProvenanceDriftCheck(engine),
+ },
+ {
+ id: 'extractor_facts_expired', resolution: 'repair', registration: 'wave',
+ hostOnly: 'Restoring expired extractor facts is a host-side, explicit-only repair.',
+ count: d => Number(d.evidenced ?? 0) + Number(d.ambiguous ?? 0),
+ impact: 'Some conversation-extractor facts were expired by the pre-v0.60.11.0 canonical projection and recall no longer returns them',
+ run: async (engine, scope) => (await import('./checks/extractor-facts.ts')).extractorFactsCheck(engine, scope.sourceIds),
+ },
];
/** A check that could not run reports unknown, never ok. */
diff --git a/src/commands/embed.ts b/src/commands/embed.ts
index ba7783fc10..550b7d0647 100644
--- a/src/commands/embed.ts
+++ b/src/commands/embed.ts
@@ -36,6 +36,8 @@ import {
import { tryAcquireDbLock, type DbLockHandle } from '../core/db-lock.ts';
import { embedBackfillLockId } from '../core/embed-backfill-lock.ts';
import { AITransientError } from '../core/ai/errors.ts';
+import { resolveEmbedConcurrency } from '../core/embed-concurrency.ts';
+export { resolveEmbedConcurrency, _resetEmbedConcurrencyClampWarningForTest } from '../core/embed-concurrency.ts';
import { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';
import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';
import {
@@ -1247,10 +1249,7 @@ async function embedAll(
// Paced runs lower this to the resolved cap (the real lever vs pooler-slot
// starvation); unpaced keeps the env/default 20. Codex P2: only ever LOWER —
// never raise above an operator's existing env cap.
- const BASE_CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);
- const CONCURRENCY = staleOpts?.paceMaxConcurrency
- ? Math.min(BASE_CONCURRENCY, staleOpts.paceMaxConcurrency)
- : BASE_CONCURRENCY;
+ const CONCURRENCY = resolveEmbedConcurrency(engine.kind, staleOpts?.paceMaxConcurrency);
async function embedOnePage(page: typeof pages[number]) {
// #1737: bail before doing any work for this page if the run was aborted.
@@ -1803,10 +1802,7 @@ async function embedAllStale(
// Paced runs lower concurrency to the resolved cap (E-1: worker count IS the
// lever on this single pool, no separate permit). Codex P2: pacing only ever
// LOWERS concurrency — never raise above an operator's existing env cap.
- const BASE_CONCURRENCY = parseInt(process.env.GBRAIN_EMBED_CONCURRENCY || '20', 10);
- const CONCURRENCY = staleOpts?.paceMaxConcurrency
- ? Math.min(BASE_CONCURRENCY, staleOpts.paceMaxConcurrency)
- : BASE_CONCURRENCY;
+ const CONCURRENCY = resolveEmbedConcurrency(engine.kind, staleOpts?.paceMaxConcurrency);
const pacer = staleOpts?.pacer ?? createNoopPacer();
// D3 + D3a + D8: wall-clock budget. 30 min default; env override.
diff --git a/src/commands/frontmatter.ts b/src/commands/frontmatter.ts
index 4258b57d5f..350d468652 100644
--- a/src/commands/frontmatter.ts
+++ b/src/commands/frontmatter.ts
@@ -216,7 +216,8 @@ async function runValidate(rest: string[]): Promise<void> {
const rel = relative(brainRoot, file);
// Files above/outside the brain root fall back to basename rather than
// emitting a "../"-prefixed slug for non-brain files.
- const expectedSlug = slugifyPath(rel && !rel.startsWith('..') ? rel : basename(file));
+ const slugPath = rel && !rel.startsWith('..') ? rel : basename(file);
+ const expectedSlug = slugifyPath(slugPath);
const parsed = parseMarkdown(content, file, { validate: true, expectedSlug });
const errs = parsed.errors ?? [];
const result: FileValidation = {
@@ -225,7 +226,9 @@ async function runValidate(rest: string[]): Promise<void> {
};
if (flags.fix && errs.length > 0) {
- const { content: fixed, fixes } = autoFixFrontmatter(content, { filePath: file });
+ // #5053: the fixer derives the slug from the same path validate used;
+ // the absolute path re-keyed every declared slug as a mismatch.
+ const { content: fixed, fixes } = autoFixFrontmatter(content, { filePath: slugPath });
result.fixesApplied = fixes;
if (fixes.length > 0 && !flags.dryRun) {
assertManagedFilesystemWrite(file);
diff --git a/src/commands/harness-connect.ts b/src/commands/harness-connect.ts
index 126a04baa7..57290d6e15 100644
--- a/src/commands/harness-connect.ts
+++ b/src/commands/harness-connect.ts
@@ -1,19 +1,19 @@
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { readCredentials, credentialReceipt } from '../core/harness/credentials.ts';
import { harnessAdapter } from '../core/harness/registry.ts';
-import { installHarnessConnection } from '../core/harness/install.ts';
+import { installHarnessConnection, type inlineTokenReceipt } from '../core/harness/install.ts';
import { normalizeMcpUrl } from '../core/mcp-registration.ts';
import { validateHarnessArguments } from '../core/harness/arguments.ts';
import { readHarnessConnectionStatus } from '../core/harness/status.ts';
export async function runHarnessConnect(args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) {
- console.log('gbrain connect <endpoint> --harness <id> --credentials-file <private-file> [--install | --remove] [--root <persistent-root>] [--name <name>] [--json]\ngbrain connect --harness <id> --status [--root <persistent-root>] [--name <name>] [--json]');
+ console.log('gbrain connect <endpoint> --harness <id> --credentials-file <private-file> [--install [--fresh-token] | --remove] [--root <persistent-root>] [--name <name>] [--json]\ngbrain connect --harness <id> --status [--root <persistent-root>] [--name <name>] [--json]');
return;
}
const value = (flag: string) => { const i = args.indexOf(flag); return i < 0 ? undefined : args[i + 1]; };
try {
- validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name'], flags: ['--install', '--remove', '--status', '--json'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });
+ validateHarnessArguments(args[0]?.startsWith('--') ? args : args.slice(1), { values: ['--harness', '--credentials-file', '--root', '--name'], flags: ['--install', '--remove', '--status', '--json', '--fresh-token'], aliases: { '--agent': '--harness' }, exclusive: [['--install', '--remove', '--status']] });
if (args.includes('--status')) {
const harness = value('--harness') ?? value('--agent');
if (!harness) throw new Error('--harness is required for local status; no credentials or live connection are needed');
@@ -27,9 +27,15 @@ export async function runHarnessConnect(args: string[]): Promise<void> {
const endpoint = normalizeMcpUrl(args[0] ?? '');
if (!endpoint.ok || endpoint.url !== c.mcp_url) throw new Error('Endpoint does not match the private credential handoff');
const result = args.includes('--install') || args.includes('--remove')
- ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove') })
+ ? await installHarnessConnection(c, { harness: harness.id, name: value('--name'), root: value('--root'), remove: args.includes('--remove'), credentialsFile: path, freshToken: args.includes('--fresh-token') })
: { ...credentialReceipt(c), status: 'prepared', harness: harness.id, documentation: harness.guide, next_action: 'Run this command with --install inside the intended harness environment. Keep the credential file private.' };
console.log(JSON.stringify(result, null, args.includes('--json') ? undefined : 2));
+ const token = result as Partial<ReturnType<typeof inlineTokenReceipt>>;
+ if (!args.includes('--json') && token.token_storage === 'inline' && token.if_exposed) {
+ console.error(`The bearer token is stored inline in ${token.config_path}; this output never prints it. Renew it with: ${token.renew_command}`);
+ console.error(`If it was exposed: ${token.if_exposed.steps.join(' Then: ')} See ${token.if_exposed.docs_url}.`);
+ if (token.token_warning) console.error(`WARNING: ${token.token_warning}`);
+ }
if (result.status === 'pending' || 'remote_membership_pending' in result && result.remote_membership_pending) setCliExitVerdict(2);
} catch (error) {
console.log(JSON.stringify({ status: 'error', reason: 'connection_setup_failed', message: error instanceof Error ? error.message : 'Connection setup failed' }));
diff --git a/src/commands/hook.ts b/src/commands/hook.ts
index 0322e08634..c16ac329f8 100644
--- a/src/commands/hook.ts
+++ b/src/commands/hook.ts
@@ -34,7 +34,6 @@
*/
import {
- appendFileSync,
chmodSync,
existsSync,
mkdirSync,
@@ -226,16 +225,18 @@ export interface HookIo {
// ── Entry point ─────────────────────────────────────────────────────────────
+export const HOOK_EVENTS = ['session-start', 'user-prompt', 'stop', 'session-end', 'compact'] as const;
+
const USAGE = `Usage: gbrain hook <event>
Events (wired into .claude/settings.local.json by gbrain bootstrap):
- session-start print the greeting digest (MEMORY.md sections, last session,
- push status, hook health) to stdout
+ session-start print the greeting digest (MEMORY.md sections, push status,
+ hook health) to stdout
user-prompt read hook JSON on stdin, request per-turn context from a
running 'gbrain serve' over IPC, print additionalContext JSON
(--harness <claude-code|codex|opencode> sets the feedback-loop
channel; default claude-code, unknown values fall back to the default)
- stop append to the per-session live buffer
+ stop bank the writeback backstop and spawn the workspace push
session-end ingest the session transcript into the dream corpus
(secret-scanned), prune old corpus files, push the workspace
compact (PreCompact) bank the window's standing entities into the
@@ -261,7 +262,7 @@ export async function runHook(args: string[], io: HookIo = {}): Promise<number>
const v = args[harnessIdx + 1];
if (v === 'claude-code' || v === 'codex' || v === 'opencode') io = { ...io, harness: v };
}
- if (!event || !['session-start', 'user-prompt', 'stop', 'session-end', 'compact'].includes(event)) {
+ if (!event || !(HOOK_EVENTS as readonly string[]).includes(event)) {
process.stderr.write(USAGE + '\n');
return 1;
}
@@ -423,7 +424,7 @@ function ensureDir0700(dir: string): string {
return dir;
}
-function sanitizeSessionId(id: unknown): string {
+export function sanitizeSessionId(id: unknown): string {
// Leading dashes are stripped so the id can never be parsed as a FLAG by a
// downstream argv consumer (the detached memorable spawn passes it as a
// positional value) — hook stdin is untrusted input.
@@ -487,10 +488,6 @@ async function hookSessionStart(io: HookIo): Promise<number> {
const digest = memoryDigest(join(ws, 'MEMORY.md'));
if (digest) out.push(digest);
- // 2. Last-session line from the stop-buffer dir [G15 consumer].
- const last = await lastSessionLine();
- if (last) out.push(last);
-
// 3. Push staleness [B4].
const pushNote = await pushStatusNote();
if (pushNote) out.push(pushNote);
@@ -637,32 +634,6 @@ async function liveBufferDir(): Promise<string> {
return ensureDir0700(join(home, 'transcripts', 'live'));
}
-async function lastSessionLine(): Promise<string | null> {
- try {
- const dir = await liveBufferDir();
- let newest: { path: string; mtime: number } | null = null;
- for (const name of readdirSync(dir)) {
- if (!name.endsWith('.txt')) continue;
- const p = join(dir, name);
- const st = statSync(p);
- if (!newest || st.mtimeMs > newest.mtime) newest = { path: p, mtime: st.mtimeMs };
- }
- if (!newest) return null;
- const lines = readFileSync(newest.path, 'utf8').split('\n').filter((l) => l.trim());
- const last = lines[lines.length - 1];
- if (!last) return null;
- try {
- const e = JSON.parse(last) as { ts?: string; exchange?: string };
- const snippet = typeof e.exchange === 'string' ? ` — ${e.exchange.slice(0, 200)}` : '';
- return `Last session activity: ${e.ts ?? 'unknown time'}${snippet}`;
- } catch {
- return `Last session activity: ${last.slice(0, 200)}`;
- }
- } catch {
- return null;
- }
-}
-
async function pushStatusNote(): Promise<string | null> {
try {
// One reader + one aggregation for every status surface [D8]; per-root
@@ -1444,16 +1415,9 @@ async function hookStop(io: HookIo): Promise<number> {
let j: Record<string, unknown> | null = null;
try {
j = await readStdinJson(io, 300);
- const sessionId = sanitizeSessionId(j?.session_id);
- const dir = await liveBufferDir();
- const exchange = firstString(j, ['last_assistant_message', 'lastAssistantMessage', 'prompt']);
- const entry = {
- ts: new Date().toISOString(),
- session_id: sessionId,
- ...(exchange ? { exchange: exchange.slice(0, 400) } : {}),
- };
- appendFileSync(join(dir, `${sessionId}.txt`), JSON.stringify(entry) + '\n', { mode: 0o600 });
- gcOldFiles(dir, STOP_BUFFER_RETENTION_MS);
+ // #5558: stop no longer buffers assistant text; GC drains any buffers
+ // older binaries left behind.
+ gcOldFiles(await liveBufferDir(), STOP_BUFFER_RETENTION_MS);
} catch (e) {
outcome = 'error';
reason = errorCode(e);
@@ -1594,15 +1558,6 @@ async function hookStop(io: HookIo): Promise<number> {
return 0;
}
-function firstString(j: Record<string, unknown> | null, keys: string[]): string | null {
- if (!j) return null;
- for (const k of keys) {
- const v = j[k];
- if (typeof v === 'string' && v.trim()) return v;
- }
- return null;
-}
-
function gcOldFiles(dir: string, maxAgeMs: number): void {
try {
const cutoff = Date.now() - maxAgeMs;
diff --git a/src/commands/jobs.ts b/src/commands/jobs.ts
index 0ffe65604b..cf1d06d0c4 100644
--- a/src/commands/jobs.ts
+++ b/src/commands/jobs.ts
@@ -99,7 +99,7 @@ export async function refreshGatewayForJob(engine: BrainEngine): Promise<void> {
// pins this set against the registerBuiltinJob call sites — a gateway-using
// handler registered via bare worker.register() runs with a stale gateway
// (the #3387 chronicle_extract silent-no_events class).
-const GATEWAY_REFRESH_JOB_NAMES = new Set([
+export const GATEWAY_REFRESH_JOB_NAMES = new Set([
'embed',
'extract-conversation-facts',
'enrich',
@@ -154,6 +154,7 @@ const JOBS_HELP = `gbrain jobs — Minions job queue
USAGE
gbrain jobs authorize-legacy --ids 12,34 [--expect <snapshot_digest> --yes] [--json]
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize" [--expect <hash> --yes] [--json]
gbrain jobs submit <name> [--params JSON] [--follow] [--priority N]
[--delay Nms] [--max-attempts N] [--max-stalled N]
[--max-waiting N]
@@ -166,6 +167,7 @@ USAGE
gbrain jobs list [--status S] [--queue Q] [--limit N] [--json]
gbrain jobs get <id> [--json]
gbrain jobs cancel <id>
+ gbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--expect <hash> --yes] [--json]
gbrain jobs retry <id>
gbrain jobs prune [--older-than 30d] [--dry-run]
gbrain jobs delete <id>
@@ -376,10 +378,31 @@ OPTIONS
USAGE
gbrain jobs authorize-legacy --ids 12,34 --json
gbrain jobs authorize-legacy --ids 12,34 --expect <snapshot_digest> --yes --json
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture" [--json]
+ gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture" --expect <hash> --yes
+
+Stop producers (gbrain serve, gbrain autopilot) and workers and cancel active jobs
+first. A command without --yes only previews; apply requires the exact reviewed hash
+and --yes. --select keys: status (waiting, delayed, waiting-children, paused,
+completed, failed) and name, each taking | alternatives. The --select preview lists
+counts by job name and status, the first 20 ids and the preview hash, and the apply
+authorizes exactly the previewed set. Dependencies are shown but never implicitly
+authorized. IDs, data, schedule and retries persist.
+`,
+ cancel: `gbrain jobs cancel — cancel a job, or preview-bound bulk cancel of legacy jobs
-Stop producers and workers and drain active jobs first. The first command only
-previews; apply requires the exact reviewed snapshot digest and --yes. Dependencies
-are shown but never implicitly authorized. IDs, data, schedule and retries persist.
+USAGE
+ gbrain jobs cancel <id>
+ gbrain jobs cancel --select "status=waiting|paused,name=synthesize" [--json]
+ gbrain jobs cancel --select "status=waiting|paused,name=synthesize" --expect <hash> --yes
+
+--select picks live jobs whose submission authority is missing or unsupported
+(the rows that block workers after an upgrade across v0.50). Keys: status
+(waiting, delayed, waiting-children, paused) and name, each taking | alternatives.
+Without --yes it only previews: counts by job name and status, the first 20 ids,
+parents that return to waiting, and the preview hash. The apply cancels exactly
+the previewed set; a selection that would cascade to a job outside it refuses.
+Stop producers and workers and cancel active jobs (gbrain jobs cancel <id>) first.
`,
prune: `gbrain jobs prune — delete old terminal jobs
diff --git a/src/commands/jobs/authorize-legacy.ts b/src/commands/jobs/authorize-legacy.ts
index 3bb548855b..62cd086b75 100644
--- a/src/commands/jobs/authorize-legacy.ts
+++ b/src/commands/jobs/authorize-legacy.ts
@@ -1,10 +1,49 @@
/** `gbrain jobs authorize-legacy` (dispatched by runJobs in src/commands/jobs.ts). */
-import { parseFlag, type JobsCommandContext } from './shared.ts';
-import { authorizeLegacyJobs, parseLegacyJobIds } from '../../core/minions/authorize-legacy.ts';
+import { paidJobNames, parseFlag, reportJobsError, selectionSummaryLines, type JobsCommandContext } from './shared.ts';
+import { applyLegacySelection, authorizeLegacyJobs, parseLegacyJobIds, previewLegacySelection } from '../../core/minions/authorize-legacy.ts';
+import { parseLegacyJobSelection } from '../../core/minions/legacy-selection.ts';
+import { catalogueError } from '../../core/error-catalogue.ts';
+import { OperationError } from '../../core/ops/contract.ts';
export async function runJobsAuthorizeLegacy({ args, engine }: JobsCommandContext): Promise<void> {
- const ids = parseLegacyJobIds(parseFlag(args, '--ids'));
- const preview = args.includes('--dry-run');
- const result = await authorizeLegacyJobs(engine, ids, preview ? undefined : parseFlag(args, '--expect'), !preview && args.includes('--yes'));
- console.log(JSON.stringify(result, null, 2));
+ const json = args.includes('--json');
+ try {
+ const select = parseFlag(args, '--select');
+ if (select === undefined && !args.includes('--select')) {
+ const ids = parseLegacyJobIds(parseFlag(args, '--ids'));
+ const preview = args.includes('--dry-run');
+ const result = await authorizeLegacyJobs(engine, ids, preview ? undefined : parseFlag(args, '--expect'), !preview && args.includes('--yes'));
+ console.log(JSON.stringify(result, null, 2));
+ return;
+ }
+ if (args.includes('--ids')) {
+ throw catalogueError('legacy_job_selection_invalid', 'Pass either --ids or --select, not both.', 'gbrain jobs authorize-legacy --select "status=waiting"');
+ }
+ const selection = parseLegacyJobSelection(select, 'authorize-legacy');
+ const expected = parseFlag(args, '--expect');
+ const yes = args.includes('--yes');
+ // --dry-run always previews, even next to --expect/--yes, matching the --ids path.
+ if (!args.includes('--dry-run') && (expected !== undefined || yes)) {
+ const result = await applyLegacySelection(engine, selection, expected, yes);
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ console.log(`Authorized ${result.authorized} legacy job(s) matching ${result.selection}. Restart producers and workers now.`);
+ return;
+ }
+ const preview = await previewLegacySelection(engine, selection);
+ const paid = await paidJobNames(Object.keys(preview.summary.by_name));
+ if (json) { console.log(JSON.stringify({ ...preview, paid_job_names: paid }, null, 2)); return; }
+ console.log(`Legacy jobs matching ${preview.selection} (SQL NULL authority, authorizable): ${preview.summary.total}`);
+ for (const line of selectionSummaryLines(preview.summary, paid)) console.log(line);
+ if (preview.unsupported_ids.length) {
+ console.log(`Unsupported non-NULL authority (not authorizable; cancel locally): ${preview.unsupported_ids.slice(0, 20).join(', ')}${preview.unsupported_ids.length > 20 ? ' …' : ''}`);
+ }
+ if (!preview.preview_hash) { console.log('Nothing to authorize.'); return; }
+ console.log(`Startup-blocking dependencies outside the selection: ${preview.startup_blocking_dependency_count}`);
+ console.log(`Preview hash: ${preview.preview_hash}`);
+ console.log(`Apply exactly this set: ${preview.apply_command}`);
+ console.log('Full rows: re-run with --json. Nothing was changed.');
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ reportJobsError(error, json);
+ }
}
diff --git a/src/commands/jobs/cancel.ts b/src/commands/jobs/cancel.ts
index 3c9206fd84..cef37e7949 100644
--- a/src/commands/jobs/cancel.ts
+++ b/src/commands/jobs/cancel.ts
@@ -1,7 +1,45 @@
/** `gbrain jobs cancel` (dispatched by runJobs in src/commands/jobs.ts). */
-import type { JobsCommandContext } from './shared.ts';
+import { paidJobNames, parseFlag, reportJobsError, selectionSummaryLines, type JobsCommandContext } from './shared.ts';
+import { applyLegacyCancel, previewLegacyCancel } from '../../core/minions/legacy-cancel.ts';
+import { parseLegacyJobSelection } from '../../core/minions/legacy-selection.ts';
+import { OperationError } from '../../core/ops/contract.ts';
-export async function runJobsCancel({ args, queue }: JobsCommandContext): Promise<void> {
+/** `--select <filter> [--expect <hash> --yes]`: preview-bound bulk cancel of legacy rows (DX-T2). */
+async function runLegacyCancel({ args, engine }: JobsCommandContext): Promise<void> {
+ const json = args.includes('--json');
+ try {
+ const selection = parseLegacyJobSelection(parseFlag(args, '--select'), 'cancel');
+ const expected = parseFlag(args, '--expect');
+ const yes = args.includes('--yes');
+ // --dry-run always previews, even next to --expect/--yes, matching the --ids path.
+ if (!args.includes('--dry-run') && (expected !== undefined || yes)) {
+ const result = await applyLegacyCancel(engine, selection, expected, yes);
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ console.log(`Cancelled ${result.cancelled_ids.length} legacy job(s) matching ${result.selection}.`);
+ return;
+ }
+ const preview = await previewLegacyCancel(engine, selection);
+ const paid = await paidJobNames(Object.keys(preview.summary.by_name));
+ if (json) { console.log(JSON.stringify({ ...preview, paid_job_names: paid }, null, 2)); return; }
+ console.log(`Legacy jobs matching ${preview.selection} to cancel (missing or unsupported authority): ${preview.summary.total}`);
+ for (const line of selectionSummaryLines(preview.summary, paid)) console.log(line);
+ if (preview.unsupported_ids.length) console.log(` Unsupported non-NULL authority among them: ${preview.unsupported_ids.slice(0, 20).join(', ')}`);
+ if (!preview.preview_hash) { console.log('Nothing to cancel.'); return; }
+ if (preview.parent_transitions.length) {
+ console.log(`Parents that return to waiting: ${preview.parent_transitions.map(p => p.id).join(', ')}`);
+ }
+ console.log(`Preview hash: ${preview.preview_hash}`);
+ console.log(`Cancel exactly this set: ${preview.apply_command}`);
+ console.log('Full rows: re-run with --json. Nothing was changed.');
+ } catch (error) {
+ if (!(error instanceof OperationError)) throw error;
+ reportJobsError(error, json);
+ }
+}
+
+export async function runJobsCancel(ctx: JobsCommandContext): Promise<void> {
+ const { args, queue } = ctx;
+ if (args.includes('--select')) return runLegacyCancel(ctx);
const id = parseInt(args[1], 10);
if (isNaN(id)) { console.error('Error: job ID required.'); process.exit(1); }
diff --git a/src/commands/jobs/shared.ts b/src/commands/jobs/shared.ts
index f5e9e5d236..d0609f298e 100644
--- a/src/commands/jobs/shared.ts
+++ b/src/commands/jobs/shared.ts
@@ -6,6 +6,9 @@
import type { BrainEngine } from '../../core/engine.ts';
import type { MinionQueue } from '../../core/minions/queue.ts';
import type { MinionJob } from '../../core/minions/types.ts';
+import type { OperationError } from '../../core/ops/contract.ts';
+import type { SelectionSummary } from '../../core/minions/legacy-selection.ts';
+import { setCliExitVerdict } from '../../core/cli-force-exit.ts';
import { parseNiceValue } from '../../core/minions/niceness.ts';
import { defaultTimeoutMsFor, defaultLockDurationMsFor } from '../../core/minions/handler-timeouts.ts';
@@ -227,3 +230,29 @@ export function formatJobDetail(job: MinionJob): string {
lines.push(` Data: ${JSON.stringify(job.data)}`);
return lines.join('\n');
}
+
+/** Renders a coded jobs refusal: the `toJSON()` envelope on stdout with --json, the human lines on stderr, exit 1. */
+export function reportJobsError(error: OperationError, json: boolean): void {
+ if (json) console.log(JSON.stringify(error.toJSON(), null, 2));
+ console.error(`Error [${error.code}]: ${error.message}`);
+ if (error.suggestion) console.error(`Fix: ${error.suggestion}`);
+ if (error.docs) console.error(`Docs: ${error.docs}`);
+ setCliExitVerdict(1);
+}
+
+/** Handlers outside the gateway-refresh set that can still spend: embedding by default, or the subagent and optimizer loops. */
+const OTHER_PAID_JOB_NAMES = new Set(['subagent', 'skillopt', 'import', 'reindex', 'sync', 'ingest_capture']);
+
+/** Job names whose handlers can make paid model-provider calls (DX-O3(d) marks them in a legacy preview). */
+export async function paidJobNames(names: Iterable<string>): Promise<string[]> {
+ const { GATEWAY_REFRESH_JOB_NAMES } = await import('../jobs.ts');
+ return [...new Set(names)].filter(name => GATEWAY_REFRESH_JOB_NAMES.has(name) || OTHER_PAID_JOB_NAMES.has(name)).sort();
+}
+
+/** DX-O3(d) human preview lines: counts by job name and status, the first 20 ids, paid markers. */
+export function selectionSummaryLines(summary: SelectionSummary, paid: readonly string[]): string[] {
+ const lines = Object.entries(summary.by_name).sort(([a], [b]) => a.localeCompare(b)).map(([name, counts]) =>
+ ` ${name}: ${Object.entries(counts).map(([status, n]) => `${status} ${n}`).join(', ')}${paid.includes(name) ? ' [may make paid provider calls]' : ''}`);
+ if (summary.total) lines.push(` First ${summary.first_ids.length} ids: ${summary.first_ids.join(', ')}${summary.total > summary.first_ids.length ? ' …' : ''}`);
+ return lines;
+}
diff --git a/src/commands/migrations/in-process.ts b/src/commands/migrations/in-process.ts
index 9c9c66271b..50a13e3c47 100644
--- a/src/commands/migrations/in-process.ts
+++ b/src/commands/migrations/in-process.ts
@@ -22,6 +22,7 @@
*/
import { execSync } from 'child_process';
+import { resolveChildCliInvocation } from '../../core/minions/job-isolation.ts';
import { loadConfig, toEngineConfig } from '../../core/config.ts';
import { buildGatewayConfig } from '../../core/ai/build-gateway-config.ts';
@@ -88,6 +89,32 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promise
return { engine: config.engine };
}
+/**
+ * #5184: point every `gbrain` command word in a migration's shell command at
+ * the CLI that is running this migration (the compiled executable, or bun plus
+ * the source entrypoint), through the same `resolveChildCliInvocation` the
+ * supervisor and autopilot use. A bare `gbrain` resolved from PATH can be a
+ * different version, or a wrapper that sets its own GBRAIN_HOME or database
+ * URL, so backfills and installs would act on another brain. When the running
+ * CLI cannot be identified the command is left as written (PATH resolution).
+ */
+export function gbrainChildCommand(
+ cmd: string,
+ env: Record<string, string | undefined> = process.env,
+ execPath: string = process.execPath,
+ argv1: string | undefined = process.argv[1],
+ platform: NodeJS.Platform = process.platform,
+): string {
+ const inv = resolveChildCliInvocation(env, execPath, argv1, () => null);
+ if (!inv) return cmd;
+ // execSync runs cmd.exe on Windows, which does not understand single quotes.
+ const quote = platform === 'win32'
+ ? (s: string) => `"${s}"`
+ : (s: string) => `'${s.replace(/'/g, "'\\''")}'`;
+ const prefix = [inv.cmd, ...inv.argsPrefix].map(quote).join(' ');
+ return cmd.replace(/(^|\|\||&&|;)(\s*)gbrain(?=\s|$)/g, (_m, sep: string, space: string) => `${sep}${space}${prefix}`);
+}
+
/**
* Run a `gbrain ...` subcommand as a subprocess, capturing child stderr so a
* failure surfaces the real reason. Used for the non-schema backfill phases
@@ -101,7 +128,8 @@ export async function runMigrateOnlyCore(opts?: { timeoutMs?: number }): Promise
*/
export function runGbrainSubprocess(cmd: string, opts?: { timeoutMs?: number }): string {
try {
- const out = execSync(cmd, {
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- cmd is a fixed migration subcommand string from the orchestrators; gbrainChildCommand prefixes the running CLI (#5184)
+ const out = execSync(gbrainChildCommand(cmd), {
stdio: ['inherit', 'pipe', 'pipe'],
timeout: opts?.timeoutMs ?? MIGRATE_ONLY_TIMEOUT_MS,
env: process.env,
diff --git a/src/commands/migrations/v0_11_0.ts b/src/commands/migrations/v0_11_0.ts
index cc9be74ab0..60c58eeed8 100644
--- a/src/commands/migrations/v0_11_0.ts
+++ b/src/commands/migrations/v0_11_0.ts
@@ -24,8 +24,9 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, lst
import { join, resolve, dirname } from 'path';
import { execSync } from 'child_process';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
+import { gbrainChildCommand } from './in-process.ts';
import { savePreferences, loadPreferences } from '../../core/preferences.ts';
-import { loadConfig } from '../../core/config.ts';
+import { loadConfig, configPath, gbrainPath } from '../../core/config.ts';
// Bug 3 — appendCompletedMigration moved to the runner (apply-migrations.ts).
import { promptLine } from '../../core/cli-util.ts';
import { VERSION } from '../../version.ts';
@@ -35,9 +36,10 @@ const AGENTS_MD_MARKER = '<!-- gbrain:subagent-routing v0.11.0 -->';
const CRON_MIGRATED_PROPERTY = '_gbrain_migrated_by';
const MAX_HOST_FILE_BYTES = 1_000_000;
+// home() locates host-agent config ($HOME/.claude, $HOME/.openclaw); gbrain's
+// own state follows GBRAIN_HOME via gbrainPath() (#5549).
function home(): string { return process.env.HOME || ''; }
-function gbrainDir(): string { return join(home(), '.gbrain'); }
-function pendingHostWorkPath(): string { return join(gbrainDir(), 'migrations', 'pending-host-work.jsonl'); }
+function pendingHostWorkPath(): string { return gbrainPath('migrations', 'pending-host-work.jsonl'); }
export interface PendingHostWorkEntry {
type: 'cron-handler-needs-host-registration' | 'agents-md-dispatcher-needs-host-review';
@@ -83,7 +85,7 @@ async function phaseASchema(opts: OrchestratorOpts): Promise<OrchestratorPhaseRe
function phaseBSmoke(opts: OrchestratorOpts): OrchestratorPhaseResult {
if (opts.dryRun) return { name: 'smoke', status: 'skipped', detail: 'dry-run' };
try {
- execSync('gbrain jobs smoke', { stdio: 'inherit', timeout: 30_000, env: process.env });
+ execSync(gbrainChildCommand('gbrain jobs smoke'), { stdio: 'inherit', timeout: 30_000, env: process.env });
return { name: 'smoke', status: 'complete' };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
@@ -259,7 +261,7 @@ function rewriteCronManifest(
// We load config lazily to avoid a hard dep.
let enginePglite = false;
try {
- const cfg = JSON.parse(readFileSync(join(gbrainDir(), 'config.json'), 'utf-8'));
+ const cfg = JSON.parse(readFileSync(configPath(), 'utf-8'));
enginePglite = cfg?.engine === 'pglite';
} catch { /* best-effort */ }
@@ -407,7 +409,7 @@ function phaseFInstall(opts: OrchestratorOpts): OrchestratorPhaseResult {
if (loadConfig()?.engine === 'pglite') {
return { name: 'install', status: 'skipped', detail: 'PGLite is single-writer; use gbrain serve for background maintenance' };
}
- execSync('gbrain autopilot --install --yes', { stdio: 'inherit', timeout: 60_000, env: process.env });
+ execSync(gbrainChildCommand('gbrain autopilot --install --yes'), { stdio: 'inherit', timeout: 60_000, env: process.env });
return { name: 'install', status: 'complete' };
} catch (e) {
return { name: 'install', status: 'failed', detail: e instanceof Error ? e.message : String(e) };
diff --git a/src/commands/migrations/v0_12_0.ts b/src/commands/migrations/v0_12_0.ts
index 206e5ed023..55c3c2137d 100644
--- a/src/commands/migrations/v0_12_0.ts
+++ b/src/commands/migrations/v0_12_0.ts
@@ -31,7 +31,7 @@
*/
import { execSync } from 'child_process';
-import { runGbrainSubprocess } from './in-process.ts';
+import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
import { childGlobalFlags } from '../../core/cli-options.ts';
// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).
@@ -69,7 +69,7 @@ function phaseBConfigCheck(opts: OrchestratorOpts): OrchestratorPhaseResult & {
// Default behavior when unset = enabled (per isAutoLinkEnabled).
let raw = '';
try {
- raw = execSync('gbrain config get auto_link', { encoding: 'utf-8', timeout: 10_000, env: process.env }).trim();
+ raw = execSync(gbrainChildCommand('gbrain config get auto_link'), { encoding: 'utf-8', timeout: 10_000, env: process.env }).trim();
} catch {
// get exits non-zero when the key isn't set — that's fine, defaults to enabled.
raw = '';
@@ -124,7 +124,7 @@ interface StatsSnapshot {
function readStats(): StatsSnapshot | null {
try {
- const out = execSync('gbrain get_stats --json 2>/dev/null || gbrain stats', {
+ const out = execSync(gbrainChildCommand('gbrain get_stats --json 2>/dev/null || gbrain stats'), {
encoding: 'utf-8', timeout: 30_000, env: process.env,
});
// The fallback `gbrain stats` prints human-readable output; parse loosely.
diff --git a/src/commands/migrations/v0_12_2.ts b/src/commands/migrations/v0_12_2.ts
index 28d61d0ba4..27ae984f95 100644
--- a/src/commands/migrations/v0_12_2.ts
+++ b/src/commands/migrations/v0_12_2.ts
@@ -21,7 +21,7 @@
*/
import { execSync } from 'child_process';
-import { runGbrainSubprocess } from './in-process.ts';
+import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
import { childGlobalFlags } from '../../core/cli-options.ts';
// Bug 3 — ledger writes moved to the runner (apply-migrations.ts).
@@ -66,7 +66,7 @@ function phaseCVerify(opts: OrchestratorOpts): OrchestratorPhaseResult {
// Any accidental stdout progress from the child would break JSON.parse
// (per Codex review #12). NOTE: we deliberately do NOT pass
// --progress-json here — this child is parsed, not watched.
- const out = execSync('gbrain repair-jsonb --dry-run --json', {
+ const out = execSync(gbrainChildCommand('gbrain repair-jsonb --dry-run --json'), {
encoding: 'utf-8', timeout: 60_000, env: process.env,
stdio: ['ignore', 'pipe', 'inherit'],
});
diff --git a/src/commands/migrations/v0_13_0.ts b/src/commands/migrations/v0_13_0.ts
index 076369725b..181b460a97 100644
--- a/src/commands/migrations/v0_13_0.ts
+++ b/src/commands/migrations/v0_13_0.ts
@@ -26,7 +26,7 @@
*/
import { execSync } from 'child_process';
-import { runGbrainSubprocess } from './in-process.ts';
+import { gbrainChildCommand, runGbrainSubprocess } from './in-process.ts';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
// Bug 3 — ledger writes moved to the runner (apply-migrations.ts). The
// orchestrator returns its result and the runner persists it.
@@ -38,12 +38,14 @@ import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhase
// ~10s (ALTER + index builds). Bumped timeout accounts for slow Supabase
// links (v0.12.1 pattern — migrations can time out on the 60s default).
//
-// Shell out to the canonical `gbrain` shim on PATH (`/usr/local/bin/gbrain`
-// by default). An earlier revision resolved via the active Node/Bun runtime
-// binary, but on bun-installed trees that binary is `bun` — the spawned
-// `bun extract ...` gets reinterpreted as `bun run extract` and crashes the
-// upgrade mid-migration. The shim is already the canonical wrapper; trust
-// it. Regression guarded by test/migrations-v0_13_0.test.ts.
+// Children run the CLI that is running this migration (#5184,
+// gbrainChildCommand): the compiled executable, or bun plus the running
+// cli.ts, else the `gbrain` on PATH. An earlier revision spawned the bare
+// runtime binary, which on bun-installed trees is `bun` — `bun extract ...`
+// was reinterpreted as `bun run extract` and crashed the upgrade
+// mid-migration; resolveChildCliInvocation never returns bun without the
+// cli.ts entrypoint. Regression guarded by test/migrations-v0_13_0.test.ts
+// and test/migration-child-cli.test.ts.
async function phaseASchema(opts: OrchestratorOpts): Promise<OrchestratorPhaseResult> {
if (opts.dryRun) return { name: 'schema', status: 'skipped', detail: 'dry-run' };
@@ -87,7 +89,7 @@ function phaseCVerify(opts: OrchestratorOpts): OrchestratorPhaseResult {
// docs-only brains, and brains with no entity pages legitimately
// produce 0. Phase B's own stdout shows `Links: created N` which is
// the authoritative signal — user sees it during upgrade.
- const out = execSync('gbrain call get_stats', {
+ const out = execSync(gbrainChildCommand('gbrain call get_stats'), {
encoding: 'utf-8', timeout: 60_000, env: process.env,
});
const parsed = JSON.parse(out) as { link_count?: number; page_count?: number };
diff --git a/src/commands/migrations/v0_22_4.ts b/src/commands/migrations/v0_22_4.ts
index e05b29f19e..e2d963d3fc 100644
--- a/src/commands/migrations/v0_22_4.ts
+++ b/src/commands/migrations/v0_22_4.ts
@@ -25,7 +25,7 @@ import { existsSync, mkdirSync, writeFileSync, readFileSync, appendFileSync } fr
import { join } from 'path';
import type { Migration, OrchestratorOpts, OrchestratorResult, OrchestratorPhaseResult } from './types.ts';
import type { BrainEngine } from '../../core/engine.ts';
-import { loadConfig, toEngineConfig } from '../../core/config.ts';
+import { loadConfig, toEngineConfig, gbrainPath } from '../../core/config.ts';
import { createEngine } from '../../core/engine-factory.ts';
import { scanBrainSources, type AuditReport } from '../../core/brain-writer.ts';
@@ -37,10 +37,7 @@ export function __setTestEngineOverride(engine: BrainEngine | null): void {
testEngineOverride = engine;
}
-function gbrainDir(): string {
- return join(process.env.HOME || '', '.gbrain');
-}
-function migrationsDir(): string { return join(gbrainDir(), 'migrations'); }
+function migrationsDir(): string { return gbrainPath('migrations'); }
function auditReportPath(): string { return join(migrationsDir(), 'v0.22.4-audit.json'); }
function pendingHostWorkPath(): string { return join(migrationsDir(), 'pending-host-work.jsonl'); }
@@ -208,15 +205,19 @@ export const v0_22_4: Migration = {
version: '0.22.4',
featurePitch: {
headline: 'Frontmatter-guard ships — broken brain pages can\'t hide',
- description:
- 'gbrain v0.22.4 adds end-to-end frontmatter validation: a `gbrain frontmatter` CLI ' +
- '(validate / audit / install-hook), a `frontmatter_integrity` doctor subcheck, a ' +
- 'pre-commit hook helper, and a new frontmatter-guard skill. The migration is audit-only ' +
- '(it never mutates your brain) — it scans every registered source, writes a per-source ' +
- 'report to ~/.gbrain/migrations/v0.22.4-audit.json, and queues a TODO with the exact fix ' +
- 'command for malformed frontmatter only. Missing frontmatter is treated as optional metadata ' +
- 'coverage for broad document sources. Run `gbrain frontmatter validate <source-path> --fix` ' +
- 'to repair (creates centralized backups under ~/.gbrain/backups/frontmatter). Ships frontmatter-guard.',
+ // Getter: paths follow GBRAIN_HOME at print time, not module load.
+ get description() {
+ return (
+ 'gbrain v0.22.4 adds end-to-end frontmatter validation: a `gbrain frontmatter` CLI ' +
+ '(validate / audit / install-hook), a `frontmatter_integrity` doctor subcheck, a ' +
+ 'pre-commit hook helper, and a new frontmatter-guard skill. The migration is audit-only ' +
+ '(it never mutates your brain) — it scans every registered source, writes a per-source ' +
+ `report to ${auditReportPath()}, and queues a TODO with the exact fix ` +
+ 'command for malformed frontmatter only. Missing frontmatter is treated as optional metadata ' +
+ 'coverage for broad document sources. Run `gbrain frontmatter validate <source-path> --fix` ' +
+ `to repair (creates centralized backups under ${gbrainPath('backups', 'frontmatter')}). Ships frontmatter-guard.`
+ );
+ },
},
orchestrator,
};
diff --git a/src/commands/projections.ts b/src/commands/projections.ts
new file mode 100644
index 0000000000..e3674cdf8c
--- /dev/null
+++ b/src/commands/projections.ts
@@ -0,0 +1,127 @@
+/**
+ * `gbrain projections drain` (#5401): rebuilds queued Markdown and code text
+ * projections in-process, in batches of up to 100, until every row queued
+ * before the run started has been tried once. Trusted local CLI only; it is not
+ * an operation, so MCP and remediation cannot run it.
+ *
+ * Postgres: safe beside a resident owner, because each page is rebuilt under
+ * its page lock with a revision recheck. PGLite: a resident owner holds the
+ * datastore, so the command refuses before opening the engine and the
+ * resident drains the backlog itself.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import type { OperationError } from '../core/ops/contract.ts';
+import { catalogueError } from '../core/error-catalogue.ts';
+import type { LockHolderInfo } from '../core/pglite-lock.ts';
+import type { ProgressReporter } from '../core/progress.ts';
+import {
+ projectionBacklog, rebuildPendingPageProjections, type ProjectionRebuildFailure,
+} from '../core/page-state/projections.ts';
+import { SERVE_LAUNCHD_LABEL, SERVE_SYSTEMD_UNIT } from '../core/serve-service.ts';
+import { resolveAutopilotJob } from '../core/autopilot-paths.ts';
+import { detectInstalledJob } from './autopilot/jobs.ts';
+
+export const PROJECTION_DRAIN_DOCS = 'docs/guides/repair.md#projection-drain';
+const BATCH = 100;
+
+export const PROJECTIONS_HELP = `Usage: gbrain projections drain [--limit <n>] [--json]
+
+Rebuild queued Markdown and code text projections now, in batches of up to 100,
+until every row queued before the run started has been tried once.
+
+ --limit <n> Try at most n pages in this run (default: no cap)
+ --json Print {rebuilt, superseded, failed, remaining} to stdout
+
+Exit codes: 0 nothing tried failed; 1 some pages failed; 2 did not run
+(projection_owner_resident: a resident gbrain process holds this PGLite brain
+and drains it itself).
+
+On Postgres the drain is safe while \`gbrain serve\` runs. Progress goes to stderr.
+Docs: ${PROJECTION_DRAIN_DOCS}
+`;
+
+export interface ProjectionDrainResult {
+ rebuilt: number;
+ superseded: number;
+ failed: ProjectionRebuildFailure[];
+ remaining: number;
+ limited: boolean;
+}
+
+export async function drainProjections(engine: BrainEngine, opts: { limit?: number; progress?: ProgressReporter } = {}): Promise<ProjectionDrainResult> {
+ const [{ runStart }] = await engine.executeRaw<{ runStart: string }>('SELECT now()::text AS "runStart"');
+ // PGLite's clock can be coarse: wait until it passes the run start, so a page
+ // that fails in this run is stamped after it and is not tried again.
+ while (!(await engine.executeRaw<{ passed: boolean }>('SELECT now()>$1::text::timestamptz AS passed', [runStart]))[0]?.passed) {
+ await new Promise(resolve => setTimeout(resolve, 1));
+ }
+ const total = (await projectionBacklog(engine)).pending;
+ opts.progress?.start('projections.drain', opts.limit === undefined ? total : Math.min(total, opts.limit));
+ const failed: ProjectionRebuildFailure[] = [];
+ let rebuilt = 0;
+ let superseded = 0;
+ let tried = 0;
+ try {
+ while (opts.limit === undefined || tried < opts.limit) {
+ const failuresBefore = failed.length;
+ const batch = await rebuildPendingPageProjections(engine, Math.min(BATCH, (opts.limit ?? Infinity) - tried),
+ { notAfter: runStart, onFailure: failure => failed.push(failure) });
+ const attempted = batch.rebuilt + batch.superseded + failed.length - failuresBefore;
+ if (attempted === 0) break;
+ rebuilt += batch.rebuilt;
+ superseded += batch.superseded;
+ tried += attempted;
+ opts.progress?.tick(attempted, `${rebuilt} rebuilt, ${failed.length} failed`);
+ }
+ } finally {
+ opts.progress?.finish();
+ }
+ const remaining = (await projectionBacklog(engine)).pending;
+ return { rebuilt, superseded, failed, remaining, limited: opts.limit !== undefined && tried >= opts.limit && remaining > 0 };
+}
+
+/** The next step for one failed page, from the preparation error it reported. */
+export function projectionFailureNextAction(failure: ProjectionRebuildFailure): string {
+ if (failure.reason.startsWith('Code projection requires a recorded source path')) {
+ return `restore frontmatter.file or source_path on ${failure.slug}, then run \`gbrain projections drain\` again`;
+ }
+ if (failure.reason.startsWith('This page kind requires its source importer')) {
+ return `re-import it from its source: \`gbrain sync --source ${failure.source_id}\``;
+ }
+ return 'run `gbrain doctor`; the page stays queued and `gbrain projections drain` tries it again on its next run';
+}
+
+/**
+ * Stop, drain and restart commands for each way a resident owner can run. The
+ * restart runs whether or not a page failed, so a drain exit of 1 never leaves
+ * the owner stopped. `brain` keeps a mounted brain selected in every command.
+ */
+export function residentDrainSteps(pid: number | undefined, brain = 'host'): string {
+ const uid = '$(id -u)';
+ // #5195: this brain's own autopilot job, or the shared job an older install still runs it from.
+ const job = resolveAutopilotJob();
+ const installed = detectInstalledJob(job).installed;
+ const launchd = installed?.target === 'macos' ? installed.name : job.launchdLabel;
+ const systemd = installed?.target === 'linux-systemd' ? installed.name : job.systemdUnit;
+ const drain = `gbrain projections drain${brain === 'host' ? '' : ` --brain ${brain}`}`;
+ const cycle = (stop: string, start: string) => `${stop} && { ${drain}; ${start}; }`;
+ return [
+ `To drain faster, stop the owner, drain, then restart it:`,
+ ` serve service (launchd): ${cycle(`launchctl bootout gui/${uid}/${SERVE_LAUNCHD_LABEL}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${SERVE_LAUNCHD_LABEL}.plist`)}`,
+ ` serve service (systemd): ${cycle(`systemctl --user stop ${SERVE_SYSTEMD_UNIT}`, `systemctl --user start ${SERVE_SYSTEMD_UNIT}`)}`,
+ ` autopilot (launchd): ${cycle(`launchctl bootout gui/${uid}/${launchd}`, `launchctl bootstrap gui/${uid} ~/Library/LaunchAgents/${launchd}.plist`)}`,
+ ` autopilot (systemd): ${cycle(`systemctl --user stop ${systemd}`, `systemctl --user start ${systemd}`)}`,
+ ` a manual gbrain serve: stop it${pid ? ` (kill ${pid})` : ''}, run ${drain}, then start gbrain serve again`,
+ ].join('\n');
+}
+
+/** DX-O5 refusal: the drain did not run because a resident process holds this PGLite brain. */
+export function projectionOwnerResidentError(holder: LockHolderInfo, dataDir: string, brain = 'host'): OperationError {
+ const owner = `${holder.subcommand ? `gbrain ${holder.subcommand}` : 'a gbrain process'}${holder.pid ? ` (pid ${holder.pid})` : ''}`;
+ return catalogueError('projection_owner_resident',
+ `The PGLite brain at ${dataDir} is held by ${owner}, so the drain did not run.`,
+ [
+ `The upgraded resident drains queued projections itself (up to 100 pages per pass, fewer while writes wait); watch the pending count with \`gbrain doctor${brain === 'host' ? '' : ` --brain ${brain}`}\` (text_projection_readiness).`,
+ residentDrainSteps(holder.pid, brain),
+ ].join('\n'));
+}
diff --git a/src/commands/recall.ts b/src/commands/recall.ts
index 997229248e..831da37e78 100644
--- a/src/commands/recall.ts
+++ b/src/commands/recall.ts
@@ -213,9 +213,17 @@ async function resolveSourceForRecall(
engine: BrainEngine,
flagValue: string,
thinClient: boolean,
+ // #5535: whether --source/--source-id was actually PASSED. parseFlags
+ // defaults flags.source to the literal 'default', so the value alone
+ // cannot distinguish "user asked for the default source" from "user
+ // passed no source flag".
+ sourceExplicit: boolean,
): Promise<string> {
if (thinClient) {
- if (flagValue !== 'default') return flagValue;
+ // #5535: an explicit `--source default` is a real selector, not an
+ // omitted flag — return the literal id instead of falling through to
+ // GBRAIN_SOURCE / the server's own default.
+ if (sourceExplicit || flagValue !== 'default') return flagValue;
const env = process.env.GBRAIN_SOURCE;
if (env && env.length > 0 && SOURCE_ID_RE.test(env)) return env;
return 'default';
@@ -228,7 +236,10 @@ async function resolveSourceForRecall(
// empty" behavior so existing tests + scripts keep working while
// recall still benefits from the env/dotfile resolution chain.
try {
- return await resolveSourceId(engine, flagValue !== 'default' ? flagValue : null);
+ // #5535: pass the flag's literal value (including 'default') when it
+ // was explicit so tier 1 of the resolver wins; null only when the flag
+ // was omitted, which keeps the env/dotfile/config-default chain.
+ return await resolveSourceId(engine, sourceExplicit || flagValue !== 'default' ? flagValue : null);
} catch (e) {
process.stderr.write(
`[recall] source not registered: ${flagValue}. Falling back to literal value.\n`,
@@ -288,7 +299,7 @@ export async function runRecall(engine: BrainEngine, args: string[]): Promise<vo
);
}
- const sourceId = await resolveSourceForRecall(engine, flags.source, thinClient);
+ const sourceId = await resolveSourceForRecall(engine, flags.source, thinClient, flags.sourceExplicit);
// MEMORY_VERBS v1 [c4]: the verb params route through the recall OP so the
// CLI and MCP exercise the same arm (query/budget packing/superset envelope).
@@ -433,7 +444,11 @@ async function runRecallOnce(
if (resolvedSince) params.since = resolvedSince.toISOString();
if (flags.grep) params.grep = flags.grep;
if (flags.pending) params.include_pending = true;
- if (sourceId !== 'default') params.source_id = sourceId;
+ // #5535: send source_id whenever the selector was explicit — including
+ // an explicit 'default'. Omitting it let the remote server apply ITS
+ // own default (sources.default / GBRAIN_SOURCE server-side), so an
+ // explicit `--source default` silently queried a different source.
+ if (sourceId !== 'default' || flags.sourceExplicit) params.source_id = sourceId;
const raw = await callRemoteTool(cfg!, 'recall', params, { timeoutMs: 30_000 });
const unpacked = unpackToolResult<{
diff --git a/src/commands/repair.ts b/src/commands/repair.ts
index 18f8aafa36..eef9a876f9 100644
--- a/src/commands/repair.ts
+++ b/src/commands/repair.ts
@@ -6,12 +6,15 @@
* coordinated page write (or, for `safe-chunks`, a projection-only rebuild
* that takes no admission), resumes after an interruption, and stops before
* crossing 90% of a cumulative journal cap. Thin clients refuse (cli.ts).
+ * Explicit-only kinds run only when named; `--all` and the no-kind preview
+ * list them with their preview command instead, and only they accept
+ * `--expect <hash>` and `--include-ambiguous` (their preview-bound apply).
*/
import type { BrainEngine } from '../core/engine.ts';
import { setCliExitVerdict } from '../core/cli-force-exit.ts';
import { OperationError } from '../core/ops/contract.ts';
-import { REPAIR_KINDS, resolveRepairScope, runRepair, type RepairKind, type RepairResult } from '../core/repair/core.ts';
-import { REPAIR_REGISTRY, repairMaySpend, repairRunner, repairSpec } from '../core/repair/registry.ts';
+import { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';
+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMaySpend, repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';
function wrap(text: string, indent: number, width = 80): string {
const lines: string[] = [];
@@ -24,34 +27,43 @@ function wrap(text: string, indent: number, width = 80): string {
return lines.join(`\n${' '.repeat(indent)}`);
}
+const explicitKinds = EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind).join(', ');
+
export const REPAIR_HELP = `Usage: gbrain repair [<kind>] [--apply] [--source <id>] [--limit <n>] [--no-embed] [--json]
gbrain repair --all [--apply] [--source <id>] [--json]
+ gbrain repair <explicit-only kind> [--include-ambiguous] [--apply --expect <preview-hash>] [--source <id>] [--json]
Repair residual damage that \`gbrain doctor\` reports. Dry run unless --apply.
Kinds:
-${REPAIR_REGISTRY.map(spec => ` ${spec.kind.length < 13 ? spec.kind.padEnd(12) : `${spec.kind}\n${' '.repeat(14)}`} ${wrap(spec.summary, 15)}`).join('\n')}
+${REPAIR_REGISTRY.map(spec => ` ${spec.kind.length < 13 ? spec.kind.padEnd(12) : `${spec.kind}\n${' '.repeat(14)}`} ${wrap(`${spec.explicit_only
+ ? `[explicit-only; preview: ${repairPreviewCommand(spec.kind)}] ` : ''}${spec.summary}`, 15)}`).join('\n')}
Options:
--apply Write the repair (no prompt). Without it, only preview.
--source <id> Limit to one source (default: every active source).
--limit <n> Repair at most n items; rerun the same command to continue.
--no-embed safe-chunks, contextual-mode: no provider call; embed later with gbrain embed --stale.
- --all Run every kind in order (${REPAIR_KINDS.join(', ')}).
+ --all Run every kind in order (${AUTO_REPAIR_REGISTRY.map(spec => spec.kind).join(', ')}).
+ Explicit-only kinds (${explicitKinds}) never run here; name each one.
+ --expect <hash>
+ Explicit-only kinds: apply exactly the set the preview printed under this hash.
+ --include-ambiguous
+ Explicit-only kinds: widen the preview to ambiguous items (its hash covers them).
--json Machine-readable output with a stable shape.
Any other option is refused. There is no --max-usd here: to cap paid embedding
work, run the repairs through gbrain doctor --remediate --yes --include-repairs --max-usd <n>.
With no kind, previews every kind. Run it on the brain host.`;
-const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed']);
-const VALUE_FLAGS = new Set(['--source', '--limit']);
+const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--include-ambiguous']);
+const VALUE_FLAGS = new Set(['--source', '--limit', '--expect']);
-interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; source?: string; limit?: string }
+interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; source?: string; limit?: string; expect?: string }
/** Strict parse: every flag is known, value flags carry a value, at most one kind. */
export function parseRepairArgs(args: string[]): RepairArgs {
- const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false };
+ const parsed: RepairArgs = { apply: false, all: false, json: false, noEmbed: false, includeAmbiguous: false };
const positional: string[] = [];
for (let i = 0; i < args.length; i++) {
const token = args[i]!;
@@ -69,6 +81,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {
if (flag === '--apply') parsed.apply = true;
else if (flag === '--all') parsed.all = true;
else if (flag === '--json') parsed.json = true;
+ else if (flag === '--include-ambiguous') parsed.includeAmbiguous = true;
else parsed.noEmbed = true;
continue;
}
@@ -76,16 +89,23 @@ export function parseRepairArgs(args: string[]): RepairArgs {
const value = equal >= 0 ? token.slice(equal + 1) : args[++i];
if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);
if (flag === '--source') parsed.source = value;
+ else if (flag === '--expect') parsed.expect = value;
else parsed.limit = value;
}
if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,
`Kinds: ${REPAIR_KINDS.join(', ')}.`);
parsed.kind = positional[0];
+ const bound = parsed.expect !== undefined ? '--expect' : parsed.includeAmbiguous ? '--include-ambiguous' : undefined;
+ if (bound && !EXPLICIT_REPAIR_REGISTRY.some(spec => spec.kind === parsed.kind)) {
+ throw new OperationError('invalid_params', `${bound} applies only to an explicit-only kind named on the command line (${explicitKinds}).`,
+ `Preview one by name: ${repairPreviewCommand(EXPLICIT_REPAIR_REGISTRY[0]!.kind)}`);
+ }
return parsed;
}
function human(result: RepairResult): string {
const lines = [`${result.kind}: ${result.affected} item(s) ${result.mode === 'apply' ? 'pending before this run' : 'to repair'}`];
+ for (const warning of result.warnings ?? []) lines.push(` WARNING: ${warning}`);
if (result.sample.length) lines.push(` e.g. ${result.sample.join(', ')}`);
const residuals = Object.entries(result.residuals).map(([k, v]) => `${k}=${v}`).join(', ');
if (residuals) lines.push(` ${residuals}`);
@@ -95,13 +115,15 @@ function human(result: RepairResult): string {
if (result.resumed_from) lines.push(` resuming after item ${result.resumed_from.phase}:${result.resumed_from.id}`);
if (result.mode === 'apply') lines.push(` applied ${result.applied}, skipped ${result.skipped}${result.complete ? ', complete' : ''}`);
if (result.stopped) lines.push(` STOPPED: ${result.stopped.message}`);
+ for (const entry of result.listing ?? []) lines.push(` ${entry.class}: ${entry.item}${entry.detail ? ` (${entry.detail})` : ''}`);
+ if (result.mode === 'apply' && result.outcomes) lines.push(` outcomes: ${Object.entries(result.outcomes).map(([k, v]) => `${k}=${v}`).join(', ')}`);
if (result.mode === 'dry_run' && result.affected) lines.push(` apply: ${result.apply_command}`);
return lines.join('\n');
}
export async function runRepairCommand(engine: BrainEngine, args: string[]): Promise<void> {
if (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }
- const { kind, apply, all, json, noEmbed, source, limit: limitText } = parseRepairArgs(args);
+ const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, limit: limitText } = parseRepairArgs(args);
const limit = limitText === undefined ? undefined : Number(limitText);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw new OperationError('invalid_params', '--limit must be a positive integer.');
if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {
@@ -109,23 +131,26 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Pro
}
if (kind && all) throw new OperationError('invalid_params', 'Pass either a kind or --all, not both.');
if (!kind && apply && !all) throw new OperationError('invalid_params', 'Name a kind or pass --all with --apply.');
- const kinds: RepairKind[] = kind ? [kind as RepairKind] : [...REPAIR_KINDS];
+ const kinds: RepairKind[] = kind ? [kind as RepairKind] : AUTO_REPAIR_REGISTRY.map(spec => spec.kind);
+ const explicitKindsNotRun = kind ? [] : explicitRepairNotices({ source });
const scope = await resolveRepairScope(engine, source);
const runner = await repairRunner(engine, { apply, noEmbed });
const results: Array<RepairResult & { paid: boolean }> = [];
for (const k of kinds) {
- const result = await runner.run(k, scope, { limit, sourceFlag: source });
+ const result = await runner.run(k, scope, { limit, sourceFlag: source, explicit: k === kind, expect, includeAmbiguous });
results.push({ ...result, paid: repairMaySpend(repairSpec(k), noEmbed) });
if (result.stopped) break;
}
const paidKinds = results.filter(r => r.paid).map(r => r.kind);
if (json) {
- console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results, paid_kinds: paidKinds }, null, 2));
+ console.log(JSON.stringify({ scope, mode: apply ? 'apply' : 'dry_run', results, paid_kinds: paidKinds,
+ ...(explicitKindsNotRun.length ? { explicit_kinds: explicitKindsNotRun } : {}) }, null, 2));
} else {
console.log(`Scope: brain ${scope.brain_id}; sources ${scope.source_ids.join(', ') || '(none)'}`);
for (const result of results) console.log(human(result));
if (!apply && paidKinds.length) console.log(`Kinds that may queue paid embeddings: ${paidKinds.join(', ')} (pass --no-embed to skip; `
+ 'page-write kinds are re-embedded by their publication either way; cap spend with gbrain doctor --remediate --yes --include-repairs --max-usd <n>).');
+ if (explicitKindsNotRun.length) console.log(`Explicit-only kinds (not run without their name; preview each): ${explicitKindsNotRun.map(n => n.preview_command).join('; ')}`);
}
if (results.some(r => r.stopped)) setCliExitVerdict(1);
}
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index 74fe22e1ef..907d5f6da2 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -15,6 +15,8 @@ import type { BrainEngine } from '../core/engine.ts';
import type { AuthInfo } from '../core/operations.ts';
import { executeRawJsonb } from '../core/sql-query.ts';
import { MinionQueue } from '../core/minions/queue.ts';
+import { OperationError } from '../core/ops/contract.ts';
+import { ERROR_CATALOGUE } from '../core/error-catalogue.ts';
import {
computeContentHash,
validateIngestionEvent,
@@ -518,6 +520,13 @@ async function handleIngest(
message: 'Accepted. Event queued for ingestion.',
});
} catch (err) {
+ // A job row left with SQL NULL authority by an upgrade across v0.50 holds
+ // this capture's key (or fills its waiting cap): a conflict the operator
+ // resolves with the hinted recovery, not a server fault.
+ if (err instanceof OperationError && err.docs === ERROR_CATALOGUE.legacy_job_authority.docs) {
+ res.status(409).json({ error: err.code, message: err.message, hint: err.suggestion, docs_url: err.docs });
+ return;
+ }
const msg = err instanceof Error ? err.message : String(err);
console.error('POST /ingest queue submission error:', msg);
res.status(500).json({
diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.ts
index 25e0aa2cdd..38c2ec7c40 100644
--- a/src/commands/serve-http.ts
+++ b/src/commands/serve-http.ts
@@ -41,7 +41,7 @@ import {
import { canonicalOAuthResource } from '../core/oauth-grants.ts';
import type { McpSurface } from '../mcp/surface.ts';
import { bindResolveIpcForServe } from '../mcp/resolve-ipc-binding.ts';
-import { createPersistenceIpcProvider } from '../core/persistence/provider.ts';
+import { createPersistenceIpcProvider, residentPersistenceConfig } from '../core/persistence/provider.ts';
import { resolveMcpStdioSourceScope } from '../mcp/server.ts';
import { loadConfig, type GBrainConfig } from '../core/config.ts';
import { buildError } from '../core/errors.ts';
@@ -880,7 +880,7 @@ ${bootstrapFromEnv
const ipcBinding = await bindResolveIpcForServe(
engine,
(await resolveMcpStdioSourceScope(engine)).sourceId,
- await createPersistenceIpcProvider(engine, config),
+ await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? config),
);
if (ipcBinding.socketPath) {
console.error(` Resolve IPC: ${ipcBinding.socketPath}`);
diff --git a/src/commands/sources-mirror.ts b/src/commands/sources-mirror.ts
new file mode 100644
index 0000000000..84b5a11c84
--- /dev/null
+++ b/src/commands/sources-mirror.ts
@@ -0,0 +1,31 @@
+/**
+ * `gbrain sources mirror-readonly <id>` / `gbrain sources mirror-writable <id>`
+ * (#5409): set `sources.config.mirror_read_only`, the per-source read-only
+ * mirror flag (default false). While it is true, managed publication never
+ * writes a file into the source's checkout: sync imports canonical metadata
+ * database-only and page writes are stored database-only, so a mirror kept
+ * current by `git pull --ff-only` never gains local modifications.
+ * Follows `federate` / `unfederate`.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import { normalizeSourceConfig, parseSourceConfig } from '../core/sources-load.ts';
+
+export async function runMirrorMode(engine: BrainEngine, args: string[], readOnly: boolean): Promise<void> {
+ const id = args[0];
+ if (!id || id.startsWith('-')) {
+ console.error(`Usage: gbrain sources ${readOnly ? 'mirror-readonly' : 'mirror-writable'} <id>`);
+ process.exit(2);
+ }
+ const [src] = await engine.executeRaw<{ config: unknown }>('SELECT config FROM sources WHERE id=$1', [id]);
+ if (!src) {
+ console.error(`Source "${id}" not found. List sources with: gbrain sources list`);
+ process.exit(4);
+ }
+ const config = parseSourceConfig(src.config);
+ if (readOnly) config.mirror_read_only = true;
+ else delete config.mirror_read_only;
+ await engine.executeRaw('UPDATE sources SET config = $1::text::jsonb WHERE id = $2', [JSON.stringify(normalizeSourceConfig(config)), id]);
+ console.log(readOnly
+ ? `Source "${id}" is now a read-only mirror: managed sync and page writes never write files into its checkout; canonical metadata stays in the database.`
+ : `Source "${id}" is writable again: managed sync and page writes publish canonical files into its checkout.`);
+}
diff --git a/src/commands/sources.ts b/src/commands/sources.ts
index 0678faf65a..88b39bcb79 100644
--- a/src/commands/sources.ts
+++ b/src/commands/sources.ts
@@ -18,6 +18,7 @@
* gbrain sources detach — remove .gbrain-source from CWD
* gbrain sources federate <id> — sources.config.federated = true
* gbrain sources unfederate <id> — sources.config.federated = false
+ * gbrain sources mirror-readonly|mirror-writable <id> — sources.config.mirror_read_only (#5409)
* gbrain sources push [<id>|--path <dir>] — scan-gated add→commit→pull→push
* (agent-bootstrap; core in src/core/workspace-push.ts)
*
@@ -99,6 +100,7 @@ interface SourceListEntry {
name: string;
local_path: string | null;
federated: boolean;
+ mirror_read_only: boolean;
page_count: number;
last_sync_at: string | null;
}
@@ -727,6 +729,7 @@ async function runList(engine: BrainEngine, args: string[]): Promise<void> {
name: r.name,
local_path: r.local_path,
federated: isFederated(r.config),
+ mirror_read_only: parseConfig(r.config).mirror_read_only === true,
page_count: pageCount,
last_sync_at: r.last_sync_at ? new Date(r.last_sync_at).toISOString() : null,
});
@@ -1867,6 +1870,7 @@ export async function runSources(engine: BrainEngine, args: string[]): Promise<v
case 'detach': runDetach(); return;
case 'federate': return runFederate(engine, rest, true);
case 'unfederate': return runFederate(engine, rest, false);
+ case 'mirror-readonly': case 'mirror-writable': return (await import('./sources-mirror.ts')).runMirrorMode(engine, rest, sub === 'mirror-readonly');
case 'archive': return runArchive(engine, rest);
case 'restore': return runRestore(engine, rest);
case 'purge': return runPurge(engine, rest);
@@ -1951,6 +1955,8 @@ Subcommands:
brain needed. See docs/guides/github-source.md.
federate <id> Make source appear in cross-source default search.
unfederate <id> Isolate source from default search.
+ mirror-readonly <id> Read-only mirror (#5409): managed writes never touch its checkout.
+ mirror-writable <id> Undo mirror-readonly.
set-cr-mode <id> <none|title|per_chunk_synopsis>
Per-source contextual retrieval mode
override (v0.40.3.0). Pass "unset" or
diff --git a/src/commands/sync-diagnostics.ts b/src/commands/sync-diagnostics.ts
index 3d038144ca..63bdb9f91b 100644
--- a/src/commands/sync-diagnostics.ts
+++ b/src/commands/sync-diagnostics.ts
@@ -16,11 +16,14 @@ export function printManagedSyncDiagnostic(result: SyncResult, sink: NodeJS.Writ
return true;
}
-/** Informational managed-sync lines: skipped slug collisions and the links derived after the checkpoint. */
+/** Informational managed-sync lines: skipped slug collisions, refused files and the links derived after the checkpoint. */
export function printManagedSyncNotes(result: SyncResult, write: (line: string) => void): void {
for (const collision of result.slugCollisions ?? []) {
write(` Slug collision: ${collision.skipped.join(', ')} and ${collision.kept} map to ${collision.slug}; kept ${collision.kept}. Rename one file to import both.`);
}
+ for (const refusal of result.fileRefusals ?? []) {
+ write(` Refused ${refusal.code}: ${refusal.message} ${refusal.suggestion} (${refusal.docs})`);
+ }
const skips = result.legacySkips;
if (skips?.contextualMode) write(` ${skips.contextualMode} legacy file(s) skipped because they parse to the same page but have no contextual retrieval mode, which a skipped import cannot stamp; to stamp it: gbrain repair contextual-mode`);
if (skips?.canonicalBytes) write(` ${skips.canonicalBytes} legacy file(s) skipped because they parse to the same page but their bytes are not what gbrain reads back (for example, not valid UTF-8); re-save them as UTF-8 to publish them exactly.`);
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index 8b8dc2915a..db97eb054a 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -49,7 +49,8 @@ export interface SyncResult {
/** #5751: unchanged managed working-tree files skipped although a no-op publication cannot resolve their admit reason. */
legacySkips?: { contextualMode: number; canonicalBytes: number };
/** Managed sync: files skipped because another origin keeps their slug, and links derived after the checkpoint. */
- slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
+ slugCollisions?: import('../core/persistence/sync-discovery.ts').SyncSlugCollision[];
+ fileRefusals?: import('../core/persistence/sync-discovery.ts').SyncFileRefusal[]; links?: import('../core/persistence/links-maintenance.ts').ManagedLinkExtraction;
/**
* Aggregated alias/undeclared explicit-type warnings (schema.type_warnings,
* default on) — one entry per distinct non-canonical type this run.
diff --git a/src/commands/sync/imports.ts b/src/commands/sync/imports.ts
index e45b023274..abad79bc19 100644
--- a/src/commands/sync/imports.ts
+++ b/src/commands/sync/imports.ts
@@ -25,6 +25,8 @@ import {
import { isPathSafe } from '../../core/sync-git.ts';
import { resolveStallAbortSeconds, composeAbortSignals } from '../../core/sync-reconcile.ts';
import { sanitizePathForDisplay } from '../../core/sync.ts';
+import { isWindowsColonTarget } from '../../core/persistence/native-file-target.ts';
+import { ERROR_CATALOGUE } from '../../core/error-catalogue.ts';
import type { SyncOpts, SyncResult } from '../sync.ts';
import { partial, markCompleted, noteTypeWarning, maybeYield } from './sync-run.ts';
import type { SyncPlan, SyncProgress, SyncRun } from './sync-run.ts';
@@ -245,6 +247,16 @@ async function importOnePath(run: SyncRun, ctx: ImportContext, eng: BrainEngine,
const { opts, company, gitContextRoot, syncRepoPath, syncActivePack, noEmbed, pacer, progressAt, progress } = ctx;
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- `path` is a git-diff path from the synced repo (repo content can be hostile), but the joined path is checked by isPathSafe(filePath, gitContextRoot) realpath containment below before any read
const filePath = join(syncRepoPath, path);
+ // #5032: Windows cannot store ':' in a file name (it names an alternate data
+ // stream), so the file cannot be in this checkout; a named per-file refusal
+ // instead of the silent "deleted after the pin" skip below.
+ if (isWindowsColonTarget(path)) {
+ failedFiles.push({ path, error: `colon_slug_windows_write_through: ${path} has a ':' in its name, which Windows cannot store. `
+ + `Rename it without ':' on a macOS or Linux checkout and commit, then run gbrain sync${opts.sourceId ? ` --source ${opts.sourceId}` : ''} (${ERROR_CATALOGUE.colon_slug_windows_write_through.docs}).` });
+ progressAt.last = Date.now();
+ progress.tick(1, `skip:${path}`);
+ return;
+ }
if (!company && !existsSync(filePath)) {
// v0.42.x (#1794, Codex #3): the diff is against the PINNED target, but
// importFile reads the live working tree. A file added in lastCommit..pin
diff --git a/src/commands/think.ts b/src/commands/think.ts
index fce401875e..006735fa81 100644
--- a/src/commands/think.ts
+++ b/src/commands/think.ts
@@ -203,7 +203,7 @@ prints what would have been the input (exit 0).
// Persist if --save (the runThink path doesn't auto-persist; CLI does it explicitly)
if (save) {
- const persisted = await persistSynthesis(engine, result);
+ const persisted = await persistSynthesis(engine, result, { sourceId, allowedSources });
savedSlug = persisted.slug || undefined; // '' = persist-skip signal (#10)
evidenceInserted = persisted.evidenceInserted;
for (const w of persisted.warnings) result.warnings.push(w);
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 2abf6d77d8..805505d87f 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -181,6 +181,30 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
setCliExitVerdict(1);
return;
}
+ // #5311: a bare `gbrain upgrade` has no target, so the check above cannot
+ // fire, and on an exact-tag Git pin `bun update` is a successful no-op.
+ // When the version did not change and the global install pins a tag, say
+ // so and exit non-zero instead of reporting an upgrade.
+ if (!target && method === 'bun' && newVersion && newVersion === oldVersion) {
+ const pin = bunGlobalExactTagPin(resolveBunGlobalRoot());
+ if (pin) {
+ const { pendingUpgradeVersion } = await import('../core/self-upgrade.ts');
+ const latest = pendingUpgradeVersion(oldVersion);
+ const reinstall = latest ? `bun add -g github:garrytan/gbrain#v${latest}` : 'bun add -g github:garrytan/gbrain';
+ console.error(`Upgrade did not take effect: still running ${newVersion}, because the global install is pinned to ${pin} and \`bun update\` keeps a pinned tag.`);
+ console.error('Reinstall to move off the pin:');
+ console.error(` ${reinstall}`);
+ recordUpgradeError({
+ phase: 'verify-pin',
+ fromVersion: oldVersion,
+ toVersion: latest ?? 'latest',
+ error: `pinned to ${pin}; still running ${newVersion} after upgrade`,
+ hint: reinstall,
+ });
+ setCliExitVerdict(1);
+ return;
+ }
+ }
// Save old version for post-upgrade migration detection
saveUpgradeState(oldVersion, newVersion);
@@ -290,6 +314,22 @@ export function resolveBunGlobalRoot(): string {
return installRoot ?? defaultRoot;
}
+/**
+ * #5311: the exact Git tag the bun global install pins gbrain to
+ * (`github:garrytan/gbrain#v0.51.0`), or null for an unpinned or branch spec.
+ */
+export function bunGlobalExactTagPin(globalRoot: string): string | null {
+ try {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- globalRoot is resolveBunGlobalRoot(): Bun's own global install dir from BUN_INSTALL or HOME
+ const pkg = JSON.parse(readFileSync(join(globalRoot, 'package.json'), 'utf-8')) as { dependencies?: Record<string, string> };
+ const spec = pkg.dependencies?.gbrain;
+ if (typeof spec !== 'string') return null;
+ return /#v?\d+\.\d+(\.\d+)*$/.test(spec.trim()) ? spec.trim() : null;
+ } catch {
+ return null;
+ }
+}
+
function isBunGlobalRoot(dir: string): boolean {
return existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'node_modules'));
}
diff --git a/src/core/ai/errors.ts b/src/core/ai/errors.ts
index c20d57ea2f..b8a03aab6f 100644
--- a/src/core/ai/errors.ts
+++ b/src/core/ai/errors.ts
@@ -65,7 +65,31 @@ function carryStatusFields(from: unknown, to: AIServiceError): AIServiceError {
return to;
}
-export function normalizeAIError(err: unknown, context?: string): AIServiceError {
+/**
+ * Scrub upstream text in place along a wrapped error's cause chain (message,
+ * stack, the SDK's responseBody and parsed data), keeping status, headers and
+ * shape, so `.cause` walkers still classify it and nothing serialized or
+ * printed later carries what `redact` removes.
+ */
+function scrubErrorChain(err: unknown, redact: (text: string) => string): void {
+ let cur = err;
+ for (let depth = 0; depth < 4 && cur && typeof cur === 'object'; depth++) {
+ const node = cur as Record<string, unknown>;
+ for (const key of ['message', 'stack', 'responseBody']) {
+ if (typeof node[key] === 'string') try { node[key] = redact(node[key] as string); } catch { /* read-only field */ }
+ }
+ if (node.data && typeof node.data === 'object') try { node.data = JSON.parse(redact(JSON.stringify(node.data))); } catch { /* not plain data */ }
+ cur = node.cause;
+ }
+}
+
+/**
+ * `redact` scrubs upstream text before it becomes the message, and in the
+ * wrapped error (#5137: the gateway passes its provider-key redactor, since
+ * auth errors echo keys).
+ */
+export function normalizeAIError(err: unknown, context?: string, redact?: (text: string) => string): AIServiceError {
+ if (redact) scrubErrorChain(err, redact);
if (err instanceof AIServiceError) return err;
const anyErr = err as {
@@ -84,7 +108,8 @@ export function normalizeAIError(err: unknown, context?: string): AIServiceError
anyErr?.statusCode ??
(typeof anyErr?.apiErrorStatus === 'number' ? anyErr.apiErrorStatus : undefined);
const name = anyErr?.name ?? '';
- const msg = anyErr?.message ?? String(err);
+ const raw = anyErr?.message ?? String(err);
+ const msg = redact ? redact(raw) : raw;
const ctxPrefix = context ? `[${context}] ` : '';
// 4xx (except 429) = config-level, non-retryable
@@ -320,3 +345,23 @@ export function createGlobalLlmHaltTracker(): GlobalLlmHaltTracker {
note: () => lastNote,
};
}
+
+/**
+ * Embedding providers whose own documentation says a rejected request is not
+ * billed. Only for these does a permanent request-shaped rejection (HTTP 400,
+ * 413 or 422; never 401/403/429) release its invocation reservation instead of
+ * keeping the maximum debit. Verified per provider:
+ * - google: "If your request fails with a 400 or 500 error, you won't be
+ * charged for the tokens used." (ai.google.dev/gemini-api/docs/billing,
+ * "Am I charged for failed requests?", checked 2026-10-01)
+ * OpenAI, Voyage and the other embedding recipes publish no such statement, so
+ * their rejections keep the debit (token-limit rejections are handled above).
+ */
+const UNBILLED_REJECTION_PROVIDERS: ReadonlySet<string> = new Set(['google']);
+
+export function isUnbilledEmbeddingRejection(recipeId: string, err: unknown): boolean {
+ if (!UNBILLED_REJECTION_PROVIDERS.has(recipeId)) return false;
+ const e = err as { statusCode?: unknown; status?: unknown } | null;
+ const status = typeof e?.statusCode === 'number' ? e.statusCode : typeof e?.status === 'number' ? e.status : undefined;
+ return status === 400 || status === 413 || status === 422;
+}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 5ad788eb58..c36c2a43de 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -57,13 +57,15 @@ import { parseLlmJson } from '../llm-json.ts';
import type { BrainEngine } from '../engine.ts';
import { dimsProviderOptions } from './dims.ts';
import { hasAnthropicKey, stashGatewayAnthropicKeyFromEnv } from './anthropic-key.ts';
-import { AIConfigError, AITransientError, isStructuredOutputRejection, normalizeAIError } from './errors.ts';
+import { AIConfigError, AITransientError, isStructuredOutputRejection, isUnbilledEmbeddingRejection, normalizeAIError } from './errors.ts';
import { isEmbeddingZeroNormError, screenAlignedEmbeddings, screenEmbeddings, sendableEmbeddingInputs } from './embedding-guard.ts';
import { getProviderCapabilities } from './capabilities.ts';
import { runGuardrails, hasGuardrails, type GuardrailHook } from '../guardrails.ts';
import { loadConfig } from '../config.ts';
import type { GBrainConfig } from '../config.ts';
import { mergedProviderEnv } from './provider-env.ts';
+import { redactProviderKeys } from './key-redact.ts';
+import { reportEmbeddingAuthFailure } from './key-warnings.ts';
import { buildGatewayConfig, foldNativeBaseUrlsFromFilePlane } from './build-gateway-config.ts';
import { invokeAI, sdkInvocationUsage, responseInvocationUsage, hasAIInvocationGuard, isAIInvocationPolicyError } from './invocation-guard.ts';
import { createGuardedGeneration, chatInvocation } from './guarded-generation.ts';
@@ -123,6 +125,8 @@ const DEFAULT_CHAT_MODEL = 'anthropic:claude-sonnet-4-6';
// the mode bundles) — `voyage:rerank-2.5` since v0.48.2.
let _config: AIGatewayConfig | null = null;
+/** #5137: provider auth errors echo keys; scrub every key in effect before the text leaves the gateway. */
+const redactKeys = (text: string): string => redactProviderKeys(text, _config?.env ?? {});
const _modelCache = new Map<string, any>();
/**
@@ -1710,7 +1714,7 @@ async function embedSubBatch(
// deadline) — shorter wins.
abortSignal: withDefaultTimeout(opts?.abortSignal, AI_EMBED_TIMEOUT_MS),
...(hasAIInvocationGuard() ? { maxRetries: 0 } : opts?.maxRetries !== undefined ? { maxRetries: opts.maxRetries } : {}),
- }), sdkInvocationUsage, err => isTokenLimitError(err) ? { inputTokens: 0, outputTokens: 0 } : null);
+ }), sdkInvocationUsage, err => isTokenLimitError(err) || isUnbilledEmbeddingRejection(recipe.id, err) ? { inputTokens: 0, outputTokens: 0 } : null);
// Carry the threaded input_type across the SDK boundary via
// __embedInputTypeStore (the adapter strips it from providerOptions —
// see the store's doc comment). Populated only when dimsProviderOptions
@@ -1751,7 +1755,8 @@ async function embedSubBatch(
const right = await embedSubBatch(texts.slice(mid), model, providerOpts, expectedDims, recipe, modelId, opts);
return [...left, ...right];
}
- throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`);
+ reportEmbeddingAuthFailure(recipe, err);
+ throw normalizeAIError(err, `embed(${recipe.id}:${modelId})`, redactKeys);
}
}
@@ -1913,12 +1918,13 @@ export async function embedMultimodal(
}), responseInvocationUsage);
} catch (err) {
if (isAIInvocationPolicyError(err)) throw err;
- throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${parsed.modelId})`);
+ throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${parsed.modelId})`, redactKeys);
}
if (!res.ok) {
- const text = await res.text().catch(() => '');
+ const text = redactKeys(await res.text().catch(() => ''));
if (res.status === 401 || res.status === 403) {
+ reportEmbeddingAuthFailure(recipe, { status: res.status });
throw new AIConfigError(
`Voyage multimodal returned ${res.status}: ${text || 'auth failed'}.`,
`Re-export ${recipe.auth_env?.required[0]} or rotate the key at ${recipe.auth_env?.setup_url}.`,
@@ -2059,12 +2065,13 @@ async function embedMultimodalOpenAICompat(
}), responseInvocationUsage);
} catch (err) {
if (isAIInvocationPolicyError(err)) throw err;
- throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${modelId})`);
+ throw normalizeAIError(err, `embedMultimodal(${recipe.id}:${modelId})`, redactKeys);
}
if (!res.ok) {
- const text = await res.text().catch(() => '');
+ const text = redactKeys(await res.text().catch(() => ''));
if (res.status === 401 || res.status === 403) {
+ reportEmbeddingAuthFailure(recipe, { status: res.status });
const requiredKey = recipe.auth_env?.required[0];
throw new AIConfigError(
`${recipe.name} multimodal returned ${res.status}: ${text || 'auth failed'}.`,
@@ -2531,7 +2538,7 @@ export async function expand(query: string): Promise<string[]> {
} catch (err) {
if (isAIInvocationPolicyError(err)) throw err;
// Expansion is best-effort: on failure, fall back to the original query alone.
- const normalized = normalizeAIError(err, 'expand');
+ const normalized = normalizeAIError(err, 'expand', redactKeys);
if (normalized instanceof AIConfigError) {
console.warn(`[ai.gateway] expansion disabled: ${normalized.message}`);
}
@@ -3690,7 +3697,7 @@ export async function chat(opts: ChatOpts): Promise<ChatResult> {
// Pessimistic fallback (A3 amended): when err.usage isn't there, charge
// the worst-case ceiling — better to overcount on failure than under.
_recordBudget(failedCallUsage(err, { inputTokens: estimatedInputTokens, outputTokens: maxOutputTokens }));
- throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`);
+ throw normalizeAIError(err, `chat(${recipe.id}:${modelId})`, redactKeys);
}
}
diff --git a/src/core/ai/key-redact.ts b/src/core/ai/key-redact.ts
new file mode 100644
index 0000000000..c3e467ee0d
--- /dev/null
+++ b/src/core/ai/key-redact.ts
@@ -0,0 +1,18 @@
+/**
+ * #5137: scrub provider key material from upstream error text before it
+ * reaches the CLI, `--json` or a persisted job error. Providers echo keys in
+ * auth failures, whole or masked (`sk-...****abcd`).
+ */
+import { redactSecretsInText } from '../minions/handlers/shell-redact.ts';
+
+const SECRET_ENV = /(?:_API_KEY|_TOKEN|_SECRET|_PASSWORD)$/;
+
+export function redactProviderKeys(text: string, env: Record<string, string | undefined>): string {
+ if (!text) return text;
+ const secrets = Object.entries(env)
+ .filter((entry): entry is [string, string] => SECRET_ENV.test(entry[0]) && typeof entry[1] === 'string' && entry[1].length >= 8)
+ .sort(([, a], [, b]) => b.length - a.length);
+ return redactSecretsInText(text, secrets)
+ .replace(/[A-Za-z0-9_-]*\*{3,}[A-Za-z0-9_-]*/g, '<REDACTED:masked_key>')
+ .replace(/[A-Za-z0-9_-]{8,}/g, token => secrets.some(([, value]) => value.includes(token)) ? '<REDACTED:key_fragment>' : token);
+}
diff --git a/src/core/ai/key-warnings.ts b/src/core/ai/key-warnings.ts
new file mode 100644
index 0000000000..d7dcab23ae
--- /dev/null
+++ b/src/core/ai/key-warnings.ts
@@ -0,0 +1,100 @@
+/**
+ * #5137: the two key-source messages, each printed at most once per process
+ * through one replaceable sink. Env keeps winning over config keys
+ * (mergedProviderEnv); these only say which key is in effect and how to
+ * change that. Neither prints a key or any part of one.
+ *
+ * - warnShadowedProviderKeys: the CLI startup seam (src/cli.ts, which also
+ * starts `gbrain serve`) calls it for every command except `gbrain hook`.
+ * - reportEmbeddingAuthFailure: the gateway calls it on the first embedding
+ * 401/403, so a revoked key no longer fails silently.
+ */
+import { configPath, loadConfigFileOnly, type GBrainConfig } from '../config.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import type { OperationError } from '../ops/contract.ts';
+import { mergedProviderEnv, providerKeyShadows, providerKeySource, type ProviderKeyShadow } from './provider-env.ts';
+
+type Env = Record<string, string | undefined>;
+const stderrSink = (line: string) => { process.stderr.write(`${line}\n`); };
+let sink: (line: string) => void = stderrSink;
+let shadowsWarned = false;
+let authFailureReported = false;
+
+/** Test seam: capture lines and reset both once-per-process latches. */
+export function _setKeyWarningSinkForTests(next?: (line: string) => void): void {
+ sink = next ?? stderrSink;
+ shadowsWarned = false;
+ authFailureReported = false;
+}
+
+const removeVariable = (variable: string) =>
+ `To use the config key, remove ${variable} from the environment of the process that reported this (shell profile, ~/.gbrain/.env, or for a daemon its service definition) and restart that process.`;
+
+export function keyShadowWarning(shadow: ProviderKeyShadow, file = configPath()): string {
+ return `[gbrain] warning: ${shadow.variable} in this process's environment differs from ${shadow.config_key} in ${file}; the environment value is in effect. `
+ + `${removeVariable(shadow.variable)} If the environment key is intended, run \`gbrain config unset ${shadow.config_key}\`, which also stops this warning.`;
+}
+
+export function warnShadowedProviderKeys(fileCfg: GBrainConfig | null = loadConfigFileOnly(), env: Env = process.env): void {
+ if (shadowsWarned) return;
+ shadowsWarned = true;
+ try {
+ for (const shadow of providerKeyShadows(fileCfg, env)) sink(keyShadowWarning(shadow));
+ } catch { /* an invalid GBRAIN_HOME is reported by the command itself */ }
+}
+
+export interface AuthFailedProvider { id: string; name: string; auth_env?: { required: readonly string[]; optional?: readonly string[] } }
+
+/** The env variable holding a recipe's API key, which need not be required (Azure, LiteLLM) or first. */
+export function credentialEnvName(authEnv: AuthFailedProvider['auth_env']): string | undefined {
+ return [...authEnv?.required ?? [], ...authEnv?.optional ?? []].find(name => /_API_KEY$/.test(name));
+}
+
+/** DX-O8: names the key source in effect and the fixes for it. */
+export function embeddingAuthFailedError(provider: AuthFailedProvider, status: number,
+ fileCfg: GBrainConfig | null = loadConfigFileOnly(), env: Env = process.env, file = configPath()): OperationError {
+ const name = credentialEnvName(provider.auth_env);
+ const rejected = `The ${provider.name} embedding provider rejected its key (HTTP ${status})`;
+ const backfill = 'Then run `gbrain embed --stale` to embed what was saved while the key was rejected.';
+ if (provider.id === 'azure-openai' && mergedProviderEnv(fileCfg, env).AZURE_OPENAI_USE_ENTRA === '1') {
+ return catalogueError('embedding_auth_failed', `${rejected}; Azure Entra mode is on (AZURE_OPENAI_USE_ENTRA), so the rejected credential is the Azure CLI's Entra token, not an API key.`,
+ `Run \`az login\` as an identity with the "Cognitive Services OpenAI User" role on the resource, restart the process that reported this, then run \`gbrain embed --stale\`.`);
+ }
+ if (!name) return catalogueError('embedding_auth_failed', `${rejected}.`, `Check the ${provider.name} credentials, restart the process that reported this, then run \`gbrain embed --stale\`.`);
+ const source = providerKeySource(fileCfg, env, name);
+ if (source.kind === 'config') {
+ return catalogueError('embedding_auth_failed',
+ `${rejected}; the key in effect is ${source.config_key} in ${file} (${source.variable} is not set).`,
+ `Run \`gbrain config set ${source.config_key} <valid key>\` and restart any daemon that uses it. ${backfill}`);
+ }
+ if (source.kind === 'missing') {
+ return catalogueError('embedding_auth_failed', `${rejected}; no API key is set in this process (${source.variable}${source.config_key ? ` or ${source.config_key}` : ''}), so it authenticated another way (an injected gateway environment or a token such as Azure Entra).`,
+ `${source.config_key ? `Run \`gbrain config set ${source.config_key} <valid key>\`` : `Set ${source.variable} to a valid key in the environment of the process that reported this`}, restart that process, then run \`gbrain embed --stale\`.`);
+ }
+ const differs = source.shadows_config && source.config_key ? `, which differs from ${source.config_key} in ${file}` : '';
+ const intended = source.config_key
+ ? `If the environment key is intended, replace it with a valid key, restart, and run \`gbrain config unset ${source.config_key}\`.`
+ : 'Replace it with a valid key and restart that process.';
+ return catalogueError('embedding_auth_failed',
+ `${rejected}; the key in effect is ${source.variable} from this process's environment${differs}.`,
+ `${source.shadows_config ? `${removeVariable(source.variable)} ` : ''}${intended} ${backfill}`);
+}
+
+/** The HTTP status of a provider 401/403, from a fetch status or an SDK error (`statusCode`). */
+function authFailureStatus(err: unknown): number | undefined {
+ const e = err as { status?: unknown; statusCode?: unknown; apiErrorStatus?: unknown } | null;
+ const status = [e?.status, e?.statusCode, e?.apiErrorStatus].find(value => typeof value === 'number');
+ return status === 401 || status === 403 ? status : undefined;
+}
+
+/** Prints embedding_auth_failed for the first embedding 401/403 in this process; anything else is ignored. */
+export function reportEmbeddingAuthFailure(provider: AuthFailedProvider, failure: unknown,
+ fileCfg?: GBrainConfig | null, env?: Env): void {
+ const status = authFailureStatus(failure);
+ if (status === undefined || authFailureReported) return;
+ authFailureReported = true;
+ try {
+ const error = embeddingAuthFailedError(provider, status, fileCfg === undefined ? loadConfigFileOnly() : fileCfg, env ?? process.env);
+ sink(`[gbrain] Error [${error.code}]: ${error.message}\nFix: ${error.suggestion}\nDocs: ${error.docs}`);
+ } catch { /* a diagnostic must never replace the provider error */ }
+}
diff --git a/src/core/ai/provider-env.ts b/src/core/ai/provider-env.ts
index ef68c7630f..7e4f2bdff1 100644
--- a/src/core/ai/provider-env.ts
+++ b/src/core/ai/provider-env.ts
@@ -28,28 +28,49 @@
import type { GBrainConfig } from '../config.ts';
-export function mergedProviderEnv(
- cfg: GBrainConfig | null,
- env: Record<string, string | undefined> = process.env,
-): Record<string, string> {
- const fromConfig: Record<string, string> = {};
- if (cfg?.openai_api_key) fromConfig.OPENAI_API_KEY = cfg.openai_api_key;
- if (cfg?.anthropic_api_key) fromConfig.ANTHROPIC_API_KEY = cfg.anthropic_api_key;
- if (cfg?.openrouter_api_key) fromConfig.OPENROUTER_API_KEY = cfg.openrouter_api_key;
- if (cfg?.voyage_api_key) fromConfig.VOYAGE_API_KEY = cfg.voyage_api_key;
- if (cfg?.dashscope_api_key) fromConfig.DASHSCOPE_API_KEY = cfg.dashscope_api_key;
- if (cfg?.deepseek_api_key) fromConfig.DEEPSEEK_API_KEY = cfg.deepseek_api_key;
+/**
+ * File-plane API keys and the env variable each fills. The GEMINI_API_KEY
+ * alias also fills GOOGLE_GENERATIVE_AI_API_KEY (see mergedProviderEnv).
+ * TypeSafe has no config-plane key: TYPESAFE_API_KEY and its
+ * JEV_TYPESAFE_API_KEY alias are read from the environment only.
+ */
+export const CONFIG_API_KEY_ENV = [
+ ['openai_api_key', 'OPENAI_API_KEY'],
+ ['anthropic_api_key', 'ANTHROPIC_API_KEY'],
+ ['openrouter_api_key', 'OPENROUTER_API_KEY'],
+ ['voyage_api_key', 'VOYAGE_API_KEY'],
+ ['dashscope_api_key', 'DASHSCOPE_API_KEY'],
+ ['deepseek_api_key', 'DEEPSEEK_API_KEY'],
// Same seam for LiteLLM + Together, closed alongside litellm's chat
// touchpoint (v0.42.61.0 made litellm a full chat provider, so the
// config-plane gap started biting daemon/launchd/MCP contexts the same
// way voyage's #2662 did).
- if (cfg?.litellm_api_key) fromConfig.LITELLM_API_KEY = cfg.litellm_api_key;
- if (cfg?.together_api_key) fromConfig.TOGETHER_API_KEY = cfg.together_api_key;
- if (cfg?.google_api_key) fromConfig.GOOGLE_GENERATIVE_AI_API_KEY = cfg.google_api_key;
+ ['litellm_api_key', 'LITELLM_API_KEY'],
+ ['together_api_key', 'TOGETHER_API_KEY'],
+ ['google_api_key', 'GOOGLE_GENERATIVE_AI_API_KEY'],
// #4031: the Azure key was the only member of the group below left unfolded,
// so a config.json-only setup failed every embed from keyless shells
// (launchd/cron/MCP) while `config show` looked complete.
- if (cfg?.azure_openai_api_key) fromConfig.AZURE_OPENAI_API_KEY = cfg.azure_openai_api_key;
+ ['azure_openai_api_key', 'AZURE_OPENAI_API_KEY'],
+] as const satisfies ReadonlyArray<readonly [keyof GBrainConfig, string]>;
+
+const realEnv = (env: Record<string, string | undefined>, name: string): string | undefined =>
+ env[name] === undefined || env[name] === '' ? undefined : env[name];
+
+/** The env variable that supplies `name`'s value: the canonical name, or the GEMINI alias for Google. */
+function suppliedBy(env: Record<string, string | undefined>, name: string): string {
+ return name === 'GOOGLE_GENERATIVE_AI_API_KEY' && !realEnv(env, name) && realEnv(env, 'GEMINI_API_KEY') ? 'GEMINI_API_KEY' : name;
+}
+
+export function mergedProviderEnv(
+ cfg: GBrainConfig | null,
+ env: Record<string, string | undefined> = process.env,
+): Record<string, string> {
+ const fromConfig: Record<string, string> = {};
+ for (const [configKey, name] of CONFIG_API_KEY_ENV) {
+ const value = cfg?.[configKey];
+ if (value) fromConfig[name] = value;
+ }
if (cfg?.azure_openai_endpoint) fromConfig.AZURE_OPENAI_ENDPOINT = cfg.azure_openai_endpoint;
if (cfg?.azure_openai_deployment) fromConfig.AZURE_OPENAI_DEPLOYMENT = cfg.azure_openai_deployment;
if (cfg?.azure_openai_use_entra) fromConfig.AZURE_OPENAI_USE_ENTRA = cfg.azure_openai_use_entra;
@@ -63,3 +84,49 @@ export function mergedProviderEnv(
}
return merged;
}
+
+/** #5137: an env variable whose real value shadows a different config-plane key. Names only, never values. */
+export interface ProviderKeyShadow {
+ variable: string;
+ config_key: string;
+}
+
+/**
+ * #5137: every config-plane key that an environment value overrides with a
+ * different value (env wins, as in mergedProviderEnv). Pure. `fileCfg` must be
+ * the file-only config (`loadConfigFileOnly`): `loadConfig` already folds
+ * OPENAI/ANTHROPIC/OPENROUTER env values into the config fields.
+ */
+export function providerKeyShadows(
+ fileCfg: GBrainConfig | null,
+ env: Record<string, string | undefined> = process.env,
+): ProviderKeyShadow[] {
+ const shadows: ProviderKeyShadow[] = [];
+ for (const [configKey, name] of CONFIG_API_KEY_ENV) {
+ const fromConfig = fileCfg?.[configKey];
+ const variable = suppliedBy(env, name);
+ const fromEnv = realEnv(env, variable);
+ if (fromConfig && fromEnv && fromEnv !== fromConfig) shadows.push({ variable, config_key: configKey });
+ }
+ return shadows;
+}
+
+/** #5137: where the key a recipe reads from `name` comes from, by name only. */
+export type ProviderKeySource =
+ | { kind: 'env'; variable: string; config_key?: string; shadows_config: boolean }
+ | { kind: 'config'; variable: string; config_key: string }
+ | { kind: 'missing'; variable: string; config_key?: string };
+
+export function providerKeySource(
+ fileCfg: GBrainConfig | null,
+ env: Record<string, string | undefined>,
+ name: string,
+): ProviderKeySource {
+ const configKey = CONFIG_API_KEY_ENV.find(([, envName]) => envName === name)?.[0];
+ const variable = suppliedBy(env, name);
+ const fromEnv = realEnv(env, variable);
+ const fromConfig = configKey ? fileCfg?.[configKey] : undefined;
+ if (fromEnv) return { kind: 'env', variable, ...(configKey ? { config_key: configKey } : {}), shadows_config: !!fromConfig && fromConfig !== fromEnv };
+ if (configKey && fromConfig) return { kind: 'config', variable, config_key: configKey };
+ return { kind: 'missing', variable, ...(configKey ? { config_key: configKey } : {}) };
+}
diff --git a/src/core/ai/recipes/anthropic.ts b/src/core/ai/recipes/anthropic.ts
index 44c8af3cd8..a812b56aa2 100644
--- a/src/core/ai/recipes/anthropic.ts
+++ b/src/core/ai/recipes/anthropic.ts
@@ -25,6 +25,7 @@ export const anthropic: Recipe = {
models: [
'claude-fable-5',
'claude-fable-5-1',
+ 'claude-opus-5-5',
'claude-opus-5',
'claude-opus-4-8',
'claude-opus-4-7',
@@ -38,6 +39,7 @@ export const anthropic: Recipe = {
model_context_tokens: {
'claude-fable-5': 1_000_000,
'claude-fable-5-1': 1_000_000,
+ 'claude-opus-5-5': 1_000_000,
'claude-opus-5': 1_000_000,
'claude-sonnet-5': 1_000_000,
'claude-opus-4-8': 1_000_000,
diff --git a/src/core/ai/recipes/claude-cli.ts b/src/core/ai/recipes/claude-cli.ts
index 68bfbdcb1d..4526aa8850 100644
--- a/src/core/ai/recipes/claude-cli.ts
+++ b/src/core/ai/recipes/claude-cli.ts
@@ -55,6 +55,7 @@ export const claudeCli: Recipe = {
'claude-haiku-4-5-20251001',
'claude-fable-5',
'claude-fable-5-1',
+ 'claude-opus-5-5',
'claude-opus-5',
'claude-opus-4-8',
'claude-opus-4-7',
@@ -74,6 +75,7 @@ export const claudeCli: Recipe = {
models: [
'claude-fable-5',
'claude-fable-5-1',
+ 'claude-opus-5-5',
'claude-opus-5',
'claude-opus-4-8',
'claude-opus-4-7',
diff --git a/src/core/autopilot-paths.ts b/src/core/autopilot-paths.ts
index 035d90c635..9e8890f1eb 100644
--- a/src/core/autopilot-paths.ts
+++ b/src/core/autopilot-paths.ts
@@ -20,9 +20,11 @@
* because that is where the daemon itself writes; a `GBRAIN_HOME` install
* otherwise has readers looking in a different directory than the writer.
*/
-import { existsSync, readFileSync } from 'fs';
-import { join } from 'path';
-import { gbrainPath } from './config.ts';
+import { existsSync, linkSync, mkdirSync, readFileSync, realpathSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'fs';
+import { homedir } from 'os';
+import { dirname, join, resolve } from 'path';
+import { randomBytes } from 'crypto';
+import { configDir, gbrainPath } from './config.ts';
/**
* The daemon's lock file. Its mtime IS the liveness heartbeat — the tick loop
@@ -42,29 +44,236 @@ export function autopilotDisabledMarkerPath(): string {
return join(gbrainPath(), 'autopilot-disabled');
}
+/** The pre-#5195 shared job names, still used by the default brain. */
+export const DEFAULT_AUTOPILOT_LAUNCHD_LABEL = 'com.gbrain.autopilot';
+export const DEFAULT_AUTOPILOT_SYSTEMD_UNIT = 'gbrain-autopilot.service';
+
/**
- * The launchd job label / plist basename (systemd keeps its own unit name).
+ * The launchd job label / plist basename. `suffix` names a non-default brain's
+ * own job (#5195); the default brain keeps the shared label.
*
* The env override is a TEST SEAM, not a user knob: it exists so the real-launchd
* lifecycle e2e can load a genuinely unique job on a dev Mac without colliding
* with — or tearing down — the machine's actual autopilot install. It is read at
- * CALL time, so every invocation touching the same install (install, status,
- * uninstall, the generated wrapper's self-disable) must run with the same value;
- * a mismatched pair reports a false not-installed or misses the plist.
+ * CALL time and wins over the per-brain suffix, so every invocation touching the
+ * same install (install, status, uninstall, the generated wrapper's self-disable)
+ * must run with the same value; a mismatched pair reports a false not-installed
+ * or misses the plist.
*
* The grammar check is load-bearing: the label reaches a plist FILENAME and a
* double-quoted shell line inside the generated wrapper. `escapeXml` protects
* only the XML site, so slashes, quotes, whitespace, `$`, backticks, and
* dot-dot must be rejected here.
*/
-export function autopilotLaunchdLabel(): string {
- const label = process.env.GBRAIN_AUTOPILOT_LABEL ?? 'com.gbrain.autopilot';
+export function autopilotLaunchdLabel(suffix: string | null = null): string {
+ const label = process.env.GBRAIN_AUTOPILOT_LABEL
+ ?? (suffix ? `${DEFAULT_AUTOPILOT_LAUNCHD_LABEL}.${suffix}` : DEFAULT_AUTOPILOT_LAUNCHD_LABEL);
if (!/^[A-Za-z0-9._-]+$/.test(label) || label.includes('..')) {
throw new Error(`invalid GBRAIN_AUTOPILOT_LABEL: ${JSON.stringify(label)}`);
}
return label;
}
+/** realpath, or `resolve` for a directory that does not exist yet (ENG-O11). */
+export function canonicalDir(path: string): string {
+ // nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- canonicalizes the operator's own brain home for the install-id record; no fs write
+ try { return realpathSync(path); } catch { return resolve(path); }
+}
+
+/**
+ * #5195: the default brain is the one at `~/.gbrain` (GBRAIN_HOME unset, or
+ * pointing at the user's home). It keeps the shared job names so existing
+ * installs need no migration; every other brain gets its own job.
+ */
+export function isDefaultBrainHome(): boolean {
+ return canonicalDir(configDir()) === canonicalDir(join(homedir(), '.gbrain'));
+}
+
+/** Where a non-default brain records the random id its job names derive from. */
+export function autopilotInstallIdPath(): string {
+ return gbrainPath('autopilot-install-id');
+}
+
+interface InstallIdRecord { id: string; realpath: string; created_at: string }
+
+function readInstallIdRecord(): InstallIdRecord | null {
+ try {
+ const rec = JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8')) as Partial<InstallIdRecord>;
+ if (typeof rec.id !== 'string' || !/^[0-9a-f]{8,64}$/.test(rec.id)) return null;
+ if (typeof rec.realpath !== 'string' || !rec.realpath) return null;
+ return { id: rec.id, realpath: rec.realpath, created_at: typeof rec.created_at === 'string' ? rec.created_at : '' };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Read-only view of this brain's install id (T4, ENG-O11). The record names the
+ * directory it was written for, because a copied brain carries the file along:
+ * - same — recorded for this directory;
+ * - moved — the recorded directory no longer exists, so this brain is it,
+ * moved or renamed (the id, and the job, carry over);
+ * - copied — the recorded directory still exists elsewhere, so this is a
+ * copy that has not installed its own job yet;
+ * - none — never installed.
+ */
+export function resolveAutopilotInstallId():
+ | { relation: 'same' | 'moved'; id: string; recordedPath: string }
+ | { relation: 'copied' | 'none'; id: null; recordedPath: string | null } {
+ const rec = readInstallIdRecord();
+ if (!rec) return { relation: 'none', id: null, recordedPath: null };
+ if (rec.realpath === canonicalDir(configDir())) return { relation: 'same', id: rec.id, recordedPath: rec.realpath };
+ if (!existsSync(rec.realpath)) return { relation: 'moved', id: rec.id, recordedPath: rec.realpath };
+ return { relation: 'copied', id: null, recordedPath: rec.realpath };
+}
+
+function writeRecordExclusive(path: string, rec: InstallIdRecord): boolean {
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
+ writeFileSync(tmp, JSON.stringify(rec) + '\n', { mode: 0o644 });
+ try {
+ linkSync(tmp, path);
+ return true;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'EEXIST') return false;
+ try {
+ writeFileSync(path, JSON.stringify(rec) + '\n', { flag: 'wx', mode: 0o644 });
+ return true;
+ } catch (e2) {
+ if ((e2 as NodeJS.ErrnoException).code === 'EEXIST') return false;
+ throw e2;
+ }
+ } finally {
+ try { unlinkSync(tmp); } catch { /* already gone */ }
+ }
+}
+
+function replaceRecord(path: string, rec: InstallIdRecord): void {
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
+ writeFileSync(tmp, JSON.stringify(rec) + '\n', { mode: 0o644 });
+ renameSync(tmp, path);
+}
+
+/**
+ * One installer at a time decides a move or a copy: without it two installers
+ * of a freshly copied brain could each mint an id, and the one whose record
+ * lost would leave a job nobody can find. A crashed holder's lock is broken
+ * after 30 seconds.
+ */
+function withInstallIdLock<T>(fn: () => T): T {
+ const lock = `${autopilotInstallIdPath()}.lock`;
+ const deadline = Date.now() + 10_000;
+ for (;;) {
+ try {
+ mkdirSync(lock);
+ break;
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'EEXIST') throw e;
+ try { if (Date.now() - statSync(lock).mtimeMs > 30_000) { rmdirSync(lock); continue; } } catch { continue; }
+ if (Date.now() > deadline) throw new Error(`another autopilot install holds ${lock}; retry when it finishes`);
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25);
+ }
+ }
+ try { return fn(); } finally { try { rmdirSync(lock); } catch { /* already gone */ } }
+}
+
+/**
+ * The install id for this brain, minting or re-homing it as ENG-O11 describes.
+ * The first record is created exclusively, so concurrent first installs agree on
+ * one id; a move keeps the id and records the new directory; a copy mints its
+ * own id so the original brain's job is never taken over. Moves and copies are
+ * decided under a lock, so concurrent installers settle on one id.
+ */
+export function ensureAutopilotInstallId(): string {
+ mkdirSync(configDir(), { recursive: true });
+ const path = autopilotInstallIdPath();
+ const here = canonicalDir(configDir());
+ const current = resolveAutopilotInstallId();
+ if (current.relation === 'same') return current.id;
+ if (current.relation === 'none') {
+ const fresh = { id: randomBytes(16).toString('hex'), realpath: here, created_at: new Date().toISOString() };
+ if (writeRecordExclusive(path, fresh)) return fresh.id;
+ }
+ return withInstallIdLock(() => {
+ const locked = resolveAutopilotInstallId();
+ if (locked.relation === 'same') return locked.id;
+ if (locked.relation === 'moved') {
+ replaceRecord(path, { id: locked.id, realpath: here, created_at: readInstallIdRecord()?.created_at || new Date().toISOString() });
+ return locked.id;
+ }
+ const fresh = { id: randomBytes(16).toString('hex'), realpath: here, created_at: new Date().toISOString() };
+ replaceRecord(path, fresh);
+ return fresh.id;
+ });
+}
+
+/**
+ * Every name one brain's autopilot job uses (#5195). The default brain keeps the
+ * shared pre-#5195 names; any other brain gets `<name>-<suffix>` names, where the
+ * suffix is the first 8 hex characters of its install id. `unassigned` is a
+ * non-default brain that has no id yet (never installed, or an uninstalled
+ * copy): it owns no named job, and its names are the shared ones only so the
+ * pure generators have something to print.
+ */
+export interface AutopilotJob {
+ kind: 'default' | 'suffixed' | 'unassigned';
+ suffix: string | null;
+ launchdLabel: string;
+ systemdUnit: string;
+ /** Ephemeral-container start script, under the brain's own home. */
+ startScriptPath: string;
+ /** Trailing crontab comment that marks this brain's line; null for the default brain. */
+ cronMarker: string | null;
+ wrapperPath: string;
+ logPath: string;
+ errPath: string;
+ installIdPath: string | null;
+ /** configDir() at resolution time. */
+ homeDir: string;
+}
+
+export function resolveAutopilotJob(opts: { mint?: boolean } = {}): AutopilotJob {
+ const homeDir = configDir();
+ let kind: AutopilotJob['kind'] = 'default';
+ let suffix: string | null = null;
+ if (!isDefaultBrainHome()) {
+ const id = opts.mint ? ensureAutopilotInstallId() : resolveAutopilotInstallId().id;
+ suffix = id ? id.slice(0, 8) : null;
+ kind = suffix ? 'suffixed' : 'unassigned';
+ }
+ return {
+ kind,
+ suffix,
+ launchdLabel: autopilotLaunchdLabel(suffix),
+ systemdUnit: suffix ? `gbrain-autopilot-${suffix}.service` : DEFAULT_AUTOPILOT_SYSTEMD_UNIT,
+ startScriptPath: join(homeDir, suffix ? `start-autopilot-${suffix}.sh` : 'start-autopilot.sh'),
+ cronMarker: suffix ? `# gbrain-autopilot:${suffix}` : null,
+ wrapperPath: join(homeDir, 'autopilot-run.sh'),
+ logPath: join(homeDir, 'autopilot.log'),
+ errPath: join(homeDir, 'autopilot.err'),
+ installIdPath: kind === 'default' ? null : autopilotInstallIdPath(),
+ homeDir,
+ };
+}
+
+/**
+ * Who a job definition belongs to, judged by the wrapper path it runs (the
+ * wrapper always lives at `<brain home>/autopilot-run.sh`):
+ * - own — this brain's wrapper;
+ * - dangling — a wrapper that no longer exists (a moved or deleted brain);
+ * - other — a live wrapper of another brain (`home` is that brain's dir);
+ * - unknown — the definition names no wrapper.
+ */
+export function autopilotWrapperOwner(
+ wrapperPath: string | null,
+ homeDir: string = configDir(),
+): { owner: 'own' | 'dangling' | 'unknown' } | { owner: 'other'; home: string } {
+ if (!wrapperPath) return { owner: 'unknown' };
+ const dir = dirname(wrapperPath);
+ if (canonicalDir(dir) === canonicalDir(homeDir)) return { owner: 'own' };
+ if (!existsSync(wrapperPath)) return { owner: 'dangling' };
+ return { owner: 'other', home: dir };
+}
+
/**
* Cooperative pause. While present the tick loop keeps heartbeating but does no
* work. `gbrain migrate` uses it to quiesce the daemon for the
diff --git a/src/core/backup/repository.ts b/src/core/backup/repository.ts
index eba98a51ca..2b71c7978f 100644
--- a/src/core/backup/repository.ts
+++ b/src/core/backup/repository.ts
@@ -1,7 +1,7 @@
import { execFile, execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { existsSync, realpathSync, statSync } from 'node:fs';
-import { GIT_ENV } from '../git-remote.ts';
+import { buildGitEnv } from '../git-remote.ts';
import { pushStatusPathForRoot, readPushStatusForRoot } from '../workspace-push.ts';
import { readManifest } from '../bootstrap/format.ts';
import { BACKUP_VERIFICATION_MAX_AGE_MS, type BackupAssetVerdict } from './status-file.ts';
@@ -12,10 +12,29 @@ export const BACKUP_REMOTE_TIMEOUT_MS = 2_000;
export interface RemoteProbeBudget { remaining: number; deadline?: number }
+/** Variables that locate the user's own git config, credentials and network path. */
+export const BACKUP_GIT_ENV_ALLOWLIST = ['HOME', 'PATH', 'XDG_CONFIG_HOME', 'SSH_AUTH_SOCK', 'GIT_CONFIG_GLOBAL',
+ 'HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'NO_PROXY', 'no_proxy'] as const;
+export const BACKUP_GIT_ENV_WINDOWS_ALLOWLIST = ['USERPROFILE', 'APPDATA', 'SystemRoot'] as const;
+
+/**
+ * The probe env passes only the allowlist, so git reads the user's config and
+ * credential helpers (#5794) but never a repository-redirecting variable such
+ * as GIT_DIR or GIT_WORK_TREE; the no-prompt overrides always win.
+ */
+export function backupGitEnv(source: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const key of [...BACKUP_GIT_ENV_ALLOWLIST, ...(platform === 'win32' ? BACKUP_GIT_ENV_WINDOWS_ALLOWLIST : [])]) {
+ const value = source[key];
+ if (value !== undefined) env[key] = value;
+ }
+ return { ...env, ...buildGitEnv(platform) };
+}
+
function git(root: string, args: string[]): string {
return execFileSync('git', ['-C', root, ...args], {
encoding: 'utf8', timeout: 2_000, maxBuffer: 1024 * 1024,
- stdio: ['ignore', 'pipe', 'pipe'], env: GIT_ENV,
+ stdio: ['ignore', 'pipe', 'pipe'], env: backupGitEnv(),
}).trim();
}
@@ -99,7 +118,7 @@ export async function assessBackupRepository(
'-c', 'protocol.https.allow=always', '-c', 'protocol.http.allow=always', '-c', 'protocol.ssh.allow=always',
'-c', 'http.followRedirects=false', '-c', 'credential.interactive=false', 'ls-remote', '--exit-code', '--refs', 'origin', ref], {
encoding: 'utf8', timeout: Math.min(BACKUP_REMOTE_TIMEOUT_MS, remainingMs), maxBuffer: 64 * 1024,
- env: { ...GIT_ENV, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', SSH_ASKPASS_REQUIRE: 'never', GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=2' },
+ env: { ...backupGitEnv(), GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', SSH_ASKPASS_REQUIRE: 'never', GIT_SSH_COMMAND: 'ssh -oBatchMode=yes -oStrictHostKeyChecking=yes -oConnectTimeout=2' },
}, (error, stdout) => error ? reject(error) : resolve(stdout));
}).catch(error => {
asset.verification = { state: error.code === 2 ? 'missing_ref' : 'unavailable', checked_at: now.toISOString(), repository_fingerprint: fingerprint };
diff --git a/src/core/brain-writer.ts b/src/core/brain-writer.ts
index 86b9aed01f..0ed94705df 100644
--- a/src/core/brain-writer.ts
+++ b/src/core/brain-writer.ts
@@ -126,6 +126,9 @@ export function createFrontmatterBackup(filePath: string, opts: FrontmatterBacku
* - MISSING_CLOSE — insert `---` before the first heading found inside
* the YAML zone
* - SLUG_MISMATCH — remove `slug:` line (gbrain derives slug from path)
+ * when `opts.filePath` is given. It must be the path
+ * the slug derives from (relative to the brain or
+ * source root, #5053), never an absolute path.
*
* Idempotent: running twice is a no-op on already-clean input. Any error class
* not in the list above is left untouched (e.g. EMPTY_FRONTMATTER, YAML_PARSE,
@@ -374,7 +377,7 @@ export function writeBrainPage(
let toWrite = content;
let fixes: AuditFix[] = [];
if (opts.autoFix) {
- const result = autoFixFrontmatter(content, { filePath });
+ const result = autoFixFrontmatter(content, { filePath: relative(resolvedSource, resolvedTarget) });
toWrite = result.content;
fixes = result.fixes;
}
diff --git a/src/core/brainstorm/judges.ts b/src/core/brainstorm/judges.ts
index 3c50c99d42..37dafb4d8d 100644
--- a/src/core/brainstorm/judges.ts
+++ b/src/core/brainstorm/judges.ts
@@ -63,6 +63,7 @@ export const MAX_OUTPUT_TOKENS_CEIL = 32_000;
export const ANTHROPIC_OUTPUT_CAPS: Record<string, number> = {
'claude-fable-5': 64_000,
'claude-fable-5-1': 64_000,
+ 'claude-opus-5-5': 32_000,
'claude-opus-5': 32_000,
'claude-sonnet-5': 64_000,
'claude-opus-4-8': 32_000,
diff --git a/src/core/calibration/voice-gate.ts b/src/core/calibration/voice-gate.ts
index d9dd38bbab..c1d588da57 100644
--- a/src/core/calibration/voice-gate.ts
+++ b/src/core/calibration/voice-gate.ts
@@ -27,7 +27,7 @@
import { chat as gatewayChat } from '../ai/gateway.ts';
import type { VoiceGateMode } from './templates.ts';
-import { TIER_DEFAULTS } from '../model-config.ts';
+import { resolveTierDefault } from '../model-config.ts';
/**
* Verdict the Haiku judge returns for a candidate string. Pass-through
@@ -160,7 +160,9 @@ export async function defaultJudge(input: {
.replace('{CANDIDATE}', input.candidate);
const result = await gatewayChat({
messages: [{ role: 'user', content: prompt }],
- model: TIER_DEFAULTS.utility,
+ // #5165: the key-aware utility tier, not the Anthropic floor, so an
+ // install without Anthropic credit judges with a provider it has.
+ model: resolveTierDefault('utility'),
maxTokens: 100,
});
return parseJudgeOutput(result.text);
diff --git a/src/core/chunkers/code.ts b/src/core/chunkers/code.ts
index 6a80b359a6..7bda4e454c 100644
--- a/src/core/chunkers/code.ts
+++ b/src/core/chunkers/code.ts
@@ -20,7 +20,7 @@
import { chunkText as recursiveChunk } from './recursive.ts';
import { buildQualifiedName } from './qualified-names.ts';
-import { MERGE_PROTECTED_SYMBOL_TYPES } from './def-types.ts';
+import { MERGE_PROTECTED_SYMBOL_TYPES, declaresFunctionValue } from './def-types.ts';
import { estimateTokens, estimateEmbedTokens, estimateEmbedTokensCeiling, DEFAULT_MAX_CHUNK_TOKENS } from './token-estimate.ts';
import { safeSplitIndex } from '../text-safe.ts';
import {
@@ -140,7 +140,8 @@ import G_ZIG from '../../assets/wasm/grammars/tree-sitter-zig.wasm' with { type:
// top-level defs indexed to ZERO symbols). Chunk boundaries change for every
// previously-merged file, so the bump forces a re-chunk that recovers the
// erased symbols.
-export const CHUNKER_VERSION = 7;
+// v8 (N13-1): `const f = () => …` definitions keep their own named chunk.
+export const CHUNKER_VERSION = 8;
// Lazy-loaded tree-sitter module (v0.22.x API: Parser is default export)
let Parser: typeof import('web-tree-sitter') | null = null;
@@ -184,6 +185,8 @@ export interface CodeChunkMetadata {
* Null when symbolName is missing (merged chunks, module-level fallback).
*/
symbolNameQualified?: string | null;
+ /** N13-1: a const/let/var whose value is a function — merge-protected (def-types.ts). */
+ definesFunction?: boolean;
}
export interface CodeChunk {
@@ -835,13 +838,15 @@ async function chunkParsedLanguage(
}
if (estimateTokens(nodeText) <= largeThreshold) {
- chunks.push(buildChunk({
+ const chunk = buildChunk({
body: nodeText, filePath, language, symbolName, symbolType,
startLine: node.startPosition.row + 1,
endLine: endNode.endPosition.row + 1,
index: chunks.length,
parentSymbolPath: [],
- }));
+ });
+ if (declaresFunctionValue(typeNode)) chunk.metadata.definesFunction = true;
+ chunks.push(chunk);
continue;
}
@@ -947,7 +952,8 @@ function mergeSmallSiblings(chunks: CodeChunk[], chunkTarget: number): CodeChunk
// accumulated into one. The set is a derived view of code-def's DEF_TYPES
// (def-types.ts), so the lookup allowlist and this guard cannot drift.
const isDefChunk = (c: CodeChunk): boolean =>
- c.metadata.symbolName != null && MERGE_PROTECTED_SYMBOL_TYPES.has(c.metadata.symbolType);
+ c.metadata.symbolName != null &&
+ (MERGE_PROTECTED_SYMBOL_TYPES.has(c.metadata.symbolType) || c.metadata.definesFunction === true);
const merged: CodeChunk[] = [];
let i = 0;
while (i < chunks.length) {
diff --git a/src/core/chunkers/def-types.ts b/src/core/chunkers/def-types.ts
index fbf3254405..028a71ce2f 100644
--- a/src/core/chunkers/def-types.ts
+++ b/src/core/chunkers/def-types.ts
@@ -78,3 +78,20 @@ export const MERGE_PROTECTED_SYMBOL_TYPES: ReadonlySet<string> = new Set([
'export statement',
'decorated definition',
]);
+
+const FUNCTION_VALUE_TYPES = new Set(['arrow_function', 'function_expression', 'function', 'generator_function']);
+
+/**
+ * gbrain-evals N13-1: a TS/JS `lexical_declaration` / `variable_declaration`
+ * whose declarator value is a function (`const f = () => …`, `let g =
+ * function () {…}`) is a named function definition wearing a mergeable run
+ * type. The chunker stamps it `definesFunction` so mergeSmallSiblings keeps
+ * it (and its symbol_name, which code-def resolves) on its own chunk, while
+ * plain const/let value runs still merge. Takes a tree-sitter node.
+ */
+export function declaresFunctionValue(node: any): boolean {
+ if (node.type !== 'lexical_declaration' && node.type !== 'variable_declaration') return false;
+ return node.namedChildren.some(
+ (child: any) => child.type === 'variable_declarator' && FUNCTION_VALUE_TYPES.has(child.childForFieldName('value')?.type),
+ );
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index e23f26d2ea..2431787672 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -23,13 +23,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
'backup': ['--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--mode', '--output', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout'],
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
- 'book-mirror': ['--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'book-mirror': ['--access', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--exit-code', '--file', '--force', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-ancestor', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-tags', '--no-verify', '--no-write-fetch-head', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skills', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
- 'calibration': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
+ 'calibration': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--federated-read', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
'call': ['--brain', '--help', '--json', '--source'],
- 'capture': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],
+ 'capture': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--request-id', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--timeout', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],
'check-backlinks': ['--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
'check-update': ['--brain', '--ff-only', '--force-retry', '--help', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--non-interactive', '--refresh-cache', '--remediation-plan', '--source', '--swap-only', '--version', '--yes'],
@@ -40,18 +40,18 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--source'],
'compile-context': ['--brain', '--budget', '--check', '--help', '--include', '--json', '--out', '--source', '--stdout', '--target'],
'config': ['--admin-intent', '--all', '--all-from', '--background', '--brain', '--call-site', '--coverage-override', '--dataset', '--db-url', '--egress', '--embedding-dimensions', '--embedding-model', '--expected-state', '--explain', '--follow', '--force', '--from', '--help', '--input', '--json', '--limit', '--markdown', '--min', '--out', '--path', '--pattern', '--pglite', '--progress-interval', '--progress-json', '--provider', '--query', '--quiet', '--raw', '--recommended', '--session', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--timeout', '--to', '--url', '--what-if-threshold', '--yes'],
- 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
+ 'connect': ['--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--public-url', '--pure', '--register', '--remove', '--root', '--scope', '--scopes', '--show-token', '--source', '--status', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--yes'],
'connectors': ['--all', '--background', '--brain', '--cookie', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--limit', '--no-browser', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--token', '--try-oauth', '--window-days'],
'conversation-parser': ['--brain', '--help', '--json', '--source'],
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],
'db-repair': ['--apply', '--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],
- 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
+ 'doctor': ['--abbrev-ref', '--abort', '--admin-intent', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--older-than', '--once', '--others', '--out', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--recommended', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
'embed': ['--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--yes'],
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
- 'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
+ 'enrich': ['--access', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--federated-read', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--with-code-intel', '--yes'],
'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],
'extract': ['--admin-intent', '--after-slug', '--apply-preview', '--background', '--backup-verified', '--brain', '--break-lock', '--by-mention', '--catch-up', '--checkpoint', '--concurrency', '--confirm', '--db-url', '--dir', '--dry-run', '--expected-epoch', '--expected-state', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--limit', '--manifest', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--prune-orphans', '--quiet', '--rebuild', '--repair-attendance', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
@@ -69,26 +69,27 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--content-root', '--db-only', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--quiet', '--schema-pack', '--scopes', '--show-toplevel', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
- 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
+ 'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--federated-read', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--images', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--pause', '--phase', '--pid-file', '--priority', '--prune-orphans', '--queue', '--quiet', '--reason', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--reset-checkpoint', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--select', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--vectors', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
'lint': ['--abbrev-ref', '--abort', '--all', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--exit-code', '--explain', '--file', '--fix', '--follow', '--get', '--get-url', '--git-dir', '--git-path', '--help', '--is-ancestor', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-tags', '--no-verify', '--no-write-fetch-head', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
- 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
+ 'maintain': ['--all', '--apply', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--expect', '--explain', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--no-embed', '--no-pull', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--preview', '--probe-pglite', '--prune-orphans', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--request-id', '--reset', '--resume', '--retry-failed', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
'mcp': ['--admin-token-file', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],
'migrate': ['--all', '--apply', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--force-retry', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--max-cost-usd', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--status'],
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],
- 'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'onboard': ['--access', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],
'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--vectors', '--yes'],
'post-upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
- 'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'projections': ['--brain', '--enable-dcr', '--help', '--http', '--install', '--json', '--limit', '--now', '--port', '--public-url', '--remove', '--source', '--status', '--surface', '--user'],
+ 'protocol': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],
- 'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-id', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
+ 'recall': ['--access', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--follow', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--request-id', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--source-id', '--stats', '--supersessions', '--surface', '--timeout', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--workers', '--yes'],
'reindex-code': ['--background', '--brain', '--break-lock', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--path', '--progress-interval', '--progress-json', '--quiet', '--source', '--status', '--timeout', '--workers', '--yes'],
@@ -96,7 +97,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'reindex-search-vector': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--yes'],
'reinit-pglite': ['--abbrev-ref', '--all', '--allow-create-db', '--allow-docker', '--allow-empty', '--brain', '--break-lock', '--cached', '--chat-model', '--concurrency', '--confirm-destructive', '--content-root', '--db-only', '--diff-filter', '--embedding-dimensions', '--embedding-model', '--empty', '--entity', '--exclude', '--exclude-standard', '--expansion-model', '--filters', '--fix', '--force', '--force-break-lock', '--format', '--full', '--full-history', '--git', '--grant-types', '--hard-deadline', '--help', '--http', '--include-gitignored', '--include-hidden', '--interval', '--is-ancestor', '--is-shallow-repository', '--issuer-url', '--json', '--key', '--local-postgres', '--max-age', '--max-sources', '--mcp-only', '--mcp-url', '--migrate-only', '--missing-path', '--model', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-git', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-sync', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--others', '--parallel', '--path', '--pglite', '--prefer-postgres', '--priority', '--provenance', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--schema-pack', '--scopes', '--serial', '--show-toplevel', '--skip-embed-check', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--supabase', '--surface', '--timeout', '--to', '--url', '--verify', '--version', '--watch', '--workers', '--working-tree', '--yes'],
'remote': ['--brain', '--help', '--json', '--mcp-only', '--scopes', '--source', '--timeout'],
- 'repair': ['--all', '--apply', '--brain', '--help', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
+ 'repair': ['--all', '--apply', '--brain', '--expect', '--help', '--include-ambiguous', '--include-repairs', '--json', '--limit', '--max-cost', '--max-usd', '--no-embed', '--remediate', '--source', '--stale', '--yes'],
'repair-jsonb': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--supabase', '--timeout', '--url'],
'report': ['--brain', '--content', '--dir', '--help', '--json', '--source', '--title', '--type'],
'repos': ['--abbrev-ref', '--abort', '--access', '--account', '--admin-intent', '--after', '--all', '--allow-unverified-remote', '--allowed-operations', '--app-id', '--app-install', '--app-pem', '--apply', '--audit', '--backups', '--before', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--budget-usd-per-day', '--cached', '--calendar-id', '--cleanup-dead-local-locks', '--clear', '--clone-dir', '--confirm-destructive', '--confirm-quiesced', '--count', '--days', '--decisions', '--delegated-namespace', '--delegated-slug-prefixes', '--detect', '--diff-filter', '--dir', '--dry-run', '--exclude', '--exclude-standard', '--exit-code', '--expected-epoch', '--expected-incarnation', '--expected-state', '--federated', '--federated-read', '--file', '--fix', '--force', '--format', '--from', '--get', '--get-url', '--git-dir', '--git-path', '--github-repo', '--grant-types', '--help', '--history-days', '--http', '--id', '--include', '--include-warns', '--is-ancestor', '--is-inside-work-tree', '--json', '--keep-storage', '--kind', '--limit', '--local', '--manifest', '--max-cost-usd', '--message', '--name', '--name-only', '--no-cron', '--no-embed', '--no-federate', '--no-federated', '--no-harden', '--no-pull', '--no-tags', '--no-verify', '--no-write-fetch-head', '--others', '--out', '--params', '--pat-file', '--path', '--plan', '--preview', '--probe', '--profile', '--push', '--push-only', '--quiet', '--rebase', '--redirect-uri', '--remove-backup', '--repair', '--replace', '--repos', '--request-id', '--reset-checkpoint', '--retry-failed', '--scope', '--scopes', '--secret', '--self-transfer', '--services', '--set', '--shared-skills', '--short', '--show-toplevel', '--slug-prefixes', '--source', '--source-id', '--source-ids', '--stale', '--status', '--surface', '--takes-holders', '--token', '--token-command', '--token-endpoint-auth-method', '--token-env', '--token-ttl', '--unset-all', '--url', '--usage', '--yes'],
@@ -116,12 +117,12 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--reset-checkpoint', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
- 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--images', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
+ 'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--expect', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--preview', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--prune-orphans', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],
'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
'upgrade': ['--acknowledge-no-backup', '--admin-intent', '--all', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--check', '--concurrency', '--confirm-quiesced', '--content-root', '--cost-estimate', '--embedding-dimensions', '--embedding-model', '--expected-epoch', '--expected-state', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--path', '--pause', '--quiet', '--reason', '--remediation-plan', '--repo', '--require-db', '--resume', '--self-transfer', '--skills-dir', '--skip-verify', '--source', '--status', '--swap-only', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
- 'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
+ 'whoknows': ['--access', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--federated-read', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
};
diff --git a/src/core/code-intel/recursive-walk.ts b/src/core/code-intel/recursive-walk.ts
index e13fb901a8..8509b1e49c 100644
--- a/src/core/code-intel/recursive-walk.ts
+++ b/src/core/code-intel/recursive-walk.ts
@@ -120,30 +120,45 @@ async function disambiguateSymbol(
}
/**
- * Detect the language of a qualified symbol by looking at the owning
- * chunk's language. Returns null when not found.
+ * Languages of every chunk defining a qualified symbol. A bare name can be
+ * defined in several files and languages at once (gbrain-evals N13-3: a Go
+ * and a Python `shared_helper` share the qualified name), so the gate must
+ * see all of them, not one arbitrary row.
*/
-async function detectSymbolLanguage(
+async function symbolLanguages(
engine: BrainEngine,
qualified: string,
sourceId: string,
-): Promise<string | null> {
+): Promise<string[]> {
try {
const rows = await engine.executeRaw<{ language: string | null }>(
- `SELECT content_chunks.language
+ `SELECT DISTINCT content_chunks.language
FROM content_chunks
JOIN pages p ON p.id = content_chunks.page_id
WHERE p.source_id = $1 AND ${codeReadFilter([], {})}
AND content_chunks.symbol_name_qualified = $2
- LIMIT 1`,
+ AND content_chunks.language IS NOT NULL`,
[sourceId, qualified],
);
- return rows[0]?.language ?? null;
+ return rows.map((r) => r.language as string);
} catch {
- return null;
+ return [];
}
}
+const isSupportedLang = (lang: string): boolean =>
+ SUPPORTED_LANGS.includes(lang as (typeof SUPPORTED_LANGS)[number]);
+
+/** Edge origin chunks written in a supported language (one batched read). */
+async function supportedChunkIds(engine: BrainEngine, ids: number[]): Promise<Set<number>> {
+ if (ids.length === 0) return new Set();
+ const rows = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM content_chunks WHERE id = ANY($1::int[]) AND language = ANY($2::text[])`,
+ [ids, [...SUPPORTED_LANGS]],
+ );
+ return new Set(rows.map((r) => Number(r.id)));
+}
+
/**
* BFS recursive walk. Returns the depth-grouped result envelope.
*/
@@ -169,11 +184,17 @@ export async function runRecursiveWalk(
qualifiedStart = matches[0]!;
}
- // Step 2: language gate (per D18 honest scope).
- const lang = await detectSymbolLanguage(engine, qualifiedStart, opts.sourceId);
- if (lang && !SUPPORTED_LANGS.includes(lang as (typeof SUPPORTED_LANGS)[number])) {
+ // Step 2: language gate (per D18 honest scope), scoped to the symbol's
+ // own definitions: unsupported only when NO defining chunk is in a
+ // supported language. When an unsupported-language namesake shares the
+ // qualified name, the walk keeps only edges whose origin chunk is in a
+ // supported language, so the namesake's call graph does not leak in.
+ const langs = await symbolLanguages(engine, qualifiedStart, opts.sourceId);
+ const lang = langs.find(isSupportedLang) ?? langs[0] ?? null;
+ if (lang && !isSupportedLang(lang)) {
return { result: 'unsupported_language', supported: SUPPORTED_LANGS };
}
+ const mixedLanguages = langs.some((l) => !isSupportedLang(l));
// Step 3: BFS walk.
const visited = new Set<string>([qualifiedStart]);
@@ -199,6 +220,14 @@ export async function runRecursiveWalk(
} catch {
edges = [];
}
+ if (mixedLanguages && edges.length > 0) {
+ try {
+ const keep = await supportedChunkIds(engine, edges.map((e) => e.from_chunk_id));
+ edges = edges.filter((e) => keep.has(e.from_chunk_id));
+ } catch {
+ edges = [];
+ }
+ }
// freshness check: any edge whose owning chunk has edges_backfilled_at IS NULL
// → partial. v0.34 W3b's getCachedOrCompute will gate this further.
diff --git a/src/core/connectors/item-holds-store.ts b/src/core/connectors/item-holds-store.ts
index 22d0bd2caa..f4a07d1585 100644
--- a/src/core/connectors/item-holds-store.ts
+++ b/src/core/connectors/item-holds-store.ts
@@ -15,8 +15,10 @@
* writes (op `managed-connector-retry`), so the re-attempt is admitted under a
* new request identity.
*/
-import { existsSync, readFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { atomicWriteFileSync } from '../atomic-write.ts';
+import { withFilesystemPublication } from '../persistence/filesystem-guard.ts';
import type { BrainEngine } from '../engine.ts';
import { digest } from '../persistence/digest.ts';
import { connectorCheckpointKey, connectorIdentity, isConnectorSourceKind, type ConnectorKind } from '../persistence/connector-identity.ts';
@@ -35,6 +37,14 @@ export async function managedBrain(engine: Exec): Promise<boolean> {
return brain?.enabled === true;
}
+/** The classic-mode state file of a connector source, or null when it has no state directory. */
+export function classicConnectorStateFile(source: ConnectorSourceRow): string | null {
+ const kind = source.config.kind;
+ if (!isConnectorSourceKind(kind)) return null;
+ const dir = (connectorIdentity(kind, source.config, source.local_path).config as { dir?: string }).dir;
+ return dir ? join(dir, kind === 'google' ? '.google-source.json' : '.github-source.json') : null;
+}
+
/** The connector's cursor state, wherever this brain keeps it. */
export async function readConnectorCursorState(engine: Exec, source: ConnectorSourceRow, managed?: boolean): Promise<Record<string, unknown> | null> {
const kind = source.config.kind;
@@ -46,10 +56,8 @@ export async function readConnectorCursorState(engine: Exec, source: ConnectorSo
[connectorCheckpointKey(source.id, source.incarnation, identity)]);
return row?.completed_keys?.[0]?.state ?? null;
}
- const dir = (identity.config as { dir?: string }).dir;
- if (!dir) return null;
- const file = join(dir, kind === 'google' ? '.google-source.json' : '.github-source.json');
- if (!existsSync(file)) return null;
+ const file = classicConnectorStateFile(source);
+ if (!file || !existsSync(file)) return null;
// A corrupt state file is unknown hold state, not "no holds": the caller reports it.
return JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>;
}
@@ -72,6 +80,84 @@ export async function readAllSourceHolds(engine: Exec, opts: { sourceIds?: strin
return out;
}
+export interface HoldCarry {
+ source_id: string;
+ /** Held items in the managed checkpoint (0: only stale classic holds are cleared). */
+ items: number;
+ state_file: string | null;
+ unreadable?: string;
+ /** The host that owns the source's worktree when it is not this host. */
+ owner_host?: string;
+}
+
+const CONNECTOR_SOURCES_SQL = "SELECT id,incarnation::text AS incarnation,local_path,config FROM sources WHERE archived IS NOT TRUE AND config->>'kind' IN ('google','github') ORDER BY id";
+
+/** True when the hold cannot be carried from this host: deactivation keeps refusing for it. */
+export function holdCarryBlocked(carry: HoldCarry): boolean {
+ return carry.items > 0 && (!carry.state_file || !!carry.unreadable || !!carry.owner_host);
+}
+
+async function evaluateHoldCarry(engine: Exec, source: ConnectorSourceRow, hostId: string | null): Promise<{ holds: unknown; carry: HoldCarry } | null> {
+ const holds = (await readConnectorCursorState(engine, source, true))?.item_holds;
+ const items = heldItems(holds).length;
+ const file = classicConnectorStateFile(source);
+ let classic: Record<string, unknown> | null = null;
+ let unreadable: string | undefined;
+ if (file && existsSync(file)) {
+ try { classic = JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown>; } catch (e) { unreadable = e instanceof Error ? e.message : String(e); }
+ }
+ // Nothing to carry and no copy left behind by an earlier, aborted deactivation.
+ if (!items && !(classic && 'item_holds' in classic)) return null;
+ const [owner] = await engine.executeRaw<{ owner: string | null }>(`SELECT w.owner_host_id::text AS owner FROM persistence_source_bindings b
+ JOIN persistence_worktrees w ON w.id=b.worktree_id WHERE b.source_id=$1 LIMIT 1`, [source.id]);
+ const foreign = owner?.owner && owner.owner !== hostId ? owner.owner : undefined;
+ return { holds, carry: { source_id: source.id, items, state_file: file, ...(unreadable ? { unreadable } : {}), ...(foreign ? { owner_host: foreign } : {}) } };
+}
+
+/**
+ * Managed holds and where classic mode will read them after `sources writer
+ * deactivate`: each source's classic state file (`.google-source.json` /
+ * `.github-source.json`) on the host that owns the source. A source with no
+ * state directory, an existing classic state file that does not parse, or a
+ * worktree owned by another host cannot take its holds from here
+ * (holdCarryBlocked). Read-only.
+ */
+export async function planHoldCarry(engine: Exec, hostId: string | null): Promise<HoldCarry[]> {
+ const out: HoldCarry[] = [];
+ for (const source of await engine.executeRaw<ConnectorSourceRow>(CONNECTOR_SOURCES_SQL)) {
+ const evaluated = await evaluateHoldCarry(engine, source, hostId);
+ if (evaluated) out.push(evaluated.carry);
+ }
+ return out;
+}
+
+/**
+ * Make each locally owned source's classic state file hold exactly its managed
+ * `item_holds` (every other field kept), so a held item stays held, retried and
+ * reported after deactivation, and a hold copied by an earlier deactivation
+ * that then aborted (and was resolved in managed mode since) is cleared.
+ * Throws for a blocked carry; deactivation refuses those first.
+ */
+export async function carryHoldsToClassicState(engine: Exec, hostId: string | null): Promise<HoldCarry[]> {
+ const carried: HoldCarry[] = [];
+ for (const source of await engine.executeRaw<ConnectorSourceRow>(CONNECTOR_SOURCES_SQL)) {
+ const evaluated = await evaluateHoldCarry(engine, source, hostId);
+ if (!evaluated) continue;
+ const { holds, carry } = evaluated;
+ if (holdCarryBlocked(carry)) throw new Error(`connector source ${carry.source_id} cannot take its held items on this host`);
+ if (!carry.state_file || carry.unreadable || carry.owner_host) continue;
+ const file = carry.state_file;
+ const { item_holds: _previous, ...rest } = existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) as Record<string, unknown> : {};
+ mkdirSync(dirname(file), { recursive: true });
+ // Deactivation holds the worktree locks and the sources rows, so this write is
+ // its publication into a root that is still registered as managed.
+ await withFilesystemPublication([dirname(file)], async () =>
+ atomicWriteFileSync(file, JSON.stringify(carry.items ? { ...rest, item_holds: holds } : rest, null, 2)));
+ if (carry.items) carried.push(carry);
+ }
+ return carried;
+}
+
export async function readHoldRetryKeys(engine: Exec, sourceId: string, incarnation: string): Promise<string[]> {
const [row] = await engine.executeRaw<{ completed_keys: Array<{ keys?: unknown }> }>(
'SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [HOLD_RETRY_OP, connectorStateKey(sourceId, incarnation)]);
diff --git a/src/core/context/compile-view.ts b/src/core/context/compile-view.ts
index d040c77c1d..8a5ce80789 100644
--- a/src/core/context/compile-view.ts
+++ b/src/core/context/compile-view.ts
@@ -18,7 +18,10 @@
* not frontmatter) ∪ `listPages({updated_after: anchor−30d, sourceId,
* limit})` for recency. The RESOLVED sourceId is passed into EVERY
* listPages call and EVERY body read (`getPage(slug, {sourceId})`) —
- * unscoped reads are the cross-source-leak invariant class.
+ * unscoped reads are the cross-source-leak invariant class. Every arm also
+ * passes `excludePrivate: true`: the compiled file lands in AGENTS.md /
+ * CLAUDE.md imports, the same world-only injected-context posture as the
+ * turn hook, so `visibility: private` pages never become candidates.
*
* Score = recency-decay(vs anchor) × longest-prefix boost from
* DEFAULT_SOURCE_BOOSTS, plus a fixed pin bonus for tag-pinned pages.
@@ -191,14 +194,14 @@ async function fetchCandidates(
const [prefixResults, tagPages, probe] = await Promise.all([
Promise.all(
prefixes.map((slugPrefix) =>
- engine.listPages({ slugPrefix, sourceId, sort: 'slug', limit: PREFIX_CANDIDATE_LIMIT }),
+ engine.listPages({ slugPrefix, sourceId, excludePrivate: true, sort: 'slug', limit: PREFIX_CANDIDATE_LIMIT }),
),
),
// Tag arm — explicit pins (few by construction; slug sort for stable order).
- engine.listPages({ tag: COMPILE_CONTEXT_TAG, sourceId, sort: 'slug' }),
+ engine.listPages({ tag: COMPILE_CONTEXT_TAG, sourceId, excludePrivate: true, sort: 'slug' }),
// Recency-anchor probe: the newest updated_at in the source (ties share
// the timestamp, so tie order cannot change the probed VALUE).
- engine.listPages({ sourceId, sort: 'updated_desc', limit: 1 }),
+ engine.listPages({ sourceId, excludePrivate: true, sort: 'updated_desc', limit: 1 }),
]);
for (const pages of prefixResults) add(pages, false);
add(tagPages, true);
@@ -216,6 +219,7 @@ async function fetchCandidates(
const recent = await engine.listPages({
updated_after: windowStart,
sourceId,
+ excludePrivate: true,
sort: 'updated_desc',
limit: RECENCY_CANDIDATE_LIMIT,
});
diff --git a/src/core/context/retrieval-reflex.ts b/src/core/context/retrieval-reflex.ts
index 42e28261f2..bb2cd6a26e 100644
--- a/src/core/context/retrieval-reflex.ts
+++ b/src/core/context/retrieval-reflex.ts
@@ -20,7 +20,10 @@
* Privacy (eng-review D5): the synopsis is taken from a SAFE source —
* frontmatter `summary` if present, else the page body with takes/private-fact
* fences STRIPPED (same boundary get_page applies to untrusted readers). Raw
- * compiled_truth is never injected.
+ * compiled_truth is never injected. Page visibility: `visibility: private`
+ * and derived-private pages never resolve unless the caller passes
+ * `excludePrivate: false` (trusted local only) — the same page filter remote
+ * search applies (search/private-visibility.ts).
*/
import type { BrainEngine } from '../engine.ts';
@@ -30,6 +33,7 @@ import { escapeLikePattern } from '../search/sql-ranking.ts';
import { slugify } from '../entities/resolve.ts';
import { stripTakesFence } from '../takes-fence.ts';
import { stripFactsFence } from '../facts-fence.ts';
+import { privatePagesFilterFragment } from '../search/private-visibility.ts';
import type { EntityCandidate } from './entity-salience.ts';
import { reflexPointerRationale } from './reflex-rationale.ts';
import { logVolunteerEventsFireAndForget, volunteerEventRowsFrom } from './volunteer-events.ts';
@@ -140,6 +144,15 @@ export interface ResolvePointersOpts {
* config — the resolver itself never touches config (sync hot path).
*/
lexicalArms?: boolean;
+ /**
+ * Hide `visibility: private` (and derived-private) pages from every arm,
+ * using the same predicate remote search applies. Default true
+ * (fail-closed): pointers are injected into agent prompts, so the IPC
+ * resolve, turn-context and direct-Postgres reflex lanes stay world-only.
+ * Only a trusted local caller (volunteer_context with remote === false,
+ * via resolveExcludePrivatePages) passes false.
+ */
+ excludePrivate?: boolean;
}
export interface PageRow {
@@ -167,9 +180,9 @@ export async function resolveEntitiesToPointers(
const maxPointers = opts.maxPointers ?? DEFAULT_MAX_POINTERS;
const priorLc = (opts.priorContextText ?? '').toLowerCase();
- // v0.46.15 identity wave: the two new lexical arms (weak-alias + surname)
- // share one kill switch. Default ON; `false` reproduces pre-wave behavior.
+ // v0.46.15: weak-alias + surname arms share one kill switch (default ON).
const lexicalArms = opts.lexicalArms !== false;
+ const privacySql = opts.excludePrivate === false ? '' : `AND ${privatePagesFilterFragment('p')}`;
// display lookup keyed by normalized query, so resolved slugs can recover a
// human surface form for the pointer label.
@@ -283,8 +296,8 @@ export async function resolveEntitiesToPointers(
if (hitSlugs.size) {
try {
const liveRows = await engine.executeRaw<{ slug: string; source_id: string }>(
- `SELECT slug, source_id FROM pages
- WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND slug = ANY($2::text[])`,
+ `SELECT p.slug, p.source_id FROM pages p
+ WHERE p.deleted_at IS NULL AND p.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[]) ${privacySql}`,
[sourceIds, [...hitSlugs]],
);
for (const r of liveRows) liveAliasKeys.add(keyOf(r.source_id, r.slug));
@@ -343,24 +356,24 @@ export async function resolveEntitiesToPointers(
// class ("Labs", "Systems" as pseudo-surnames).
rows = useSurnameArm
? await engine.executeRaw<PageRow>(
- `SELECT slug, source_id, title, type, frontmatter, compiled_truth
- FROM pages
- WHERE deleted_at IS NULL
- AND source_id = ANY($1::text[])
- AND ( lower(title) = ANY($2::text[])
- OR slug = ANY($3::text[])
- OR slug LIKE ANY($4::text[])
- OR (lower(title) LIKE ANY($5::text[]) AND type = 'person') )`,
+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth
+ FROM pages p
+ WHERE p.deleted_at IS NULL ${privacySql}
+ AND p.source_id = ANY($1::text[])
+ AND ( lower(p.title) = ANY($2::text[])
+ OR p.slug = ANY($3::text[])
+ OR p.slug LIKE ANY($4::text[])
+ OR (lower(p.title) LIKE ANY($5::text[]) AND p.type = 'person') )`,
[sourceIds, titlesLc, exactSlugs, slugSuffixes, surnamePatterns],
)
: await engine.executeRaw<PageRow>(
- `SELECT slug, source_id, title, type, frontmatter, compiled_truth
- FROM pages
- WHERE deleted_at IS NULL
- AND source_id = ANY($1::text[])
- AND ( lower(title) = ANY($2::text[])
- OR slug = ANY($3::text[])
- OR slug LIKE ANY($4::text[]) )`,
+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth
+ FROM pages p
+ WHERE p.deleted_at IS NULL ${privacySql}
+ AND p.source_id = ANY($1::text[])
+ AND ( lower(p.title) = ANY($2::text[])
+ OR p.slug = ANY($3::text[])
+ OR p.slug LIKE ANY($4::text[]) )`,
[sourceIds, titlesLc, exactSlugs, slugSuffixes],
);
} catch {
@@ -373,9 +386,9 @@ export async function resolveEntitiesToPointers(
if (aliasOnly.length) {
try {
const extra = await engine.executeRaw<PageRow>(
- `SELECT slug, source_id, title, type, frontmatter, compiled_truth
- FROM pages
- WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND slug = ANY($2::text[])`,
+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth
+ FROM pages p
+ WHERE p.deleted_at IS NULL ${privacySql} AND p.source_id = ANY($1::text[]) AND p.slug = ANY($2::text[])`,
[sourceIds, aliasOnly.map((p) => p.slug)],
);
for (const r of extra) rowByKey.set(keyOf(r.source_id, r.slug), r);
@@ -457,11 +470,11 @@ export async function resolveEntitiesToPointers(
if (cjkNorms.length) {
try {
const cjkRows = await engine.executeRaw<PageRow>(
- `SELECT slug, source_id, title, type, frontmatter, compiled_truth
- FROM pages
- WHERE deleted_at IS NULL
- AND source_id = ANY($1::text[])
- AND ( lower(title) = ANY($2::text[]) OR slug = ANY($3::text[]) )`,
+ `SELECT p.slug, p.source_id, p.title, p.type, p.frontmatter, p.compiled_truth
+ FROM pages p
+ WHERE p.deleted_at IS NULL ${privacySql}
+ AND p.source_id = ANY($1::text[])
+ AND ( lower(p.title) = ANY($2::text[]) OR p.slug = ANY($3::text[]) )`,
[sourceIds, cjkNorms, cjkNorms],
);
const cjkHits = new Map<string, Array<{ slug: string; source_id: string }>>();
diff --git a/src/core/context/turn-context.ts b/src/core/context/turn-context.ts
index f972fd78b6..3cd344897b 100644
--- a/src/core/context/turn-context.ts
+++ b/src/core/context/turn-context.ts
@@ -6,7 +6,8 @@
* existing, deterministic sources —
*
* 1. reflex pointers — extractCandidatesFromWindow → resolveEntitiesToPointers
- * (slug-only suppression, the windowed contract)
+ * (slug-only suppression, the windowed contract;
+ * private pages excluded like remote search, N8-2)
* 2. volunteered pages — volunteerContext (confidence-gated, ≤3, deduped
* against section 1 via excludeSlugs)
* 3. hot facts — getBrainHotMemoryMeta's cache + shape [ENG-11], with
@@ -240,6 +241,7 @@ export async function assembleTurnContext(
suppression: 'slug-only',
maxPointers: DEFAULT_MAX_POINTERS,
lexicalArms: opts.lexicalArms,
+ excludePrivate: true,
});
pointers = block?.pointers ?? [];
}
@@ -261,6 +263,7 @@ export async function assembleTurnContext(
// v0.46.15+ lexical-arms kill switch rides the same threading as the
// pointer arm above (ResolvePointersOpts.lexicalArms).
lexicalArms: opts.lexicalArms,
+ excludePrivate: true,
});
}
} catch {
diff --git a/src/core/context/volunteer.ts b/src/core/context/volunteer.ts
index c4a491015e..d5c934eaaf 100644
--- a/src/core/context/volunteer.ts
+++ b/src/core/context/volunteer.ts
@@ -71,6 +71,8 @@ export interface VolunteerOpts {
minConfidence?: number;
/** v0.46.15: lexical-arms kill switch — see ResolvePointersOpts.lexicalArms. */
lexicalArms?: boolean;
+ /** Private-page filter — see ResolvePointersOpts.excludePrivate (default true). */
+ excludePrivate?: boolean;
}
/** Shared wire protocol for window turns — watch.ts imports this so the two
@@ -287,6 +289,7 @@ export async function volunteerContext(
suppression: ropts.suppression,
maxPointers: ropts.maxPointers,
lexicalArms: ropts.lexicalArms,
+ excludePrivate: opts.excludePrivate,
}),
candidates,
turns.length,
diff --git a/src/core/conversation-parser/builtins.ts b/src/core/conversation-parser/builtins.ts
index 3d05b1ca92..32862b390f 100644
--- a/src/core/conversation-parser/builtins.ts
+++ b/src/core/conversation-parser/builtins.ts
@@ -494,6 +494,9 @@ export const BUILTIN_PATTERNS: readonly PatternEntry[] = [
multi_line: false,
quick_reject: /^\*\*/,
score_full_body: true,
+ // N12-1: three or more one-off bold labels with no repeated speaker
+ // are a status note, not a transcript.
+ repeat_speaker_min_turns: 3,
test_positive: [
'**Alice Example:** Okay, start on.',
'**Participant 2:** he tried to reset it remotely the other night.',
diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.ts
index 9973eceb9f..eaaf66f743 100644
--- a/src/core/conversation-parser/parse.ts
+++ b/src/core/conversation-parser/parse.ts
@@ -759,6 +759,24 @@ export function parseConversation(
const diag = { unrecognized_headings: [] as string[], date_fallback_count: 0 };
const messages = applyPattern(body, top.entry, dateCtx, diag);
+ // Structure gate (N12-1): enough turns with every speaker distinct is a
+ // list of labels, not a conversation.
+ const minTurns = top.entry.repeat_speaker_min_turns;
+ if (
+ minTurns !== undefined &&
+ messages.length >= minTurns &&
+ new Set(messages.map((m) => m.speaker)).size === messages.length
+ ) {
+ return {
+ messages: [],
+ phase: 'no_match',
+ patterns_scored: patternsScored,
+ unmatched_line_count: opts.diagnostic
+ ? body.split(/\r?\n/).filter((l) => l.trim().length > 0).length
+ : undefined,
+ };
+ }
+
// Timezone warning surface (D19).
let timezone_warning: string | undefined;
if (
diff --git a/src/core/conversation-parser/types.ts b/src/core/conversation-parser/types.ts
index 410107e7a5..113a47bbe9 100644
--- a/src/core/conversation-parser/types.ts
+++ b/src/core/conversation-parser/types.ts
@@ -240,6 +240,15 @@ export interface PatternEntry {
* real transcript stays ~1.0.
*/
score_full_body?: boolean;
+ /**
+ * Conversational-structure gate for broad label-shaped patterns
+ * (gbrain-evals N12-1). When the parsed body has at least this many
+ * turns and no speaker ever speaks twice, the page is a list of one-off
+ * labels (`**Status:** … **Owner:** … **Next step:** …`), not an
+ * exchange, and the orchestrator returns no_match. Density scoring
+ * cannot see this: a short status block clears the 0.05 floor.
+ */
+ repeat_speaker_min_turns?: number;
/** D7: module-load validation — known-positive sample lines. */
test_positive: string[];
/** D7: module-load validation — known-negative sample lines. */
diff --git a/src/core/cycle/auto-think.ts b/src/core/cycle/auto-think.ts
index 928c33dba0..567f67ab0b 100644
--- a/src/core/cycle/auto-think.ts
+++ b/src/core/cycle/auto-think.ts
@@ -42,6 +42,8 @@ export interface AutoThinkPhaseOpts {
client?: ThinkLLMClient;
/** Override the audit-ledger path (tests). */
auditPath?: string;
+ /** #5426: source the cycle runs for; syntheses are saved there. */
+ sourceId?: string;
}
export interface AutoThinkConfig {
@@ -173,6 +175,7 @@ export async function runPhaseAutoThink(
// Fail-closed trust: the local dream cycle must say so explicitly, or
// trajectory injection degrades to visibility='world' rows.
remote: false,
+ ...(opts.sourceId ? { sourceId: opts.sourceId } : {}),
});
// #1698: an empty synthesis (no LLM available / malformed output / empty-JSON answer)
// must NOT count as complete or advance the cooldown — that is the same silent-success
@@ -185,7 +188,7 @@ export async function runPhaseAutoThink(
const warnings = [...result.warnings];
let slug: string | undefined;
if (config.autoCommit) {
- const persisted = await persistSynthesis(engine, result);
+ const persisted = await persistSynthesis(engine, result, opts.sourceId ? { sourceId: opts.sourceId } : {});
slug = persisted.slug || undefined; // '' = persist-skip signal (#1698)
warnings.push(...persisted.warnings);
}
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index fa82f8bc8e..ad12770464 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -60,6 +60,7 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'connector_checkpoints',
'connector_held_items',
'derived_visibility',
+ 'extractor_facts_expired',
'orphan_persistence_bindings',
'safe_index_pending',
'self_capture',
@@ -85,6 +86,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
'embed_staleness',
'embedding_column_registry',
'embedding_env_override',
+ // #5137: an env provider key shadowing a different config key.
+ 'embedding_key_source',
'embedding_migration_state',
'embedding_provider',
// #5691: query-instruction advisory for instruction-style embedding models.
@@ -220,6 +223,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'pool_budget',
'progressive_batch_audit_health',
'queue_health',
+ // #5157: queued jobs from before the v0.50 authority cutover block every worker.
+ 'legacy_job_authority',
'reranker_health',
'rls',
'rls_event_trigger',
diff --git a/src/core/embed-concurrency.ts b/src/core/embed-concurrency.ts
new file mode 100644
index 0000000000..9daff449cc
--- /dev/null
+++ b/src/core/embed-concurrency.ts
@@ -0,0 +1,38 @@
+import { resolvePoolSize } from './db.ts';
+
+let warnedEmbedConcurrencyClamp = false;
+
+/** Test seam: let the clamp warning print again. */
+export function _resetEmbedConcurrencyClampWarningForTest(): void {
+ warnedEmbedConcurrencyClamp = false;
+}
+
+/**
+ * Parallel page-embedding workers: GBRAIN_EMBED_CONCURRENCY (default 20),
+ * lowered to a paced run's cap, and on Postgres never above the client pool
+ * (#5183). Each worker holds a connection across its read and upsert, so more
+ * workers than pool connections left the run waiting on itself: no progress,
+ * no error, 0% CPU. An explicit setting that gets lowered is reported once
+ * per process; the default is lowered silently.
+ */
+export function resolveEmbedConcurrency(
+ engineKind: string,
+ paceMaxConcurrency?: number,
+ env: Record<string, string | undefined> = process.env,
+ poolSize: number = resolvePoolSize(),
+): number {
+ const explicit = env.GBRAIN_EMBED_CONCURRENCY;
+ const parsed = parseInt(explicit || '20', 10);
+ const base = Number.isFinite(parsed) && parsed > 0 ? parsed : 20;
+ const paced = paceMaxConcurrency ? Math.min(base, paceMaxConcurrency) : base;
+ if (engineKind !== 'postgres' || paced <= poolSize) return paced;
+ const clamped = Math.max(1, poolSize);
+ if (explicit && !warnedEmbedConcurrencyClamp) {
+ warnedEmbedConcurrencyClamp = true;
+ process.stderr.write(
+ `[embed] GBRAIN_EMBED_CONCURRENCY=${explicit} is above the connection pool (${poolSize}); using ${clamped} workers. ` +
+ `Raise GBRAIN_POOL_SIZE or lower GBRAIN_EMBED_CONCURRENCY to match.\n`,
+ );
+ }
+ return clamped;
+}
diff --git a/src/core/engine-sql/code-edges.ts b/src/core/engine-sql/code-edges.ts
index 3a85202eb1..95cb6f9f5c 100644
--- a/src/core/engine-sql/code-edges.ts
+++ b/src/core/engine-sql/code-edges.ts
@@ -161,7 +161,14 @@ export async function getEdgesByChunk(
return [...chunkRows, ...symbolRows].map(r => rowToCodeEdge(r as Record<string, unknown>));
}
-function rowToCodeEdge(row: Record<string, unknown>): CodeEdgeResult {
+/**
+ * Shared by both engines' reads. `resolved` is true for a code_edges_chunk
+ * row AND for a code_edges_symbol row the resolver stamped with
+ * edge_metadata.resolved_chunk_id (gbrain-evals N13-2); to_chunk_id still
+ * reports the stored column.
+ */
+export function rowToCodeEdge(row: Record<string, unknown>): CodeEdgeResult {
+ const edgeMetadata = (row.edge_metadata as Record<string, unknown>) ?? {};
return {
id: row.id as number,
from_chunk_id: row.from_chunk_id as number,
@@ -169,8 +176,8 @@ function rowToCodeEdge(row: Record<string, unknown>): CodeEdgeResult {
from_symbol_qualified: (row.from_symbol_qualified as string) ?? '',
to_symbol_qualified: (row.to_symbol_qualified as string) ?? '',
edge_type: (row.edge_type as string) ?? '',
- edge_metadata: (row.edge_metadata as Record<string, unknown>) ?? {},
+ edge_metadata: edgeMetadata,
source_id: row.source_id == null ? null : (row.source_id as string),
- resolved: Boolean(row.resolved),
+ resolved: Boolean(row.resolved) || typeof edgeMetadata.resolved_chunk_id === 'number',
};
}
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
new file mode 100644
index 0000000000..9e81a0b87d
--- /dev/null
+++ b/src/core/error-catalogue.ts
@@ -0,0 +1,57 @@
+/**
+ * Error catalogue for coded refusals (fix wave 5, DX-O2 / ENG-O12).
+ *
+ * One entry per refusal: the stable wire `code` and the docs anchor that
+ * explains it. Every entry's anchor must exist in its guide; the doc test
+ * (`test/error-catalogue.test.ts`) resolves each `docs` against the Markdown
+ * headings and `<a id>` tags, so a renamed heading fails CI instead of
+ * leaving a dead link in an error.
+ *
+ * Wire mapping: an `OperationError` carries the hint as `suggestion` and the
+ * anchor as `docs` (its `toJSON()` serializes both for CLI `--json` and MCP);
+ * a CLI-only refusal may use a `StructuredError`, which names them `hint` and
+ * `docs_url`. `/ingest` renders an `OperationError` as
+ * `{ error, message, hint, docs_url }`.
+ *
+ * Entries are keyed by name, not code, so one code can carry two anchors:
+ * `legacy_job_authority` keeps the existing `permission_denied` code and adds
+ * its own anchor. Add a refusal by adding one entry and its doc heading.
+ */
+import { OperationError } from './ops/contract.ts';
+import { StructuredAgentError, buildError } from './errors.ts';
+
+export interface CatalogueEntry {
+ /** Stable machine-readable code on the wire. */
+ code: string;
+ /** Repository-relative docs pointer, `docs/guides/<guide>.md#<anchor>`. */
+ docs: string;
+}
+
+export const ERROR_CATALOGUE = {
+ legacy_jobs_active: { code: 'legacy_jobs_active', docs: 'docs/guides/repair.md#legacy-jobs-active' },
+ legacy_job_selection_invalid: { code: 'legacy_job_selection_invalid', docs: 'docs/guides/repair.md#legacy-job-selection-invalid' },
+ legacy_job_authority: { code: 'permission_denied', docs: 'docs/guides/repair.md#legacy-job-authority' },
+ preview_changed: { code: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed' },
+ projection_owner_resident: { code: 'projection_owner_resident', docs: 'docs/guides/repair.md#projection-owner-resident' },
+ explicit_kind_required: { code: 'explicit_kind_required', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },
+ repair_kind_unavailable: { code: 'unavailable', docs: 'docs/guides/repair.md#explicit-only-repair-kinds' },
+ colon_slug_windows_write_through: { code: 'colon_slug_windows_write_through', docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through' },
+ embedding_auth_failed: { code: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed' },
+} as const satisfies Record<string, CatalogueEntry>;
+
+export type CatalogueName = keyof typeof ERROR_CATALOGUE;
+
+/**
+ * An `OperationError` for a catalogue entry. `message` is one sentence; `hint`
+ * is the exact command to run next, filled with real values.
+ */
+export function catalogueError(name: CatalogueName, message: string, hint: string): OperationError {
+ const entry = ERROR_CATALOGUE[name];
+ return new OperationError(entry.code, message, hint, entry.docs);
+}
+
+/** The same refusal as a `StructuredError` envelope, for CLI-only surfaces. */
+export function catalogueStructuredError(name: CatalogueName, errorClass: string, message: string, hint: string): StructuredAgentError {
+ const entry = ERROR_CATALOGUE[name];
+ return new StructuredAgentError(buildError({ class: errorClass, code: entry.code, message, hint, docs_url: entry.docs }));
+}
diff --git a/src/core/facts/managed-fact-write.ts b/src/core/facts/managed-fact-write.ts
index 18659d4c46..8f827aeae4 100644
--- a/src/core/facts/managed-fact-write.ts
+++ b/src/core/facts/managed-fact-write.ts
@@ -24,13 +24,14 @@ export async function managedFactWritePreflight(engine: BrainEngine, sourceId: s
* replays its receipt. Returned ids follow input order.
*/
export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: string, entity: string | null,
- facts: FenceInputFact[], options: { supersede?: boolean } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {
+ facts: FenceInputFact[], options: { supersede?: boolean; attributeFallback?: boolean } = {}): Promise<{ inserted: number; duplicate: number; superseded: number; ids: number[] }> {
const out = { inserted: 0, duplicate: 0, superseded: 0, ids: new Array<number>(facts.length) };
for (const visibility of ['private', 'world'] as const) {
const positions = facts.flatMap((fact, i) => fact.visibility === visibility ? [i] : []);
if (!positions.length) continue;
const group = positions.map(i => facts[i]);
const ctx = factsContext(engine, sourceId, { writer: 'fence_write', entity, visibility, supersede: options.supersede === true,
+ ...(options.attributeFallback ? { attribute_fallback: true } : {}),
facts: group.map(f => [f.fact, f.kind, f.source, f.notability, f.confidence ?? 1, f.validFrom?.toISOString() ?? null,
f.validUntil?.toISOString() ?? null, f.sessionId, f.context ?? null]) }, group[0].sessionId);
const session = (await prepareManagedFactsSession(ctx, { turnText: '' }))!;
@@ -42,7 +43,8 @@ export async function publishManagedEntityFacts(engine: BrainEngine, sourceId: s
notability: f.notability, source: f.source, context: f.context ?? null, confidence: f.confidence ?? 1,
valid_from: f.validFrom, valid_until: f.validUntil ?? null, source_session: f.sessionId,
embedding: signature && f.embedding_model === signature.model && f.embedding?.length === signature.dimensions ? f.embedding : null }));
- result = await publishManagedFacts(engine, session, ctx, extracted, visibility, undefined, { supersede: options.supersede, explicitContext: true });
+ result = await publishManagedFacts(engine, session, ctx, extracted, visibility, undefined,
+ { supersede: options.supersede, explicitContext: true, attributeFallback: options.attributeFallback });
}
out.inserted += result.inserted;
out.duplicate += result.duplicate;
diff --git a/src/core/facts/write-single.ts b/src/core/facts/write-single.ts
index c76dba294b..e48e72cdd1 100644
--- a/src/core/facts/write-single.ts
+++ b/src/core/facts/write-single.ts
@@ -127,11 +127,13 @@ export async function writeSingleFact(
if (managed) {
// The coordinator's fact intent owns dedup, supersession, the fence row and
- // the file on a managed brain; the legacy direct writes stay unmanaged.
+ // the file on a managed brain; the legacy direct writes stay unmanaged. An
+ // entity with no page keeps its resolver slug database-only, as the
+ // unmanaged path stores it, so dedup is per entity.
const { publishManagedEntityFacts } = await import('./managed-fact-write.ts');
const written = await publishManagedEntityFacts(engine, sourceId, resolvedSlug, [{ fact: factText, kind, notability: 'medium',
source: input.provenance, visibility, confidence: input.confidence ?? 1.0, validFrom: new Date(), validUntil,
- embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true });
+ embedding, embedding_model: embeddingModel, sessionId: input.sessionId ?? null }], { supersede: true, attributeFallback: true });
const [stored] = await engine.executeRaw<{ entity_slug: string | null }>('SELECT entity_slug FROM facts WHERE id=$1', [written.ids[0]]);
return { id: written.ids[0], status: written.superseded ? 'superseded' : written.inserted ? 'inserted' : 'duplicate', entity_slug: stored?.entity_slug ?? null,
valid_until: validUntil, degraded_dedup: degradedDedup };
diff --git a/src/core/google/loop-detect.ts b/src/core/google/loop-detect.ts
index db1ba2146a..2d76f52e35 100644
--- a/src/core/google/loop-detect.ts
+++ b/src/core/google/loop-detect.ts
@@ -20,7 +20,9 @@
* - outbound without a question mark is FYI, not an ask
* - suppressed senders/threads (gbrain loops mute) never open NEW loops;
* existing loops keep their state
- * - grace windows: inbound 24h, outbound 72h — fresh mail is not a loop yet
+ * - grace windows: inbound 24h, outbound 72h — fresh mail is not a loop yet;
+ * measured from the oldest unanswered message in the trailing run, so a
+ * nudge or follow-up does not restart the clock
*
* Pure verdict function + a thin apply step; the apply step is called from
* runGoogleSync per touched thread and must never fail the sync.
@@ -128,6 +130,16 @@ export function detectThreadLoop(
const threadSuppressed = suppressions?.threads.has(thread.threadId) ?? false;
+ // The trailing run: substantive messages since the last turn flip, all on
+ // the last speaker's side. Grace windows are measured from the OLDEST
+ // message in the run that carries the obligation (an inbound message with
+ // me in To:, or my outbound ask), so a fresh nudge or follow-up never
+ // restarts the clock on a request that has already waited past the window
+ // — the open-lane twin of the close-lane rule that a nudge is not a reply.
+ let runStart = substantive.length - 1;
+ while (runStart > 0 && isMine(substantive[runStart - 1], myAddresses) === lastIsMine) runStart--;
+ const run = substantive.slice(runStart);
+
if (!lastIsMine) {
// ── Last word is theirs: do I owe a reply? ──
// List mail never owes a reply.
@@ -136,7 +148,8 @@ export function detectThreadLoop(
const inTo = last.to.some((a) => myAddresses.has(a));
if (!inTo) return { open: [], close };
if (threadSuppressed || suppressions?.senders.has(last.fromAddress)) return { open: [], close };
- if (ageHours(last.internalDateMs, now) < INBOUND_GRACE_HOURS) return { open: [], close };
+ const owedSince = run.find((m) => m.to.some((a) => myAddresses.has(a))) ?? last;
+ if (ageHours(owedSince.internalDateMs, now) < INBOUND_GRACE_HOURS) return { open: [], close };
return {
open: [
{
@@ -161,7 +174,8 @@ export function detectThreadLoop(
if (recipients.length === 0) return { open: [], close };
const counterparty = recipients[0];
if (threadSuppressed || suppressions?.senders.has(counterparty)) return { open: [], close };
- if (ageHours(last.internalDateMs, now) < OUTBOUND_GRACE_HOURS) return { open: [], close };
+ const askedSince = run.find((m) => m.bodyText.includes('?')) ?? last;
+ if (ageHours(askedSince.internalDateMs, now) < OUTBOUND_GRACE_HOURS) return { open: [], close };
return {
open: [
{
diff --git a/src/core/harness/install.ts b/src/core/harness/install.ts
index d9b025d59d..32b250f745 100644
--- a/src/core/harness/install.ts
+++ b/src/core/harness/install.ts
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
import { existsSync, readFileSync, mkdirSync, lstatSync, unlinkSync, readdirSync } from 'node:fs';
-import { dirname, join } from 'node:path';
+import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { acquireBootstrapLock } from '../bootstrap/lock.ts';
@@ -11,6 +12,7 @@ import { renderAgentLauncher } from '../agent-install/launcher.ts';
import { isValidName, shellQuote } from '../mcp-registration.ts';
import { GBRAIN_MCP_INSTRUCTIONS } from '../../mcp/instructions.ts';
import { harnessAdapter } from './registry.ts';
+import { GIT_ENV } from '../git-remote.ts';
import { credentialAccessToken, credentialReceipt, type HarnessCredentials } from './credentials.ts';
import { assertNoSymlinks, checkedRoot, confinedPath, sha256, privateWrite } from '../agent-install/state.ts';
import { installSharedSkillsConnection } from './shared-skills.ts';
@@ -18,7 +20,7 @@ import type { SharedSkillsToolCaller } from '../shared-skills/adapter.ts';
import { harnessSharedSkillsRoot } from './status.ts';
export interface InstallOptions { harness: string; name?: string; root?: string; configPath?: string; remove?: boolean;
- sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string }
+ sharedSkills?: HarnessCredentials['shared_skills']; toolCaller?: SharedSkillsToolCaller; nativeSkillsDir?: string; credentialsFile?: string; freshToken?: boolean }
const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
const readJson = (path: string): Record<string, any> => {
assertNoSymlinks(path);
@@ -41,12 +43,44 @@ function nativeEntry(path: string, format: string, name: string): unknown {
return entries?.[name];
}
+/** The Git working tree whose next commit would include `path`, or null when it is ignored or outside every tree. */
+function committingGitTree(path: string): string | null {
+ const git = (args: string[]) => execFileSync('git', ['-C', dirname(path), ...args],
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10_000, env: { ...process.env, ...GIT_ENV } }).trim();
+ let tree: string;
+ try { tree = git(['rev-parse', '--show-toplevel']); } catch { return null; }
+ try { git(['check-ignore', '-q', '--', path]); return null; } catch { return tree; }
+}
+
+/** Where an installed bearer token lives and how to replace it, never the token itself (#5775). */
+export function inlineTokenReceipt(c: HarnessCredentials, harness: string, name: string, configPath: string, reload: string, credentialsFile?: string) {
+ const renew = ['gbrain connect', shellQuote(c.mcp_url), '--harness', shellQuote(harness), '--credentials-file',
+ credentialsFile ? shellQuote(credentialsFile) : '<private-handoff-file>', ...(name === 'gbrain' ? [] : ['--name', shellQuote(name)]), '--install', ...(c.client_secret ? ['--fresh-token'] : [])].join(' ');
+ const invalidate = (apply: string) => `gbrain mcp admin invalidate-tokens ${shellQuote(c.client_id)}${apply} --url ${shellQuote(c.mcp_url)} --admin-token-file <owner-admin-token-file> --json`;
+ const tree = committingGitTree(configPath);
+ // A cached unexpired handoff token may be the invalidated one, so renewal always exchanges a new token.
+ const replace = c.client_secret ? `Write a freshly exchanged token here: ${renew}`
+ : `This handoff cannot exchange a new token; get a new private handoff from the brain owner (gbrain mcp grant on the brain host), then run: ${renew}`;
+ return {
+ token_storage: 'inline' as const, config_path: configPath, renew_command: renew,
+ if_exposed: {
+ steps: [`On the brain host, preview: ${invalidate('')}`, `Apply with the previewed revision: ${invalidate(' --yes --if-version <revision>')}`,
+ replace, reload],
+ docs_url: 'docs/mcp/ADMIN.md#invalidate-tokens-revoke-or-delete',
+ },
+ ...(tree ? { token_warning: `${configPath} is inside the Git working tree ${tree}, so committing there would publish this bearer token. `
+ + `Add ${relative(tree, configPath).split('\\').join('/')} to that repository's .gitignore or move the configuration; if it was already committed, follow if_exposed.` } : {}),
+ };
+}
+
function assertEntryOwned(entry: unknown, prior: Record<string, any>) {
if (entry !== undefined && (!prior.client_id || ![prior.entry_hash, prior.pending_entry_hash].includes(hash(entry)))) throw new Error('configuration_conflict: refusing to replace an unowned or edited MCP entry');
}
/** Install only in the current environment. Foreign entries are never adopted. */
export async function installHarnessConnection(c: HarnessCredentials, opts: InstallOptions) {
+ // A cached unexpired token may be the invalidated one; every later step (config and shared skills) uses the new token.
+ if (opts.freshToken && !opts.remove) c = { ...c, access_token: await credentialAccessToken({ ...c, access_token: undefined }), expires_at: undefined };
const adapter = harnessAdapter(opts.harness);
const name = opts.name ?? 'gbrain';
if (!isValidName(name)) throw new Error('Invalid connection name');
@@ -116,7 +150,8 @@ export async function installHarnessConnection(c: HarnessCredentials, opts: Inst
next_action: pending ? 'Local configuration and unchanged owned skills were removed. Remote membership deactivation remains pending; retry when host authority is available.'
: 'The client configuration was removed. Revoke the grant on the brain host if access should end.' };
}
- const nextReceipt = { ...common, entry_hash: hash(nativeEntry(configPath, adapter.connection, name)), status: 'installed', config_path: configPath };
+ const nextReceipt = { ...common, entry_hash: hash(nativeEntry(configPath, adapter.connection, name)), status: 'installed',
+ ...inlineTokenReceipt(c, adapter.id, name, configPath, adapter.reload, opts.credentialsFile) };
atomicWriteTextFile(receiptPath, `${JSON.stringify(nextReceipt, null, 2)}\n`, { forceMode: 0o600 });
const shared_skills = deactivated ?? await installSharedSkillsConnection(c, { ...opts, root: join(dirname(configPath), `.gbrain-${adapter.id}-${name}`) });
return { ...nextReceipt, shared_skills, remote_membership_pending: 'remote_membership_pending' in shared_skills && shared_skills.remote_membership_pending === true };
diff --git a/src/core/minions/authorize-legacy.ts b/src/core/minions/authorize-legacy.ts
index 184fe0653d..b984732a88 100644
--- a/src/core/minions/authorize-legacy.ts
+++ b/src/core/minions/authorize-legacy.ts
@@ -1,15 +1,35 @@
/** Local-only, explicit preview/CAS authorization of pre-cutover job rows. */
import type { BrainEngine } from '../engine.ts';
-import { APPLICATION_AUTHORITY, authorityDigest, parseSubmissionAuthority } from './submission-authority.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { OperationError } from '../ops/contract.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { APPLICATION_AUTHORITY, parseSubmissionAuthority } from './submission-authority.ts';
+import {
+ assertNoActiveJobs, formatSelection, selectCommand, selectedStatuses, summarizeSelection,
+ type LegacyJobSelection, type SelectionSummary,
+} from './legacy-selection.ts';
+
+const IDS_EXAMPLE = 'gbrain jobs authorize-legacy --ids 12,34';
+
+function idsPreviewCommand(ids: number[]): string {
+ return `gbrain jobs authorize-legacy --ids ${ids.join(',')}`;
+}
+
+function selectionInvalid(message: string, hint: string) {
+ return catalogueError('legacy_job_selection_invalid', message, hint);
+}
export function parseLegacyJobIds(raw: string | undefined): number[] {
- if (!raw || !/^\d+(,\d+)*$/.test(raw)) throw new Error('authorize-legacy requires --ids <id,id,...>; implicit/all-job approval is unavailable');
+ if (!raw || !/^\d+(,\d+)*$/.test(raw)) {
+ throw selectionInvalid('authorize-legacy requires --ids <id,id,...> or --select <filter>; implicit/all-job approval is unavailable.',
+ `${IDS_EXAMPLE}, or gbrain jobs authorize-legacy --select "status=waiting"`);
+ }
const ids = [...new Set(raw.split(',').map(Number))].sort((a, b) => a - b);
- if (ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error('job ids must be positive safe integers');
+ if (ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw selectionInvalid('Job ids must be positive safe integers.', IDS_EXAMPLE);
return ids;
}
-async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
+async function snapshot(engine: BrainEngine, ids: number[], lock: boolean, previewCommand: string) {
// The controlled cutover normally has no producers. Lock the graph table on
// apply as well so a descendant insertion/reparent cannot race the CAS.
if (lock) {
@@ -19,16 +39,20 @@ async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
const jobs = await engine.executeRaw<Record<string, unknown>>(
`SELECT *, submission_authority IS NULL AS legacy_authority_is_null
FROM minion_jobs WHERE id = ANY($1::int[]) ORDER BY id${lock ? ' FOR UPDATE' : ''}`, [ids]);
- if (jobs.length !== ids.length) throw new Error('One or more selected jobs no longer exist');
+ if (jobs.length !== ids.length) {
+ const found = new Set(jobs.map(job => Number(job.id)));
+ throw selectionInvalid(`Selected jobs no longer exist: ${ids.filter(id => !found.has(id)).slice(0, 10).join(', ')}.`, `Re-run the preview: ${previewCommand}`);
+ }
// JSONB null also decodes to JS null. Only the SQL NULL left by the cutover
// represents historical provenance; never downgrade unknown/versioned authority.
- if (jobs.some(job => job.legacy_authority_is_null !== true)) {
- throw new Error('Every selected job must have SQL NULL submission authority. For unsupported non-NULL authority, use matching application/database versions or explicitly cancel the job locally.');
+ const unsupported = jobs.filter(job => job.legacy_authority_is_null !== true).map(job => Number(job.id));
+ if (unsupported.length) {
+ throw selectionInvalid(`Every selected job must have SQL NULL submission authority; jobs ${unsupported.slice(0, 10).join(', ')} carry unsupported non-NULL authority.`,
+ `Run matching application and database versions, or cancel them locally: ${unsupported.slice(0, 10).map(id => `gbrain jobs cancel ${id}`).join('; ')}.`);
}
- const [active] = await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM minion_jobs WHERE status = 'active'");
// The controlled upgrade drains before review. Recovery decisions belong to
// the local operator, never an implicit status/retry rewrite in this command.
- if (Number(active?.count ?? 0)) throw new Error('Drain or cancel all active jobs and stop producers/workers before authorizing legacy jobs');
+ await assertNoActiveJobs(engine, previewCommand);
const graph = await engine.executeRaw<Record<string, unknown>>(
`WITH RECURSIVE connected(id) AS (
SELECT id FROM minion_jobs WHERE id = ANY($1::int[])
@@ -42,12 +66,12 @@ async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
// fields prove authority. The operator is approving the actual historical work.
const sources = await engine.executeRaw<Record<string, unknown>>('SELECT id, local_path, config, archived, created_at FROM sources ORDER BY id');
const version = await engine.getConfig('version');
- const digest = authorityDigest({ preview_version: 1, authority_version: 1, version, jobs, dependencies, sources });
+ const digest = previewHash({ preview_version: 1, authority_version: 1, version, jobs, dependencies, sources });
return {
preview_version: 1 as const, authority_version: 1 as const, snapshot_digest: digest,
jobs: jobs.map(job => ({
id: job.id, name: job.name, status: job.status, data: job.data, previous_authority: job.submission_authority,
- data_digest: authorityDigest(job.data), parent_job_id: job.parent_job_id,
+ data_digest: previewHash(job.data), parent_job_id: job.parent_job_id,
delay_until: job.delay_until, attempts_made: job.attempts_made,
})),
// Full recursive graph, including payload and failure policy, makes downstream
@@ -64,17 +88,91 @@ async function snapshot(engine: BrainEngine, ids: number[], lock: boolean) {
};
}
-export async function authorizeLegacyJobs(engine: BrainEngine, ids: number[], expected?: string, yes = false) {
- if (ids.length === 0 || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw new Error('Explicit positive job ids required');
- if (!yes && expected === undefined) return { ...(await snapshot(engine, ids, false)), applied: false, authorized: 0 };
- if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) throw new Error('Apply requires BOTH --expect <preview snapshot_digest> and --yes');
+export async function authorizeLegacyJobs(engine: BrainEngine, ids: number[], expected?: string, yes = false, previewCommand = idsPreviewCommand(ids)) {
+ if (ids.length === 0 || ids.some(id => !Number.isSafeInteger(id) || id <= 0)) throw selectionInvalid('Explicit positive job ids are required.', IDS_EXAMPLE);
+ if (!yes && expected === undefined) return { ...(await snapshot(engine, ids, false, previewCommand)), applied: false, authorized: 0 };
+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) {
+ throw selectionInvalid('Apply requires BOTH --expect <preview snapshot_digest> and --yes.',
+ expected && /^[a-f0-9]{64}$/.test(expected) ? `${previewCommand} --expect ${expected} --yes` : `Preview first: ${previewCommand}`);
+ }
return engine.transaction(async tx => {
- const preview = await snapshot(tx, ids, true);
- if (preview.snapshot_digest !== expected) throw new Error('Legacy authorization snapshot changed; preview and review again');
+ const preview = await snapshot(tx, ids, true, previewCommand);
+ if (preview.snapshot_digest !== expected) {
+ throw catalogueError('preview_changed', `Legacy authorization snapshot changed since ${expected}; re-run ${previewCommand} and use the new hash.`,
+ `Re-run the preview: ${previewCommand}`);
+ }
const changed = await tx.executeRaw<{ id: number }>(
`UPDATE minion_jobs SET submission_authority = $2::jsonb
WHERE id = ANY($1::int[]) AND submission_authority IS NULL RETURNING id`, [ids, APPLICATION_AUTHORITY]);
- if (changed.length !== ids.length) throw new Error('Legacy authorization CAS failed; no jobs authorized');
+ if (changed.length !== ids.length) throw previewChangedError(expected, previewCommand);
return { ...preview, applied: true, authorized: changed.length };
});
}
+
+interface ApprovedLegacySelection { selection: string; ids: number[]; snapshot_digest: string }
+
+export interface LegacySelectionPreview {
+ selection: string;
+ preview_command: string;
+ /** Selected rows with SQL NULL authority: the set an apply authorizes. */
+ summary: SelectionSummary;
+ /** Matching live rows whose non-NULL authority is unsupported; never authorizable. */
+ unsupported_ids: number[];
+ /** The hash `--expect` takes: the filter plus the snapshot digest the apply re-checks. */
+ preview_hash: string | null;
+ apply_command: string | null;
+ startup_blocking_dependency_count: number;
+ snapshot: Awaited<ReturnType<typeof snapshot>> | null;
+ applied: false;
+}
+
+/**
+ * `gbrain jobs authorize-legacy --select <filter>`: lists every matching SQL
+ * NULL row, hashes the same snapshot `--ids` reviews and saves the exact id
+ * set under that hash, so `--expect <hash> --yes` approves exactly it.
+ */
+export async function previewLegacySelection(engine: BrainEngine, selection: LegacyJobSelection): Promise<LegacySelectionPreview> {
+ const previewCommand = selectCommand('authorize-legacy', selection);
+ const rows = await engine.executeRaw<{ id: number; name: string; status: string; submission_authority: unknown; legacy_authority_is_null: boolean }>(
+ `SELECT id, name, status, submission_authority, submission_authority IS NULL AS legacy_authority_is_null
+ FROM minion_jobs
+ WHERE status = ANY($1::text[]) AND (cardinality($2::text[]) = 0 OR name = ANY($2::text[]))
+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb
+ ORDER BY id`, [selectedStatuses('authorize-legacy', selection), selection.names]);
+ const legacy = rows.filter(row => row.legacy_authority_is_null === true);
+ const unsupported_ids = rows.filter(row => row.legacy_authority_is_null !== true && !parseSubmissionAuthority(row.submission_authority)).map(row => Number(row.id));
+ const base = { selection: formatSelection(selection), preview_command: previewCommand, summary: summarizeSelection(legacy), unsupported_ids, applied: false as const };
+ if (!legacy.length) return { ...base, preview_hash: null, apply_command: null, startup_blocking_dependency_count: 0, snapshot: null };
+ const ids = legacy.map(row => Number(row.id));
+ const preview = await snapshot(engine, ids, false, previewCommand);
+ // The approval hash binds the filter as well as the snapshot, so two filters
+ // that happen to select the same rows never overwrite each other's set.
+ const hash = previewHash({ selection: base.selection, snapshot_digest: preview.snapshot_digest });
+ await saveApprovedSet<ApprovedLegacySelection>(engine, { command: 'authorize-legacy', hash }, [{ selection: base.selection, ids, snapshot_digest: preview.snapshot_digest }]);
+ return {
+ ...base, preview_hash: hash, apply_command: selectCommand('authorize-legacy', selection, hash),
+ startup_blocking_dependency_count: preview.effects.startup_blocking_dependency_ids.length, snapshot: preview,
+ };
+}
+
+/** `--select <filter> --expect <hash> --yes`: authorizes exactly the set the preview saved under `hash`, or refuses whole. */
+export async function applyLegacySelection(engine: BrainEngine, selection: LegacyJobSelection, expected: string | undefined, yes: boolean) {
+ const previewCommand = selectCommand('authorize-legacy', selection);
+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) {
+ throw selectionInvalid('Apply requires BOTH --expect <preview hash> and --yes.',
+ expected && /^[a-f0-9]{64}$/.test(expected) ? selectCommand('authorize-legacy', selection, expected) : `Preview first: ${previewCommand}`);
+ }
+ const approved = await loadApprovedSet<ApprovedLegacySelection>(engine, { command: 'authorize-legacy', hash: expected, previewCommand });
+ const [item] = approved.items;
+ if (!item || item.selection !== formatSelection(selection) || !item.ids.length || !item.snapshot_digest) throw previewChangedError(expected, previewCommand);
+ let result;
+ try {
+ result = await authorizeLegacyJobs(engine, item.ids, item.snapshot_digest, true, previewCommand);
+ } catch (error) {
+ if (error instanceof OperationError && error.code === 'preview_changed') throw previewChangedError(expected, previewCommand);
+ throw error;
+ }
+ await clearApprovedSet(engine, { command: 'authorize-legacy', hash: expected });
+ return { selection: item.selection, authorized_ids: item.ids, ...result };
+}
+
diff --git a/src/core/minions/idempotency-coalesce.ts b/src/core/minions/idempotency-coalesce.ts
new file mode 100644
index 0000000000..289475d2c4
--- /dev/null
+++ b/src/core/minions/idempotency-coalesce.ts
@@ -0,0 +1,78 @@
+/**
+ * The idempotency-key halves of `MinionQueue.add` (#5157 / #5114): the fast
+ * path before any other admission work and the insert-race resolution after
+ * `ON CONFLICT DO NOTHING`. Both apply `coalesceDecision` to the raw row, so
+ * SQL NULL authority stays distinguishable from JSONB null.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { ERROR_CATALOGUE } from '../error-catalogue.ts';
+import { OperationError } from '../ops/contract.ts';
+import { LEGACY_AUTHORITY_COLUMN, coalesceDecision, legacyJobAuthorityError, type SubmissionAuthority } from './submission-authority.ts';
+import { rowToMinionJob, type MinionJob } from './types.ts';
+
+/**
+ * `coalesceDecision`, with a legacy refusal's hint naming the active job ids
+ * to cancel first, so the printed recovery runs verbatim.
+ */
+export async function decideCoalesce(tx: BrainEngine, row: Record<string, unknown>, authority: SubmissionAuthority): Promise<'coalesce' | 'release'> {
+ try {
+ return coalesceDecision(row, authority);
+ } catch (error) {
+ if (!(error instanceof OperationError) || error.docs !== ERROR_CATALOGUE.legacy_job_authority.docs) throw error;
+ const active = await tx.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status = 'active' ORDER BY id LIMIT 10");
+ throw legacyJobAuthorityError(row, active.map(job => Number(job.id)));
+ }
+}
+
+const KEYED_ROW_SQL = `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobs WHERE idempotency_key = $1`;
+
+function coalescedJob(row: Record<string, unknown>): MinionJob {
+ const job = rowToMinionJob(row);
+ job.coalesced = true;
+ return job;
+}
+
+/**
+ * Frees a dead or cancelled row's idempotency key so a fresh attempt can be
+ * inserted, keeping the released key in its data for the dream breaker. The
+ * update rechecks the key, the terminal status and the SQL NULL-ness of the
+ * authority it was decided on, so a row reviewed or resubmitted in between
+ * keeps its key and the caller's insert conflicts into the race path instead.
+ */
+async function releaseIdempotencyKey(tx: BrainEngine, row: Record<string, unknown>, key: string): Promise<void> {
+ await tx.executeRaw(
+ `UPDATE minion_jobs SET idempotency_key = NULL, data = data || $2::text::jsonb
+ WHERE id = $1 AND idempotency_key = $3 AND status IN ('dead','cancelled')
+ AND (submission_authority IS NULL) = $4::boolean`,
+ [row.id, JSON.stringify({ __released_idempotency_key: key }), key, row.legacy_authority_is_null === true],
+ );
+}
+
+/** Fast path: the row already holding `key`, coalesced, or null once a releasable key was freed (or none exists). */
+export async function coalesceOnIdempotencyKey(tx: BrainEngine, key: string, authority: SubmissionAuthority): Promise<MinionJob | null> {
+ const [existing] = await tx.executeRaw<Record<string, unknown>>(KEYED_ROW_SQL, [key]);
+ if (!existing) return null;
+ if (await decideCoalesce(tx, existing, authority) === 'coalesce') return coalescedJob(existing);
+ await releaseIdempotencyKey(tx, existing, key);
+ return null;
+}
+
+/**
+ * Runs the INSERT; when `ON CONFLICT DO NOTHING` returns no row, re-reads the
+ * winner and applies the same rule. A dead or cancelled winner has its key
+ * released and the insert is retried once in the same transaction.
+ */
+export async function insertOrCoalesce(
+ tx: BrainEngine, insertSql: string, params: unknown[], key: string | undefined, authority: SubmissionAuthority,
+): Promise<{ inserted: Record<string, unknown> } | { coalesced: MinionJob }> {
+ let [inserted] = await tx.executeRaw<Record<string, unknown>>(insertSql, params);
+ for (let retried = false; !inserted && key; retried = true) {
+ const [winner] = await tx.executeRaw<Record<string, unknown>>(KEYED_ROW_SQL, [key]);
+ if (!winner) throw new Error(`idempotency_key ${key} insert returned no row and no existing row found`);
+ if (await decideCoalesce(tx, winner, authority) === 'coalesce') return { coalesced: coalescedJob(winner) };
+ if (retried) throw new Error(`idempotency_key ${key} was released but the retried insert still conflicted`);
+ await releaseIdempotencyKey(tx, winner, key);
+ [inserted] = await tx.executeRaw<Record<string, unknown>>(insertSql, params);
+ }
+ return { inserted: inserted! };
+}
diff --git a/src/core/minions/legacy-cancel.ts b/src/core/minions/legacy-cancel.ts
new file mode 100644
index 0000000000..ca3882d83d
--- /dev/null
+++ b/src/core/minions/legacy-cancel.ts
@@ -0,0 +1,115 @@
+/**
+ * `gbrain jobs cancel --select <filter>` (DX-T2, ENG-O5): bulk cancellation
+ * of the live rows the claim gate blocks on (SQL NULL or unsupported
+ * authority), preview-bound like `authorize-legacy --select`.
+ *
+ * The preview hashes the complete cancellation closure `cancelJobs` would
+ * produce: the selected rows, and the parents that return from
+ * waiting-children to waiting once their last open child is cancelled. A
+ * selection whose closure would also cancel a descendant outside the
+ * selected set refuses (E-T4), naming those ids. The apply recomputes the
+ * closure under a table lock, refuses with `preview_changed` if its hash
+ * moved, and cancels through `cancelJobs` in the same transaction.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { MinionQueue } from './queue.ts';
+import { LIVE_JOB_STATUSES, parseSubmissionAuthority } from './submission-authority.ts';
+import type { MinionJobStatus } from './types.ts';
+import {
+ assertNoActiveJobs, formatSelection, selectCommand, selectedStatuses, summarizeSelection,
+ type LegacyJobSelection, type SelectionSummary,
+} from './legacy-selection.ts';
+
+export const LEGACY_CANCEL_REASON = 'legacy_review: cancelled by gbrain jobs cancel --select';
+
+interface ClosureRow { id: number; name: string; status: string; parent_job_id: number | null; updated_at: unknown; submission_authority: unknown; legacy_authority_is_null: boolean }
+
+async function cancelClosure(engine: BrainEngine, selection: LegacyJobSelection) {
+ const previewCommand = selectCommand('cancel', selection);
+ await assertNoActiveJobs(engine, previewCommand);
+ const candidates = await engine.executeRaw<ClosureRow>(
+ `SELECT id, name, status, parent_job_id, updated_at, submission_authority, submission_authority IS NULL AS legacy_authority_is_null
+ FROM minion_jobs
+ WHERE status = ANY($1::text[]) AND (cardinality($2::text[]) = 0 OR name = ANY($2::text[]))
+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb
+ ORDER BY id`, [selectedStatuses('cancel', selection), selection.names]);
+ const rows = candidates.filter(row => !parseSubmissionAuthority(row.submission_authority));
+ const ids = rows.map(row => Number(row.id));
+ // The same recursion cancelJobs runs: every live descendant of a selected root.
+ const outside = ids.length ? await engine.executeRaw<{ id: number }>(
+ `WITH RECURSIVE descendants AS (
+ SELECT id, 0 AS d FROM minion_jobs WHERE id = ANY($1::int[])
+ UNION ALL
+ SELECT m.id, descendants.d + 1 FROM minion_jobs m JOIN descendants ON m.parent_job_id = descendants.id WHERE descendants.d < 100
+ ) SELECT DISTINCT j.id FROM minion_jobs j
+ WHERE j.id IN (SELECT id FROM descendants) AND NOT (j.id = ANY($1::int[]))
+ AND j.status = ANY($2::text[])
+ ORDER BY j.id`, [ids, [...LIVE_JOB_STATUSES]]) : [];
+ if (outside.length) {
+ const named = outside.slice(0, 10).map(row => Number(row.id));
+ throw catalogueError('legacy_job_selection_invalid',
+ `Cancelling the selection would also cancel ${outside.length} descendant job(s) outside it: ${named.join(', ')}${outside.length > 10 ? ' …' : ''}.`,
+ `Cancel them on purpose first (${named.map(id => `gbrain jobs cancel ${id}`).join('; ')}) or widen the filter to select them, then re-run ${previewCommand}.`);
+ }
+ const parents = [...new Set(rows.map(row => row.parent_job_id).filter((id): id is number => id != null && !ids.includes(Number(id))))];
+ const transitions = parents.length ? await engine.executeRaw<{ id: number }>(
+ `SELECT p.id FROM minion_jobs p
+ WHERE p.id = ANY($1::int[]) AND p.status = 'waiting-children'
+ AND NOT EXISTS (SELECT 1 FROM minion_jobs c WHERE c.parent_job_id = p.id
+ AND c.status NOT IN ('completed','failed','dead','cancelled') AND NOT (c.id = ANY($2::int[])))
+ ORDER BY p.id`, [parents, ids]) : [];
+ const parent_transitions = transitions.map(row => ({ id: Number(row.id), from: 'waiting-children', to: 'waiting' }));
+ const hash = previewHash({ preview_version: 1, command: 'jobs-cancel', selection: formatSelection(selection), rows, parent_transitions });
+ return { previewCommand, rows, ids, parent_transitions, hash };
+}
+
+export interface LegacyCancelPreview {
+ selection: string;
+ preview_command: string;
+ summary: SelectionSummary;
+ /** Selected rows whose non-NULL authority is unsupported (also cancelled). */
+ unsupported_ids: number[];
+ parent_transitions: Array<{ id: number; from: string; to: string }>;
+ preview_hash: string | null;
+ apply_command: string | null;
+ rows: ClosureRow[];
+ applied: false;
+}
+
+interface ApprovedCancel { selection: string; ids: number[] }
+
+/** Preview: lists and hashes the closure, saves the exact id set under that hash. Changes no job. */
+export async function previewLegacyCancel(engine: BrainEngine, selection: LegacyJobSelection): Promise<LegacyCancelPreview> {
+ const closure = await cancelClosure(engine, selection);
+ const base = {
+ selection: formatSelection(selection), preview_command: closure.previewCommand, summary: summarizeSelection(closure.rows),
+ unsupported_ids: closure.rows.filter(row => row.legacy_authority_is_null !== true).map(row => Number(row.id)),
+ parent_transitions: closure.parent_transitions, rows: closure.rows, applied: false as const,
+ };
+ if (!closure.ids.length) return { ...base, preview_hash: null, apply_command: null };
+ await saveApprovedSet<ApprovedCancel>(engine, { command: 'jobs-cancel', hash: closure.hash }, [{ selection: base.selection, ids: closure.ids }]);
+ return { ...base, preview_hash: closure.hash, apply_command: selectCommand('cancel', selection, closure.hash) };
+}
+
+/** Apply: cancels exactly the previewed closure through cancelJobs in one transaction, or refuses whole. */
+export async function applyLegacyCancel(engine: BrainEngine, selection: LegacyJobSelection, expected: string | undefined, yes: boolean) {
+ const previewCommand = selectCommand('cancel', selection);
+ if (!yes || !expected || !/^[a-f0-9]{64}$/.test(expected)) {
+ throw catalogueError('legacy_job_selection_invalid', 'Apply requires BOTH --expect <preview hash> and --yes.',
+ expected && /^[a-f0-9]{64}$/.test(expected) ? selectCommand('cancel', selection, expected) : `Preview first: ${previewCommand}`);
+ }
+ const approved = await loadApprovedSet<ApprovedCancel>(engine, { command: 'jobs-cancel', hash: expected, previewCommand });
+ const [item] = approved.items;
+ if (!item || item.selection !== formatSelection(selection) || !item.ids.length) throw previewChangedError(expected, previewCommand);
+ return engine.transaction(async tx => {
+ await tx.executeRaw('LOCK TABLE minion_jobs IN SHARE ROW EXCLUSIVE MODE');
+ const closure = await cancelClosure(tx, selection);
+ if (closure.hash !== expected || previewHash(closure.ids) !== previewHash(item.ids)) throw previewChangedError(expected, previewCommand);
+ const cancelled = await new MinionQueue(tx).cancelJobs(closure.ids, { reason: LEGACY_CANCEL_REASON, rootStatuses: selectedStatuses('cancel', selection) as MinionJobStatus[] });
+ if (cancelled.length !== closure.ids.length) throw previewChangedError(expected, previewCommand);
+ await clearApprovedSet(tx, { command: 'jobs-cancel', hash: expected });
+ return { selection: item.selection, cancelled_ids: closure.ids, parent_transitions: closure.parent_transitions, applied: true as const };
+ });
+}
diff --git a/src/core/minions/legacy-selection.ts b/src/core/minions/legacy-selection.ts
new file mode 100644
index 0000000000..023c3b64b0
--- /dev/null
+++ b/src/core/minions/legacy-selection.ts
@@ -0,0 +1,128 @@
+/**
+ * Preview-bound bulk selection of legacy job rows (#5157 T3, DX-T2): the
+ * `--select` grammar, the active-job precondition and the preview summary
+ * shared by `gbrain jobs authorize-legacy --select` and `gbrain jobs cancel
+ * --select`. Both are CLI-only: neither is an operation, so MCP and
+ * remediation can never run them.
+ *
+ * Grammar: `--select "status=<s>[|<s>…],name=<job-name>[|<name>…]"`, keys
+ * `status` and `name`, at least one key. A missing `status` key means every
+ * status the command handles.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { catalogueError } from '../error-catalogue.ts';
+
+export type LegacySelectCommand = 'authorize-legacy' | 'cancel';
+
+export interface LegacyJobSelection {
+ /** Statuses as given (deduplicated); empty means every status the command handles. */
+ statuses: string[];
+ names: string[];
+}
+
+/** Statuses each command handles. Active rows are never selected: they refuse with `legacy_jobs_active`. */
+export const SELECT_STATUSES: Record<LegacySelectCommand, readonly string[]> = {
+ 'authorize-legacy': ['waiting', 'delayed', 'waiting-children', 'paused', 'completed', 'failed'],
+ cancel: ['waiting', 'delayed', 'waiting-children', 'paused'],
+};
+
+export const SELECT_EXAMPLE: Record<LegacySelectCommand, string> = {
+ 'authorize-legacy': 'status=waiting|paused,name=synthesize|ingest_capture',
+ cancel: 'status=waiting|paused,name=synthesize',
+};
+
+export function formatSelection(selection: LegacyJobSelection): string {
+ return [
+ selection.statuses.length ? `status=${selection.statuses.join('|')}` : '',
+ selection.names.length ? `name=${selection.names.join('|')}` : '',
+ ].filter(Boolean).join(',');
+}
+
+/** The filled preview command, or the apply command when `hash` is given. */
+export function selectCommand(command: LegacySelectCommand, selection: LegacyJobSelection, hash?: string): string {
+ const preview = `gbrain jobs ${command} --select "${formatSelection(selection)}"`;
+ return hash ? `${preview} --expect ${hash} --yes` : preview;
+}
+
+/** The statuses a selection covers. */
+export function selectedStatuses(command: LegacySelectCommand, selection: LegacyJobSelection): string[] {
+ return selection.statuses.length ? selection.statuses : [...SELECT_STATUSES[command]];
+}
+
+export function parseLegacyJobSelection(raw: string | undefined, command: LegacySelectCommand): LegacyJobSelection {
+ const invalid = (what: string) => catalogueError('legacy_job_selection_invalid',
+ `${what}; --select takes the keys status and name, with statuses ${SELECT_STATUSES[command].join('|')}.`,
+ `gbrain jobs ${command} --select "${SELECT_EXAMPLE[command]}"`);
+ if (!raw?.trim()) throw invalid('--select needs a filter');
+ const selection: LegacyJobSelection = { statuses: [], names: [] };
+ const seen = new Set<string>();
+ for (const part of raw.split(',')) {
+ const eq = part.indexOf('=');
+ const key = (eq < 0 ? part : part.slice(0, eq)).trim();
+ if (key !== 'status' && key !== 'name') throw invalid(`Unknown --select key "${key}"`);
+ if (seen.has(key)) throw invalid(`--select names the key "${key}" twice`);
+ seen.add(key);
+ const values = eq < 0 ? [''] : part.slice(eq + 1).split('|').map(value => value.trim());
+ if (values.some(value => !value)) throw invalid(`--select key "${key}" needs a value for every | alternative`);
+ if (key === 'status') {
+ const unknown = values.find(value => !SELECT_STATUSES[command].includes(value));
+ if (unknown) throw invalid(`Unknown --select status "${unknown}"`);
+ selection.statuses = [...new Set(values)];
+ } else {
+ selection.names = [...new Set(values)];
+ }
+ }
+ return selection;
+}
+
+/** Shared stop instruction for every legacy-job refusal (ENG-O4: active jobs are cancelled, never finished). */
+export const STOP_PRODUCERS = 'Stop producers (gbrain serve, gbrain autopilot) and workers';
+
+/** Every live status a legacy review can authorize: one preview then covers what a required cancellation leaves behind. */
+export const REVIEWABLE_LIVE_STATUSES = ['waiting', 'delayed', 'waiting-children', 'paused'] as const;
+
+/** The filled preview that reviews every live SQL NULL row the claim gate blocks on. */
+export const LIVE_LEGACY_PREVIEW = selectCommand('authorize-legacy', { statuses: [...REVIEWABLE_LIVE_STATUSES], names: [] });
+
+/**
+ * The recovery order every legacy refusal names (DX-O3(b)): stop producers
+ * and workers, cancel active jobs, preview every reviewable live status (a
+ * cancellation can move a parent from waiting-children to waiting, so a
+ * filter built from today's statuses could miss it), apply with the printed
+ * hash, restart.
+ */
+export function legacyRecoveryHint(activeIds: readonly number[] = []): string {
+ const cancels = activeIds.length ? activeIds.slice(0, 10).map(id => `gbrain jobs cancel ${id}`).join('; ') : 'gbrain jobs cancel <id>';
+ return `${STOP_PRODUCERS}, cancel active jobs (${cancels}), preview with ${LIVE_LEGACY_PREVIEW}, apply with the printed --expect <hash> --yes, then restart them.`;
+}
+
+/** `legacy_jobs_active`: legacy rows are reviewed only with nothing active. Lists up to 10 ids to cancel. */
+export async function assertNoActiveJobs(engine: BrainEngine, previewCommand: string): Promise<void> {
+ const active = await engine.executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE status = 'active' ORDER BY id LIMIT 11");
+ if (!active.length) return;
+ const [total] = active.length > 10
+ ? await engine.executeRaw<{ count: string }>("SELECT count(*)::text AS count FROM minion_jobs WHERE status = 'active'")
+ : [{ count: String(active.length) }];
+ const cancels = active.slice(0, 10).map(row => `gbrain jobs cancel ${row.id}`).join('; ');
+ const more = active.length > 10 ? `; list the rest with gbrain jobs list --status active` : '';
+ throw catalogueError('legacy_jobs_active',
+ `${total!.count} job(s) are active, so legacy jobs cannot be reviewed until producers and workers are stopped and active jobs are cancelled.`,
+ `${STOP_PRODUCERS}, cancel the active jobs (${cancels}${more}), then re-run ${previewCommand}.`);
+}
+
+export interface SelectionSummary {
+ total: number;
+ /** Counts by job name, then status. */
+ by_name: Record<string, Record<string, number>>;
+ first_ids: number[];
+}
+
+/** DX-O3(d): counts by job name and status plus the first 20 ids; the full rows stay in `--json`. */
+export function summarizeSelection(rows: ReadonlyArray<{ id: unknown; name: unknown; status: unknown }>): SelectionSummary {
+ const by_name: Record<string, Record<string, number>> = {};
+ for (const row of rows) {
+ const counts = by_name[String(row.name)] ??= {};
+ counts[String(row.status)] = (counts[String(row.status)] ?? 0) + 1;
+ }
+ return { total: rows.length, by_name, first_ids: rows.slice(0, 20).map(row => Number(row.id)) };
+}
diff --git a/src/core/minions/queue.ts b/src/core/minions/queue.ts
index 89adbabfcb..712459815d 100644
--- a/src/core/minions/queue.ts
+++ b/src/core/minions/queue.ts
@@ -8,13 +8,14 @@
* await queue.prune({ olderThan: new Date(Date.now() - 30 * 86400000) });
*/
-import { APPLICATION_AUTHORITY, assertSameAuthority, assertNoUnreviewedJobs, authorizeJobExecution, currentSubmissionAuthority, parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';
+import { APPLICATION_AUTHORITY, LEGACY_AUTHORITY_COLUMN, assertNoUnreviewedJobs, authorizeJobExecution, currentSubmissionAuthority, parseSubmissionAuthority, type SubmissionAuthority } from './submission-authority.ts';
import type { BrainEngine } from '../engine.ts';
import type {
MinionJob, MinionJobInput, MinionJobStatus, InboxMessage, TokenUpdate,
MinionQueueOpts, ChildDoneMessage, ChildOutcome, Attachment, AttachmentInput,
} from './types.ts';
import { rowToMinionJob, rowToInboxMessage, rowToAttachment } from './types.ts';
+import { coalesceOnIdempotencyKey, decideCoalesce, insertOrCoalesce } from './idempotency-coalesce.ts';
import { validateAttachment } from './attachments.ts';
import { isProtectedJobName } from './protected-names.ts';
import { assertEmbedBackfillQueueAdmission } from './embed-backfill-admission.ts';
@@ -162,19 +163,21 @@ type CoalesceAuditEvent = {
* audit append is filesystem I/O, and doing it while holding the advisory
* lock + a pool connection would let a hung audit volume serialize every
* submission for the scope (adversarial-review finding). */
-function coalesceReturn(
+async function coalesceReturn(
+ tx: BrainEngine,
row: Record<string, unknown>,
audit: Omit<CoalesceAuditEvent, 'returned_job_id'>,
sink: (ev: CoalesceAuditEvent) => void,
authority: SubmissionAuthority,
-): MinionJob {
- assertSameAuthority(row.submission_authority, authority);
+): Promise<MinionJob> {
+ if (await decideCoalesce(tx, row, authority) !== 'coalesce') throw new Error(`job ${String(row.id)} is ${String(row.status)} and cannot be a coalesce target`);
const coalesced = rowToMinionJob(row);
coalesced.coalesced = true;
sink({ ...audit, returned_job_id: coalesced.id });
return coalesced;
}
+
export class MinionQueue {
readonly maxSpawnDepth: number;
readonly maxAttachmentBytes: number;
@@ -345,23 +348,8 @@ export class MinionQueue {
// We NULL the key (preserving the row, with the released key in its
// data for the dream breaker) and fall through to the INSERT below.
if (opts?.idempotency_key) {
- const existing = await tx.executeRaw<Record<string, unknown>>(
- `SELECT * FROM minion_jobs WHERE idempotency_key = $1`,
- [opts.idempotency_key]
- );
- if (existing.length > 0) {
- const existingJob = rowToMinionJob(existing[0]);
- assertSameAuthority(existingJob.submission_authority, authority);
- if (existingJob.status === 'dead' || existingJob.status === 'cancelled') {
- await tx.executeRaw(
- `UPDATE minion_jobs SET idempotency_key = NULL, data = data || $2::text::jsonb WHERE id = $1`,
- [existingJob.id, JSON.stringify({ __released_idempotency_key: opts.idempotency_key })]
- );
- } else {
- existingJob.coalesced = true;
- return existingJob;
- }
- }
+ const existing = await coalesceOnIdempotencyKey(tx, opts.idempotency_key, authority);
+ if (existing) return existing;
}
// 1a. Param-coalescing (admission): an identical parentless submit —
@@ -390,7 +378,7 @@ export class MinionQueue {
const matchParams: unknown[] = [jobName, admissionQueue, paramHash];
if (ttlHours != null) matchParams.push(ttlHours / 2);
const match = await tx.executeRaw<Record<string, unknown>>(
- `SELECT * FROM minion_jobs
+ `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobs
WHERE name = $1 AND queue = $2 AND status = 'waiting'
AND parent_job_id IS NULL
AND data->>'__param_hash' = $3
@@ -400,7 +388,7 @@ export class MinionQueue {
matchParams
);
if (match.length > 0) {
- return coalesceReturn(match[0], {
+ return coalesceReturn(tx, match[0], {
queue: admissionQueue,
name: jobName,
param_hash: paramHash,
@@ -501,7 +489,7 @@ export class MinionQueue {
const pendingCount = parseInt(pendingCountRows[0]?.count ?? '0', 10);
if (pendingCount >= maxPending) {
const existingPending = await tx.executeRaw<Record<string, unknown>>(
- `SELECT * FROM minion_jobs
+ `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobs
WHERE name = $1 AND queue = $2 AND ${pendingCond}
AND ${scopeExact}
ORDER BY CASE WHEN status = 'waiting' THEN 0 ELSE 1 END, created_at DESC, id DESC
@@ -509,7 +497,7 @@ export class MinionQueue {
[jobName, backpressureQueue, bpSourceId]
);
if (existingPending.length > 0) {
- return coalesceReturn(existingPending[0], {
+ return coalesceReturn(tx, existingPending[0], {
queue: backpressureQueue,
name: jobName,
pending_count: pendingCount,
@@ -531,7 +519,7 @@ export class MinionQueue {
const waitingCount = parseInt(waitingCountRows[0]?.count ?? '0', 10);
if (waitingCount >= maxWaiting) {
const existingWaiting = await tx.executeRaw<Record<string, unknown>>(
- `SELECT * FROM minion_jobs
+ `SELECT *, ${LEGACY_AUTHORITY_COLUMN} FROM minion_jobs
WHERE name = $1 AND queue = $2 AND status = 'waiting'
AND ${scopeWildcard}
ORDER BY created_at DESC, id DESC
@@ -539,7 +527,7 @@ export class MinionQueue {
[jobName, backpressureQueue, bpSourceId]
);
if (existingWaiting.length > 0) {
- return coalesceReturn(existingWaiting[0], {
+ return coalesceReturn(tx, existingWaiting[0], {
queue: backpressureQueue,
name: jobName,
waiting_count: waitingCount,
@@ -660,25 +648,12 @@ export class MinionQueue {
];
if (hasMaxStalled) params.push(clampedMaxStalled);
- const inserted = await tx.executeRaw<Record<string, unknown>>(insertSql, params);
-
- // ON CONFLICT DO NOTHING returns 0 rows — fall back to SELECT to fetch the
- // existing row that won the race.
- if (inserted.length === 0 && opts?.idempotency_key) {
- const existing = await tx.executeRaw<Record<string, unknown>>(
- `SELECT * FROM minion_jobs WHERE idempotency_key = $1`,
- [opts.idempotency_key]
- );
- if (existing.length === 0) {
- throw new Error(`idempotency_key ${opts.idempotency_key} insert returned no row and no existing row found`);
- }
- const raced = rowToMinionJob(existing[0]);
- assertSameAuthority(raced.submission_authority, authority);
- raced.coalesced = true; // third coalesce path: lost the insert race
- return raced;
- }
+ // ON CONFLICT DO NOTHING returns 0 rows: a concurrent submit won the
+ // race, and its row goes through the same coalesce rule (third path).
+ const outcome = await insertOrCoalesce(tx, insertSql, params, opts?.idempotency_key, authority);
+ if ('coalesced' in outcome) return outcome.coalesced;
- const child = rowToMinionJob(inserted[0]);
+ const child = rowToMinionJob(outcome.inserted);
// 4. Flip parent to waiting-children if this is a fresh child insert.
// Only transition from non-terminal, non-already-waiting-children states.
diff --git a/src/core/minions/submission-authority.ts b/src/core/minions/submission-authority.ts
index 50506adbb7..f7c0b51b56 100644
--- a/src/core/minions/submission-authority.ts
+++ b/src/core/minions/submission-authority.ts
@@ -5,6 +5,8 @@ import { realpathSync, statSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import type { AuthInfo, OperationContext } from '../ops/contract.ts';
import { OperationError } from '../ops/contract.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { STOP_PRODUCERS, legacyRecoveryHint, selectCommand } from './legacy-selection.ts';
import { normalizeSlugPrefix } from '../ops/context.ts';
import { hasScope } from '../scope.ts';
import { coerceLegacyPermissions, normalizeTokenScopes, parseLegacyTokenScope } from '../legacy-token-scope.ts';
@@ -266,12 +268,67 @@ export async function assertRemoteJobControl(ctx: OperationContext, job: MinionJ
await authorizeJobExecution(ctx.engine, job);
}
+/** Statuses the claim gate covers: a row in one of them blocks every worker while its authority is unparsable. */
+export const LIVE_JOB_STATUSES = ['waiting', 'active', 'delayed', 'waiting-children', 'paused'] as const;
+
+/**
+ * The claim gate's population predicate, shared by `assertNoUnreviewedJobs`
+ * and the doctor `legacy_job_authority` check so their counts can never drift.
+ * Callers keep the rows `parseSubmissionAuthority` rejects.
+ */
+export const UNREVIEWED_LIVE_JOBS_WHERE = `status IN (${LIVE_JOB_STATUSES.map(s => `'${s}'`).join(',')})
+ AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb`;
+
+/** Select-list column every coalesce read adds so SQL NULL stays distinguishable from JSONB null. */
+export const LEGACY_AUTHORITY_COLUMN = 'submission_authority IS NULL AS legacy_authority_is_null';
+
+/** `permission_denied` for a job row whose SQL NULL authority predates the v0.50 cutover. */
+export function legacyJobAuthorityError(row: Record<string, unknown>, activeIds: readonly number[] = []): OperationError {
+ const id = String(row.id), name = String(row.name), status = String(row.status);
+ const what = `Queued job authorization: job ${id} (${name}, ${status}) has no submission authority because it predates the upgrade, so it cannot be reused until it is reviewed.`;
+ if (status === 'completed' || status === 'failed') {
+ return catalogueError('legacy_job_authority', what,
+ `Resubmit with a new idempotency key; a local operator can review the old row with ${selectCommand('authorize-legacy', { statuses: [status], names: [name] })}.`);
+ }
+ if (status === 'active') {
+ return catalogueError('legacy_job_authority', what, `${STOP_PRODUCERS}, then cancel it: gbrain jobs cancel ${id}; run gbrain doctor to review the rest.`);
+ }
+ return catalogueError('legacy_job_authority', what, legacyRecoveryHint(activeIds));
+}
+
+const RELEASABLE = new Set(['dead', 'cancelled']);
+
+/**
+ * The one coalesce rule for `MinionQueue.add` (idempotency fast path, param
+ * coalescing, the pending and waiting caps, and the insert race). `row` is a
+ * raw `minion_jobs` row selected with `LEGACY_AUTHORITY_COLUMN`.
+ *
+ * Only SQL NULL authority (rows from before the v0.50 cutover) gets the
+ * legacy rule: a dead or cancelled key is released, a completed or failed row
+ * coalesces for application callers only, and a live row is refused for every
+ * caller because the claim gate keeps workers from ever running it. JSONB
+ * null, malformed and future-version authority keep the cross-authority
+ * denial, as does any authority that differs from the caller's.
+ */
+export function coalesceDecision(row: Record<string, unknown>, authority: SubmissionAuthority): 'coalesce' | 'release' {
+ const status = String(row.status);
+ if (row.legacy_authority_is_null === true) {
+ if (RELEASABLE.has(status)) return 'release';
+ if ((status === 'completed' || status === 'failed') && authority.kind === 'application') return 'coalesce';
+ throw legacyJobAuthorityError(row);
+ }
+ assertSameAuthority(row.submission_authority, authority);
+ return RELEASABLE.has(status) ? 'release' : 'coalesce';
+}
+
/** Startup and claim gate: do not let sweeps silently destroy unresolved legacy dependency graphs. */
export async function assertNoUnreviewedJobs(engine: BrainEngine): Promise<void> {
const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>(
`SELECT id, submission_authority FROM minion_jobs
- WHERE status IN ('waiting','active','delayed','waiting-children','paused')
- AND submission_authority IS DISTINCT FROM '{"version":1,"kind":"application"}'::jsonb`);
+ WHERE ${UNREVIEWED_LIVE_JOBS_WHERE}`);
const invalid = rows.filter(row => !parseSubmissionAuthority(row.submission_authority));
- if (invalid.length) deny(`${invalid.length} legacy jobs have missing or unsupported authority; stop producers/workers. Review SQL NULL rows with jobs authorize-legacy --ids ...; unsupported non-NULL authority requires matching application/database versions or explicit local cancellation before workers start`);
+ if (!invalid.length) return;
+ throw catalogueError('legacy_job_authority',
+ `Queued job authorization: ${invalid.length} legacy jobs have missing or unsupported authority, so workers cannot start until they are reviewed.`,
+ `${legacyRecoveryHint()} Rows with unsupported non-NULL authority need matching application and database versions, or gbrain jobs cancel <id>; gbrain doctor lists them.`);
}
diff --git a/src/core/model-pricing.ts b/src/core/model-pricing.ts
index 23a4648058..8c53e7e18e 100644
--- a/src/core/model-pricing.ts
+++ b/src/core/model-pricing.ts
@@ -80,6 +80,9 @@ function anthro(input: number, output: number, cacheReadMult = ANTHROPIC_CACHE_R
export const ANTHROPIC_CACHE_READ_MULT_OVERRIDES: Record<string, number> = {
// Fable 5.1 bills cache hits at 0.025x base input ($0.25/MTok on $10).
'anthropic:claude-fable-5-1': 0.025,
+ // Opus 5.5 bills cache hits at 0.05x base input ($0.20/MTok on $4),
+ // verified 2026-10-01 against the published Opus 5.5 price list.
+ 'anthropic:claude-opus-5-5': 0.05,
};
/**
@@ -100,6 +103,9 @@ export const CANONICAL_PRICING: Record<string, ModelPricing> = {
'anthropic:claude-fable-5-1': anthro(10.00, 50.00, ANTHROPIC_CACHE_READ_MULT_OVERRIDES['anthropic:claude-fable-5-1']),
// Opus 4.x/5: $5 in / $25 out. Opus 5 (new generation) shares the same
// per-token rate as 4.8 (released 2026-05-28) — closes gbrain#1819.
+ // Opus 5.5 (released 2026-09-22): $4 in / $20 out, cache writes 1.25x
+ // ($5). Fast mode ($8/$40) is not modeled. Closes gbrain#5359.
+ 'anthropic:claude-opus-5-5': anthro( 4.00, 20.00, ANTHROPIC_CACHE_READ_MULT_OVERRIDES['anthropic:claude-opus-5-5']),
'anthropic:claude-opus-5': anthro( 5.00, 25.00),
'anthropic:claude-opus-4-8': anthro( 5.00, 25.00),
'anthropic:claude-opus-4-7': anthro( 5.00, 25.00),
diff --git a/src/core/op-checkpoint.ts b/src/core/op-checkpoint.ts
index 9ef9c491d4..3e75f3d0bd 100644
--- a/src/core/op-checkpoint.ts
+++ b/src/core/op-checkpoint.ts
@@ -498,7 +498,7 @@ export async function purgeStaleCheckpoints(
`WITH deleted AS (
DELETE FROM op_checkpoints
WHERE updated_at < now() - ($1 || ' days')::interval
- AND op NOT IN ('managed-atoms','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
+ AND op NOT IN ('managed-atoms','managed-atoms-generation','managed-connector','managed-connector-retry','managed-connector-state','managed-connector-migration')
AND NOT (op='managed-sync' AND (COALESCE(completed_keys->0->>'done','false')<>'true' OR EXISTS (
SELECT 1 FROM op_checkpoints f WHERE f.op='managed-sync-failure' AND f.fingerprint=op_checkpoints.fingerprint)))
AND op<>'managed-sync-failure'
diff --git a/src/core/ops/context.ts b/src/core/ops/context.ts
index 1c94d5356d..b3088939b5 100644
--- a/src/core/ops/context.ts
+++ b/src/core/ops/context.ts
@@ -79,8 +79,11 @@ export function validateUploadPath(filePath: string, root: string, strict = true
}
/**
- * Op-boundary page-slug segment (#4665): cjk.ts's PAGE_SLUG_SEG shape widened
- * LOCALLY so `.` and `_` are allowed as segment-CONTINUATION characters. The
+ * Op-boundary page-slug segment (#4665/#5032): cjk.ts's PAGE_SLUG_SEG shape
+ * widened LOCALLY so `.` and `_` are allowed as part-CONTINUATION characters.
+ * Colon separates individually valid parts inside a path segment, preserving
+ * existing integration slugs such as `calendar:event-id` without admitting
+ * empty or dot-led parts (`calendar:../x` remains invalid). The
* sync slugifier deliberately preserves both (`notes/v1.0.0`,
* `people/my_file_name` — see slugifySegment in src/core/sync.ts), so the
* put_page boundary must round-trip every slug sync can produce. The lead
@@ -95,13 +98,14 @@ export function validateUploadPath(filePath: string, root: string, strict = true
// underscores (`_index.md` → `_index`, the Hugo convention), so rejecting
// them recreates the un-updatable-synced-page class this widen closes.
// Dot stays continuation-only — `..` traversal remains impossible.
-const OP_PAGE_SLUG_SEG = `[${SLUG_WORD_CHARS}_][${SLUG_WORD_CHARS}._\\-]*`;
+const OP_PAGE_SLUG_PART = `[${SLUG_WORD_CHARS}_][${SLUG_WORD_CHARS}._\\-]*`;
+const OP_PAGE_SLUG_SEG = `${OP_PAGE_SLUG_PART}(?::${OP_PAGE_SLUG_PART})*`;
/**
* Allowlist validator for page slugs. Rejects URL-encoded traversal, backslashes,
* control chars, RTL overrides, Unicode lookalikes — anything outside the allowlist.
- * Format: lowercase alphanumeric segments (dot/underscore/hyphen continuation
- * allowed) separated by single forward slashes.
+ * Format: alphanumeric parts (dot/underscore/hyphen continuation allowed),
+ * optionally colon-separated within segments; segments use single forward slashes.
*/
export function validatePageSlug(slug: string): void {
if (typeof slug !== 'string' || slug.length === 0) {
@@ -114,7 +118,7 @@ export function validatePageSlug(slug: string): void {
// for the \p{...} classes in OP_PAGE_SLUG_SEG). Shape rules (word-char lead,
// dot/underscore/hyphen continuation) preserved.
if (!new RegExp(`^${OP_PAGE_SLUG_SEG}(\\/${OP_PAGE_SLUG_SEG})*$`, 'iu').test(slug)) {
- throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, with '.', '_', '-' after the first character of a segment, forward-slash separated segments)`);
+ throw new OperationError('invalid_params', `Invalid page_slug: ${slug} (allowed: letters/numbers in any script, with '.', '_', '-' after the first character of a part, optional colon-separated namespace parts, and forward-slash separated segments)`);
}
}
@@ -597,10 +601,16 @@ export function linkReadScopeOpts(ctx: OperationContext): { sourceId?: string; s
* trusted local (remote === false) → `{}` (spans the whole brain)
* remote → the caller's grant (sourceScopeOpts)
* - explicit `source_id`:
- * remote + federated grant that doesn't include it → permission_denied
+ * remote, outside the caller's grant or scalar scope, and outside
+ * `explicitReads` (when passed) → permission_denied
* otherwise → `{ sourceId }`
* - neither → the caller's grant (sourceScopeOpts).
*
+ * `explicitReads` (#5081) is the explicit-read admission set; only
+ * `federatedSearchScope` passes it. The other callers (image, loops,
+ * code-intel) pass nothing and keep denying every id outside the scope, with
+ * the original hint.
+ *
* `code_traversal_cache_clear` is intentionally NOT a caller — it is localOnly
* and carries its own destructive D8 all_sources guard.
*/
@@ -608,6 +618,7 @@ export function resolveRequestedScope(
ctx: OperationContext,
sourceIdParam: string | undefined,
allSourcesParam = false,
+ explicitReads?: readonly string[],
): { sourceId?: string; sourceIds?: string[] } {
const wantsAll = allSourcesParam || sourceIdParam === ALL_SOURCES;
if (wantsAll) {
@@ -618,11 +629,14 @@ export function resolveRequestedScope(
const granted = scope.sourceIds !== undefined
? scope.sourceIds.includes(sourceIdParam)
: scope.sourceId === sourceIdParam;
- if (ctx.remote !== false && !granted) {
+ if (ctx.remote !== false && !granted && !explicitReads?.includes(sourceIdParam)) {
throw new OperationError(
'permission_denied',
'Requested source is outside your granted sources',
- 'Request access to this source, or omit source_id to search within your grant.',
+ explicitReads === undefined
+ ? 'Request access to this source, or omit source_id to search within your grant.'
+ : explicitReadDeniedHint(ctx, sourceIdParam),
+ explicitReads === undefined ? undefined : EXPLICIT_READ_DOCS,
);
}
return { sourceId: sourceIdParam };
@@ -630,6 +644,53 @@ export function resolveRequestedScope(
return sourceScopeOpts(ctx);
}
+const EXPLICIT_READ_DOCS = 'docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection';
+
+/**
+ * #5081 / DX-O6(c): why an explicit read was refused, with the exact command
+ * that would admit it. A granted token is told about its grant; a connection
+ * bound by GBRAIN_SOURCE or a .gbrain-source pin is told about the binding
+ * (its own opt-out, the target's opt-out, or a target that was never
+ * federated); an unbound connection is told the target is not federated.
+ */
+function explicitReadDeniedHint(ctx: OperationContext, id: string): string {
+ const auth = ctx.auth;
+ if (auth !== undefined && (auth.allowedSources !== undefined || auth.hasSourceGrant !== false)) {
+ const granted = auth.allowedSources ?? (auth.sourceId !== undefined ? [auth.sourceId] : []);
+ return auth.principal?.kind === 'oauth_client'
+ ? `Your token is not granted ${id}; ask the brain owner to grant it ` +
+ `(gbrain auth rescope-client ${auth.principal.id} --federated-read ${[...granted, id].join(',')}).`
+ : `Your token is not granted ${id}; ask the brain owner to grant it.`;
+ }
+ const binding = ctx.explicitReadBinding;
+ if (binding === undefined) {
+ return `${id} is not federated; the brain owner can run \`gbrain sources federate ${id}\` on the brain host, ` +
+ 'or omit source_id to read within this connection\'s sources.';
+ }
+ const bound = `This connection is bound to source ${binding.sourceId} (${binding.via}).`;
+ const unbind = binding.via === 'GBRAIN_SOURCE'
+ ? 'start this connection without GBRAIN_SOURCE'
+ : 'start this connection outside the directory pinned by .gbrain-source';
+ if (binding.optedOut.includes(binding.sourceId)) {
+ return `${bound} ${binding.sourceId} opted out of federation (federated: false), so it reads no other source; ` +
+ `the brain owner can run \`gbrain sources federate ${binding.sourceId}\` on the brain host, or ${unbind}.`;
+ }
+ const reason = binding.optedOut.includes(id) ? 'opted out of federation (federated: false)' : 'is not federated';
+ return `${bound} ${id} ${reason}; the brain owner can run \`gbrain sources federate ${id}\` on the brain host, or ${unbind}.`;
+}
+
+/**
+ * #5081: the sources an explicit `source_id` read may name beyond the scope.
+ * A grant (`ctx.auth.allowedSources`) governs alone. Otherwise a bound stdio
+ * connection uses its binding's set, and an unbound connection uses the set
+ * its unqualified reads already span (`localFederatedSourceIds`), so an
+ * explicit read there is never wider than an unqualified one.
+ */
+function explicitReadAdmission(ctx: OperationContext): readonly string[] {
+ if (ctx.auth?.allowedSources !== undefined) return [];
+ return ctx.explicitReadBinding?.sourceIds ?? ctx.localFederatedSourceIds ?? [];
+}
+
/**
* #4329: parse a per-call `source_id` param. Pre-fix, get_page / delete_page /
* restore_page had NO source_id in their contracts, so an agent-passed
@@ -675,6 +736,10 @@ export function parseSourceIdParam(
* unqualified reads (#3242 — pages ingested into a `federated: true` source
* were invisible to get_page/search/list_pages while resolve_slugs leaked them).
*
+ * An explicit per-call `source_id` is admitted inside the explicit-read set
+ * (#5081, `explicitReadAdmission`): the binding's set for a connection bound
+ * by GBRAIN_SOURCE or a .gbrain-source pin, otherwise the federated set.
+ *
* The expansion NEVER applies when:
* - a concrete per-call `source_id` was passed (explicit wins);
* - the resolver already produced a federated array (OAuth grant governs);
@@ -694,7 +759,7 @@ export function federatedSearchScope(
ctx: OperationContext,
sourceIdParam?: string,
): { sourceId?: string; sourceIds?: string[] } {
- const scope = resolveRequestedScope(ctx, sourceIdParam);
+ const scope = resolveRequestedScope(ctx, sourceIdParam, false, explicitReadAdmission(ctx));
if (
(sourceIdParam === undefined || sourceIdParam === ALL_SOURCES) &&
ctx.auth?.allowedSources === undefined &&
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index c543b341b4..791729e2e2 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -465,6 +465,29 @@ export interface OperationContext {
* wins, and a context without this field never widens.
*/
localFederatedSourceIds?: string[];
+ /**
+ * #5081 — explicit-read admission for a stdio connection bound by an
+ * explicit tier (`GBRAIN_SOURCE` or a `.gbrain-source` pin). Set ONLY by
+ * the stdio transport (src/mcp/server.ts), never from caller params and
+ * never for an HTTP token. Unlike `localFederatedSourceIds` it never widens
+ * an unqualified read; `federatedSearchScope` only uses it to admit an
+ * explicit per-call `source_id` inside `sourceIds`.
+ */
+ explicitReadBinding?: ExplicitReadBinding;
+}
+
+/**
+ * #5081 — the bound source, how it was bound, the sources an explicit
+ * `source_id` read may name (the bound source first, then every non-archived
+ * `config.federated === true` source; just the bound source when it opted out
+ * with `config.federated === false`), and the sources that opted out, which
+ * only shape the denial hint.
+ */
+export interface ExplicitReadBinding {
+ sourceId: string;
+ via: 'GBRAIN_SOURCE' | '.gbrain-source';
+ sourceIds: string[];
+ optedOut: string[];
}
export interface Operation {
diff --git a/src/core/ops/insights.ts b/src/core/ops/insights.ts
index d901b07164..ced82a3837 100644
--- a/src/core/ops/insights.ts
+++ b/src/core/ops/insights.ts
@@ -79,6 +79,7 @@ const volunteer_context: Operation = {
const turns = parseWindow(p.window);
const { loadConfig: loadCfgForArms } = await import('../config.ts');
const { lexicalArmsEnabled } = await import('../context/reflex.ts');
+ const { resolveExcludePrivatePages } = await import('../search/private-visibility.ts');
const pages = await volunteerContext(ctx.engine, turns, {
sourceIds,
priorContext: typeof p.prior_context === 'string' ? p.prior_context : undefined,
@@ -87,6 +88,8 @@ const volunteer_context: Operation = {
// v0.46.15+ kill switch for the lexical recall arms (weak-alias +
// surname) — file-plane gate, threaded per ResolvePointersOpts.
lexicalArms: lexicalArmsEnabled(loadCfgForArms()),
+ // N8-1: the same private-page gate remote search applies.
+ excludePrivate: await resolveExcludePrivatePages(ctx.engine, ctx.remote),
});
// Feedback-loop logging: fire-and-forget batched INSERT through the
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 14472ec8c2..7779da250a 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -224,7 +224,7 @@ const fetch_page: Operation = {
const slug = identity?.slug ?? id.trim();
const missing = () => new OperationError('page_not_found', 'Page not found', 'Pass an id returned by a current `search` call.');
let sourceOpts: ReturnType<typeof federatedSearchScope>;
- try { sourceOpts = federatedSearchScope(ctx); }
+ try { sourceOpts = federatedSearchScope(ctx, identity?.sourceId); }
catch (error) {
if (error instanceof OperationError && error.code === 'permission_denied') throw missing();
throw error;
diff --git a/src/core/ops/search.ts b/src/core/ops/search.ts
index f27f00e58d..b1a6ff675e 100644
--- a/src/core/ops/search.ts
+++ b/src/core/ops/search.ts
@@ -245,13 +245,26 @@ async function buildRetrievalResponseMeta(
/**
* #3985: normalize the `types` param. MCP passes a real array; the CLI
* passes `--types person,company` as one string. Rejects non-string entries
- * and an all-empty list loudly (invalid_params) instead of silently
- * dropping the filter. The SQL-level plumbing (SearchOpts.types → both
- * engines' keyword/title/vector legs) has existed since v0.33 (whoknows);
- * this just exposes it on the public search/query ops.
+ * and a non-empty list whose entries trim/filter to nothing loudly
+ * (invalid_params) instead of silently dropping the filter.
+ *
+ * #5390: a structurally empty array (`[]`), `""` or a whitespace-only string
+ * carries no user intent — it is
+ * what OpenAI-family MCP clients send when an LLM over-fills every optional
+ * parameter with a type-zero value. Treat it as absent (no filter applied)
+ * rather than throwing, so the search still runs unfiltered. A non-empty
+ * list that filters to nothing (`['']`, `',,'`) still throws, so a CLI
+ * `--types ,` typo is still loud. The SQL-level plumbing (SearchOpts.types
+ * → both engines' keyword/title/vector legs) has existed since v0.33
+ * (whoknows); this just exposes it on the public search/query ops.
*/
function normalizeTypesParam(raw: unknown): string[] | undefined {
if (raw === undefined || raw === null) return undefined;
+ // #5390: a structurally empty array, an empty string or a whitespace-only
+ // string is treated as absent, not as a request for an impossible filter.
+ // The CLI typo guard below still catches `',,'`, `' , '` and `['']`.
+ if (Array.isArray(raw) && raw.length === 0) return undefined;
+ if (typeof raw === 'string' && raw.trim() === '') return undefined;
const arr = Array.isArray(raw)
? raw
: typeof raw === 'string'
@@ -773,15 +786,9 @@ const query: Operation = {
relationalRetrieval: true,
autocut: false, decide: { remote: ctx.remote !== false, rerankOnly: true }, // System One: S2-S5 off on the re-run
detail,
- // Preserve the caller's #3985 type filter on the re-run (raw
- // pass-through; the base call already rejected malformed input).
- ...(Array.isArray(p.types) || typeof p.types === 'string'
- ? {
- types: (Array.isArray(p.types) ? (p.types as string[]) : (p.types as string).split(','))
- .map((t) => t.trim())
- .filter(Boolean),
- }
- : {}),
+ // Preserve the caller's #3985 type filter on the re-run, as
+ // normalized for the base call (#5390: [] and "" stay absent).
+ ...(types ? { types } : {}),
language: (p.lang as string) || undefined,
symbolKind: (p.symbol_kind as string) || undefined,
// Preserve the caller's symbol-proximity constraints too — an
diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.ts
index d263cdde33..6c47803f9a 100644
--- a/src/core/ops/takes.ts
+++ b/src/core/ops/takes.ts
@@ -24,6 +24,7 @@ import {
TakesWriteError,
} from '../takes-write.ts';
import { embedQuery } from '../embedding.ts';
+import { ALL_SOURCES } from '../source-id.ts';
import { privatePagesFilterFragment } from '../search/private-visibility.ts';
// --- v0.28: Takes ---
@@ -238,7 +239,11 @@ const think: Operation = {
let savedSlug: string | undefined;
let evidenceInserted = 0;
if (safeSave) {
- const persisted = await persistSynthesis(ctx.engine, result);
+ const persisted = await persistSynthesis(ctx.engine, result, {
+ // '__all__' is a read scope, not a write destination: an unscoped save keeps the default source.
+ sourceId: ctx.sourceId === ALL_SOURCES ? undefined : ctx.sourceId,
+ ...(thinkScope.allowedSources ? { allowedSources: thinkScope.allowedSources } : {}),
+ });
savedSlug = persisted.slug;
evidenceInserted = persisted.evidenceInserted;
for (const w of persisted.warnings) result.warnings.push(w);
diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.ts
index 35baa868cd..bec7493e28 100644
--- a/src/core/page-state/projections.ts
+++ b/src/core/page-state/projections.ts
@@ -302,25 +302,69 @@ const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources s
*/
const statisticsDebt = new WeakMap<BrainEngine, { rebuilt: number; rows: number | null }>();
+/**
+ * #5401: a failed rebuild waits this long before the resident retries it. One
+ * fragment over `page_projection_jobs j`, shared by the consumer's idle probe
+ * and the resident's selector.
+ */
+export const PROJECTION_RETRY_READY_SQL = "(j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds')";
+
+export interface ProjectionRebuildFailure { source_id: string; slug: string; reason: string }
+
+export interface ProjectionRebuildOptions {
+ /** Stop starting new pages once this many milliseconds have passed since the call began; the first page always starts. */
+ deadlineMs?: number;
+ /** Injectable clock in milliseconds, for the deadline. */
+ now?: () => number;
+ /**
+ * Only rows last queued or failed at or before this database instant (text,
+ * cast in SQL so microseconds survive). A caller that waits for the database
+ * clock to pass it tries each row at most once per run.
+ */
+ notAfter?: string;
+ /** Skip failed rows inside their retry window (PROJECTION_RETRY_READY_SQL). */
+ retryCooldown?: boolean;
+ /** Receives each failed page; without it a generic stderr line is printed. */
+ onFailure?: (failure: ProjectionRebuildFailure) => void;
+}
+
+/** Live Markdown and code rows a rebuild can take, and how many of them last failed. */
+export async function projectionBacklog(engine: Pick<BrainEngine, 'executeRaw'>): Promise<{ pending: number; failed: number; oldest_age_seconds: number | null }> {
+ const [row] = await engine.executeRaw<{ pending: number; failed: number; oldest: number | null }>(`SELECT COUNT(*)::int AS pending,
+ COUNT(*) FILTER (WHERE j.reason='rebuild_failed')::int AS failed,
+ EXTRACT(EPOCH FROM now()-MIN(j.updated_at))::float8 AS oldest
+ FROM page_projection_jobs j ${PROJECTION_JOB_PROBES}`);
+ const oldest = row?.oldest === null || row?.oldest === undefined ? null : Math.max(0, Math.floor(Number(row.oldest)));
+ return { pending: Number(row?.pending ?? 0), failed: Number(row?.failed ?? 0), oldest_age_seconds: oldest };
+}
+
/** Bounded and keyless. Unsupported media remains queued for its source importer. */
-export async function rebuildPendingPageProjections(engine: BrainEngine, limit = 20): Promise<{ rebuilt: number; superseded: number }> {
+export async function rebuildPendingPageProjections(engine: BrainEngine, limit = 20, opts: ProjectionRebuildOptions = {}): Promise<{ rebuilt: number; superseded: number }> {
+ const now = opts.now ?? Date.now;
+ const startedAt = now();
+ const params: unknown[] = [Math.max(1, Math.min(limit, 100))];
+ const filters: string[] = [];
+ if (opts.retryCooldown) filters.push(PROJECTION_RETRY_READY_SQL);
+ if (opts.notAfter !== undefined) { params.push(opts.notAfter); filters.push(`j.updated_at<=$${params.length}::text::timestamptz`); }
const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string; page_kind: string }>(`SELECT s.id AS source_id,j.source_incarnation,j.slug,j.revision,p.page_kind
- FROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs
+ FROM (SELECT source_incarnation,slug,revision,updated_at FROM page_projection_jobs j
+ ${filters.length ? `WHERE ${filters.join(' AND ')}` : ''}
ORDER BY updated_at,source_incarnation,slug OFFSET 0) j
${PROJECTION_JOB_PROBES}
- ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, [Math.max(1, Math.min(limit, 100))]);
+ ORDER BY j.updated_at,j.source_incarnation,j.slug LIMIT $1`, params);
let rebuilt = 0;
let superseded = 0;
- for (const job of jobs) {
- const prepared = await engine.transaction(async tx => {
- await tx.lockPageKeys([{ sourceId: job.source_id, slug: job.slug }]);
- const pending = await tx.executeRaw(`SELECT 1 FROM page_projection_jobs
- WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);
- if (!pending.length) return null;
- return readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });
- });
- if (!prepared || prepared.snapshot.sourceIncarnation !== job.source_incarnation || prepared.snapshot.revision !== job.revision) { superseded++; continue; }
+ for (const [index, job] of jobs.entries()) {
+ if (opts.deadlineMs !== undefined && index > 0 && now() - startedAt >= opts.deadlineMs) break;
try {
+ const prepared = await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: job.source_id, slug: job.slug }]);
+ const pending = await tx.executeRaw(`SELECT 1 FROM page_projection_jobs
+ WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);
+ if (!pending.length) return null;
+ return readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });
+ });
+ if (!prepared || prepared.snapshot.sourceIncarnation !== job.source_incarnation || prepared.snapshot.revision !== job.revision) { superseded++; continue; }
const projection = await preparePageProjection(prepared);
await installPageProjection(engine, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });
rebuilt++;
@@ -328,7 +372,8 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =
if (!(error instanceof PageRevisionConflictError)) {
await engine.executeRaw(`UPDATE page_projection_jobs SET reason='rebuild_failed',updated_at=now()
WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);
- process.stderr.write('[gbrain] Projection rebuild failed; work remains queued. Inspect projection readiness and the recorded source path.\n');
+ if (opts.onFailure) opts.onFailure({ source_id: job.source_id, slug: job.slug, reason: (error instanceof Error ? error.message : String(error)).split('\n')[0].slice(0, 300) });
+ else process.stderr.write('[gbrain] Projection rebuild failed; work remains queued. Inspect projection readiness and the recorded source path.\n');
continue;
}
superseded++;
diff --git a/src/core/page-summary.ts b/src/core/page-summary.ts
index d861d2578c..e50e052eec 100644
--- a/src/core/page-summary.ts
+++ b/src/core/page-summary.ts
@@ -34,6 +34,7 @@ import { chat, type ChatOpts, type ChatResult } from './ai/gateway.ts';
import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.ts';
import { sanitizeSynopsis } from './embedding-context.ts';
import { resolveTierDefault } from './model-config.ts';
+import { safeSplitIndex } from './text-safe.ts';
/**
* Default cap on synopsis output tokens. ~200 tokens gives 50-100 token
@@ -258,8 +259,9 @@ function buildUserPrompt(
// frontmatter, intro paragraphs carry the document-level anchor).
let trimmedDoc = documentText;
if (documentText.length > SYNOPSIS_DOC_MAX_CHARS) {
- trimmedDoc = documentText.slice(0, SYNOPSIS_DOC_MAX_CHARS) +
- `\n\n[... ${documentText.length - SYNOPSIS_DOC_MAX_CHARS} chars truncated for synopsis budget ...]`;
+ const cut = safeSplitIndex(documentText, SYNOPSIS_DOC_MAX_CHARS);
+ trimmedDoc = documentText.slice(0, cut) +
+ `\n\n[... ${documentText.length - cut} chars truncated for synopsis budget ...]`;
}
return [
`<page_title>${pageTitle}</page_title>`,
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index caf60bc477..27d5f8e98e 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -8,7 +8,7 @@ import { isValidSourceId } from '../source-id.ts';
import { assertValidSlugPrefixes } from '../grants/encoding.ts';
import { isWriteRequestId } from './types.ts';
import { writerDiagnostics } from './control.ts';
-import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, prepareWriterTransfer, worktreeManifest } from './ownership.ts';
+import { acceptWriterTransfer, claimWorktree, getWorktreeBinding, humanManifestProgress, prepareWriterTransfer, worktreeManifest } from './ownership.ts';
import { existingLocalHostId, currentVerifiedLocalWriter, persistenceHome, readLocalWriter, registerLocalWriter, revokeLocalWriter, type LocalGrant } from './identity.ts';
import type { PersistenceAdminOperation } from './admin-contract.ts';
import { operationScopesAllowed } from '../scope.ts';
@@ -233,12 +233,12 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) throw new OperationError('permission_denied', 'Only the current owner can prepare a transfer.');
const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { selfTransfer: params.self_transfer === true, dryRun: true });
- return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: Object.keys(manifest.files).length } };
+ return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count } };
}
const expectedState = await requireWriterAdminIntent(engine, operation, params);
const prepared = await prepareWriterTransfer(engine, sourceId, undefined, expectedState, { selfTransfer: params.self_transfer === true });
return { prepared: true, source_id: sourceId, worktree_id: prepared.worktree_id, owner_epoch: prepared.owner_epoch,
- manifest: { digest: prepared.manifest.digest, file_count: Object.keys(prepared.manifest.files).length } };
+ manifest: { digest: prepared.manifest.digest, file_count: prepared.manifest.file_count } };
}
if (operation === 'writer_transfer_accept') {
keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);
@@ -249,7 +249,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.');
if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, existingLocalHostId()!, undefined, { selfTransfer: true, dryRun: true });
if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()),
- manifest_matches: worktreeManifest(root).digest === params.manifest, expected_epoch: params.expected_epoch };
+ manifest_matches: worktreeManifest(root, { progress: humanManifestProgress() }).digest === params.manifest, expected_epoch: params.expected_epoch };
const expectedState = await requireWriterAdminIntent(engine, operation, params);
await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, undefined, expectedState, { selfTransfer: params.self_transfer === true });
return { transferred: true, binding: await getWorktreeBinding(engine, sourceId) };
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index a289eb7554..ae0719dda9 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -26,6 +26,7 @@ export interface AtomOrigin {
pageId: number | null;
revision: string | null;
visibility: 'private' | 'world';
+ generation?: number;
}
export interface ManagedAtomSession {
sourceId: string;
@@ -36,7 +37,7 @@ export interface ManagedAtomSession {
retry?: { runKey: string; checkpointKey: string; expectedCheckpoint: unknown; rows: WriteRequest[]; origin: AtomOrigin };
}
export interface AtomIntent extends Record<string, unknown> {
- kind: 'managed_atom_page' | 'managed_atom_complete';
+ kind: 'managed_atom_page' | 'managed_atom_delete' | 'managed_atom_complete';
runKey: string;
origin: AtomOrigin;
expected_revision?: string;
@@ -65,6 +66,7 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,
throw new OperationError('permission_denied', 'Atom maintenance requires a source-wide grant.');
}
await authorizeWrite(engine, authority, 'put_page', 'atoms/preflight');
+ await authorizeWrite(engine, authority, 'delete_page', 'atoms/preflight');
const binding = await getWorktreeBinding(engine, sourceId);
const root = source.local_path || (sourceId === 'default' ? await engine.getConfig('sync.repo_path') : null);
const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
@@ -118,8 +120,43 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSe
if (!snapshot || snapshot.sourceIncarnation !== session.incarnation || snapshot.page.content_hash !== item.contentHash || snapshot.page.compiled_truth !== item.content) {
throw new OperationError('revision_conflict', 'The atom input changed before extraction.');
}
+ const generation = await atomGeneration(engine, snapshot.page.id, item.contentHash);
return { kind: item.kind, locator: item.slug, contentHash: item.contentHash, textHash: sha256(item.content), pageId: snapshot.page.id,
- revision: snapshot.revision, visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }) };
+ revision: snapshot.revision, visibility: effectiveVisibility({ kind: 'page', page: snapshot.page }), ...(generation > 0 ? { generation } : {}) };
+}
+
+export const ATOM_GENERATION_OP = 'managed-atoms-generation';
+export const ATOM_RETIRED_BY_REEXTRACT = 'managed-reextract';
+
+/**
+ * The generation a page's content keys on: the content a retirement kept (the extraction that retired) keeps
+ * the generation its accepted batch already used, so that batch stays resumable; every other content moves on.
+ */
+async function atomGeneration(engine: BrainEngine, pageId: number, contentHash: string): Promise<number> {
+ const [row] = await engine.executeRaw<{ generation: string | null; keep: string | null; keep_generation: string | null }>(
+ `SELECT completed_keys->0->>'generation' AS generation, completed_keys->0->>'keep' AS keep, completed_keys->0->>'keep_generation' AS keep_generation
+ FROM op_checkpoints WHERE op='${ATOM_GENERATION_OP}' AND fingerprint=$1`, [String(pageId)]);
+ if (!row) return 0;
+ return Number((row.keep !== null && row.keep === contentHash ? row.keep_generation : row.generation) ?? 0);
+}
+
+/**
+ * Retiring an origin page's atoms invalidates its earlier completed extractions: the generation
+ * changes the run key of every other content, so a retained receipt is not replayed, and discovery
+ * offers the page again. `keepContentHash` (the extraction that retired) keeps its key and its state.
+ */
+export async function bumpAtomGeneration(tx: BrainEngine, sourceId: string, incarnation: string, pageId: number, keepContentHash: string | null): Promise<void> {
+ const kept = keepContentHash === null ? null : await atomGeneration(tx, pageId, keepContentHash);
+ await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys)
+ VALUES('${ATOM_GENERATION_OP}',$1,jsonb_build_array(jsonb_build_object('generation',1,'keep',$2::text,'keep_generation',$3::integer)))
+ ON CONFLICT(op,fingerprint) DO UPDATE SET updated_at=now(), completed_keys=jsonb_build_array(jsonb_build_object('generation',
+ COALESCE((op_checkpoints.completed_keys->0->>'generation')::integer,0)+1,'keep',$2::text,'keep_generation',$3::integer))`,
+ [String(pageId), keepContentHash, kept]);
+ await tx.executeRaw('DELETE FROM extract_atoms_page_state WHERE source_incarnation=$1::uuid AND page_id=$2 AND content_hash IS DISTINCT FROM $3::text',
+ [incarnation, pageId, keepContentHash]);
+ await tx.executeRaw(`DELETE FROM op_checkpoints WHERE op='managed-atoms' AND completed_keys->0->>'sourceId'=$1
+ AND completed_keys->0->>'kind'='page' AND completed_keys->0->>'pageId'=$2 AND completed_keys->0->>'contentHash' IS DISTINCT FROM $3::text`,
+ [sourceId, String(pageId), keepContentHash]);
}
/**
@@ -127,13 +164,21 @@ export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSe
* revision-only source change (a tag, a timeline row) is the same input for
* the drain and for an explicit retry (#5699).
*/
+function atomInput(session: ManagedAtomSession, origin: AtomOrigin): unknown[] {
+ return ['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash];
+}
+
+/** A retirement's regeneration generation enters the drain's key above 0, so earlier receipts are not replayed. */
function atomInputKey(session: ManagedAtomSession, origin: AtomOrigin): string {
- return digest(['managed-atoms-v1', session.incarnation, origin.kind, origin.locator, origin.pageId, origin.contentHash]);
+ return digest([...atomInput(session, origin), ...(origin.generation ? [origin.generation] : [])]);
}
-/** The retry check adds the extracted text's hash: a transcript retry reads the current file under the retained content hash. */
+/**
+ * The retry check adds the extracted text's hash: a transcript retry reads the current file under the retained content hash.
+ * It leaves the generation out: a retirement the reviewed batch itself committed must not invalidate its own retry.
+ */
export function atomRetryInputKey(session: ManagedAtomSession, origin: AtomOrigin): string {
- return digest([atomInputKey(session, origin), origin.textHash]);
+ return digest([digest(atomInput(session, origin)), origin.textHash]);
}
function runKey(session: ManagedAtomSession, origin: AtomOrigin): string {
@@ -203,14 +248,21 @@ export async function resumeManagedAtoms(engine: BrainEngine, session: ManagedAt
return true;
}
+export interface ManagedAtomRetirement {
+ slug: string;
+ pageId: number;
+ revision: string;
+}
+
export async function publishManagedAtoms(engine: BrainEngine, session: ManagedAtomSession, origin: AtomOrigin,
- atoms: Array<{ slug: string; content: string; links: LinkBatchInput[]; expectedTarget?: { pageId: number | null; revision: string | null } }>, failure?: string): Promise<WriteReceipt[]> {
+ atoms: Array<{ slug: string; content: string; links: LinkBatchInput[]; expectedTarget?: { pageId: number | null; revision: string | null } }>,
+ failure?: string, reviewedRetirements?: ManagedAtomRetirement[]): Promise<WriteReceipt[]> {
const key = runKey(session, origin);
const inputs: Array<{ slug: string; pageId: number | null; intent: AtomIntent }> = [];
for (const atom of atoms) {
await authorizeWrite(engine, session.authority, 'put_page', atom.slug);
const snapshot = await engine.readPageSnapshot(atom.slug, { sourceId: session.sourceId, includeDeleted: true });
- if (snapshot && (snapshot.page.deleted_at || snapshot.page.type !== 'atom' ||
+ if (snapshot && ((snapshot.page.deleted_at && !snapshot.page.frontmatter.retired_by) || snapshot.page.type !== 'atom' ||
(origin.kind === 'page' ? snapshot.page.frontmatter.source_slug !== origin.locator : snapshot.page.frontmatter.source_path !== origin.locator))) {
throw new OperationError('page_identity_changed', 'The atom target belongs to another origin or was removed.');
}
@@ -222,6 +274,24 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}),
...(target.revision ? { expected_revision: target.revision } : {}), content: atom.content, links: atom.links } as AtomIntent });
}
+ const originKey = origin.kind === 'page' ? 'source_slug' : 'source_path';
+ const retirements = failure ? [] : reviewedRetirements ?? await engine.executeRaw<ManagedAtomRetirement>(
+ `SELECT slug,id AS "pageId",knowledge_revision::text AS revision FROM pages
+ WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL
+ AND frontmatter->>'${originKey}'=$2
+ AND COALESCE(frontmatter->>'source_hash','')<>$3
+ AND NULLIF(frontmatter->>'imported_from','') IS NULL
+ AND NOT (slug=ANY($4::text[]))
+ ORDER BY slug`,
+ [session.sourceId, origin.locator, origin.contentHash.slice(0, 16), atoms.map(atom => atom.slug)],
+ );
+ for (const retirement of retirements) {
+ await authorizeWrite(engine, session.authority, 'delete_page', retirement.slug);
+ inputs.push({ slug: retirement.slug, pageId: retirement.pageId, intent: {
+ kind: 'managed_atom_delete', runKey: key, origin, expected_revision: retirement.revision,
+ ...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}),
+ } as AtomIntent });
+ }
const rows = await engine.transaction(async tx => {
const children: string[] = [];
const accepted: WriteRequest[] = [];
@@ -234,7 +304,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
worktreeId: session.binding?.worktree_id, topologyGeneration: session.binding?.topology_generation,
slug: input.slug, pageId: input.pageId, requestId, callerIntent: input.intent, intent: input.intent });
accepted.push(row);
- if (input.intent.kind === 'managed_atom_page') children.push(row.id);
+ if (input.intent.kind !== 'managed_atom_complete') children.push(row.id);
}
return accepted;
});
@@ -256,7 +326,7 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
export async function prepareManagedAtomMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as AtomIntent | null;
- if (!p || !['managed_atom_page', 'managed_atom_complete'].includes(p.kind) || !p.origin || row.authority.remote) {
+ if (!p || !['managed_atom_page', 'managed_atom_delete', 'managed_atom_complete'].includes(p.kind) || !p.origin || row.authority.remote) {
throw new OperationError('permission_denied', 'Unsupported atom maintenance intent.');
}
const validate = async (tx: BrainEngine) => {
@@ -272,18 +342,40 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
};
await validate(engine);
const additionalPageKeys = p.origin.kind === 'page' ? [{ sourceId: row.source_id, slug: p.origin.locator }] : [];
+ if (p.kind === 'managed_atom_delete') {
+ await authorizeWrite(engine, row.authority, 'delete_page', row.slug);
+ const prepared = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
+ return { ...prepared, additionalPageKeys, validate: async tx => {
+ await validate(tx);
+ await authorizeWrite(tx, row.authority, 'delete_page', row.slug);
+ await prepared.validate?.(tx);
+ }, apply: async tx => {
+ const result = await prepared.apply(tx);
+ if (!prepared.noop) {
+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+ WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [ATOM_RETIRED_BY_REEXTRACT, new Date().toISOString(), row.page_id, row.source_id]);
+ if (p.origin.kind === 'page' && p.origin.pageId !== null) {
+ await bumpAtomGeneration(tx, row.source_id, row.source_incarnation, p.origin.pageId, p.origin.contentHash);
+ }
+ }
+ return { ...result, atom_run_key: p.runKey, atom_kind: p.kind };
+ } };
+ }
if (p.kind === 'managed_atom_complete') {
const targets = await engine.executeRaw<{ slug: string }>('SELECT slug FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuid',
[p.children ?? [], row.source_incarnation]);
additionalPageKeys.push(...targets.map(target => ({ sourceId: row.source_id, slug: target.slug })));
return { observedRevision: null, noop: true, additionalPageKeys, validate, apply: async tx => {
const children = p.children ?? [];
- const committed = await tx.executeRaw<{ id: string }>(`SELECT r.id FROM persistence_requests r
- JOIN pages atom ON atom.source_id=r.source_id AND atom.slug=r.slug
- AND atom.knowledge_revision::text=r.outcome->>'revision' AND atom.deleted_at IS NULL AND atom.type='atom'
+ const committed = await tx.executeRaw<{ id: string; kind: AtomIntent['kind'] }>(`SELECT r.id,
+ COALESCE(r.intent->>'kind',r.outcome->>'atom_kind') AS kind FROM persistence_requests r
+ JOIN pages atom ON atom.source_id=r.source_id AND atom.slug=r.slug AND atom.type='atom'
WHERE r.id=ANY($1::uuid[]) AND r.source_incarnation=$2::uuid
AND r.state='committed' AND COALESCE(r.intent->>'runKey',r.outcome->>'atom_run_key')=$3
- AND COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_page'`, [children, row.source_incarnation, p.runKey]);
+ AND ((COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_page'
+ AND atom.knowledge_revision::text=r.outcome->>'revision' AND atom.deleted_at IS NULL)
+ OR (COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_delete'
+ AND atom.id=r.page_id AND atom.deleted_at IS NOT NULL))`, [children, row.source_incarnation, p.runKey]);
if (committed.length !== children.length) throw new OperationError('revision_conflict', 'The atom batch is not fully committed.');
if (p.origin.kind === 'page') {
const snapshot = await tx.readPageSnapshot(p.origin.locator, { sourceId: row.source_id });
@@ -303,11 +395,14 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
[p.checkpointKey, checkpoint, p.expectedCheckpoint === null ? null : JSON.stringify(p.expectedCheckpoint)]);
if (!advanced.length) throw new OperationError('revision_conflict', 'The reviewed atom retry checkpoint changed.');
}
- return { status: p.failure ? 'failed' : 'completed', atoms: children.length, ...(p.failure ? { failure: p.failure } : {}) };
+ return { status: p.failure ? 'failed' : 'completed',
+ atoms: committed.filter(child => child.kind === 'managed_atom_page').length,
+ retired: committed.filter(child => child.kind === 'managed_atom_delete').length,
+ ...(p.failure ? { failure: p.failure } : {}) };
} };
}
await authorizeWrite(engine, row.authority, 'put_page', row.slug);
- const prepared = await preparePageMutation(engine, { ...row, operation: 'put_page' }, config);
+ const prepared = await preparePageMutation(engine, { ...row, operation: 'put_page' }, config, undefined, undefined, { allowMissingFile: true });
return { ...prepared, additionalPageKeys, validate: async tx => { await validate(tx); await authorizeWrite(tx, row.authority, 'put_page', row.slug); await prepared.validate?.(tx); }, apply: async tx => {
const result = await prepared.apply(tx);
if (p.links?.length) await tx.addLinksBatch(p.links, { auditSite: 'cycle.extract_atoms.provenance' });
@@ -315,9 +410,14 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
} };
}
+/** The completed, failure-free `managed-atoms` checkpoint `ac` for one page at its current content hash. */
+export function managedAtomCompletedSql(page: { sourceId: string; slug: string; pageId: string; contentHash: string }): string {
+ return `ac.op='managed-atoms' AND ac.completed_keys->0->>'sourceId'=${page.sourceId}
+ AND ac.completed_keys->0->>'incarnation'=(SELECT incarnation::text FROM sources WHERE id=${page.sourceId})
+ AND ac.completed_keys->0->>'kind'='page' AND ac.completed_keys->0->>'locator'=${page.slug}
+ AND ac.completed_keys->0->>'pageId'=${page.pageId}::text AND ac.completed_keys->0->>'contentHash'=${page.contentHash}
+ AND ac.completed_keys->0->>'failure' IS NULL`;
+}
+
export const MANAGED_ATOM_DISCOVERY_SQL = `AND NOT EXISTS (SELECT 1 FROM op_checkpoints ac
- WHERE ac.op='managed-atoms' AND ac.completed_keys->0->>'sourceId'=p.source_id
- AND ac.completed_keys->0->>'incarnation'=(SELECT incarnation::text FROM sources WHERE id=p.source_id)
- AND ac.completed_keys->0->>'kind'='page' AND ac.completed_keys->0->>'locator'=p.slug
- AND ac.completed_keys->0->>'pageId'=p.id::text AND ac.completed_keys->0->>'contentHash'=p.content_hash
- AND ac.completed_keys->0->>'failure' IS NULL)`;
+ WHERE ${managedAtomCompletedSql({ sourceId: 'p.source_id', slug: 'p.slug', pageId: 'p.id', contentHash: 'p.content_hash' })})`;
diff --git a/src/core/persistence/atom-retry.ts b/src/core/persistence/atom-retry.ts
index cab63de8f0..dc2ecc2618 100644
--- a/src/core/persistence/atom-retry.ts
+++ b/src/core/persistence/atom-retry.ts
@@ -1,7 +1,7 @@
import { readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
-import { atomRetryInputKey, managedAtomSession, publishManagedAtoms, readAtomOrigin, resumeManagedAtoms, type AtomIntent } from './atom-maintenance.ts';
+import { atomRetryInputKey, managedAtomSession, publishManagedAtoms, readAtomOrigin, resumeManagedAtoms, type AtomIntent, type ManagedAtomRetirement } from './atom-maintenance.ts';
import { isWriteReceipt } from './types.ts';
export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: string, requestId: string, retryId: string): Promise<Record<string, unknown>> {
@@ -23,7 +23,8 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
const checkpoint = retry.expectedCheckpoint as Array<{ failure?: string }> | null;
if (checkpoint && !checkpoint[0]?.failure) return { status: 'completed', replayed: true, model_rerun: false };
const saved = retry.rows.filter(row => row.intent?.kind === 'managed_atom_page');
- if (saved.length) {
+ const deleted = retry.rows.filter(row => row.intent?.kind === 'managed_atom_delete');
+ if (saved.length || deleted.length) {
const atoms: Parameters<typeof publishManagedAtoms>[3] = [];
for (const row of saved) {
const p = row.intent as AtomIntent;
@@ -37,7 +38,18 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
if (typeof p.content !== 'string') throw new OperationError('storage_error', 'The retained atom publication content is unavailable.');
atoms.push({ slug: row.slug, content: p.content, links: p.links ?? [], expectedTarget: { pageId, revision } });
}
- const receipts = await publishManagedAtoms(engine, session, current, atoms);
+ const retirements: ManagedAtomRetirement[] = [];
+ for (const row of deleted) {
+ const p = row.intent as AtomIntent;
+ const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
+ const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision;
+ if (typeof revision !== 'string' || row.page_id === null || !target ||
+ target.page.id !== row.page_id || target.revision !== revision || Boolean(target.page.deleted_at) !== (row.state === 'committed')) {
+ throw new OperationError('page_identity_changed', 'An atom retirement target changed independently of the failed publication.');
+ }
+ retirements.push({ slug: row.slug, pageId: row.page_id, revision });
+ }
+ const receipts = await publishManagedAtoms(engine, session, current, atoms, undefined, retirements);
return { status: 'completed', model_rerun: false, write_requests: receipts };
}
if (!retry.rows.some(row => row.outcome?.failure)) throw new OperationError('invalid_params', 'This failed batch has no malformed extraction to retry.');
diff --git a/src/core/persistence/bundle-files.ts b/src/core/persistence/bundle-files.ts
index 8728d5b571..d190139926 100644
--- a/src/core/persistence/bundle-files.ts
+++ b/src/core/persistence/bundle-files.ts
@@ -18,12 +18,22 @@ function unsafe(): OperationError {
return new OperationError('storage_error', 'Skill publication requires bounded regular files without aliases, links, or special files.');
}
+/**
+ * #5776: check each path segment, not the joined relative path. On Windows the
+ * separator is a backslash, so testing the whole relative path for one
+ * rejected every nested bundle file there.
+ */
+export function bundleRelativePathIsSafe(rel: string, pathSep: string = sep): boolean {
+ const parts = rel.split(pathSep);
+ return parts.length <= BUNDLE_FILE_LIMITS.depth && parts.every(part => part !== '' && !/[\\/\x00-\x1f:]/.test(part));
+}
+
export function readBundleFile(path: string, root: string): { bytes: Buffer; mode: number } | null {
if (!path.isWellFormed() || path !== path.normalize('NFC')) throw unsafe();
const rel = relative(root, path);
if (!isAbsolute(path) || path !== resolve(path) || !rel || isAbsolute(rel) || rel.startsWith(`..${sep}`) || rel === '..'
|| !rel.isWellFormed() || rel !== rel.normalize('NFC')
- || rel.split(sep).length > BUNDLE_FILE_LIMITS.depth || /[\\\x00-\x1f:]/.test(rel)) throw unsafe();
+ || !bundleRelativePathIsSafe(rel)) throw unsafe();
if (realpathSync(root) !== root || !lstatSync(root).isDirectory()) throw unsafe();
const parts = rel.split(sep);
let current = root;
diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.ts
index 6a6de27bcd..d99307321c 100644
--- a/src/core/persistence/consumer.ts
+++ b/src/core/persistence/consumer.ts
@@ -1,16 +1,35 @@
import type { BrainEngine, ReservedConnection } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { claimNextWrite, compactWriteReceipts, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
+import { CLAIMABLE_WRITE_SQL, claimNextWrite, compactWriteReceipts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';
import { finishUnpublishedFailure, publishMutation, recoverPublication, type PreparedMutation } from './coordinator.ts';
import { localHostId } from './identity.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';
-import { rebuildPendingPageProjections } from '../page-state/projections.ts';
+import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';
import { publicationConcurrency } from './pool-capacity.ts';
import { runPersistenceEffects } from './effects.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { isWriteErrorCode } from './types.ts';
+/**
+ * #5401: one resident projection invocation takes up to this many pages and
+ * starts no new page once the budget has passed since it began. When a write is
+ * claimable at its start it takes the small batch, so the drain never delays
+ * queued writes by more than about two page rebuilds.
+ */
+export const RESIDENT_PROJECTION_PAGES = 100;
+export const RESIDENT_PROJECTION_BUDGET_MS = 250;
+export const WRITE_WAITING_PROJECTION_PAGES = 2;
+
+export async function runResidentProjectionInvocation(engine: BrainEngine, hostId: string, excludeRoots: string[],
+ now: () => number = Date.now, signal?: AbortSignal) {
+ // Advisory and bounded by the caller's signal: a probe that cannot answer
+ // (for example behind a table lock) counts as a waiting write.
+ const writesWaiting = publicationConcurrency(engine) > 0 && await hasClaimableWrite(engine, hostId, excludeRoots, signal).catch(() => true);
+ return rebuildPendingPageProjections(engine, writesWaiting ? WRITE_WAITING_PROJECTION_PAGES : RESIDENT_PROJECTION_PAGES,
+ { deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now, retryCooldown: true });
+}
+
export type PrepareMutation = (engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal) => Promise<PreparedMutation>;
export class PersistenceConsumer {
private stopping = false;
@@ -92,13 +111,7 @@ export class PersistenceConsumer {
const retryingTopologies = [...this.topologyRetryAfter.keys()];
const [row] = await this.phase('idle_probe', async signal => this.probeQuery<{ work: boolean }>(await this.acquireIdleLane(signal), `SELECT (
EXISTS (SELECT 1 FROM persistence_requests r LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
- AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))
- AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
- AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
- AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier
- WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)
- AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))
+ WHERE ${CLAIMABLE_WRITE_SQL}
AND ($3::boolean OR r.blocked_reason IS DISTINCT FROM 'writer_pool_capacity'))
OR EXISTS (SELECT 1 FROM persistence_requests r JOIN persistence_worktrees w ON w.id=r.worktree_id
WHERE w.owner_host_id=$1::uuid AND r.recovery IS NOT NULL AND NOT (r.worktree_id::text=ANY($2::text[])))
@@ -117,7 +130,7 @@ export class PersistenceConsumer {
OR EXISTS (SELECT 1 FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation
JOIN pages p ON p.source_id=s.id AND p.slug=j.slug
WHERE p.deleted_at IS NULL AND NOT s.archived AND p.page_kind IN ('markdown','code')
- AND (j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds'))
+ AND ${PROJECTION_RETRY_READY_SQL})
OR EXISTS (SELECT 1 FROM persistence_topology_changes c
JOIN persistence_worktrees w ON w.id=(c.recovery->>'worktreeId')::uuid
WHERE c.recovery IS NOT NULL AND w.owner_host_id=$1::uuid AND NOT (c.id::text=ANY($4::text[])))
@@ -246,7 +259,9 @@ export class PersistenceConsumer {
.then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error))
.finally(() => { this.maintenanceWorker = undefined; });
}
- if (!this.projectionWorker) this.projectionWorker = rebuildPendingPageProjections(this.engine, 2)
+ if (!this.projectionWorker) this.projectionWorker = runResidentProjectionInvocation(this.engine, this.hostId,
+ [...this.activeRoots, ...this.rootRetryAfter.keys()], Date.now, this.engine.kind === 'postgres'
+ ? AbortSignal.any([this.abort.signal, AbortSignal.timeout(this.opts.phaseMs ?? 5000)]) : undefined)
.catch(error => this.report(error)).finally(() => { this.projectionWorker = undefined; });
// Recover only our owner roots. Kernel exclusion, not elapsed heartbeat,
// proves that a previous process can no longer be publishing this root.
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.ts
index dd72a62b11..8ee017187a 100644
--- a/src/core/persistence/coordinator.ts
+++ b/src/core/persistence/coordinator.ts
@@ -23,6 +23,7 @@ import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, recoveryStagingFil
import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
+import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
interface PreparedMutationBase {
sourceExclusive?: boolean;
@@ -33,7 +34,7 @@ interface PreparedMutationBase {
contentUnchanged?: boolean;
deferEmbedding?: boolean;
/** Why a page write bound to a worktree publishes no file (receipt `write_through.skipped`). */
- databaseOnlyReason?: 'db_only' | 'unbound_source';
+ databaseOnlyReason?: 'db_only' | 'unbound_source' | 'mirror_read_only';
/** Must perform only transaction-composable database work. */
apply(tx: BrainEngine): Promise<Record<string, unknown>>;
validate?(tx: BrainEngine): Promise<void>;
@@ -209,6 +210,11 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
if ((snapshot?.revision ?? null) !== prepared.observedRevision) throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');
}
await prepared.validate?.(tx);
+ // #5409: a file target prepared before the source became a read-only mirror is never published.
+ if (!skill && prepared.file && await sourceMirrorReadOnly(tx, row.source_id, true)) {
+ throw new OperationError('source_changed', 'The source became a read-only mirror after this write was prepared; nothing was written to its checkout.',
+ 'Retry the write with a new request_id; it is now stored database-only.');
+ }
if (recovery) {
const records = recoveryFiles(recovery);
for (const record of records) if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) {
@@ -235,10 +241,12 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr
}
const outcome = await withCoordinatedWrite(tx, [row.source_id], () => prepared.apply(tx));
if (!skill) await classifyUnboundPage(tx, row);
+ if (prepared.databaseOnlyReason === 'mirror_read_only') await classifyMirrorPage(tx, row);
const final = skill ? null : await tx.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if (final) outcome.revision = final.revision;
outcome.persistence = { mode: files.length ? 'filesystem' : 'database', ...(files.length ? { file_written: !prepared.noop } : {}), ...(skill ? { git_state: 'not_requested' } : {}) };
outcome.write_through = files.length ? { written: !prepared.noop } : { written: false, skipped: prepared.databaseOnlyReason ?? row.authority.databaseOnlyReason ?? 'no_repo_configured' };
+ if (prepared.databaseOnlyReason === 'mirror_read_only') outcome.storage = 'database_only';
if (row.operation === 'put_page' && row.authority.remote && row.authority.databaseOnlyReason === 'no_repo_configured') outcome.write_through = withNoRepoWriteThroughWarning(outcome.write_through as { written: boolean; skipped?: string }, row.source_id);
if ((outcome.write_through as { skipped?: string }).skipped === 'unbound_source') {
outcome.write_through = { ...outcome.write_through as object, warning: unboundWriteWarning(row.operation, row.source_id, row.authority.databaseOnlyReason === 'unbound_source') };
diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.ts
index c713c17c03..7acf6d65f1 100644
--- a/src/core/persistence/deactivation.ts
+++ b/src/core/persistence/deactivation.ts
@@ -37,7 +37,7 @@ import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots } from '.
import { recordTopologyChange } from './topology-receipts.ts';
import { lockTopologyPrincipal, topologyPrincipal } from './topology-locks.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
-import { readAllSourceHolds } from '../connectors/item-holds-store.ts';
+import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry, type HoldCarry } from '../connectors/item-holds-store.ts';
import { PHYSICAL_ROOT_MARKER, physicalRootReservationPath } from './physical-root-record.ts';
export const DEACTIVATE_DOCS = 'docs/architecture/topologies.md#deactivate-runbook';
@@ -68,6 +68,8 @@ export interface DeactivationReport {
source_bindings: number;
kept: { skill_bundles_enabled: boolean; writer_protocol_floor: number; writer_protocol_registrations: number };
blockers: DeactivationBlocker[];
+ /** Held connector items copied (or, on a dry run, to be copied) into each source's classic state file. */
+ carried_holds?: HoldCarry[];
local_markers?: LocalMarkerReport;
}
@@ -113,11 +115,20 @@ export async function deactivationBlockers(engine: BrainEngine): Promise<Deactiv
: e.state === 'failed' ? `gbrain sources writer retry-effects ${e.source_id} --request-id ${e.request_id} --dry-run`
: 'wait for the owner to drain it, then rerun deactivate' });
}
- // Managed connector holds live in the managed checkpoint, which classic mode does not read: a held item outside
- // the classic backfill window would drop out of retries and coverage warnings, so it is resolved first.
- for (const source of await readAllSourceHolds(engine)) {
- blockers.push({ kind: 'connector_holds', id: source.sourceId, source_id: source.sourceId, detail: `${source.held.length} held ${source.kind} item(s)`,
- exit: `gbrain sources status ${source.sourceId} names each item's error; fix its cause, then gbrain sources retry-held ${source.sourceId} and gbrain sync --source ${source.sourceId} (a successful re-attempt clears the hold)` });
+ // Managed connector holds live in the managed checkpoint, which classic mode does not read. Deactivation copies
+ // them into each source's classic state file; only a source whose holds have nowhere to go blocks it.
+ for (const carry of await planHoldCarry(engine, existingLocalHostId())) {
+ if (!holdCarryBlocked(carry)) continue;
+ const resolve = `gbrain sources status ${carry.source_id} names each item's error; fix its cause, then gbrain sources retry-held ${carry.source_id} and gbrain sync --source ${carry.source_id} (a successful re-attempt clears the hold)`;
+ blockers.push({ kind: 'connector_holds', id: carry.source_id, source_id: carry.source_id,
+ detail: carry.owner_host
+ ? `${carry.items} held item(s) on a worktree owned by host ${carry.owner_host}; deactivate cannot write that host's classic state`
+ : carry.state_file
+ ? `${carry.items} held item(s); the classic state file ${carry.state_file} does not parse (${carry.unreadable})`
+ : `${carry.items} held item(s) and no classic state directory to carry them into`,
+ exit: carry.owner_host
+ ? `run deactivate on host ${carry.owner_host}; or ${resolve}`
+ : carry.state_file ? `move ${carry.state_file} aside, then rerun deactivate; or ${resolve}` : resolve });
}
const leases = await engine.executeRaw<{ id: string; holder_host: string; holder_pid: number }>(
'SELECT id, holder_host, holder_pid FROM gbrain_cycle_locks WHERE ttl_expires_at > now() ORDER BY id');
@@ -164,7 +175,10 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
...(opts.dryRun ? {} : { local_markers: await cleanupRetiredManagedMarkers(engine) }) };
}
const blockers = await deactivationBlockers(engine);
- if (opts.dryRun) return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers };
+ if (opts.dryRun) {
+ const carried_holds = (await planHoldCarry(engine, existingLocalHostId())).filter(c => c.items > 0 && !holdCarryBlocked(c));
+ return { ...base, mode: 'managed', deactivated: false, mode_epoch: Number(brain.mode_epoch), blockers, carried_holds };
+ }
if (blockers.length) throw blockedError(blockers);
const principal = await topologyPrincipal(engine);
const requestId = opts.requestId ?? randomUUID();
@@ -196,6 +210,8 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
await opts.hooks?.afterLocks?.();
const inside = await deactivationBlockers(tx);
if (inside.length) throw blockedError(inside);
+ // Written before commit: if the transaction then fails, the brain stays managed and ignores these files.
+ const carried_holds = await carryHoldsToClassicState(tx, hostId);
const retired = await retiredTopology(tx);
const [epoch] = await tx.executeRaw<{ mode_epoch: string }>(
'UPDATE persistence_brain SET enabled=false, mode_epoch=mode_epoch+1 WHERE singleton=1 RETURNING mode_epoch::text');
@@ -210,7 +226,7 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?
incarnation: null, worktrees: retired.worktrees.map(w => w.id) }, outcome);
await refreshManagedFilesystemRoots(tx, managedFilesystemDatastorePath(engine));
return { ...base, mode: 'classic' as const, deactivated: true, mode_epoch: Number(epoch.mode_epoch), retired_mode_epoch: Number(current.mode_epoch),
- retired_worktrees: retired.worktrees, source_bindings: retired.bindings, blockers: [] };
+ retired_worktrees: retired.worktrees, source_bindings: retired.bindings, blockers: [], carried_holds };
});
} finally { for (const lock of locks.reverse()) await lock.release(); }
return { ...report, local_markers: await cleanupRetiredManagedMarkers(engine) };
diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.ts
index 33e947cfeb..ddb120cbdb 100644
--- a/src/core/persistence/effect-model.ts
+++ b/src/core/persistence/effect-model.ts
@@ -3,6 +3,7 @@ import type { WithdrawalTarget } from '../facts/withdrawal-discovery.ts';
export type EffectKind = 'git' | 'embedding' | 'withdrawal-mirror' | 'facts-backstop';
export interface ParkedTarget { slug?: string; error_code: string }
+export interface SkippedTarget { slug: string; reason: 'metafile' | 'file_database_drift' }
/** A Git or withdrawal target parks after this many consecutive execution failures. */
export const PARK_AFTER_FAILURES = 5;
export interface EffectRecovery {
@@ -39,7 +40,9 @@ export interface PersistenceEffect {
/** Parked scan targets an explicit retry authorized for one more attempt. */
retry_slugs?: string[];
/** Explicit retry authorizations granted to this effect's parked targets. */
- retried?: number };
+ retried?: number;
+ /** #5396: scan targets passed without a file publication (a sync-skip metafile, or a file with an uncoordinated local edit). */
+ skipped?: SkippedTarget[] };
state: 'queued' | 'running' | 'committed' | 'failed';
execution_token: string | null;
claim_expires_at: string | Date | null;
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index 29f22a83d8..c2e8c9c77f 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';
import { existsSync, statSync } from 'node:fs';
-import { join, relative, sep } from 'node:path';
+import { basename, join, relative, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import type { GBrainConfig } from '../config.ts';
@@ -30,10 +30,12 @@ import { guardEffectSource, recoverEffectPublication, reserveEffectRecovery } fr
import { commitGitTargets, publishGitEffect, pushGitRoot } from './effect-git.ts';
import { isDurabilityHardenedAsync } from '../brain-repo-durability.ts';
import { dispatchFactsBackstopEffect } from './effect-facts.ts';
-import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect } from './effect-model.ts';
+import { PARK_AFTER_FAILURES, type EffectRecovery, type PersistenceEffect, type SkippedTarget } from './effect-model.ts';
+import { SYNC_SKIP_FILES } from '../sync.ts';
import { recoveryStagingFile } from './staging.ts';
import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
+import { sourceMirrorReadOnly } from './mirror-read-only.ts';
export interface EffectWorkerOptions {
hostId: string;
@@ -77,7 +79,8 @@ async function finishPage(engine: BrainEngine, effect: PersistenceEffect, snapsh
}
/** Missing physical files never prevent the authoritative withdrawal from materializing. */
-async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot, hostId: string): Promise<void> {
+async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEffect, snapshot: PageSnapshot, hostId: string,
+ skipped?: SkippedTarget['reason']): Promise<void> {
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
await guardEffectSource(tx, effect, hostId);
@@ -85,10 +88,32 @@ async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEff
const current = await tx.readPageSnapshot(snapshot.page.slug, { sourceId: effect.source_id, includeDeleted: true });
if (current?.revision !== snapshot.revision || current.page.id !== snapshot.page.id) throw new OperationError('revision_conflict', 'The withdrawal page changed during preparation.');
await materializePageSnapshot(tx, current);
+ if (skipped) await recordSkippedTarget(tx, effect, { slug: current.page.slug, reason: skipped });
await finishPage(tx, effect, current);
});
}
+/** At most this many skipped scan targets are recorded on one effect. */
+const SKIPPED_TARGET_LIMIT = 100;
+
+async function recordSkippedTarget(engine: BrainEngine, effect: PersistenceEffect, target: SkippedTarget): Promise<void> {
+ await engine.executeRaw(`UPDATE persistence_effects SET data=jsonb_set(data,'{skipped}',COALESCE(data->'skipped','[]'::jsonb)||$3::text::jsonb)
+ WHERE id=$1 AND execution_token=$2::uuid AND jsonb_array_length(COALESCE(data->'skipped','[]'::jsonb))<$4`,
+ [effect.id, effect.execution_token, JSON.stringify([target]), SKIPPED_TARGET_LIMIT]);
+}
+
+/**
+ * #5396: sync never imports a metafile (RESOLVER.md carries the managed durability block by design),
+ * so its legacy page and file diverge; a scan never publishes either one to the other.
+ */
+function isMetafilePage(snapshot: PageSnapshot): boolean {
+ return !!snapshot.page.source_path && (SYNC_SKIP_FILES as readonly string[]).includes(basename(snapshot.page.source_path));
+}
+
+function isFileDatabaseDrift(error: unknown): boolean {
+ return error instanceof OperationError && error.code === 'source_changed' && error.detail === 'file_database_drift';
+}
+
/** The target a failing attempt was working on; unset means the failure is effect-wide. */
interface EffectAttempt { target?: string }
@@ -97,8 +122,16 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
if (!snapshot) { await completeEffect(engine, effect); return; }
attempt.target = snapshot.page.slug;
if (snapshot.sourceIncarnation !== effect.source_incarnation) throw new OperationError('source_changed', 'The mirror source was replaced.');
+ if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }
const content = serializePageToMarkdown(snapshot.page, snapshot.tags);
- const file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;
+ let file: Awaited<ReturnType<typeof prepareFileTarget>>;
+ try {
+ file = binding?.local_path ? await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot, content, opts.hostId, { allowMissing: true }) : undefined;
+ } catch (error) {
+ if (!isFileDatabaseDrift(error)) throw error;
+ await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'file_database_drift');
+ return;
+ }
if (!file || snapshot.page.deleted_at || !existsSync(file.path)) {
// A withdrawal cannot resurrect a deleted or missing physical page.
await materializeAndAdvance(engine, effect, snapshot, opts.hostId);
@@ -142,6 +175,8 @@ async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffec
async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding | null, opts: EffectWorkerOptions,
attempt: EffectAttempt, hardened: boolean | undefined): Promise<void> {
if (!binding?.local_path) { await completeEffect(engine, effect, { git: 'skipped', reason: 'no_repo_configured' }); return; }
+ // #5409: a read-only mirror's checkout is never committed to; its publications wrote no file.
+ if (await sourceMirrorReadOnly(engine, effect.source_id)) { await completeEffect(engine, effect, { git: 'skipped', reason: 'mirror_read_only' }); return; }
const root = binding.local_path;
if (!targetedWithdrawalEffect(effect) && !effect.data.source_scan) {
const target = await singleFileGitTarget(engine, effect, { ...binding, local_path: root }, attempt);
@@ -152,8 +187,20 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
const snapshot = await selectedEffectPage(engine, effect);
if (!snapshot) { await completeEffect(engine, effect); return; }
attempt.target = snapshot.page.slug;
- const file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,
- snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });
+ const skip = async (reason: SkippedTarget['reason']) => engine.transaction(async tx => {
+ await recordSkippedTarget(tx, effect, { slug: snapshot.page.slug, reason });
+ await finishPage(tx, effect, snapshot);
+ });
+ if (isMetafilePage(snapshot)) { await skip('metafile'); return; }
+ let file: Awaited<ReturnType<typeof prepareFileTarget>>;
+ try {
+ file = await prepareFileTarget(engine, { ...effect, slug: snapshot.page.slug }, snapshot,
+ snapshot.page.deleted_at ? null : serializePageToMarkdown(snapshot.page, snapshot.tags), opts.hostId, { allowMissing: true });
+ } catch (error) {
+ if (!isFileDatabaseDrift(error)) throw error;
+ await skip('file_database_drift');
+ return;
+ }
if (!file) throw new OperationError('source_changed', 'The Git binding changed.');
const path = file.path;
if (!existsSync(path)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId); return; }
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index 08c5d0da3a..0ca5beb6b5 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -33,6 +33,11 @@ export interface ManagedFactIntent extends Record<string, unknown> {
expected_revision?: string; facts?: FrozenExtractedFact[]; children?: string[];
/** Direct single-fact writes keep writeSingleFact's supersession rule. */
supersede?: true;
+ /**
+ * writeSingleFact only: a `memory/unattributed` row keeps the resolver's
+ * fallback slug as its entity (no row number), so dedup stays per entity.
+ */
+ attribute_fallback?: true;
embedding?: FactEmbeddingSignature | null;
}
export interface ManagedFactsSession {
@@ -212,7 +217,7 @@ export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFa
export async function publishManagedFacts(engine: BrainEngine, session: ManagedFactsSession, ctx: FactsBackstopCtx,
facts: ExtractedFact[], visibility: 'private' | 'world', pageSlug?: string,
- options: { supersede?: boolean; explicitContext?: boolean } = {}): Promise<ManagedFactsResult> {
+ options: { supersede?: boolean; explicitContext?: boolean; attributeFallback?: boolean } = {}): Promise<ManagedFactsResult> {
const embedded = facts.some(fact => fact.embedding !== null && fact.embedding !== undefined);
if (embedded) await assertManagedFactsEmbedding(engine, session.config, session.embedding);
const sourceId = session.authority.sourceId;
@@ -223,10 +228,11 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
const resolved = fact.entity_slug ? await resolveEntitySlugWithSource(engine, sourceId, fact.entity_slug) : null;
const entitySlug = resolved && resolved.source !== 'fallback_slugify' ? resolved.slug : null;
const slug = entitySlug ?? 'memory/unattributed';
+ const attributed = entitySlug ?? (options.attributeFallback && resolved ? resolved.slug : null);
await authorizeWrite(engine, session.authority, 'extract_facts', slug);
await authorizePageVisibility(engine, session.authority, slug);
const group = groups.get(slug) ?? [];
- group.push({ ...fact, entity_slug: entitySlug, visibility, context: options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null,
+ group.push({ ...fact, entity_slug: attributed, visibility, context: options.explicitContext ? fact.context ?? null : ctx.sourceSlug ?? pageSlug ?? null,
embedding: fact.embedding ? Array.from(fact.embedding) : null,
valid_from: (fact.valid_from ?? ctx.validFrom ?? new Date()).toISOString(), valid_until: fact.valid_until?.toISOString() ?? null });
groups.set(slug, group);
@@ -234,10 +240,11 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
const inputs: Array<{ slug: string; pageId: number | null; intent: ManagedFactIntent }> = [];
for (const [slug, group] of groups) {
const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
- if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug !== null) && !snapshot) throw new OperationError('page_identity_changed', 'The resolved fact entity was removed.');
+ if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug === slug) && !snapshot) throw new OperationError('page_identity_changed', 'The resolved fact entity was removed.');
inputs.push({ slug, pageId: snapshot?.page.id ?? null, intent: { kind: 'managed_facts_entity', batchKey: session.batchKey,
inputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,
embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),
+ ...(options.attributeFallback ? { attribute_fallback: true as const } : {}),
...(snapshot ? { expected_revision: snapshot.revision } : {}), facts: group } });
}
const rows = await engine.transaction(async tx => {
diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.ts
index 3826221cfb..1757d40531 100644
--- a/src/core/persistence/facts-prepare.ts
+++ b/src/core/persistence/facts-prepare.ts
@@ -74,7 +74,10 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
throw new OperationError('revision_conflict', 'The fact entity changed after extraction admission.');
}
const facts = (p.facts ?? []).map(fact => ({ ...thawFact(fact), embedding_model: fact.embedding ? p.embedding?.model ?? null : null }));
- if (!facts.length || facts.some(fact => fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot)) {
+ // writeSingleFact's opt-in: an unattributed row keeps its fallback entity slug, database-only.
+ const fallback = (fact: { entity_slug: string | null }) => p.attribute_fallback === true && row.slug === 'memory/unattributed'
+ && fact.entity_slug !== null && fact.entity_slug !== row.slug;
+ if (!facts.length || facts.some(fact => !fallback(fact) && (fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot))) {
throw new OperationError('invalid_params', 'The prepared facts do not match their entity.');
}
let body = snapshot?.page.compiled_truth ?? '';
@@ -86,14 +89,14 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ
const seen = new Map<string, number>();
for (const fact of facts) {
await assertFactNotWithdrawn(engine, row.source_id, fact);
- const key = JSON.stringify([fact.fact, fact.visibility]);
+ const key = JSON.stringify([fact.fact, fact.visibility, fact.entity_slug]);
const earlier = seen.get(key);
if (earlier !== undefined) { entries.push({ fact, duplicateId: null, duplicateOf: earlier }); continue; }
seen.set(key, entries.length);
const decision = await decideSingleFact(engine, row.source_id, fact, fact.embedding ?? null, fact.embedding_model);
const supersedes = p.supersede === true && decision.status === 'superseded' ? decision.candidate! : undefined;
if (decision.candidate && !supersedes) { entries.push({ fact, duplicateId: decision.candidate.id }); continue; }
- const rowNum = fact.entity_slug !== null ? nextRow++ : undefined;
+ const rowNum = fact.entity_slug !== null && !fallback(fact) ? nextRow++ : undefined;
if (rowNum !== undefined) body = upsertFactRow(body, { rowNum, claim: fact.fact, kind: fact.kind, visibility: fact.visibility,
confidence: fact.confidence ?? 1, notability: fact.notability ?? 'medium', source: fact.source, context: fact.context ?? undefined,
validFrom: formatFenceDate(fact.valid_from!), validUntil: fact.valid_until ? formatFenceDate(fact.valid_until) : undefined,
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index a874d27d24..8019e54d45 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -66,8 +66,17 @@ export interface PersistenceIpcAdminRequest {
registration: PersistenceIpcRegistration;
}
+/** #5401: the resident's queued text-projection backlog. Counts only, never identifiers. */
+export interface PersistenceProjectionStatus {
+ pending: number;
+ failed: number;
+ oldest_age_seconds: number | null;
+}
+
export interface PersistenceIpcProvider {
brainId: string;
+ /** Read-only and credential-free, like capabilities: serves doctor while this process holds the datastore. */
+ projectionStatus?(): Promise<PersistenceProjectionStatus>;
/** Authenticate registration against the DB, reconstruct context, then dispatch through the registry. */
dispatch(request: PersistenceIpcRequest): Promise<unknown>;
/** Verify the live CLI registration again; never accept stdio or a wire trust assertion. */
@@ -201,6 +210,15 @@ export async function startPersistenceIpcServer(
} satisfies PersistenceIpcCapabilities }));
return;
}
+ if (record(request) && exactKeys(request, ['version', 'kind']) && request.version === 1 && request.kind === 'projection_status') {
+ if (!provider.projectionStatus) throw new OperationError('unavailable', 'This owner does not report projection status.');
+ if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw new OperationError('queue_capacity', 'The persistence listener is at capacity; retry shortly.');
+ active++;
+ admitted = true;
+ const status = await provider.projectionStatus();
+ if (!socket.destroyed) socket.end(responseFrame({ version: 1, ok: true, result: status }));
+ return;
+ }
if (!operationRequest(request) && !administrationRequest(request)) throw new OperationError('invalid_params', 'Invalid persistence request envelope.');
if (request.brain_id !== provider.brainId) throw new OperationError('source_changed', 'The persistence listener now serves a different brain.');
if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw new OperationError('queue_capacity', 'The persistence listener is at capacity; retry this request ID.');
@@ -342,6 +360,17 @@ export async function requestPersistenceCapabilities(socketPath: string, timeout
return value as unknown as PersistenceIpcCapabilities;
}
+function count(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
+}
+
+export async function requestPersistenceProjectionStatus(socketPath: string, timeoutMs = 2_000): Promise<PersistenceProjectionStatus> {
+ const value = await exchange(socketPath, { version: 1, kind: 'projection_status' }, timeoutMs);
+ if (!record(value) || !count(value.pending) || !count(value.failed)
+ || !(value.oldest_age_seconds === null || count(value.oldest_age_seconds))) throw new PersistenceIpcTransportError(false);
+ return { pending: value.pending, failed: value.failed, oldest_age_seconds: value.oldest_age_seconds };
+}
+
export async function requestPersistenceOperation(socketPath: string, request: PersistenceIpcRequest, timeoutMs = 30_000): Promise<unknown> {
if (!operationRequest(request)) throw new OperationError('invalid_params', 'Invalid persistence request envelope.');
return exchange(socketPath, request, timeoutMs,
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index 54505171a6..268d15d482 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -182,20 +182,34 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
} };
}
-/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */
-export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {
- return engine.transactionDirect(async tx => {
- await declarePersistenceProtocol(tx);
- const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
- LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
- WHERE r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
+/**
+ * The rows `claimNextWrite` may claim, over `persistence_requests r LEFT JOIN
+ * persistence_worktrees w`, with $1 = host id and $2 = excluded root keys. An
+ * unresolved head blocks its entire root.
+ */
+export const CLAIMABLE_WRITE_SQL = `r.state='queued' AND (r.worktree_id IS NULL OR (w.owner_host_id=$1::uuid AND w.state='active'))
AND NOT (COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)=ANY($2::text[]))
AND NOT EXISTS (SELECT 1 FROM persistence_effects blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM persistence_requests blocked WHERE blocked.worktree_id=r.worktree_id AND blocked.recovery IS NOT NULL)
AND NOT EXISTS (SELECT 1 FROM persistence_requests earlier
WHERE COALESCE(earlier.worktree_id::text,'db:'||earlier.source_incarnation::text)
=COALESCE(r.worktree_id::text,'db:'||r.source_incarnation::text)
- AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))
+ AND earlier.sequence<r.sequence AND earlier.state IN ('queued','running','recovering'))`;
+
+/** #5401: whether `claimNextWrite` would find a row now. Read-only: no lock and no claim. */
+export async function hasClaimableWrite(engine: SqlEngine, hostId: string, excludeRoots: string[] = [], signal?: AbortSignal): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ claimable: boolean }>(`SELECT EXISTS (SELECT 1 FROM persistence_requests r
+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id WHERE ${CLAIMABLE_WRITE_SQL} LIMIT 1) AS claimable`, [hostId, excludeRoots], { signal });
+ return row?.claimable === true;
+}
+
+/** Claims commit before OS-lock waits. An unresolved head blocks its entire root. */
+export async function claimNextWrite(engine: BrainEngine, hostId: string, leaseMs = 30_000, excludeRoots: string[] = []): Promise<WriteRequest | null> {
+ return engine.transactionDirect(async tx => {
+ await declarePersistenceProtocol(tx);
+ const [row] = await tx.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r
+ LEFT JOIN persistence_worktrees w ON w.id=r.worktree_id
+ WHERE ${CLAIMABLE_WRITE_SQL}
ORDER BY r.sequence LIMIT 1 FOR UPDATE OF r SKIP LOCKED`, [hostId, excludeRoots]);
if (!row) return null;
const [claimed] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='running',
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index 1211254fb4..3477a08564 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { configDir, type GBrainConfig } from '../config.ts';
import { resolveBrainId } from '../brain-resolver.ts';
+import { getCliOptions } from '../cli-options.ts';
import { loadMounts, type MountEntry } from '../brain-registry.ts';
import { inspectLockHolder } from '../pglite-lock.ts';
import { resolveSourceIdEngineFree } from '../source-resolver.ts';
@@ -29,6 +30,19 @@ export function persistenceConfigForBrain(
return { engine: mount.engine, database_path: mount.database_path, database_url: mount.database_url } as GBrainConfig;
}
+/**
+ * The persistence config of the brain a resident serve's engine opened, resolved
+ * exactly as the CLI resolves it (--brain, GBRAIN_BRAIN_ID, .gbrain-mount, mount
+ * path), so a mounted serve binds the owner socket the CLI probes (#5237).
+ * Host-level settings stay; only the datastore identity follows the mount.
+ */
+export function residentPersistenceConfig(hostConfig: GBrainConfig | null, cwd = process.cwd()): GBrainConfig | null {
+ const brainId = resolveBrainId(getCliOptions().brain, cwd);
+ if (brainId === 'host') return hostConfig;
+ const brain = persistenceConfigForBrain(hostConfig, brainId, loadMounts())!;
+ return { ...hostConfig, engine: brain.engine, database_path: brain.database_path, database_url: brain.database_url } as GBrainConfig;
+}
+
/** Reads an existing registration only. Revocation/missing credentials never create a new principal. */
export function readPersistenceCliRegistration(brainId: string): PersistenceIpcRegistration {
// Capability validation has already constrained this filename component to a UUID.
diff --git a/src/core/persistence/mirror-read-only.ts b/src/core/persistence/mirror-read-only.ts
new file mode 100644
index 0000000000..8b8bd5baed
--- /dev/null
+++ b/src/core/persistence/mirror-read-only.ts
@@ -0,0 +1,31 @@
+/**
+ * #5409: a per-source read-only mirror (`sources.config.mirror_read_only`,
+ * default false, set by `gbrain sources mirror-readonly|mirror-writable`).
+ * The source's Git remote is authoritative: managed publication never writes
+ * a file into its checkout. Sync imports canonical metadata database-only, and
+ * a page write into the source is stored database-only (`storage:
+ * "database_only"` on the receipt), so `git pull --ff-only` keeps working.
+ * A page created that way (no recorded file) carries
+ * `pages.database_only_reason='mirror_read_only'` and stays database-only
+ * after `mirror-writable`, as an unbound-source page does (#5254).
+ */
+import type { SqlEngine } from './model.ts';
+
+/** `lock`: inside a publication, hold the source row so a concurrent mode change waits for this write. */
+export async function sourceMirrorReadOnly(engine: SqlEngine, sourceId: string, lock = false): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ read_only: boolean }>(
+ `SELECT COALESCE(config->>'mirror_read_only','false')='true' AS read_only FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [sourceId]);
+ return row?.read_only === true;
+}
+
+/** Marks a page this publication stored database-only because its source is a read-only mirror and it has no recorded file. */
+export async function classifyMirrorPage(tx: SqlEngine, row: { source_id: string; slug: string }): Promise<void> {
+ await tx.executeRaw(`UPDATE pages SET database_only_reason='mirror_read_only'
+ WHERE source_id=$1 AND slug=$2 AND database_only_reason IS NULL AND NULLIF(source_path,'') IS NULL`, [row.source_id, row.slug]);
+}
+
+export async function isMirrorOnlyPage(engine: SqlEngine, sourceId: string, slug: string): Promise<boolean> {
+ const [row] = await engine.executeRaw<{ database_only_reason: string | null }>(
+ 'SELECT database_only_reason FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);
+ return row?.database_only_reason === 'mirror_read_only';
+}
diff --git a/src/core/persistence/native-file-target.ts b/src/core/persistence/native-file-target.ts
index 3844983d15..21f5679faa 100644
--- a/src/core/persistence/native-file-target.ts
+++ b/src/core/persistence/native-file-target.ts
@@ -1,6 +1,7 @@
import { lstatSync, readdirSync, realpathSync, statSync, type BigIntStats } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import { OperationError } from '../ops/contract.ts';
+import { catalogueError } from '../error-catalogue.ts';
export function nativeFileTarget(root: string, target: string, code?: string): string {
const unsafe = () => new OperationError(code ?? 'source_changed', 'The canonical file target has no unambiguous native identity.',
@@ -51,3 +52,20 @@ export function nativeFileTarget(root: string, target: string, code?: string): s
throw inaccessible();
}
}
+
+/**
+ * #5032: `:` is not a legal NTFS file-name character (Windows reads it as an
+ * alternate data stream), so a page whose canonical file name would contain
+ * one has no file on Windows. Refused rather than mangled; database-only
+ * writes of the same slug are unaffected.
+ */
+export function colonSlugWindowsRefusal(slug: string, sourceId: string): OperationError {
+ return catalogueError('colon_slug_windows_write_through',
+ `Page ${slug} has a ':' in its file name, which Windows cannot store.`,
+ `Use a slug without ':' (for example ${slug.replaceAll(':', '-')}), or write ${slug} from a macOS or Linux host that owns source ${sourceId}.`);
+}
+
+/** #5032: true when this process is on Windows and the relative file target contains `:`. */
+export function isWindowsColonTarget(relativeTarget: string): boolean {
+ return process.platform === 'win32' && relativeTarget.includes(':');
+}
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 53e212ef55..ce3e0f9607 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -4,6 +4,8 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { discoverGitRoot } from '../sync-git.ts';
+import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';
+import { createProgress, type ProgressOptions } from '../progress.ts';
import { digest, sha256 } from './digest.ts';
import { localHostId, persistenceHome } from './identity.ts';
import type { SqlEngine, WriteRequest } from './model.ts';
@@ -153,30 +155,61 @@ export async function activateManagedPersistence(engine: BrainEngine, opts: { co
await activatePersistence(engine, opts);
}
-/** Deterministic content manifest includes deletions by exact path-set equality. */
-export function worktreeManifest(root: string): { digest: string; files: Record<string, string> } {
+export interface WorktreeManifest { digest: string; file_count: number }
+export type StoredWorktreeManifest = WorktreeManifest & { canonical_stamp?: string; self_transfer?: PhysicalRootRecovery };
+export const MANIFEST_PROGRESS_MIN_FILES = 5000;
+
+/**
+ * Deterministic content manifest includes deletions by exact path-set equality.
+ * The per-file hash map stays local; stored manifests carry only its digest
+ * and file count, so their size does not grow with the worktree.
+ */
+export function worktreeManifest(root: string, opts: { progress?: ProgressOptions } = {}): WorktreeManifest {
const canonical = realpathSync(root);
- const files: Record<string, string> = {};
+ const paths: string[] = [];
const visit = (dir: string) => {
for (const name of readdirSync(dir).sort()) {
if (name === '.git' || name === '.gbrain-managed' || isPhysicalRootMetadata(name)) continue;
const path = join(dir, name), info = lstatSync(path);
if (info.isSymbolicLink()) throw new OperationError('writer_manifest_unsafe', 'Canonical worktree transfer requires a symlink-free manifest.');
if (info.isDirectory()) visit(path);
- else if (info.isFile()) files[relative(canonical, path).split(sep).join('/')] = sha256(readFileSync(path));
+ else if (info.isFile()) paths.push(path);
}
};
visit(canonical);
- return { digest: digest(files), files };
+ const progress = opts.progress && paths.length > MANIFEST_PROGRESS_MIN_FILES ? createProgress(opts.progress) : undefined;
+ progress?.start('sources.manifest_hash', paths.length);
+ const files: Record<string, string> = {};
+ for (const path of paths) {
+ files[relative(canonical, path).split(sep).join('/')] = sha256(readFileSync(path));
+ progress?.tick();
+ }
+ progress?.finish();
+ return { digest: digest(files), file_count: paths.length };
+}
+
+/** Human-mode progress for manifest hashing; JSON and quiet modes report nothing. */
+export function humanManifestProgress(): ProgressOptions | undefined {
+ const options = cliOptsToProgressOptions(getCliOptions());
+ return options.mode === 'auto' ? options : undefined;
+}
+
+/** Drops a legacy per-file map from a stored manifest, keeping every other field. */
+export function compactStoredManifest<T extends { digest: string; files?: Record<string, string>; file_count?: number }>(manifest: T): Omit<T, 'files'> & { file_count: number } {
+ const { files, ...rest } = manifest;
+ return { ...rest, file_count: rest.file_count ?? Object.keys(files ?? {}).length };
}
export async function prepareWriterTransfer(engine: BrainEngine, sourceId: string, hostId = localHostId(), expectedAdminState?: string,
- opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: ReturnType<typeof worktreeManifest> }> {
+ opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: StoredWorktreeManifest }> {
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding || binding.owner_host_id !== hostId || !binding.local_path) throw new OperationError('permission_denied', 'Only the current owner can prepare this transfer.');
if (!binding.coordination_path) throw new OperationError('recovery_required', 'The recorded coordination path is missing.');
const lock = opts.selfTransfer ? await acquireNativeLock(binding.coordination_path, { timeoutMs: 5000 }) : await acquireWorktree(binding, 5000);
if (!lock) throw new OperationError('write_pending', 'The worktree is busy; retry transfer preparation.');
try {
+ // The native lock already excludes writers, so hash before checking out a
+ // connection. A hashing failure surfaces after the root checks below, as before.
+ const hashed = (() => { try { return worktreeManifest(binding.local_path!, { progress: humanManifestProgress() }); } catch (error) { return error as Error; } })();
return await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await assertWriterAdminState(tx, expectedAdminState);
@@ -193,7 +226,8 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
const recovery = opts.selfTransfer ? inspectPhysicalRootRecovery(binding.local_path!, { brainId: brain.brain_id,
worktreeId: binding.worktree_id, hostId, coordinationPath: binding.coordination_path! }) : undefined;
if (!opts.selfTransfer) assertPhysicalRoot(binding.local_path!, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });
- const manifest = { ...worktreeManifest(binding.local_path!), ...(recovery ? { self_transfer: recovery } : {}) };
+ if (hashed instanceof Error) throw hashed;
+ const manifest: StoredWorktreeManifest = { ...hashed, ...(recovery ? { self_transfer: recovery } : {}) };
if (!opts.dryRun) await tx.executeRaw(`UPDATE persistence_worktrees SET state='draining',manifest=$2::text::jsonb WHERE id=$1::uuid`, [binding.worktree_id, JSON.stringify(manifest)]);
return { worktree_id: binding.worktree_id, owner_epoch: String(owner.owner_epoch), manifest };
});
@@ -202,8 +236,6 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string, path: string, expectedEpoch: string, expectedManifest: string, hostId = localHostId(), expectedAdminState?: string,
opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<void> {
const root = realpathSync(resolve(path));
- const manifest = worktreeManifest(root);
- if (manifest.digest !== expectedManifest) throw new OperationError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.');
const binding = await getWorktreeBinding(engine, sourceId, hostId);
if (!binding) throw new OperationError('not_found', 'Source has no worktree owner.');
if (opts.selfTransfer && binding.owner_host_id !== hostId) throw new OperationError('permission_denied', 'Self-transfer requires the current owner host.');
@@ -213,6 +245,8 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
const lock = await acquireNativeLock(coordination, { timeoutMs: 5000 });
if (!lock) throw new OperationError('write_pending', 'Successor worktree is busy.');
try {
+ if (worktreeManifest(root, { progress: humanManifestProgress() }).digest !== expectedManifest)
+ throw new OperationError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.');
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await assertWriterAdminState(tx, expectedAdminState);
@@ -222,7 +256,7 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
if (!!owner.manifest.self_transfer !== !!opts.selfTransfer || JSON.stringify(await getWorktreeBinding(tx, sourceId, hostId)) !== JSON.stringify(binding)) throw new OperationError('writer_transfer_conflict', 'The prepared transfer mode or binding changed.');
const pending = await tx.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND (state IN ('running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [binding.worktree_id]);
const mirrors = await tx.executeRaw('SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [binding.worktree_id]);
- if (pending.length || mirrors.length || worktreeManifest(root).digest !== expectedManifest) throw new OperationError('recovery_required', 'Transfer state changed; prepare again.');
+ if (pending.length || mirrors.length) throw new OperationError('recovery_required', 'Transfer state changed; prepare again.');
if (opts.selfTransfer) repairPhysicalRoot(root, owner.manifest.self_transfer!, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination }, opts.dryRun);
else if (!opts.dryRun) await preparePhysicalRootTransfer(tx, root, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination, expectedEpoch });
if (opts.dryRun) return;
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 5c91c8c081..64e361505d 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -19,7 +19,10 @@ import { assertPurgeParams } from './purge-params.ts';
import type { Principal } from './model.ts';
import { normalizeSubagentPageInput } from './page-input.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';
+import { isUnboundSourcePage, readUnboundWritePolicy, unboundSourceError } from './unbound-source.ts';
+import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';
+import { publishesDatabaseOnly } from './page-prepare.ts';
+import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { isConnectorSourceKind } from './connector-identity.ts';
export async function requestPrincipalForContext(ctx: OperationContext): Promise<Principal> {
@@ -180,6 +183,16 @@ export async function submitPageMutation(ctx: OperationContext,
authority.databaseOnlyReason = 'unbound_source';
}
}
+ // #5032: this host publishes the canonical file, and on Windows a ':' in its
+ // name cannot be stored; refuse before admission. Database-only writes pass,
+ // including read-only mirror sources and pages created while one (#5409).
+ if (writeThrough && binding?.owner_host_id === localHostId() && binding.local_path && isWindowsColonTarget(snapshot?.page.source_path ?? `${slug}.md`)
+ && !(snapshot && !snapshot.page.source_path && await isUnboundSourcePage(ctx.engine, sourceId, slug))
+ && !await sourceMirrorReadOnly(ctx.engine, sourceId)
+ && !(snapshot && !snapshot.page.source_path && await isMirrorOnlyPage(ctx.engine, sourceId, slug))
+ && !publishesDatabaseOnly(join(binding.local_path, binding.relative_path), slug, snapshot)) {
+ throw colonSlugWindowsRefusal(slug, sourceId);
+ }
const row = await admitWrite(ctx.engine, { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,
slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,
worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index d0d2c20ada..3b4bd4c43f 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -1,7 +1,7 @@
import { isEmbedSkipped } from '../embed-skip.ts';
import { isQuarantined } from '../quarantine.ts';
import { existsSync, readFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { join, relative } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
@@ -28,8 +28,9 @@ import { isAutoLinkEnabled } from '../link-extraction.ts';
import { prepareAutomaticLinks } from './links-preparation.ts';
import { preparePageAdvisories, remoteLinkHint, pageNoopAdvisories } from './page-advisories.ts';
import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';
-import { nativeFileTarget } from './native-file-target.ts';
+import { colonSlugWindowsRefusal, isWindowsColonTarget, nativeFileTarget } from './native-file-target.ts';
import { isSourceDbOnlySlug } from './source-storage.ts';
+import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';
import { DERIVE_PHASE_DB_ONLY_DEFAULTS } from '../storage-config.ts';
import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';
import { readSlugRootMode } from '../sync-anchor.ts';
@@ -71,9 +72,20 @@ function putProvenance(row: WriteRequest, snapshot: PageSnapshot | null, parsed:
function isNeverFiledDerivedPage(slug: string, page: { source_path?: string | null; source_uri?: string | null }): boolean {
return !page.source_path && !page.source_uri && DERIVE_PHASE_DB_ONLY_DEFAULTS.some(prefix => slug.startsWith(prefix));
}
+/**
+ * A live page whose canonical file is absent publishes to the database only
+ * when its slug is a declared db_only path or a never-filed derive-phase page.
+ */
+export function publishesDatabaseOnly(root: string, slug: string, snapshot: PageSnapshot | null): boolean {
+ if (!snapshot || snapshot.page.deleted_at) return false;
+ return isSourceDbOnlySlug(root, slug, 'refuse') || isNeverFiledDerivedPage(slug, snapshot.page);
+}
export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequest, 'source_id' | 'worktree_id' | 'slug'>, snapshot: PageSnapshot | null,
content: string | null, hostId?: string, options: { allowMissing?: boolean; capture?: { path: string; hash: string } } = {}): Promise<PreparedMutation['file']> {
if (!row.worktree_id) return undefined;
+ // #5409: a read-only mirror's checkout belongs to its Git remote; nothing is written or removed there.
+ if (await sourceMirrorReadOnly(engine, row.source_id)) return undefined;
+ if (snapshot && !snapshot.page.source_path && await isMirrorOnlyPage(engine, row.source_id, row.slug)) return undefined;
// #5254: a page written while its source was unbound stays database-only in
// every state (live, tombstone, restore, revert, delete, purge); any file at
// its derived path is not its canonical file and is neither written nor removed.
@@ -84,20 +96,24 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
// #5622: a new page captured from a file inside the source is published to that file.
const capturedPath = !snapshot && options.capture ? options.capture.path : recordedPathFromFileUri(snapshot?.page.source_uri, root);
const mode = snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, root) : undefined;
- const path = nativeFileTarget(root, resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug, mode)
- ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`)));
+ const candidate = resolveSourceLocalFilePath(root, snapshot?.page.source_path, row.slug, mode)
+ ?? (capturedPath ? join(root, capturedPath) : join(root, `${row.slug}.md`));
+ if (isWindowsColonTarget(relative(root, candidate))) {
+ if (!options.allowMissing && publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;
+ throw colonSlugWindowsRefusal(row.slug, row.source_id);
+ }
+ const path = nativeFileTarget(root, candidate);
if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical file target is outside its registered source.');
const before = existsSync(path) ? readFileSync(path) : null;
if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {
// A declared db_only page has no canonical file by design and publishes to
// the database only. gbrain.yml is consulted only here, where the write
// would otherwise refuse, so an invalid config can only change the refusal.
- if (isSourceDbOnlySlug(root, row.slug, 'refuse')) return undefined;
// Derive-phase output (atoms/, concepts/, ...) is database-only by design and
// deliberately never declared in gbrain.yml. A page there that never recorded a
// canonical file publishes to the database only; a recorded file that went
// missing still refuses below.
- if (isNeverFiledDerivedPage(row.slug, snapshot.page)) return undefined;
+ if (publishesDatabaseOnly(root, row.slug, snapshot)) return undefined;
throw new OperationError('source_changed', 'The canonical file was removed outside coordinated publication.',
'Import the local deletion or recover the canonical file before editing this page.');
}
@@ -128,20 +144,24 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ
/**
* Receipt reason for a page write that publishes no file. Invariant: for a
* bound row, prepareFileTarget returns no target only for a live declared
- * db_only page whose file is absent, or a page written while its source was
- * unbound (#5254) in any state; every other case returns a target or throws.
+ * db_only page whose file is absent, a page of a read-only mirror source
+ * (#5409), or a page written while its source was unbound (#5254) in any state; every other case returns a target or throws.
*/
export function databaseOnlyPublication(row: Pick<WriteRequest, 'worktree_id'>, file: PreparedMutation['file']): Pick<PreparedMutation, 'databaseOnlyReason'> {
return row.worktree_id && !file ? { databaseOnlyReason: 'db_only' } : {};
}
async function pageDatabaseOnlyPublication(engine: SqlEngine, row: WriteRequest, file: PreparedMutation['file']): Promise<Pick<PreparedMutation, 'databaseOnlyReason'>> {
const reason = databaseOnlyPublication(row, file);
+ if (reason.databaseOnlyReason && (await sourceMirrorReadOnly(engine, row.source_id) || await isMirrorOnlyPage(engine, row.source_id, row.slug))) {
+ return { databaseOnlyReason: 'mirror_read_only' };
+ }
return reason.databaseOnlyReason && await isUnboundSourcePage(engine, row.source_id, row.slug) ? { databaseOnlyReason: 'unbound_source' } : reason;
}
/** Providers and parsing run before the OS lock and before any publication transaction. */
export async function preparePageMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig,
- preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal): Promise<PreparedMutation> {
+ preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,
+ options: { allowMissingFile?: boolean } = {}): Promise<PreparedMutation> {
signal?.throwIfAborted();
if (!row.intent) throw new OperationError('storage_error', 'A pending write lost its normalized intent.');
await assertKnowledgePublicationAllowed(engine, row);
@@ -168,7 +188,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
// Tombstones still own their recorded artifact. Purge always attempts its
// removal before the guarded hard-delete and receipt commit; failure rolls
// back to the prior row, and replay survives the eventual absence of that row.
- const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge });
+ const file = await prepareFileTarget(engine, row, snapshot, null, undefined, { allowMissing: purge || options.allowMissingFile });
return { observedRevision, noop, file, ...await pageDatabaseOnlyPublication(engine, row, file), apply: async tx => {
if (purge) {
await tx.deletePage(row.slug, source);
@@ -278,7 +298,7 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest
? await prepareAutomaticLinks(engine,row.slug,ready.parsedPage,row.source_id) : undefined;
const capture = row.operation === 'capture' && typeof p.capture_path === 'string' && typeof p.capture_file_hash === 'string'
? { path: p.capture_path, hash: p.capture_file_hash } : undefined;
- const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture });
+ const file = await prepareFileTarget(engine, row, snapshot, targetDeleted ? null : rendered, undefined, { capture, allowMissing: options.allowMissingFile });
const mintMode = file && !snapshot?.page.source_path ? await scannerSlugRootMode(engine, row.source_id, file.root) : undefined;
const sourcePath = file && mintMode ? scannerSourcePath(file.root, file.path, mintMode) : undefined;
// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).
diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.ts
index d720d1e718..a26909dbbe 100644
--- a/src/core/persistence/prepared-maintenance.ts
+++ b/src/core/persistence/prepared-maintenance.ts
@@ -118,8 +118,18 @@ export async function publishMaintenancePage(engine: BrainEngine, authority: Mai
/** A maintenance request with its own intent kind, keyed by the intent (a retry replays its receipt). */
export async function submitMaintenanceIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
- intent: Record<string, unknown> & { kind: string; expected_revision: string | null }): Promise<Record<string, unknown>> {
- return submitMaintenance(engine, authority, slug, intent, maintenanceRequestId({ authority: authority.writer, slug, intent }));
+ intent: Record<string, unknown> & { kind: string; expected_revision: string | null }, requestId?: string): Promise<Record<string, unknown>> {
+ return submitMaintenance(engine, authority, slug, intent, requestId ?? maintenanceRequestId({ authority: authority.writer, slug, intent }));
+}
+
+/**
+ * A database-only maintenance request under a caller-chosen request id: a
+ * preview-approved item (`gbrain repair extractor-facts`) replays its own id
+ * after a crash. No worktree is bound, so no file is staged.
+ */
+export async function submitDatabaseMaintenanceIntent(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
+ intent: Record<string, unknown> & { kind: string; expected_revision: string | null }, requestId: string): Promise<Record<string, unknown>> {
+ return submitMaintenance(engine, authority, slug, intent, requestId, false);
}
export async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,
@@ -263,6 +273,7 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,
export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
if (row.authority.remote) throw new OperationError('permission_denied', 'Remote maintenance publication is not supported.');
+ if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);
if (row.intent?.kind === 'managed_maintenance_page') {
const prepared = await preparePageMutation(engine, row.intent.expected_revision === null
? { ...row, intent: { ...row.intent, expected_revision: undefined } } : row, config);
@@ -282,6 +293,7 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Write
if (row.intent?.kind === 'managed_maintenance_adopt_fact_fence') return prepareFactFenceAdoption(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);
if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(engine, row, config);
+ if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);
if (row.intent?.kind !== 'managed_maintenance_consolidate') throw new OperationError('invalid_params', 'Unsupported maintenance request.');
const p = row.intent;
const facts = p.facts as FactSnapshot[];
diff --git a/src/core/persistence/preview-approval.ts b/src/core/persistence/preview-approval.ts
new file mode 100644
index 0000000000..582278a2e2
--- /dev/null
+++ b/src/core/persistence/preview-approval.ts
@@ -0,0 +1,104 @@
+/**
+ * Preview-bound approval (fix wave 5, ENG-O1), shared by every command whose
+ * apply must touch exactly the set its preview showed: `gbrain jobs
+ * authorize-legacy --select`, `gbrain jobs cancel --select`, `gbrain repair
+ * stale-atoms` and `gbrain repair extractor-facts`.
+ *
+ * The flow is the same for all four:
+ *
+ * 1. The preview computes `previewHash(parts)` over everything the operator
+ * reviewed (brain and source identity, the listed items with their
+ * revisions or evidence, the selection options) and saves the items with
+ * `saveApprovedSet`. It prints the hash and the filled apply command.
+ * 2. The apply passes the hash back (`--expect <hash>`). `loadApprovedSet`
+ * returns the saved items, or refuses with `preview_changed` when no set
+ * was saved under that hash or the set is older than the checkpoint purge
+ * window. A refused load never returns a partial set, so an apply either
+ * starts from the whole approved set or not at all.
+ * 3. The apply replays the approved items (each with its own request id, so
+ * a resumed apply after a crash replays the same requests and reconciles
+ * their receipts before advancing), rechecking each item against the
+ * live state, and calls `clearApprovedSet` when it finishes.
+ *
+ * Sets live in `op_checkpoints` (`op='repair-approval'`, keyed by command and
+ * hash), so no migration is needed. `purgeStaleCheckpoints` deletes rows older
+ * than its TTL (7 days by default); `APPROVAL_MAX_AGE_DAYS` matches it, so a
+ * set the purge may already have taken is never trusted.
+ *
+ * `previewHash` is SHA-256 over the same key-sorted JSON as
+ * `authorityDigest` (`minions/submission-authority.ts`), so the existing
+ * `authorizeLegacyJobs --ids` snapshot digest is byte-identical when computed
+ * through this helper.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { OperationError } from '../ops/contract.ts';
+import { catalogueError } from '../error-catalogue.ts';
+import { digest } from './digest.ts';
+
+export const PREVIEW_APPROVAL_OP = 'repair-approval';
+
+/** The default `purgeStaleCheckpoints` TTL; an older approved set may already be gone. */
+export const APPROVAL_MAX_AGE_DAYS = 7;
+
+export type PreviewApprovalCommand = 'authorize-legacy' | 'jobs-cancel' | 'stale-atoms' | 'extractor-facts';
+
+export interface ApprovedSetKey {
+ command: PreviewApprovalCommand;
+ /** The preview hash the operator passed with `--expect`. */
+ hash: string;
+ /** The read-only command that prints a fresh preview, filled with the caller's real flags. */
+ previewCommand: string;
+}
+
+export interface ApprovedSet<T> {
+ command: PreviewApprovalCommand;
+ hash: string;
+ items: T[];
+ /** When the preview last saved this set (database clock, ISO 8601). */
+ approved_at: string;
+}
+
+/** SHA-256 hex over key-sorted JSON of everything the preview showed. */
+export function previewHash(parts: unknown): string {
+ return digest(parts);
+}
+
+/** `preview_changed`: the hash no longer names a saved, fresh approved set. */
+export function previewChangedError(hash: string, previewCommand: string): OperationError {
+ return catalogueError('preview_changed', `The preview changed since ${hash}; re-run ${previewCommand} and use the new hash.`,
+ `Re-run the preview: ${previewCommand}`);
+}
+
+function fingerprint(command: PreviewApprovalCommand, hash: string): string {
+ return `${command}:${hash}`;
+}
+
+/** Saves (or re-confirms, restarting its age) the approved set a preview printed. */
+export async function saveApprovedSet<T>(engine: BrainEngine, key: Omit<ApprovedSetKey, 'previewCommand'>, items: readonly T[]): Promise<void> {
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)
+ ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
+ [PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash), JSON.stringify([{ command: key.command, hash: key.hash, items }])]);
+}
+
+/**
+ * The whole approved set saved under `hash`, or `preview_changed` when it is
+ * missing, malformed or older than `APPROVAL_MAX_AGE_DAYS`. Age is measured on
+ * the database clock, the same clock the purge uses.
+ */
+export async function loadApprovedSet<T>(engine: BrainEngine, key: ApprovedSetKey): Promise<ApprovedSet<T>> {
+ const [row] = await engine.executeRaw<{ completed_keys: Array<{ command?: string; hash?: string; items?: T[] }>; fresh: boolean; approved_at: string }>(
+ `SELECT completed_keys, updated_at >= now() - ($3 || ' days')::interval AS fresh,
+ to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS approved_at
+ FROM op_checkpoints WHERE op=$1 AND fingerprint=$2`,
+ [PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash), String(APPROVAL_MAX_AGE_DAYS)]);
+ const saved = row?.completed_keys?.[0];
+ if (!row || row.fresh !== true || saved?.command !== key.command || saved.hash !== key.hash || !Array.isArray(saved.items)) {
+ throw previewChangedError(key.hash, key.previewCommand);
+ }
+ return { command: key.command, hash: key.hash, items: saved.items, approved_at: row.approved_at };
+}
+
+/** Drops an approved set once its apply finished. */
+export async function clearApprovedSet(engine: BrainEngine, key: Omit<ApprovedSetKey, 'previewCommand'>): Promise<void> {
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [PREVIEW_APPROVAL_OP, fingerprint(key.command, key.hash)]);
+}
diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.ts
index c169b4e7de..42380714d8 100644
--- a/src/core/persistence/provider.ts
+++ b/src/core/persistence/provider.ts
@@ -10,6 +10,8 @@ import { startPersistenceConsumer, assertPersistenceAccepting } from './service.
import { isWriteErrorCode, isWriteReceipt } from './types.ts';
import type { PersistenceIpcProvider } from './ipc.ts';
import { runPersistenceAdministration } from './administration.ts';
+export { residentPersistenceConfig } from './local-client.ts';
+import { projectionBacklog } from '../page-state/projections.ts';
/** Resident lifecycle owns the consumer; each connection proves its own durable registration. */
export async function createPersistenceIpcProvider(engine: BrainEngine, config: GBrainConfig): Promise<PersistenceIpcProvider> {
@@ -22,7 +24,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:
}
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
startPersistenceConsumer(engine, config);
- return { brainId: brain.brain_id, dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {
+ return { brainId: brain.brain_id, projectionStatus: () => projectionBacklog(engine), dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {
assertPersistenceAccepting(engine);
if (request.brain_id !== brain.brain_id) throw new OperationError('permission_denied', 'This registration belongs to a different brain.');
const operation = operations.find(op => op.name === request.operation);
diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.ts
index f13a017183..f32ebea465 100644
--- a/src/core/persistence/reconcile-state.ts
+++ b/src/core/persistence/reconcile-state.ts
@@ -37,9 +37,25 @@ export interface ReconcileState {
/** The `source_path` apply records for a `slug_derived` origin. */
originSourcePath: string | null;
}
+/**
+ * Cycle bookkeeping that `cycle.ts` stamps into `sources.config` after every
+ * successful source cycle. It is not reconcile policy, so it stays out of the
+ * policy digest: otherwise an autopilot cycle between preview and apply made
+ * every reconcile preview stale.
+ */
+const CYCLE_STAMP_KEYS = ['last_source_cycle_at', 'last_full_cycle_at'];
+
export async function reconcilePolicyDigest(engine: BrainEngine, sourceId: string): Promise<string> {
const config = await loadConfigWithEngine(engine, loadConfig());
- const [source] = await engine.executeRaw('SELECT config,contextual_retrieval_mode,trust_frontmatter_overrides FROM sources WHERE id=$1', [sourceId]);
+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT config,contextual_retrieval_mode,trust_frontmatter_overrides FROM sources WHERE id=$1', [sourceId]);
+ let sourceConfig = row?.config;
+ if (typeof sourceConfig === 'string') {
+ try { sourceConfig = JSON.parse(sourceConfig); } catch { /* digest the raw text */ }
+ }
+ if (sourceConfig && typeof sourceConfig === 'object' && !Array.isArray(sourceConfig)) {
+ sourceConfig = Object.fromEntries(Object.entries(sourceConfig).filter(([key]) => !CYCLE_STAMP_KEYS.includes(key)));
+ }
+ const source = row ? { ...row, config: sourceConfig } : row;
return digest({ version: 1, config, source, literals: loadOperatorLiterals(), disabled: process.env.GBRAIN_NO_SANITY ?? null });
}
export function staleReconcile(what: string): never {
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index d3330eaccf..4f074d811d 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -9,7 +9,7 @@ import { parseSourceConfig } from '../sources-load.ts';
import { redactSourceConfig } from '../source-config-redact.ts';
import { discoverGitRoot } from '../sync-git.ts';
import { isInsideGitRepo, hasTrackedContent } from '../git-remote.ts';
-import { containsPath, getWorktreeBinding, type WorktreeBinding, worktreeManifest } from './ownership.ts';
+import { containsPath, getWorktreeBinding, humanManifestProgress, type WorktreeBinding, type WorktreeManifest, worktreeManifest } from './ownership.ts';
import { localHostId } from './identity.ts';
import { advanceTopology, lockTopologyPrincipal, lockTopologyRows, settleTopologyRequests, topologyCanonicalStamp, topologyPrincipal, withTopologyLocks } from './topology-locks.ts';
import { priorTopologyChange, recordTopologyChange, topologyReceipt } from './topology-receipts.ts';
@@ -104,10 +104,10 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
return withTopologyLocks(engine,input.sourceId,async bindings=>{
// Hash canonical bytes while holding native exclusion, without a database
// connection checked out. The final transaction rejects new pending mirrors.
- const manifests=new Map<string,ReturnType<typeof worktreeManifest>>();
+ const manifests=new Map<string,WorktreeManifest>();
for(const path of new Set([...bindings.map(binding=>binding.local_path!).filter(Boolean),...(root?[root.worktree]:[])])) {
if(!existsSync(path)) {if(input.operation==='add'&&input.createDirectory&&path===root?.worktree)continue;throw new OperationError('recovery_required','The canonical checkout is missing; restore its verified manifest first.');}
- const manifest=worktreeManifest(path);
+ const manifest=worktreeManifest(path,{progress:humanManifestProgress()});
if(Buffer.byteLength(JSON.stringify(manifest))>1_048_576) throw new OperationError('request_too_large','The verified source manifest exceeds the 1 MiB administration metadata bound.');
manifests.set(path,manifest);
}
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 55c5a5ec8d..33e33dfd48 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -12,6 +12,8 @@ import { isWriteTargetContained } from '../path-confine.ts';
import { getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { localHostId } from './identity.ts';
import { sha256 } from './digest.ts';
+import { isWindowsColonTarget } from './native-file-target.ts';
+import { ERROR_CATALOGUE } from '../error-catalogue.ts';
import { currentCompanyBrainSync } from '../company-brain/profile.ts';
import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { assertDistinctSyncOrigins, legacySyncOrigin, sameSyncOrigin, syncOriginPath, type SyncOriginScope } from './sync-origin.ts';
@@ -23,8 +25,10 @@ export interface SyncEntry { path: string; sourcePath: string; action: 'import'
renameFrom?: SyncRename; }
/** Files that map to a slug another origin keeps; they are left out of the manifest until one is renamed. */
export interface SyncSlugCollision { slug: string; kept: string; skipped: string[]; }
+/** #5032: a file sync skipped on this host with a named refusal, without failing the run. */
+export interface SyncFileRefusal { path: string; code: 'colon_slug_windows_write_through'; message: string; suggestion: string; docs: string; }
export interface SyncDiscovery { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
- companyPlan?: CompanyBrainPlan; slugCollisions?: SyncSlugCollision[];
+ companyPlan?: CompanyBrainPlan; slugCollisions?: SyncSlugCollision[]; fileRefusals?: SyncFileRefusal[];
from: string | null; target: string; entries: SyncEntry[]; uncommitted?: { added: number; modified: number; deleted: number }; slugMode: 'git-root' | 'source-root'; }
export interface ManagedSyncContext { binding: WorktreeBinding; root: string; gitRoot: string; sourceId: string; incarnation: string;
source: { last_commit: string | null; config: Record<string, unknown> }; }
@@ -133,33 +137,68 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const delta = !opts.full && source.last_commit ? computeSyncDelta(gitRoot, source.last_commit, target) : null;
const entries = new Map<string, SyncEntry>();
const renamedFrom = new Map<string, string>();
+ // #5032: a ':' path has no file on Windows. Each eligible one gets a named
+ // refusal and takes no part in this run, including the origin checks below.
+ // A deletion or rename touching one is refused on both sides, so the page
+ // keeps its identity until the change is synced from macOS or Linux.
+ const refused = new Map<string, SyncFileRefusal>();
+ const refusalMessages = {
+ import: (path: string) => `${path} has a ':' in its name, which Windows cannot store; sync skipped it.`,
+ delete: (path: string) => `${path} has a ':' in its name, which Windows cannot reconcile; sync skipped its deletion and its page stays live.`,
+ };
+ const record = (path: string, message: string) => {
+ if (eligible(path)) refused.set(path, { path, code: 'colon_slug_windows_write_through', message,
+ suggestion: `Rename it without ':' on a macOS or Linux checkout and commit, then run gbrain sync --source ${sourceId} --no-pull.`,
+ docs: ERROR_CATALOGUE.colon_slug_windows_write_through.docs });
+ };
+ const refuse = (path: string, action: SyncEntry['action'] = 'import') => {
+ if (!isWindowsColonTarget(path)) return false;
+ record(path, refusalMessages[action](path));
+ return true;
+ };
+ const storable = <T extends { source_path: string | null }>(page: T) => page.source_path === null || !isWindowsColonTarget(page.source_path);
const put = (path: string, action: SyncEntry['action'], working = false) => {
if (process.platform === 'win32' && path.includes('\\')) throw new OperationError('page_identity_changed', 'Git paths containing literal backslashes are not safe Windows sync targets.');
+ if (refuse(path, action)) return;
if (eligible(path)) entries.set(path, { path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });
};
+ const putRename = (rename: { from: string; to: string }, working = false) => {
+ if (isWindowsColonTarget(rename.from) || isWindowsColonTarget(rename.to)) {
+ for (const path of [rename.from, rename.to]) {
+ record(path, `${path} is one side of the rename ${rename.from} -> ${rename.to}, which Windows cannot reconcile; sync skipped both sides so the page keeps its identity.`);
+ }
+ return;
+ }
+ put(rename.from, 'delete', working); put(rename.to, 'import', working); renamedFrom.set(rename.to, rename.from);
+ };
if (delta?.status === 'ok') {
for (const path of [...delta.manifest.added, ...delta.manifest.modified]) put(path, 'import');
for (const path of delta.manifest.deleted) put(path, 'delete');
- for (const rename of delta.manifest.renamed) { put(rename.from, 'delete'); put(rename.to, 'import'); renamedFrom.set(rename.to, rename.from); }
+ for (const rename of delta.manifest.renamed) putRename(rename);
} else {
- const paths = syncGit(gitRoot, ['ls-tree', '-r', '--name-only', '-z', target]).split('\0')
+ const listed = syncGit(gitRoot, ['ls-tree', '-r', '--name-only', '-z', target]).split('\0')
.filter(path => path && (!scope || path.startsWith(`${scope}/`)));
+ const paths = listed.filter(path => !refuse(path));
assertDistinctSyncOrigins(paths);
const present = new Set(paths.map(path => syncOriginPath(sourcePath(path))));
for (const path of paths) put(path, 'import');
- const pages = await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
+ const livePages = await engine.executeRaw<{ slug: string; source_path: string }>('SELECT slug,source_path FROM pages WHERE source_id=$1 AND deleted_at IS NULL AND source_path IS NOT NULL', [sourceId]);
+ const gitPathOf = (origin: string) => slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin;
+ const listedSet = new Set(listed);
+ for (const page of livePages) if (!storable(page) && !listedSet.has(gitPathOf(page.source_path))) refuse(gitPathOf(page.source_path), 'delete');
+ const pages = livePages.filter(storable);
assertDistinctSyncOrigins([...present, ...pages.map(page => page.source_path)]);
for (const page of pages) {
const origin = syncOriginPath(page.source_path);
const stripped = slugMode === 'source-root' && scope && origin.startsWith(`${scope}/`) ? origin.slice(scope.length + 1) : null;
if (present.has(origin) || stripped !== null && present.has(stripped) && sameSyncOrigin(origin, stripped, originScope, page.slug)) continue;
- put(slugMode === 'source-root' && scope ? `${scope}/${origin}` : origin, 'delete');
+ put(gitPathOf(origin), 'delete');
}
}
if (working) {
for (const path of [...dirty.added, ...dirty.modified]) put(path, 'import', true);
for (const path of dirty.deleted) put(path, 'delete', true);
- for (const rename of dirty.renamed) { put(rename.from, 'delete', true); put(rename.to, 'import', true); renamedFrom.set(rename.to, rename.from); }
+ for (const rename of dirty.renamed) putRename(rename, true);
}
if (company) {
entries.clear();
@@ -177,15 +216,16 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const selected = [...entries.values()].sort((a, b) => a.action.localeCompare(b.action) || a.path.localeCompare(b.path));
if (selected.some(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path))) throw new OperationError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.');
if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw new OperationError('request_too_large', 'Sync discovery exceeds the bounded cursor size.');
- const discovered: SyncDiscovery = { binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
+ const discovered: SyncDiscovery = { ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
// Freeze all logical identities in one database statement, before yielding
// between pages. A later interactive edit must conflict with this scan.
const identities = await engine.executeRaw<{ id: number; slug: string; source_path: string | null; knowledge_revision: string }>(
'SELECT id,slug,source_path,knowledge_revision FROM pages WHERE source_id=$1', [sourceId]);
const bySlug = new Map(identities.map(p => [p.slug, p]));
const byPath = new Map<string, typeof identities>();
- assertDistinctSyncOrigins([...selected.map(entry => entry.sourcePath), ...identities.flatMap(page => page.source_path ? [page.source_path] : [])]);
- for (const page of identities) if (page.source_path) {
+ const storableIdentities = identities.filter(storable);
+ assertDistinctSyncOrigins([...selected.map(entry => entry.sourcePath), ...storableIdentities.flatMap(page => page.source_path ? [page.source_path] : [])]);
+ for (const page of storableIdentities) if (page.source_path) {
const origin = syncOriginPath(page.source_path);
byPath.set(origin, [...(byPath.get(origin) ?? []), page]);
}
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index f457c1db0a..2fdebfee40 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -15,7 +15,8 @@ import { prepareCanonicalProjections } from './canonical-projections.ts';
import { digest, sha256 } from './digest.ts';
import { preserveProtectedTakes } from './protected-takes.ts';
import { getWorktreeBinding } from './ownership.ts';
-import { assertConfiguredSyncRoot, assertSyncEntryOrigin, syncGit, syncRawHash, type SyncRename } from './sync-discovery.ts';
+import { sourceMirrorReadOnly } from './mirror-read-only.ts';
+import { assertConfiguredSyncRoot, assertSyncEntryOrigin, readSyncFile, syncGit, syncRawHash, type SyncRename } from './sync-discovery.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginPath, syncOriginScope, type SyncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, validateSyncAuthority, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
import type { PreparedContentImport } from './prepared-import.ts';
@@ -200,7 +201,18 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
throw new OperationError('invalid_params', frontmatterSlugConflictMessage(p.sourcePath, parsedInput.slug, expectedSlug));
}
if (!p.companyApproval && base && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(base, parsedInput)) {
- throw new OperationError('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.');
+ // The pinned commit can simply trail the coordinator: a committed page write reaches the
+ // working tree before its Git effect lands. When the newer working-tree bytes are the
+ // current page itself, there is nothing to import and nothing to protect; the commit that
+ // carries them is imported as a no-op by a later run.
+ // The checkpoint may advance past the pinned commit's bytes because the working tree wins, as for any local edit.
+ const working = renamed ? null : readSyncFile(root, p.path);
+ if (!working || sha256(working) !== p.rawHash
+ || !sameCanonicalImport(base, parseMarkdown(working.toString('utf8'), row.slug, { activePack }))) {
+ throw new OperationError('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.');
+ }
+ return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
+ apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }) };
}
let importContent = p.content;
if (row.authority.remote) {
@@ -234,16 +246,20 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const renamedType = renamed && parsedInput.typeExplicit !== true ? parsedInput.type : undefined;
const overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical({ ...ready.parsedPage, type: renamedType ?? ready.parsedPage.type }, tags));
if (overlay && p.companyApproval) throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');
- if (overlay && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');
+ // #5409: a read-only mirror keeps its canonical metadata in the database only; its checkout stays the remote's bytes.
+ const mirrorReadOnly = overlay && await sourceMirrorReadOnly(engine, row.source_id);
+ const writeback = overlay && !mirrorReadOnly;
+ if (writeback && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
return { observedRevision: snapshot?.revision ?? null,
// Tells the #5470 screen the content is unchanged; publication still queues its effects.
- contentUnchanged: ready.noop && !moved && !overlay,
+ contentUnchanged: ready.noop && !moved && !writeback,
...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),
validate: async tx => { await validate(tx); await ready.validate(tx); },
deferEmbedding: p.processingOptions?.noEmbed,
- ...(overlay ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),
+ ...(writeback ? { file: { root, path: join(root, p.path), content: serializePageToMarkdown(renderedPage, tags), expectedBeforeHash: p.rawHash } } : {}),
+ ...(mirrorReadOnly ? { databaseOnlyReason: 'mirror_read_only' as const } : {}),
apply: async tx => {
let applied = ready;
if (renamed) {
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index efb6707000..152ff5c6c3 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -117,6 +117,7 @@ function result(cursor: Cursor | CursorHeader, status: SyncResult['status'], rea
toCommit: cursor.authority.writer.remote ? '' : cursor.target, added: cursor.counts.added, modified: cursor.counts.modified,
deleted: cursor.counts.deleted, renamed: cursor.counts.renamed ?? 0, chunksCreated: cursor.counts.chunks, embedded: 0, pagesAffected: [],
...(cursor.slugCollisions?.length ? { slugCollisions: cursor.slugCollisions } : {}),
+ ...(cursor.fileRefusals?.length ? { fileRefusals: cursor.fileRefusals } : {}),
filesImported: cursor.index, bankedFiles: cursor.index, ...(cursor.uncommitted ? { uncommitted: cursor.uncommitted } : {}), ...(reason ? { reason } : {}),
...(cursor.counts.skippedContextualMode || cursor.counts.skippedCanonicalBytes ? { legacySkips: {
contextualMode: cursor.counts.skippedContextualMode ?? 0, canonicalBytes: cursor.counts.skippedCanonicalBytes ?? 0 } } : {}) };
diff --git a/src/core/persistence/topology-clone-model.ts b/src/core/persistence/topology-clone-model.ts
index 7644fa95ee..498818e382 100644
--- a/src/core/persistence/topology-clone-model.ts
+++ b/src/core/persistence/topology-clone-model.ts
@@ -3,7 +3,7 @@ export interface TopologyCloneRecovery {
version:1;kind:'clone';phase:'reserved'|'prepared'|'aborting';operation:'add'|'reclone';
sourceId:string;incarnation:string;worktreeId:string;ownerHostId:string;ownerEpoch:string;
target:string;stage:string;aside:string;beforeHash:string|null;afterHash:string|null;
- manifest:{digest:string;files:Record<string,string>;canonical_stamp?:string}|null;
+ manifest:{digest:string;file_count?:number;files?:Record<string,string>;canonical_stamp?:string}|null;
canonicalStamp:string;checkpoint:string|null;sourceRemoteUrl:string|null;input:SourceLifecycleInput;cloneBudget:number;
stageIdentity?:{device:string;inode:string;birthNs:string};failureCode?:string;
}
diff --git a/src/core/persistence/topology-clone.ts b/src/core/persistence/topology-clone.ts
index ef06c5d9a5..2777f2511a 100644
--- a/src/core/persistence/topology-clone.ts
+++ b/src/core/persistence/topology-clone.ts
@@ -9,7 +9,7 @@ import { isOwnedClone } from '../sources-ops.ts';
import { parseSourceConfig } from '../sources-load.ts';
import type { SourceLifecycleInput } from './source-lifecycle.ts';
import type { TopologyCloneRecovery } from './topology-clone-model.ts';
-import { getWorktreeBinding, worktreeManifest } from './ownership.ts';
+import { compactStoredManifest, getWorktreeBinding, humanManifestProgress, worktreeManifest } from './ownership.ts';
import { localHostId, persistenceHome } from './identity.ts';
import { acquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { canonicalFilesystemPath, recordManagedRoots } from './root-registry.ts';
@@ -59,7 +59,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
if(!bindings.some(binding=>binding.worktree_id===worktreeId)){newLock=await acquireNativeLock(coordination!,{timeoutMs:5000});if(!newLock)throw new OperationError('writer_lock_unavailable','The new clone coordination lock is busy.');}
let accepted:TopologyChange|undefined;
try{
- const before=existsSync(target)?worktreeManifest(target):null;
+ const before=existsSync(target)?worktreeManifest(target,{progress:humanManifestProgress()}):null;
const limits=await readJournalLimits(engine);
const reserved=Math.min(limits.worktreeRecoveryBytes,limits.brainRecoveryBytes);
const oldBytes=existsSync(target)?await topologyDirectoryBytes(target,reserved):0;
@@ -86,7 +86,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
const incarnation=source?.incarnation??randomUUID();
let canonicalStamp=currentBinding?await topologyCanonicalStamp(tx,worktreeId):'';
const [owner]=currentBinding?await tx.executeRaw<{manifest:TopologyCloneRecovery['manifest']}>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid',[worktreeId]):[];
- const manifest=before?{...before,canonical_stamp:canonicalStamp}:owner?.manifest??null;
+ const manifest=before?{...before,canonical_stamp:canonicalStamp}:owner?.manifest?compactStoredManifest(owner.manifest):null;
if(input.operation==='reclone'&&(!manifest||manifest.canonical_stamp!==canonicalStamp))
throw new OperationError('recovery_required','The missing checkout has no current verified canonical manifest. Recover it from a verified checkpoint before recloning.');
if(manifest&&Buffer.byteLength(JSON.stringify(manifest))>1_048_576)throw new OperationError('request_too_large','The canonical manifest exceeds the 1 MiB recovery metadata bound.');
@@ -125,7 +125,7 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
});
await (hooks.clone??cloneTopologyCheckout)(url,recovery.stage,recovery.cloneBudget);
const stageBytes=await topologyDirectoryBytes(recovery.stage,recovery.cloneBudget);
- const candidate=worktreeManifest(recovery.stage);
+ const candidate=worktreeManifest(recovery.stage,{progress:humanManifestProgress()});
if(Buffer.byteLength(JSON.stringify(candidate))>1_048_576)throw new OperationError('request_too_large','The cloned canonical manifest exceeds its 1 MiB recovery metadata bound.');
if(recovery.manifest&&candidate.digest!==recovery.manifest.digest)throw new OperationError('writer_manifest_mismatch','The cloned checkout differs from the verified canonical manifest, including deletions.');
flushTopologyTree(recovery.stage);flushTopologyDirectory(dirname(recovery.stage));
diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.ts
index 68c59982ef..f9a17ed68f 100644
--- a/src/core/persistence/topology-recovery.ts
+++ b/src/core/persistence/topology-recovery.ts
@@ -7,7 +7,7 @@ import { parseSourceConfig } from '../sources-load.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots, withFilesystemPublication } from './filesystem-guard.ts';
import { localHostId } from './identity.ts';
-import { worktreeManifest } from './ownership.ts';
+import { compactStoredManifest, worktreeManifest } from './ownership.ts';
import { advanceTopology, lockTopologyPrincipal, settleTopologyRequests, topologyCanonicalStamp, withTopologyLocks } from './topology-locks.ts';
import { withCoordinatedWrite } from './context.ts';
import { releaseTopologyReservation, type TopologyChange } from './topology-receipts.ts';
@@ -148,7 +148,7 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo
else await tx.executeRaw('UPDATE sources SET last_commit=NULL,last_sync_at=NULL WHERE id=$1 AND incarnation=$2::uuid',[record.sourceId,record.incarnation]);
});
await advanceTopology(tx,[record.worktreeId]);
- await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[record.worktreeId,JSON.stringify({...record.manifest,canonical_stamp:await topologyCanonicalStamp(tx,record.worktreeId)})]);
+ await tx.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid',[record.worktreeId,JSON.stringify({...(record.manifest?compactStoredManifest(record.manifest):null),canonical_stamp:await topologyCanonicalStamp(tx,record.worktreeId)})]);
await refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));
await tx.executeRaw("UPDATE persistence_topology_changes SET state='committed',outcome=outcome||$2::text::jsonb,updated_at=now() WHERE id=$1::uuid",
[row.id,JSON.stringify({cloned:true,local_path:record.target})]);
diff --git a/src/core/pglite-engine/code-edges.ts b/src/core/pglite-engine/code-edges.ts
index 4b347ed8aa..d8774416ff 100644
--- a/src/core/pglite-engine/code-edges.ts
+++ b/src/core/pglite-engine/code-edges.ts
@@ -8,6 +8,7 @@
* listed in docs/designs/refactor-wave-1/w1-inventory.md and left as is.
*/
import type { PGlite } from '@electric-sql/pglite';
+import { rowToCodeEdge } from '../engine-sql/code-edges.ts';
/** Narrow slice of PGLiteEngine this read uses. */
export interface PgliteCodeEdgesDeps {
@@ -56,17 +57,3 @@ export async function getEdgesByChunk(
);
return (rows as Record<string, unknown>[]).map(rowToCodeEdge);
}
-
-function rowToCodeEdge(row: Record<string, unknown>): import('../types.ts').CodeEdgeResult {
- return {
- id: row.id as number,
- from_chunk_id: row.from_chunk_id as number,
- to_chunk_id: row.to_chunk_id == null ? null : (row.to_chunk_id as number),
- from_symbol_qualified: (row.from_symbol_qualified as string) ?? '',
- to_symbol_qualified: (row.to_symbol_qualified as string) ?? '',
- edge_type: (row.edge_type as string) ?? '',
- edge_metadata: (row.edge_metadata as Record<string, unknown>) ?? {},
- source_id: row.source_id == null ? null : (row.source_id as string),
- resolved: Boolean(row.resolved),
- };
-}
diff --git a/src/core/process-cleanup.ts b/src/core/process-cleanup.ts
index e5ec19518c..b3be1e55d2 100644
--- a/src/core/process-cleanup.ts
+++ b/src/core/process-cleanup.ts
@@ -143,9 +143,14 @@ async function runCleanupCallbacks(): Promise<void> {
* SIGTERM). The SIGINT AbortController path in cli.ts stays untouched —
* we don't listen to SIGINT here.
*/
-export function installSignalHandlers(): void {
+export function installSignalHandlers(opts: { keepServingOnLogEpipe?: boolean } = {}): void {
if (installed) return;
installed = true;
+ // #5079: for `serve --http`, stdout/stderr are only log streams (the MCP
+ // transport is the HTTP socket), so a closed log pipe must not stop the
+ // server: the log write is dropped and it keeps serving. Everywhere else a
+ // broken pipe still exits (for stdio `serve` it means the client left).
+ const keepServing = opts.keepServingOnLogEpipe === true;
const handleSignal = (signal: NodeJS.Signals) => {
void runCleanupPass().finally(() => {
@@ -171,7 +176,7 @@ export function installSignalHandlers(): void {
attach(process, 'SIGHUP', () => handleSignal('SIGHUP'));
// Bun delivers SIGPIPE on a broken pipe (Node ignores it by default and
// surfaces only an EPIPE write error on the stream, handled below).
- attach(process, 'SIGPIPE', () => handleSignal('SIGPIPE'));
+ attach(process, 'SIGPIPE', () => { if (!keepServing) handleSignal('SIGPIPE'); });
attach(process, 'uncaughtException', (err: unknown) => {
try { process.stderr.write(`[uncaughtException] ${err instanceof Error ? err.stack ?? err.message : err}\n`); }
@@ -187,14 +192,14 @@ export function installSignalHandlers(): void {
// EPIPE on stdout — the canonical `gbrain sync | head -N` case. Route
// through the cleanup pass so locks release BEFORE we exit.
attach(process.stdout, 'error', (err: NodeJS.ErrnoException) => {
- if (err.code === 'EPIPE') {
+ if (err.code === 'EPIPE' && !keepServing) {
void triggerCleanupAndExit(0);
}
});
// Same for stderr — less common but possible (e.g. `2>&1 | head` after
// stderr was rerouted to stdout).
attach(process.stderr, 'error', (err: NodeJS.ErrnoException) => {
- if (err.code === 'EPIPE') {
+ if (err.code === 'EPIPE' && !keepServing) {
// No stderr means no useful logs on the way out; still cleanup.
void triggerCleanupAndExit(0);
}
diff --git a/src/core/remediation/plan.ts b/src/core/remediation/plan.ts
index c957d04029..ed638cbd41 100644
--- a/src/core/remediation/plan.ts
+++ b/src/core/remediation/plan.ts
@@ -12,6 +12,7 @@ import {
import { loadRecommendationContext } from './context.ts';
import type { RemediationPlan, RemediationPlanOpts } from './types.ts';
import { planRepairSteps } from './repairs.ts';
+import { explicitRepairNotices } from '../repair/registry.ts';
/**
* Synthetic check list for classification. computeRecommendations operates
@@ -74,6 +75,6 @@ export async function computeRemediationPlan(
est_total_seconds: estTotalSeconds,
est_total_usd_cost: Number(estTotalUsd.toFixed(2)),
blocked,
- ...(opts.repairs ? { repair_steps: await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed }) } : {}),
+ ...(opts.repairs ? { repair_steps: await planRepairSteps(engine, { noEmbed: opts.repairs.noEmbed }), explicit_repairs: explicitRepairNotices() } : {}),
};
}
diff --git a/src/core/remediation/repairs.ts b/src/core/remediation/repairs.ts
index d6eb8fcf55..ca1e274bce 100644
--- a/src/core/remediation/repairs.ts
+++ b/src/core/remediation/repairs.ts
@@ -8,12 +8,14 @@
* repair step always runs to completion. A paid step (one that may queue
* embeddings) is not started when its estimate exceeds the remaining budget;
* free steps still run. Repairs run in-process on the brain host through the
- * same runner `gbrain repair` uses, never as Minion jobs.
+ * same runner `gbrain repair` uses, never as Minion jobs. Explicit-only kinds
+ * are never planned or run here: the plan lists them with their preview
+ * command, and `runRepairSteps` refuses a supplied step that names one.
*/
import type { BrainEngine } from '../engine.ts';
import { OperationError } from '../ops/contract.ts';
import { resolveRepairScope, type RepairKind } from '../repair/core.ts';
-import { REPAIR_REGISTRY, repairApplyCommand, repairMaySpend, repairRunner } from '../repair/registry.ts';
+import { AUTO_REPAIR_REGISTRY, explicitKindRequired, repairApplyCommand, repairMaySpend, repairRunner, repairSpec } from '../repair/registry.ts';
export interface RepairPlanStep {
step: number;
@@ -46,12 +48,12 @@ export interface RepairStepResult {
message?: string;
}
-/** Brain-wide preview of every registered kind; kinds with nothing pending are omitted. */
+/** Brain-wide preview of every kind `--all` runs; kinds with nothing pending are omitted. */
export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boolean; kinds?: readonly RepairKind[] } = {}): Promise<RepairPlanStep[]> {
const scope = await resolveRepairScope(engine);
const runner = await repairRunner(engine, { apply: false, noEmbed: opts.noEmbed, logger: { info() {}, warn() {}, error() {} } });
const steps: RepairPlanStep[] = [];
- for (const spec of REPAIR_REGISTRY) {
+ for (const spec of AUTO_REPAIR_REGISTRY) {
if (opts.kinds && !opts.kinds.includes(spec.kind)) continue;
const preview = await runner.run(spec.kind, scope);
// contextual-mode stamps only sealed pages; pages the safe-chunks step re-seals become eligible during the run.
@@ -70,7 +72,8 @@ export async function planRepairSteps(engine: BrainEngine, opts: { noEmbed?: boo
* Apply repair steps in order. `remainingUsd()` is the budget still available
* (undefined = no cap); a paid step whose estimate exceeds it (or cannot be
* estimated under a cap) is refused before it starts and the run continues
- * with the next step. Only a trusted local caller may run repairs.
+ * with the next step. Only a trusted local caller may run repairs, and a step
+ * naming an explicit-only kind refuses the whole run before any step starts.
*/
export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[], opts: {
remote: boolean; noEmbed?: boolean; remainingUsd: () => number | undefined;
@@ -84,6 +87,8 @@ export async function runRepairSteps(engine: BrainEngine, steps: RepairPlanStep[
}): Promise<RepairStepResult[]> {
if (opts.remote !== false) throw new OperationError('permission_denied', 'Repair steps are PROTECTED: only a trusted local caller on the brain host can run them.',
'On the brain host, run: gbrain doctor --remediation-plan');
+ const explicit = steps.find(step => repairSpec(step.kind)?.explicit_only);
+ if (explicit) throw explicitKindRequired(explicit.kind);
const { BudgetExhausted } = await import('../budget/budget-tracker.ts');
const scope = await resolveRepairScope(engine);
const runner = await repairRunner(engine, { apply: true, noEmbed: opts.noEmbed });
diff --git a/src/core/remediation/types.ts b/src/core/remediation/types.ts
index b6f986c1ab..3d591bece4 100644
--- a/src/core/remediation/types.ts
+++ b/src/core/remediation/types.ts
@@ -10,6 +10,7 @@
import type { RemediationStep } from '../remediation-step.ts';
import type { RepairPlanStep, RepairStepResult } from './repairs.ts';
+import type { ExplicitRepairNotice } from '../repair/registry.ts';
/**
* Options for computeRemediationPlan. All fields are optional with
@@ -51,6 +52,8 @@ export interface RemediationPlan {
blocked: Array<{ check: string; reason: string }>;
/** Present when `repairs` was requested: PROTECTED steps that need `--include-repairs`. */
repair_steps?: RepairPlanStep[];
+ /** Present with `repair_steps`: explicit-only kinds, never planned as steps; preview each by name. */
+ explicit_repairs?: ExplicitRepairNotice[];
}
/**
diff --git a/src/core/repair/core.ts b/src/core/repair/core.ts
index 1e58c385a1..a27020ce52 100644
--- a/src/core/repair/core.ts
+++ b/src/core/repair/core.ts
@@ -23,7 +23,7 @@ import { getWriteRequest } from '../persistence/journal.ts';
import { initializeLocalPersistence, requestPrincipalForContext } from '../persistence/page-mutations.ts';
import { lookupEmbeddingPrice, estimateCostFromChars } from '../embedding-pricing.ts';
-export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects'] as const;
+export const REPAIR_KINDS = ['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects', 'stale-atoms', 'extractor-facts'] as const;
export type RepairKind = typeof REPAIR_KINDS[number];
export interface RepairScope { brain_id: string; source_ids: string[] }
@@ -38,11 +38,22 @@ export interface RepairItem {
}
export interface RepairPlan {
+ /** Operator warnings the preview prints before its items (for example an older writer that can undo the repair). */
+ warnings?: string[];
items: RepairItem[];
/** Counts of rows the kind keeps and reports instead of repairing. */
residuals: Record<string, number>;
+ /** Preview-bound kinds: the `previewHash` an apply must pass back with `--expect`. */
+ preview_hash?: string;
+ /** Preview-bound kinds: every previewed item with its class, all of which the hash covers. */
+ listing?: RepairListing[];
}
+export interface RepairListing { item: string; class: string; detail?: string }
+
+/** What the run was asked to do; preview-bound (explicit-only) kinds read `expect` and `includeAmbiguous`. */
+export interface RepairPlanOptions { apply: boolean; expect?: string; includeAmbiguous?: boolean }
+
export interface RepairHandler {
kind: RepairKind;
/** `projection`: items rebuild derived rows only and take no journal admission. Default `coordinated`. */
@@ -50,7 +61,7 @@ export interface RepairHandler {
/** False for kinds whose items are bookkeeping rows, not pages: no embedding cost. */
embeds?: boolean;
/** Pending items after `after`, in cursor order. */
- plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null): Promise<RepairPlan>;
+ plan(engine: BrainEngine, scope: RepairScope, after: RepairCursor | null, opts?: RepairPlanOptions): Promise<RepairPlan>;
/**
* Apply one item; `false` when it no longer needs repair. `embed` is false
* under --no-embed. `runId` identifies this repair run and survives a resume.
@@ -65,6 +76,7 @@ export interface RepairItemOutcome { applied: boolean; outcome: string; reason?:
export interface RepairResult {
kind: RepairKind;
mode: 'dry_run' | 'apply';
+ warnings?: string[];
scope: RepairScope;
affected: number;
sample: string[];
@@ -77,6 +89,8 @@ export interface RepairResult {
complete: boolean;
stopped?: { reason: string; message: string };
apply_command: string;
+ /** Preview-bound kinds' dry run: every item the preview hash covers. */
+ listing?: RepairListing[];
/** Per-outcome counts and the first items, for kinds that name outcomes. */
outcomes?: Record<string, number>;
outcome_items?: Array<{ item: string; outcome: string; reason?: string }>;
@@ -95,25 +109,26 @@ export async function resolveRepairScope(engine: BrainEngine, source?: string):
return { brain_id: brain?.brain_id ?? 'host', source_ids: rows.map(row => row.id) };
}
-function fingerprint(kind: RepairKind, scope: RepairScope): string {
- return digest(['repair-v1', kind, scope.brain_id, scope.source_ids]);
+/** A preview-bound apply keeps its cursor under its approval hash, so a new preview never resumes an older set's cursor. */
+function fingerprint(kind: RepairKind, scope: RepairScope, approval?: string): string {
+ return digest(['repair-v1', kind, scope.brain_id, scope.source_ids, ...(approval ? [approval] : [])]);
}
-async function readCursor(engine: BrainEngine, kind: RepairKind, scope: RepairScope): Promise<{ cursor: RepairCursor | null; runId: string | null }> {
+async function readCursor(engine: BrainEngine, kind: RepairKind, scope: RepairScope, approval?: string): Promise<{ cursor: RepairCursor | null; runId: string | null }> {
const [row] = await engine.executeRaw<{ completed_keys: Array<{ cursor?: RepairCursor | null; run_id?: string }> }>(
- "SELECT completed_keys FROM op_checkpoints WHERE op='repair' AND fingerprint=$1", [fingerprint(kind, scope)]);
+ "SELECT completed_keys FROM op_checkpoints WHERE op='repair' AND fingerprint=$1", [fingerprint(kind, scope, approval)]);
return { cursor: row?.completed_keys[0]?.cursor ?? null, runId: row?.completed_keys[0]?.run_id ?? null };
}
/** Stores the run's cursor and id; with neither, the run is finished and the row is cleared. */
-async function writeCursor(engine: BrainEngine, kind: RepairKind, scope: RepairScope, cursor: RepairCursor | null, runId: string | null): Promise<void> {
+async function writeCursor(engine: BrainEngine, kind: RepairKind, scope: RepairScope, cursor: RepairCursor | null, runId: string | null, approval?: string): Promise<void> {
if (!cursor && !runId) {
- await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair' AND fingerprint=$1", [fingerprint(kind, scope)]);
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='repair' AND fingerprint=$1", [fingerprint(kind, scope, approval)]);
return;
}
await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('repair',$1,$2::text::jsonb)
ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`,
- [fingerprint(kind, scope), JSON.stringify([{ kind, scope, cursor, run_id: runId }])]);
+ [fingerprint(kind, scope, approval), JSON.stringify([{ kind, scope, cursor, run_id: runId }])]);
}
/** Cumulative journal counters this repair's admissions consume, with their 90% stop line. */
@@ -159,11 +174,19 @@ function writerHeld(error: unknown): error is OperationError {
return error instanceof OperationError && ['owner_unavailable', 'writer_lock_unavailable', 'writer_busy'].includes(error.code);
}
+/**
+ * `explicit`: the operator named this kind on the command line. An
+ * explicit-only kind (registry `explicit_only`) refuses without it, so no
+ * `--all` loop or supplied remediation step can run one.
+ */
export async function runRepair(ctx: OperationContext, handler: RepairHandler, scope: RepairScope,
- opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[] }): Promise<RepairResult> {
+ opts: { apply: boolean; limit?: number; embeddingModel?: string; sourceFlag?: string; embed?: boolean; applyArgs?: string[];
+ explicit?: boolean; expect?: string; includeAmbiguous?: boolean }): Promise<RepairResult> {
+ const { repairSpec, explicitKindRequired } = await import('./registry.ts');
+ if (repairSpec(handler.kind)?.explicit_only && opts.explicit !== true) throw explicitKindRequired(handler.kind);
if (opts.apply) await initializeLocalPersistence(ctx);
- const { cursor: resumed, runId: storedRunId } = await readCursor(ctx.engine, handler.kind, scope);
- const plan = await handler.plan(ctx.engine, scope, resumed);
+ const { cursor: resumed, runId: storedRunId } = await readCursor(ctx.engine, handler.kind, scope, opts.apply ? opts.expect : undefined);
+ const plan = await handler.plan(ctx.engine, scope, resumed, { apply: opts.apply, expect: opts.expect, includeAmbiguous: opts.includeAmbiguous });
const pending = opts.limit !== undefined ? plan.items.slice(0, opts.limit) : plan.items;
const counters = await capacity(ctx);
const admits = (handler.publication ?? 'coordinated') === 'coordinated' ? pending.length : 0;
@@ -173,16 +196,18 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
cost: { lifetime_ids: admits, receipt_bytes: admits * RECEIPT_BYTES, embedding_pages: handler.embeds === false ? 0 : pending.length,
embedding_usd: embeddingUsd(pending.reduce((sum, item) => sum + item.chars, 0), opts.embeddingModel) },
capacity: counters.map(({ scope: key, resource, used, limit, stop_at }) => ({ scope: key, resource, used, limit, stop_at })),
- resumed_from: resumed, applied: 0, skipped: 0, complete: false,
- apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')} --apply`,
+ resumed_from: resumed, applied: 0, skipped: 0, complete: false, ...(plan.warnings?.length ? { warnings: plan.warnings } : {}),
+ apply_command: `gbrain repair ${handler.kind}${opts.sourceFlag ? ` --source ${opts.sourceFlag}` : ''}${(opts.applyArgs ?? []).map(arg => ` ${arg}`).join('')}`
+ + `${opts.includeAmbiguous ? ' --include-ambiguous' : ''} --apply${plan.preview_hash ? ` --expect ${plan.preview_hash}` : ''}`,
};
if (!opts.apply) {
+ if (plan.listing) result.listing = plan.listing;
result.complete = pending.length === plan.items.length;
return result;
}
// A resumed run keeps its id, so work it authorized is replayed, not authorized twice.
const runId = storedRunId ?? randomUUID();
- if (!storedRunId) await writeCursor(ctx.engine, handler.kind, scope, resumed, runId);
+ if (!storedRunId) await writeCursor(ctx.engine, handler.kind, scope, resumed, runId, opts.expect);
for (const [index, item] of pending.entries()) {
const remaining = pending.length - index;
const full = admits ? (await capacity(ctx)).find(c => c.used + (c.resource === 'lifetime_ids' ? 1 : RECEIPT_BYTES) > c.stop_at) : undefined;
@@ -216,10 +241,10 @@ export async function runRepair(ctx: OperationContext, handler: RepairHandler, s
+ `Inspect it with: gbrain sources writer status ${item.source_id} — then rerun \`${result.apply_command}\` to resume.` };
return result;
}
- await writeCursor(ctx.engine, handler.kind, scope, item.cursor, runId);
+ await writeCursor(ctx.engine, handler.kind, scope, item.cursor, runId, opts.expect);
}
result.complete = pending.length === plan.items.length;
- if (result.complete) await writeCursor(ctx.engine, handler.kind, scope, null, null);
+ if (result.complete) await writeCursor(ctx.engine, handler.kind, scope, null, null, opts.expect);
return result;
}
diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.ts
new file mode 100644
index 0000000000..4e8a4ebcf2
--- /dev/null
+++ b/src/core/repair/extractor-facts.ts
@@ -0,0 +1,408 @@
+/**
+ * `gbrain repair extractor-facts` (#5731, CEO-A9, ENG-O8, DX-O4, DX-T1):
+ * restore conversation-extractor facts that the pre-fix canonical projection
+ * expired.
+ *
+ * Before v0.60.11.0 every managed write to a fenceless conversation page ran
+ * the canonical facts projection with an empty fence, which expired every
+ * extractor fact of that page and cleared its `row_num` in the publication
+ * transaction. The fix stopped new expiries; this kind restores the old ones.
+ *
+ * Candidates: `source` starts with `cli:extract-conversation-facts`,
+ * `expired_at` set, `row_num` NULL (the projection's signature). Each is
+ * classified, in this order:
+ * - excluded (listed, never restored): the page is missing or deleted; the
+ * fact was superseded (`superseded_by`, E-T5); its claim was withdrawn
+ * (`fact_withdrawals`); an active fact with the same text and entity already
+ * sits on the page (a fence row or another extractor row); or another
+ * candidate of the page with the same text and entity is restored instead
+ * (the first evidenced one, else the first ambiguous one).
+ * - ambiguous (restored only with `--include-ambiguous` and the hash of that
+ * preview): an unmanaged brain (no receipts); no committed write receipt of
+ * the page completed at the exact expiry instant (`completed_at =
+ * expired_at`, which holds only when both happened in one transaction); the
+ * receipt's consumer is v0.60.11.0 or newer (a fence takeover, not the
+ * defect); or the page ever carried fence-projected facts (a fence row may
+ * have taken the fact's row number).
+ * - evidenced: everything else, restored by `--apply --expect <hash>`.
+ *
+ * `writer_version_cutoff` marks when consumers began stamping their version,
+ * so a receipt with no `consumer_version` was published by a binary older
+ * than the stamps, which shipped together with the fix.
+ *
+ * The preview lists every candidate with its class and evidence, prints a
+ * hash over them, and saves the restorable set (one item per page, each with
+ * its request id) through `persistence/preview-approval.ts`. The apply replays
+ * exactly that set: a managed brain publishes one database-only
+ * `managed_maintenance_restore_extractor_facts` request per page; an unmanaged
+ * brain writes directly under the page lock. Each fact is reclassified under
+ * the lock and restored only when its class, evidence and expiry are
+ * unchanged (`changed_since_preview` otherwise). A restored fact gets a fresh
+ * `row_num` above every row of its page, so it never looks like an unfenced
+ * legacy row. A resumed apply skips pages whose request already committed (or
+ * whose facts are already active), so a crash after publication restores no
+ * new candidate. A page already passed by this set's cursor (keyed by its
+ * approval hash) is not retried,
+ * whatever its outcome, so a `--limit` run always advances.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { VERSION } from '../../version.ts';
+import { OperationError } from '../ops/contract.ts';
+import { parseFactsFence } from '../facts-fence.ts';
+import { digest } from '../persistence/digest.ts';
+import { isTerminal } from '../persistence/model.ts';
+import { getWriteRequest } from '../persistence/journal.ts';
+import { authorizeStoredRequest, authorizeWrite } from '../persistence/authority.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { waitForWrite, writeResponse } from '../persistence/service.ts';
+import { maintenancePreflight, submitDatabaseMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { compareWriterVersions, recentWriterVersions, writerVersionLabel } from '../persistence/writer-versions.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairListing, type RepairPlan, type RepairScope } from './core.ts';
+
+export const EXTRACTOR_FACTS_INTENT = 'managed_maintenance_restore_extractor_facts';
+export const EXTRACTOR_FACTS_SOURCE_PREFIX = 'cli:extract-conversation-facts';
+/** The first release whose canonical projection leaves fenceless extractor facts alone. */
+export const EXTRACTOR_FACTS_FIX_VERSION = '0.60.11.0';
+
+export type ExtractorFactClass = 'evidenced' | 'ambiguous' | 'excluded';
+
+/**
+ * The exact expiry instant as text (UTC, microseconds). Compared as text in
+ * SQL: a bound timestamp parameter can lose its microseconds on the way in.
+ */
+const EXPIRY_TEXT = (column: string) => `to_char(${column} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')`;
+
+/** One candidate as the preview showed it; the apply rechecks every field. */
+export interface ExtractorFactCandidate {
+ id: number;
+ source_id: string;
+ slug: string;
+ class: ExtractorFactClass;
+ reason: string;
+ /** UTC, microseconds: the exact instant the projection expired it. */
+ expired_at: string;
+ /** The committed request whose publication expired it, if any. */
+ receipt: string | null;
+ receipt_consumer: string | null;
+ /** Digest of the row's claim, visibility and entity, so an edited row is not restored. */
+ fact_hash: string;
+}
+
+/** One approved page: its restorable facts and the request id its managed restore uses. */
+export interface ExtractorFactsPage {
+ source_id: string;
+ slug: string;
+ page_id: number;
+ request_id: string;
+ include_ambiguous: boolean;
+ /** The preview's source scope; an apply under another scope refuses. */
+ scope: string[];
+ facts: ExtractorFactCandidate[];
+}
+
+interface PageItem extends RepairItem { page: ExtractorFactsPage; hash: string; last: boolean }
+
+interface CandidateRow {
+ id: number | string; source_id: string; slug: string; fact: string; visibility: string; entity_slug: string | null;
+ superseded: boolean; expired_at: string; page_id: number | string | null; page_deleted: boolean | null;
+ withdrawn: boolean; active_duplicate: boolean; fence_history: boolean; fingerprint: string;
+ receipt: string | null; receipt_consumer: string | null;
+}
+
+/**
+ * Every candidate of these sources (or of one page), classified, in (source,
+ * page, id) order. Read-only; `managed` is the brain's persistence mode.
+ */
+export async function classifyExtractorFacts(db: BrainEngine, sourceIds: string[], opts: { managed: boolean; slug?: string }): Promise<ExtractorFactCandidate[]> {
+ const rows = await db.executeRaw<CandidateRow>(`
+ WITH cand AS (
+ SELECT f.id, f.source_id, f.source_markdown_slug AS slug, f.fact, f.visibility, f.entity_slug, f.expired_at AS expired,
+ f.superseded_by IS NOT NULL AS superseded, gbrain_fact_fingerprint(f.fact) AS fingerprint
+ FROM facts f
+ WHERE f.source_id=ANY($1::text[]) AND f.source LIKE '${EXTRACTOR_FACTS_SOURCE_PREFIX}%'
+ AND f.expired_at IS NOT NULL AND f.row_num IS NULL AND f.source_markdown_slug IS NOT NULL
+ AND ($2::text IS NULL OR f.source_markdown_slug=$2::text)
+ ), receipts AS (
+ SELECT DISTINCT ON (r.source_id, r.slug, r.completed_at) r.source_id, r.slug, r.completed_at,
+ r.request_id::text AS request_id, r.consumer_version
+ FROM persistence_requests r
+ JOIN (SELECT DISTINCT source_id, slug, expired FROM cand) k
+ ON k.source_id=r.source_id AND k.slug=r.slug AND k.expired=r.completed_at
+ WHERE r.state='committed'
+ ORDER BY r.source_id, r.slug, r.completed_at, r.sequence
+ ), fenced AS (
+ SELECT DISTINCT g.source_id, g.source_markdown_slug AS slug FROM facts g
+ JOIN (SELECT DISTINCT source_id, slug FROM cand) k ON k.source_id=g.source_id AND k.slug=g.source_markdown_slug
+ WHERE COALESCE(g.source,'') NOT LIKE '${EXTRACTOR_FACTS_SOURCE_PREFIX}%'
+ )
+ SELECT c.id, c.source_id, c.slug, c.fact, c.visibility, c.entity_slug, c.superseded, c.fingerprint,
+ ${EXPIRY_TEXT('c.expired')} AS expired_at,
+ p.id AS page_id, p.deleted_at IS NOT NULL AS page_deleted,
+ EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id=c.source_id AND w.visibility=c.visibility
+ AND w.fact_hash IN (gbrain_fact_fingerprint(c.fact), gbrain_fact_fingerprint_v1(c.fact))
+ AND (w.subject='*' OR w.subject=c.entity_slug)) AS withdrawn,
+ EXISTS (SELECT 1 FROM facts a WHERE a.source_id=c.source_id AND a.visibility=c.visibility
+ AND gbrain_fact_fingerprint(a.fact)=c.fingerprint AND a.source_markdown_slug=c.slug AND a.expired_at IS NULL
+ AND a.entity_slug IS NOT DISTINCT FROM c.entity_slug) AS active_duplicate,
+ fenced.slug IS NOT NULL AS fence_history,
+ r.request_id AS receipt, r.consumer_version AS receipt_consumer
+ FROM cand c
+ LEFT JOIN pages p ON p.source_id=c.source_id AND p.slug=c.slug
+ LEFT JOIN receipts r ON r.source_id=c.source_id AND r.slug=c.slug AND r.completed_at=c.expired
+ LEFT JOIN fenced ON fenced.source_id=c.source_id AND fenced.slug=c.slug
+ ORDER BY c.source_id, c.slug, c.id`, [sourceIds, opts.slug ?? null]);
+ // One representative per (page, visibility, entity, text): the first evidenced row, else the first ambiguous one.
+ const key = (row: CandidateRow) => JSON.stringify([row.source_id, row.slug, row.visibility, row.entity_slug, row.fingerprint]);
+ const base = rows.map(row => classify(row, false, opts.managed));
+ const representative = new Map<string, number>();
+ for (const klass of ['evidenced', 'ambiguous'] as const) {
+ rows.forEach((row, i) => { if (base[i][0] === klass && !representative.has(key(row))) representative.set(key(row), i); });
+ }
+ return rows.map((row, i) => {
+ const id = Number(row.id);
+ const duplicate = base[i][0] !== 'excluded' && representative.get(key(row)) !== i;
+ const [klass, reason] = duplicate ? classify(row, true, opts.managed) : base[i];
+ return { id, source_id: row.source_id, slug: row.slug, class: klass, reason, expired_at: row.expired_at,
+ receipt: row.receipt, receipt_consumer: row.receipt === null ? null : row.receipt_consumer,
+ fact_hash: digest([row.fact, row.visibility, row.entity_slug]) };
+ });
+}
+
+function classify(row: CandidateRow, duplicate: boolean, managed: boolean): [ExtractorFactClass, string] {
+ if (row.page_id === null || row.page_deleted) return ['excluded', 'page_missing'];
+ if (row.superseded) return ['excluded', 'superseded'];
+ if (row.withdrawn) return ['excluded', 'withdrawn'];
+ if (row.active_duplicate) return ['excluded', 'active_duplicate'];
+ if (duplicate) return ['excluded', 'duplicate_candidate'];
+ if (!managed) return ['ambiguous', 'unmanaged_brain'];
+ if (row.receipt === null) return ['ambiguous', 'no_same_transaction_receipt'];
+ const order = row.receipt_consumer === null ? -1 : compareWriterVersions(row.receipt_consumer, EXTRACTOR_FACTS_FIX_VERSION);
+ if (order === null || order >= 0) return ['ambiguous', 'post_fix_consumer'];
+ if (row.fence_history) return ['ambiguous', 'fence_takeover_possible'];
+ return ['evidenced', 'pre_fix_projection'];
+}
+
+const DETAILS: Record<string, string> = {
+ page_missing: 'its conversation page is missing or deleted',
+ superseded: 'a newer fact superseded it',
+ withdrawn: 'its claim was withdrawn (forget)',
+ active_duplicate: 'an active fact with the same text and entity is already on the page',
+ duplicate_candidate: 'another candidate of the page with the same text and entity is restored instead',
+ unmanaged_brain: 'unmanaged brain: no write receipt can prove the expiry',
+ no_same_transaction_receipt: 'no committed write of the page completed at the exact expiry instant',
+ post_fix_consumer: 'expired by a write published by a fixed consumer (a fence row may have taken its position)',
+ fence_takeover_possible: 'the page has carried fence facts, so a fence row may have taken its position',
+};
+
+function detail(fact: ExtractorFactCandidate): string {
+ if (fact.class !== 'evidenced') return DETAILS[fact.reason] ?? fact.reason;
+ return `expired at ${fact.expired_at} by the pre-fix projection in write ${fact.receipt}, published by ${writerVersionLabel(fact.receipt_consumer)}`;
+}
+
+/** The preview command for this scope: `--source` only when the scope is one source of several (what the operator passed). */
+async function previewCommand(engine: BrainEngine, scope: RepairScope, includeAmbiguous: boolean): Promise<string> {
+ const [{ n }] = await engine.executeRaw<{ n: number | string }>('SELECT count(*)::int AS n FROM sources WHERE archived IS NOT TRUE');
+ const narrowed = scope.source_ids.length === 1 && Number(n) > 1;
+ return `gbrain repair extractor-facts${narrowed ? ` --source ${scope.source_ids[0]}` : ''}${includeAmbiguous ? ' --include-ambiguous' : ''}`;
+}
+
+function requestIdFor(hash: string, page: Pick<ExtractorFactsPage, 'source_id' | 'slug'>, attempt: number): string {
+ const h = digest(['extractor-facts-request-v1', hash, page.source_id, page.slug, attempt]);
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
+}
+
+/**
+ * Hosts whose latest consumer since `writer_version_cutoff` is older than this
+ * release: a pre-fix consumer there can expire restored facts again.
+ */
+async function mixedVersionWarnings(engine: BrainEngine): Promise<string[]> {
+ const rows = await recentWriterVersions(engine, 30).catch(() => []);
+ const latest = new Map<string, (typeof rows)[number]>();
+ for (const row of rows.filter(r => r.role === 'consumer')) {
+ const key = `${row.host_id}|${row.principal}`;
+ const prior = latest.get(key);
+ if (!prior || (row.last_seen ?? '') > (prior.last_seen ?? '')) latest.set(key, row);
+ }
+ const hosts = new Map<string, string>();
+ for (const row of latest.values()) {
+ const order = row.version === null ? -1 : compareWriterVersions(row.version, VERSION);
+ if (order !== null && order >= 0) continue;
+ const host = row.host_id ?? 'unknown (not recorded)';
+ if (!hosts.has(host)) hosts.set(host, `${row.version_label}, last seen ${row.last_seen}`);
+ }
+ return [...hosts].map(([host, seen]) => `host ${host} still published writes with a consumer older than this release (${seen}); `
+ + `a consumer older than v${EXTRACTOR_FACTS_FIX_VERSION} expires restored extractor facts again. Upgrade and restart gbrain on that host before applying.`);
+}
+
+async function hashParts(engine: BrainEngine, scope: RepairScope, includeAmbiguous: boolean, facts: ExtractorFactCandidate[]) {
+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);
+ return { kind: 'extractor-facts-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids, include_ambiguous: includeAmbiguous }, facts };
+}
+
+function pageItem(page: ExtractorFactsPage, hash: string, index: number, last: boolean): PageItem {
+ return { cursor: { phase: 0, id: index + 1 }, source_id: page.source_id, slug: page.slug, chars: 0,
+ action: `restore ${page.facts.length} extractor fact(s)`, page, hash, last };
+}
+
+/** Pages of an approved set whose restore already finished (a committed request, or every fact active again). */
+async function finishedPages(engine: BrainEngine, hash: string, pages: ExtractorFactsPage[]): Promise<Set<string>> {
+ if (!pages.length) return new Set();
+ const committed = await engine.executeRaw<{ source_id: string; slug: string }>(`SELECT DISTINCT source_id, slug FROM persistence_requests
+ WHERE state='committed' AND operation='submit_job' AND source_id=ANY($1::text[]) AND slug=ANY($2::text[])
+ AND (intent->>'preview_hash'=$3 OR request_id=ANY($4::uuid[]))`,
+ [[...new Set(pages.map(p => p.source_id))], [...new Set(pages.map(p => p.slug))], hash, pages.map(p => p.request_id)]);
+ const active = await engine.executeRaw<{ id: number | string }>(
+ 'SELECT id FROM facts WHERE id=ANY($1::bigint[]) AND expired_at IS NULL AND row_num IS NOT NULL', [pages.flatMap(p => p.facts.map(f => f.id))]);
+ const restored = new Set(active.map(row => Number(row.id)));
+ const done = new Set(committed.map(row => `${row.source_id}\u0000${row.slug}`));
+ for (const page of pages) if (page.facts.every(f => restored.has(f.id))) done.add(`${page.source_id}\u0000${page.slug}`);
+ return done;
+}
+
+export const extractorFactsRepair: RepairHandler = {
+ kind: 'extractor-facts',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const includeAmbiguous = opts?.includeAmbiguous === true;
+ if (!opts?.apply) {
+ const managed = await managedPersistenceEnabled(engine);
+ const facts = await classifyExtractorFacts(engine, scope.source_ids, { managed });
+ const hash = previewHash(await hashParts(engine, scope, includeAmbiguous, facts));
+ const pageIds = new Map((await engine.executeRaw<{ id: number | string; source_id: string; slug: string }>(
+ 'SELECT id, source_id, slug FROM pages WHERE source_id=ANY($1::text[]) AND slug=ANY($2::text[]) AND deleted_at IS NULL',
+ [scope.source_ids, [...new Set(facts.map(f => f.slug))]])).map(row => [`${row.source_id}\u0000${row.slug}`, Number(row.id)]));
+ const pages = new Map<string, ExtractorFactsPage>();
+ for (const fact of facts) {
+ if (fact.class === 'excluded' || fact.class === 'ambiguous' && !includeAmbiguous) continue;
+ const key = `${fact.source_id}\u0000${fact.slug}`;
+ const page = pages.get(key) ?? { source_id: fact.source_id, slug: fact.slug, page_id: pageIds.get(key)!,
+ request_id: requestIdFor(hash, fact, 0), include_ambiguous: includeAmbiguous, scope: scope.source_ids, facts: [] };
+ page.facts.push(fact);
+ pages.set(key, page);
+ }
+ const approved = [...pages.values()];
+ if (approved.length) await saveApprovedSet(engine, { command: 'extractor-facts', hash }, approved);
+ const count = (klass: ExtractorFactClass) => facts.filter(f => f.class === klass).length;
+ const listing: RepairListing[] = facts.map(fact => ({ item: `${fact.source_id}:${fact.slug}#${fact.id}`,
+ class: fact.class === 'excluded' ? `excluded:${fact.reason}` : fact.class, detail: detail(fact) }));
+ return { items: approved.map((page, index) => pageItem(page, hash, index, index === approved.length - 1)), preview_hash: hash,
+ residuals: { evidenced: count('evidenced'), ambiguous: count('ambiguous'), excluded: count('excluded') },
+ listing, warnings: await mixedVersionWarnings(engine) };
+ }
+ const command = await previewCommand(engine, scope, includeAmbiguous);
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair extractor-facts --apply restores only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,
+ 'docs/guides/repair.md#explicit-only-repair-kinds');
+ }
+ const approved = await loadApprovedSet<ExtractorFactsPage>(engine, { command: 'extractor-facts', hash: opts.expect, previewCommand: command });
+ const scopeKey = JSON.stringify(scope.source_ids);
+ if (approved.items.some(page => page.include_ambiguous !== includeAmbiguous || JSON.stringify(page.scope) !== scopeKey)) {
+ throw previewChangedError(opts.expect, command);
+ }
+ // Resume: skip pages the set's cursor (keyed by its approval hash in runRepair) already passed,
+ // whatever their outcome, and pages whose restore already finished.
+ const done = await finishedPages(engine, opts.expect, approved.items);
+ const items = approved.items.map((page, index) => pageItem(page, opts.expect!, index, index === approved.items.length - 1))
+ .filter(item => afterCursor(item.cursor, after) && !done.has(`${item.source_id}\u0000${item.slug}`));
+ if (!items.length) await clearApprovedSet(engine, { command: 'extractor-facts', hash: opts.expect });
+ return { items, preview_hash: opts.expect, residuals: { already_restored_pages: approved.items.length - items.length } };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { page, hash, last } = entry as PageItem;
+ const result = await managedPersistenceEnabled(ctx.engine)
+ ? await restoreManaged(ctx.engine, ctx.config, page, hash)
+ : await ctx.engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);
+ return restorePageFacts(tx, page, false);
+ });
+ if (last) await clearApprovedSet(ctx.engine, { command: 'extractor-facts', hash });
+ const changed = page.facts.length - result.restored.length;
+ return { applied: result.restored.length > 0, outcome: !changed ? 'restored' : result.restored.length ? 'partially_restored' : 'changed_since_preview',
+ ...(changed ? { reason: `${result.restored.length} of ${page.facts.length} restored; changed since the preview: ${result.changed.join(', ')}` } : {}) };
+ },
+};
+
+interface RestoreResult { restored: number[]; changed: number[] }
+
+async function restoreManaged(engine: BrainEngine, config: Parameters<typeof waitForWrite>[2], page: ExtractorFactsPage, hash: string): Promise<RestoreResult> {
+ const unchanged: RestoreResult = { restored: [], changed: page.facts.map(f => f.id) };
+ const authority = (await maintenancePreflight(engine, page.source_id))!;
+ for (let attempt = 0; ; attempt++) {
+ const requestId = attempt === 0 ? page.request_id : requestIdFor(hash, page, attempt);
+ const prior = await getWriteRequest(engine, authority.writer.principal, requestId);
+ if (prior && isTerminal(prior) && prior.state !== 'committed') continue;
+ try {
+ let receipt: Record<string, unknown>;
+ if (prior) {
+ await authorizeStoredRequest(engine, prior);
+ receipt = writeResponse(await waitForWrite(engine, prior, config));
+ } else {
+ const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });
+ if (!snapshot || snapshot.page.id !== page.page_id) return unchanged;
+ receipt = await submitDatabaseMaintenanceIntent(engine, authority, page.slug,
+ { kind: EXTRACTOR_FACTS_INTENT, expected_revision: snapshot.revision, preview_hash: hash, page }, requestId);
+ }
+ return { restored: (receipt.restored as number[] | undefined) ?? [], changed: (receipt.changed_since_preview as number[] | undefined) ?? [] };
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return unchanged;
+ throw error;
+ }
+ }
+}
+
+/**
+ * Restores the page's approved facts that are still exactly as previewed,
+ * under the page lock: each gets a fresh row number above every fact and
+ * fence row of the page. Runs inside the managed publication or the unmanaged
+ * transaction.
+ */
+async function restorePageFacts(tx: BrainEngine, page: ExtractorFactsPage, managed: boolean): Promise<RestoreResult> {
+ const ids = page.facts.map(f => f.id);
+ await tx.executeRaw('SELECT id FROM facts WHERE source_id=$1 AND id=ANY($2::bigint[]) FOR UPDATE', [page.source_id, ids]);
+ const live = new Map((await classifyExtractorFacts(tx, [page.source_id], { managed, slug: page.slug })).map(f => [f.id, f]));
+ const [live_page] = await tx.executeRaw<{ id: number | string; compiled_truth: string | null; max_row: number | string | null }>(
+ `SELECT p.id, p.compiled_truth, (SELECT MAX(row_num) FROM facts WHERE source_id=$1 AND source_markdown_slug=$2) AS max_row
+ FROM pages p WHERE p.source_id=$1 AND p.slug=$2 AND p.deleted_at IS NULL`, [page.source_id, page.slug]);
+ // A page deleted and recreated at the same slug since the preview is another page.
+ const snapshot = live_page && Number(live_page.id) === page.page_id ? live_page : undefined;
+ const fenceRows = parseFactsFence(snapshot?.compiled_truth ?? '').facts.map(f => f.rowNum);
+ let next = Math.max(Number(snapshot?.max_row ?? 0), ...fenceRows, 0) + 1;
+ const result: RestoreResult = { restored: [], changed: [] };
+ for (const approved of page.facts) {
+ const current = live.get(approved.id);
+ const same = !!snapshot && !!current && (['class', 'reason', 'expired_at', 'receipt', 'receipt_consumer', 'fact_hash'] as const)
+ .every(field => current[field] === approved[field]);
+ const updated = same ? await tx.executeRaw(`UPDATE facts SET expired_at=NULL, row_num=$3
+ WHERE source_id=$1 AND id=$2 AND row_num IS NULL AND superseded_by IS NULL AND ${EXPIRY_TEXT('expired_at')}=$4 RETURNING id`,
+ [page.source_id, approved.id, next, approved.expired_at]) : [];
+ if (updated.length) { result.restored.push(approved.id); next++; } else result.changed.push(approved.id);
+ }
+ return result;
+}
+
+/**
+ * Preparer for `managed_maintenance_restore_extractor_facts`: a database-only
+ * publication on the page key that reclassifies and restores the approved
+ * facts of one page, reporting the rest as `changed_since_preview`.
+ */
+export async function prepareExtractorFactsRestore(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
+ const intent = row.intent as { page?: ExtractorFactsPage; preview_hash?: unknown } | null;
+ const page = intent?.page;
+ if (!page || page.source_id !== row.source_id || page.slug !== row.slug || typeof intent?.preview_hash !== 'string' || !Array.isArray(page.facts)) {
+ throw new OperationError('invalid_params', 'The extractor facts restore intent does not name its page.');
+ }
+ const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) throw new OperationError('page_identity_changed', 'The conversation page was deleted or replaced before its facts were restored.');
+ await authorizeWrite(engine, row.authority, 'submit_job', row.slug);
+ return { observedRevision: snapshot.revision, noop: true,
+ validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },
+ apply: async tx => {
+ const result = await restorePageFacts(tx, page, true);
+ return { status: 'completed', preview_hash: intent!.preview_hash, restored: result.restored, changed_since_preview: result.changed };
+ } };
+}
diff --git a/src/core/repair/registry.ts b/src/core/repair/registry.ts
index f4b3b32e18..f85c51f811 100644
--- a/src/core/repair/registry.ts
+++ b/src/core/repair/registry.ts
@@ -11,6 +11,12 @@
* page write whose embedding effect the persistence consumer runs (outside
* this process, not affected by `--no-embed`); `inline` kinds embed in this
* process unless `--no-embed` is given.
+ *
+ * `explicit_only` kinds run only when the operator names them
+ * (`gbrain repair <kind>`): `--all`, the remediation plan and run, and the
+ * post-upgrade banner list them with their preview command
+ * (`explicit_kind_required`) but never run them, and `runRepair` refuses one
+ * that was not named, so a supplied remediation step cannot run it either.
*/
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
@@ -25,6 +31,10 @@ import { requestIndexesRepair } from './request-indexes.ts';
import { connectorFencesRepair } from './connector-fences.ts';
import { orphanBindingsRepair } from './orphan-bindings.ts';
import { embeddingEffectsRepair } from './embedding-effects.ts';
+import { staleAtomsRepair } from './stale-atoms.ts';
+import { extractorFactsRepair } from './extractor-facts.ts';
+import { ERROR_CATALOGUE, catalogueError } from '../error-catalogue.ts';
+import type { OperationError } from '../ops/contract.ts';
export interface RepairKindSpec {
kind: RepairKind;
@@ -35,6 +45,8 @@ export interface RepairKindSpec {
embeds: 'effect' | 'inline' | 'none';
/** Doctor check ids whose findings this kind clears. */
checks: string[];
+ /** Runs only when named on the command line; never from `--all`, the remediation plan or a supplied step. */
+ explicit_only?: true;
}
const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
@@ -83,6 +95,19 @@ const SPECS: Record<RepairKind, Omit<RepairKindSpec, 'kind'>> = {
+ 'Each effect is reconciled (current vectors pass the effect verifier), superseded (page deleted, or a newer revision owns its own effect), '
+ 'retry_queued for its owner (paid; a consumed retry allowance gets one new bounded cycle per explicit run) or blocked with the reason. Never drops an obligation.',
},
+ 'stale-atoms': {
+ handler: staleAtomsRepair, embeds: 'none', checks: ['atom_provenance_drift'], explicit_only: true,
+ summary: 'Retire, by soft delete, page-bound atoms whose source page is gone, or whose source page changed after its current text was already extracted (#5770). '
+ + 'Preview-bound: --apply --expect <hash> retires exactly the previewed set; an atom that changed since reports changed_since_preview and is kept. '
+ + 'A later extraction that produces a retired atom again restores it. Never touches imported or file-bound atoms.',
+ },
+ 'extractor-facts': {
+ handler: extractorFactsRepair, embeds: 'none', checks: ['extractor_facts_expired'], explicit_only: true,
+ summary: 'Restore conversation-extractor facts that the pre-v0.60.11.0 canonical projection expired (#5731). Restores only facts with receipt evidence '
+ + '(a committed write of the page completed in the same transaction, by an older consumer); --include-ambiguous widens the hashed set to facts '
+ + 'without that evidence. Preview-bound: --apply --expect <hash> restores exactly the previewed set; a fact that changed since reports '
+ + 'changed_since_preview and stays expired. Superseded, withdrawn and duplicated facts are never restored. Database-only; no page is rewritten.',
+ },
};
export const REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_KINDS.map(kind => ({ kind, ...SPECS[kind] }));
@@ -92,10 +117,35 @@ export function repairMaySpend(spec: RepairKindSpec, noEmbed?: boolean): boolean
return spec.embeds === 'effect' || (spec.embeds === 'inline' && !noEmbed);
}
+/** The kinds `--all`, the remediation plan and `gbrain repair` with no kind run, in dependency order. */
+export const AUTO_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => !spec.explicit_only);
+
+/** The explicit-only kinds, listed by those surfaces with their preview command but never run by them. */
+export const EXPLICIT_REPAIR_REGISTRY: readonly RepairKindSpec[] = REPAIR_REGISTRY.filter(spec => spec.explicit_only);
+
export function repairSpec(kind: RepairKind): RepairKindSpec {
return REPAIR_REGISTRY.find(spec => spec.kind === kind)!;
}
+/** `gbrain repair <kind> [--source <id>]`, the read-only preview of one kind. */
+export function repairPreviewCommand(kind: RepairKind, opts: { source?: string } = {}): string {
+ return `gbrain repair ${kind}${opts.source ? ` --source ${opts.source}` : ''}`;
+}
+
+/** How `--all`, the remediation plan and the banner report an explicit-only kind instead of running it. */
+export interface ExplicitRepairNotice { kind: RepairKind; code: 'explicit_kind_required'; preview_command: string; docs: string }
+
+export function explicitRepairNotices(opts: { source?: string } = {}): ExplicitRepairNotice[] {
+ return EXPLICIT_REPAIR_REGISTRY.map(spec => ({ kind: spec.kind, code: 'explicit_kind_required' as const,
+ preview_command: repairPreviewCommand(spec.kind, opts), docs: ERROR_CATALOGUE.explicit_kind_required.docs }));
+}
+
+/** `explicit_kind_required`: an explicit-only kind reached a runner without being named. */
+export function explicitKindRequired(kind: RepairKind): OperationError {
+ return catalogueError('explicit_kind_required', `gbrain repair ${kind} is explicit-only and runs only when named, never from --all or a remediation step.`,
+ `Preview it on the brain host: ${repairPreviewCommand(kind)}`);
+}
+
/** The registered kind that clears a doctor check's findings, if any. */
export function repairForCheck(checkId: string): RepairKindSpec | undefined {
return REPAIR_REGISTRY.find(spec => spec.checks.includes(checkId));
@@ -118,11 +168,13 @@ export async function repairRunner(engine: BrainEngine, opts: { apply: boolean;
const logger = opts.logger ?? { info: console.error, warn: console.error, error: console.error };
return {
embeddingModel,
- async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string } = {}): Promise<RepairResult> {
+ /** `explicit`: the operator named `kind`; required for explicit-only kinds. */
+ async run(kind: RepairKind, scope: RepairScope, run: { limit?: number; sourceFlag?: string; explicit?: boolean; expect?: string; includeAmbiguous?: boolean } = {}): Promise<RepairResult> {
const ctx = { engine, config, logger, dryRun: !opts.apply, remote: false, sourceId: scope.source_ids[0] } as OperationContext;
const spec = repairSpec(kind);
return runRepair(ctx, spec.handler, scope, { apply: opts.apply, limit: run.limit, embeddingModel, sourceFlag: run.sourceFlag,
- embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [] });
+ embed: !opts.noEmbed && embeddingModel !== undefined, applyArgs: opts.noEmbed && spec.embeds === 'inline' ? ['--no-embed'] : [],
+ explicit: run.explicit, expect: run.expect, includeAmbiguous: run.includeAmbiguous });
},
};
}
diff --git a/src/core/repair/safe-chunks.ts b/src/core/repair/safe-chunks.ts
index be049f0c97..d80e011374 100644
--- a/src/core/repair/safe-chunks.ts
+++ b/src/core/repair/safe-chunks.ts
@@ -18,22 +18,6 @@ import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';
import { embedStalePages } from '../embed-stale.ts';
import { afterCursor, type RepairCursor, type RepairHandler, type RepairItem, type RepairScope } from './core.ts';
-/**
- * DX-D7: post-upgrade names the drain for pages still withheld. On a managed
- * brain `gbrain reindex --markdown` refuses; elsewhere it covers markdown only,
- * so code pages can remain. Null when nothing is withheld.
- */
-export async function safeChunkUpgradeAdvisory(engine: Pick<BrainEngine, 'executeRaw'>, managed: boolean): Promise<string | null> {
- const [row] = await engine.executeRaw<{ pending: number }>(`SELECT COUNT(*)::int AS pending FROM pages
- WHERE deleted_at IS NULL AND chunker_version < ${SAFE_FENCE_CHUNKER_VERSION}
- AND source_id IN (SELECT id FROM sources WHERE archived IS NOT TRUE)`);
- const pending = Number(row?.pending ?? 0);
- if (pending === 0) return null;
- return `[gbrain] ${pending} page(s) are below the safe-chunk index version and withheld from remote/MCP search. `
- + (managed ? 'This brain is managed, so the markdown reindex does not run here. ' : '')
- + 'Preview: gbrain repair safe-chunks — apply: gbrain repair safe-chunks --apply';
-}
-
interface PendingRow { id: number; source_id: string; slug: string; page_kind: string; rebuildable: boolean; chars: number }
export const safeChunksRepair: RepairHandler = {
diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.ts
new file mode 100644
index 0000000000..a108a58652
--- /dev/null
+++ b/src/core/repair/stale-atoms.ts
@@ -0,0 +1,217 @@
+/**
+ * `gbrain repair stale-atoms` (#5770, CEO-A7, ENG-O7, DX-O4): the one-time
+ * cleanup of atoms that drifted before managed re-extraction retired them.
+ *
+ * Two classes of live, page-bound (`source_slug`) atoms, never one with
+ * `imported_from` and never a file-bound (`source_path`-only) atom:
+ * (a) `origin_gone`: the source page is missing or soft-deleted;
+ * (b) `origin_changed`: the atom's 16-character source hash (a managed
+ * `pending:` prefix stripped) differs from its live source page's
+ * current hash, and that page already completed an extraction at its
+ * current hash (managed: the completed `managed-atoms` checkpoint;
+ * unmanaged: a non-managed atom of that page carrying the hash).
+ *
+ * The kind is explicit-only and preview-bound: the preview lists every atom
+ * with its class and saves the set under its hash; `--apply --expect <hash>`
+ * retires exactly that set. Each atom is rechecked when it is retired; one
+ * whose revision, class, origin or completion evidence changed reports
+ * `changed_since_preview` and is kept. A managed brain retires one atom per
+ * `managed_maintenance_retire_stale_atoms` request bound to the atom's
+ * revision (no live origin is required); an unmanaged brain soft-deletes it
+ * directly. Both stamp `retired_by: stale-atoms`, so a later extraction that
+ * produces the atom again restores it, and both invalidate the origin page's
+ * earlier completed extractions so a restored page is extracted again.
+ */
+import type { BrainEngine } from '../engine.ts';
+import type { GBrainConfig } from '../config.ts';
+import type { PreparedMutation } from '../persistence/coordinator.ts';
+import type { WriteRequest } from '../persistence/model.ts';
+import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { authorizeWrite } from '../persistence/authority.ts';
+import { managedPersistenceEnabled } from '../persistence/ownership.ts';
+import { preparePageMutation } from '../persistence/page-prepare.ts';
+import { maintenancePreflight, submitMaintenanceIntent } from '../persistence/prepared-maintenance.ts';
+import { bumpAtomGeneration, managedAtomCompletedSql } from '../persistence/atom-maintenance.ts';
+import { clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet } from '../persistence/preview-approval.ts';
+import { afterCursor, repairRequestId, type RepairHandler, type RepairItem, type RepairItemOutcome, type RepairPlan, type RepairScope } from './core.ts';
+
+export const STALE_ATOMS_RETIRED_BY = 'stale-atoms';
+export const STALE_ATOMS_INTENT = 'managed_maintenance_retire_stale_atoms';
+
+export type StaleAtomClass = 'origin_gone' | 'origin_changed';
+
+/** Everything the preview showed for one atom; the apply rechecks each field. */
+export interface StaleAtom {
+ id: number;
+ source_id: string;
+ /** The source incarnation the preview saw; a re-created source is a different atom. */
+ incarnation: string;
+ slug: string;
+ revision: string;
+ class: StaleAtomClass;
+ managed: boolean;
+ origin_slug: string;
+ origin_page_id: number | null;
+ origin_hash: string | null;
+ /** Class (b): the completed-extraction evidence at the origin's current hash. */
+ evidence: string | null;
+}
+
+interface StaleAtomItem extends RepairItem { atom: StaleAtom; hash: string; last: boolean }
+
+/** An approved atom carries the preview's source selection, so an apply under another `--source` refuses. */
+interface ApprovedStaleAtom extends StaleAtom { selection: string[] }
+
+/** Live stale atoms of these sources, in (class, id) order; `atomId` narrows to one atom for the apply recheck. */
+async function staleAtoms(db: BrainEngine, sourceIds: string[], atomId?: number): Promise<Array<StaleAtom & { chars: number }>> {
+ const rows = await db.executeRaw<StaleAtom & { chars: number }>(`
+ WITH atom AS (
+ SELECT a.id, a.source_id, (SELECT s.incarnation::text FROM sources s WHERE s.id=a.source_id) AS incarnation,
+ a.slug, a.knowledge_revision::text AS revision,
+ a.frontmatter->>'source_slug' AS origin_slug,
+ COALESCE(a.frontmatter->>'managed_extraction','')='true' AS managed,
+ regexp_replace(COALESCE(a.frontmatter->>'source_hash',''),'^pending:','') AS atom_hash,
+ length(COALESCE(a.compiled_truth,'')) AS chars,
+ o.id AS origin_page_id, o.slug AS origin_live_slug, o.source_id AS origin_source_id,
+ o.content_hash AS origin_hash, o.deleted_at IS NOT NULL AS origin_deleted
+ FROM pages a
+ LEFT JOIN pages o ON o.source_id=a.source_id AND o.slug=a.frontmatter->>'source_slug'
+ WHERE a.source_id=ANY($1::text[]) AND a.type='atom' AND a.deleted_at IS NULL
+ AND NULLIF(a.frontmatter->>'source_slug','') IS NOT NULL
+ AND NULLIF(a.frontmatter->>'imported_from','') IS NULL
+ AND ($2::int IS NULL OR a.id=$2::int)
+ ), classified AS (
+ SELECT atom.*, CASE
+ WHEN origin_page_id IS NULL OR origin_deleted THEN 'origin_gone'
+ WHEN origin_hash IS NOT NULL AND atom_hash<>substring(origin_hash from 1 for 16) THEN 'origin_changed'
+ END AS class,
+ CASE WHEN managed THEN (SELECT ac.fingerprint FROM op_checkpoints ac WHERE ${managedAtomCompletedSql({ sourceId: 'atom.origin_source_id',
+ slug: 'atom.origin_live_slug', pageId: 'atom.origin_page_id', contentHash: 'atom.origin_hash' })} ORDER BY ac.fingerprint LIMIT 1)
+ ELSE (SELECT 'unmanaged:'||e.id FROM pages e WHERE e.source_id=atom.source_id AND e.type='atom' AND e.deleted_at IS NULL
+ AND COALESCE(e.frontmatter->>'managed_extraction','')<>'true' AND e.frontmatter->>'source_slug'=atom.origin_slug
+ AND e.frontmatter->>'source_hash'=substring(atom.origin_hash from 1 for 16) ORDER BY e.id LIMIT 1)
+ END AS completion
+ FROM atom
+ )
+ SELECT id, source_id, incarnation, slug, revision, class, managed, origin_slug,
+ origin_page_id,
+ CASE WHEN class='origin_gone' THEN NULL ELSE origin_hash END AS origin_hash,
+ CASE WHEN class='origin_gone' THEN NULL ELSE completion END AS evidence, chars
+ FROM classified
+ WHERE class='origin_gone' OR (class='origin_changed' AND completion IS NOT NULL)
+ ORDER BY CASE class WHEN 'origin_gone' THEN 1 ELSE 2 END, id`, [sourceIds, atomId ?? null]);
+ return rows.map(row => ({ ...row, id: Number(row.id), managed: row.managed === true,
+ origin_page_id: row.origin_page_id === null ? null : Number(row.origin_page_id), chars: Number(row.chars) }));
+}
+
+function sameAtom(live: StaleAtom | undefined, approved: StaleAtom): boolean {
+ return !!live && (['id', 'source_id', 'incarnation', 'slug', 'revision', 'class', 'managed', 'origin_slug', 'origin_page_id', 'origin_hash', 'evidence'] as const)
+ .every(field => live[field] === approved[field]);
+}
+
+function previewCommand(scope: RepairScope): string {
+ return `gbrain repair stale-atoms${scope.source_ids.length === 1 ? ` --source ${scope.source_ids[0]}` : ''}`;
+}
+
+function item(atom: StaleAtom, hash: string, last: boolean): StaleAtomItem {
+ return { cursor: { phase: atom.class === 'origin_gone' ? 1 : 2, id: atom.id }, source_id: atom.source_id, slug: atom.slug,
+ chars: 0, action: `retire:${atom.class}`, atom, hash, last };
+}
+
+async function hashParts(engine: BrainEngine, scope: RepairScope, atoms: StaleAtom[]) {
+ const sources = await engine.executeRaw<{ id: string; incarnation: string }>(
+ 'SELECT id, incarnation::text AS incarnation FROM sources WHERE id=ANY($1::text[]) ORDER BY id', [scope.source_ids]);
+ return { kind: 'stale-atoms-v1', brain_id: scope.brain_id, sources, selection: { source_ids: scope.source_ids }, atoms };
+}
+
+export const staleAtomsRepair: RepairHandler = {
+ kind: 'stale-atoms',
+ embeds: false,
+ async plan(engine, scope, after, opts): Promise<RepairPlan> {
+ const command = previewCommand(scope);
+ if (!opts?.apply) {
+ const atoms = (await staleAtoms(engine, scope.source_ids)).map(({ chars: _chars, ...atom }) => atom);
+ const hash = previewHash(await hashParts(engine, scope, atoms));
+ if (atoms.length) await saveApprovedSet<ApprovedStaleAtom>(engine, { command: 'stale-atoms', hash }, atoms.map(atom => ({ ...atom, selection: scope.source_ids })));
+ return { items: atoms.map((atom, index) => item(atom, hash, index === atoms.length - 1)), preview_hash: hash,
+ residuals: { origin_gone: atoms.filter(atom => atom.class === 'origin_gone').length,
+ origin_changed: atoms.filter(atom => atom.class === 'origin_changed').length },
+ listing: atoms.map(atom => ({ item: `${atom.source_id}:${atom.slug}`, class: atom.class,
+ detail: atom.class === 'origin_gone' ? `source page ${atom.origin_slug} is gone`
+ : `source page ${atom.origin_slug} now at ${atom.origin_hash!.slice(0, 16)}` })) };
+ }
+ if (!opts.expect) {
+ throw new OperationError('invalid_params', 'gbrain repair stale-atoms --apply retires only the set a preview printed.',
+ `Preview first: ${command} — then run the apply command it prints: ${command} --apply --expect <preview-hash>`,
+ 'docs/guides/repair.md#explicit-only-repair-kinds');
+ }
+ const approved = await loadApprovedSet<ApprovedStaleAtom>(engine, { command: 'stale-atoms', hash: opts.expect, previewCommand: command });
+ if (approved.items.some(atom => JSON.stringify(atom.selection) !== JSON.stringify(scope.source_ids))) throw previewChangedError(opts.expect, command);
+ const items = approved.items.map(({ selection: _selection, ...atom }, index) => item(atom, opts.expect!, index === approved.items.length - 1));
+ return { items: items.filter(entry => afterCursor(entry.cursor, after)), preview_hash: opts.expect, residuals: {} };
+ },
+ async apply(ctx, entry): Promise<RepairItemOutcome> {
+ const { atom, hash, last } = entry as StaleAtomItem;
+ const outcome = await retireStaleAtom(ctx, atom);
+ if (last) await clearApprovedSet(ctx.engine, { command: 'stale-atoms', hash });
+ return outcome;
+ },
+};
+
+async function retireStaleAtom(ctx: OperationContext, atom: StaleAtom): Promise<RepairItemOutcome> {
+ const engine = ctx.engine;
+ const changed = (reason: string): RepairItemOutcome => ({ applied: false, outcome: 'changed_since_preview', reason });
+ if (!sameAtom((await staleAtoms(engine, [atom.source_id], atom.id))[0], atom)) return changed('the atom or its source page changed');
+ if (await managedPersistenceEnabled(engine)) {
+ const authority = (await maintenancePreflight(engine, atom.source_id))!;
+ try {
+ await submitMaintenanceIntent(engine, authority, atom.slug, { kind: STALE_ATOMS_INTENT, expected_revision: atom.revision, atom },
+ await repairRequestId(ctx, 'stale-atoms', atom, atom.revision));
+ } catch (error) {
+ if (error instanceof OperationError && ['revision_conflict', 'page_not_found', 'page_identity_changed'].includes(error.code)) return changed(error.message);
+ if (error instanceof OperationError && error.code === 'source_changed') return { applied: false, outcome: 'file_conflict', reason: error.message };
+ throw error;
+ }
+ return { applied: true, outcome: 'retired' };
+ }
+ const retired = await engine.transaction(async tx => {
+ await tx.lockPageKeys([{ sourceId: atom.source_id, slug: atom.slug }, { sourceId: atom.source_id, slug: atom.origin_slug }]);
+ if (!sameAtom((await staleAtoms(tx, [atom.source_id], atom.id))[0], atom)) return false;
+ await tx.createVersion(atom.slug, { sourceId: atom.source_id });
+ await tx.softDeletePage(atom.slug, { sourceId: atom.source_id });
+ await stampRetirement(tx, atom);
+ return true;
+ });
+ return retired ? { applied: true, outcome: 'retired' } : changed('the atom or its source page changed');
+}
+
+async function stampRetirement(tx: BrainEngine, atom: StaleAtom): Promise<void> {
+ await tx.executeRaw(`UPDATE pages SET frontmatter=frontmatter||jsonb_build_object('retired_by',$1::text,'retired_at',$2::text)
+ WHERE id=$3 AND source_id=$4 AND deleted_at IS NOT NULL`, [STALE_ATOMS_RETIRED_BY, new Date().toISOString(), atom.id, atom.source_id]);
+ if (atom.origin_page_id === null) return;
+ const [{ incarnation }] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [atom.source_id]);
+ await bumpAtomGeneration(tx, atom.source_id, incarnation, atom.origin_page_id, atom.class === 'origin_changed' ? atom.origin_hash : null);
+}
+
+/** Preparer for `managed_maintenance_retire_stale_atoms`: rechecks the atom's class under its and its origin's page locks, then retires it. */
+export async function prepareStaleAtomRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
+ const atom = row.intent!.atom as StaleAtom;
+ if (!atom || atom.slug !== row.slug || atom.source_id !== row.source_id || atom.id !== Number(row.page_id)) {
+ throw new OperationError('invalid_params', 'The stale atom retirement intent does not name its atom.');
+ }
+ const unchanged = async (db: BrainEngine) => {
+ if (!sameAtom((await staleAtoms(db, [row.source_id], atom.id))[0], atom)) {
+ throw new OperationError('revision_conflict', 'The stale atom or its source page changed since the preview.');
+ }
+ };
+ await unchanged(engine);
+ await authorizeWrite(engine, row.authority, 'delete_page', row.slug);
+ const page = await preparePageMutation(engine, { ...row, operation: 'delete_page' }, config, undefined, undefined, { allowMissingFile: true });
+ return { ...page, additionalPageKeys: [...(page.additionalPageKeys ?? []), { sourceId: row.source_id, slug: atom.origin_slug }],
+ validate: async tx => { await page.validate?.(tx); await authorizeWrite(tx, row.authority, 'delete_page', row.slug); await unchanged(tx); },
+ apply: async tx => {
+ const outcome = await page.apply(tx);
+ await stampRetirement(tx, atom);
+ return { ...outcome, retired_by: STALE_ATOMS_RETIRED_BY };
+ } };
+}
diff --git a/src/core/serve-invocation.ts b/src/core/serve-invocation.ts
new file mode 100644
index 0000000000..f22757a923
--- /dev/null
+++ b/src/core/serve-invocation.ts
@@ -0,0 +1,25 @@
+/**
+ * #5079: is this process `serve --http`, whose stdout/stderr are log streams
+ * only (the MCP transport is the HTTP socket)? cli.ts installs the cleanup
+ * handlers through installCleanupSignalHandlers below, before main(). Kept
+ * out of cli-force-exit.ts, which most commands import: the CLI flag-registry
+ * generator harvests flag literals from imported modules, so the literal here
+ * would widen their accepted flags.
+ */
+import { parseGlobalFlags } from './cli-options.ts';
+import { installSignalHandlers } from './process-cleanup.ts';
+
+export function isHttpServeInvocation(argv: string[] = process.argv.slice(2)): boolean {
+ let rest: string[];
+ try {
+ rest = parseGlobalFlags(argv).rest;
+ } catch {
+ rest = argv;
+ }
+ return rest[0] === 'serve' && rest.includes('--http');
+}
+
+/** cli.ts entrypoint: the process-cleanup handlers, log-pipe tolerant for `serve --http` only. */
+export function installCleanupSignalHandlers(argv: string[] = process.argv.slice(2)): void {
+ installSignalHandlers({ keepServingOnLogEpipe: isHttpServeInvocation(argv) });
+}
diff --git a/src/core/source-resolver.ts b/src/core/source-resolver.ts
index 0eb01df9b9..8a1fe3cb6f 100644
--- a/src/core/source-resolver.ts
+++ b/src/core/source-resolver.ts
@@ -16,6 +16,7 @@
import { readFileSync, lstatSync, type Stats } from 'fs';
import { join, dirname, resolve } from 'path';
import type { BrainEngine } from './engine.ts';
+import type { ExplicitReadBinding } from './ops/contract.ts';
import { isSourceFederated, parseSourceConfig } from './sources-load.ts';
import { SOURCE_ID_RE, isValidSourceId, ALL_SOURCES } from './source-id.ts';
import { isTrustedDotfile, realpathOrResolve, realpathOrResolveAsync } from './path-confine.ts';
@@ -882,16 +883,51 @@ export async function localFederatedSourceIds(
tier: SourceTier,
): Promise<string[] | undefined> {
if (tier === 'flag' || tier === 'env' || tier === 'dotfile') return undefined;
- let rows: Array<{ id: string; config: unknown; archived?: boolean }>;
+ return federatedSetFor(await liveSourceRows(engine), sourceId);
+}
+
+/**
+ * #5081 — explicit-read admission for a stdio connection bound by
+ * `GBRAIN_SOURCE` (tier `env`) or a `.gbrain-source` pin (tier `dotfile`).
+ * The admitted set is exactly what `localFederatedSourceIds` would compute for
+ * the same source on a non-explicit tier (one shared `federatedSetFor`), so a
+ * bound connection may NAME the sources an unbound one reads unqualified. The
+ * #2928 isolated anchor (`config.federated === false`) admits only itself.
+ * Unqualified reads of a bound connection stay scalar: the result goes on
+ * `OperationContext.explicitReadBinding`, never `localFederatedSourceIds`.
+ * Returns undefined for every other tier (no extra query).
+ */
+export async function explicitReadBinding(
+ engine: BrainEngine,
+ sourceId: string,
+ tier: SourceTier,
+): Promise<ExplicitReadBinding | undefined> {
+ if (tier !== 'env' && tier !== 'dotfile') return undefined;
+ const rows = await liveSourceRows(engine);
+ return {
+ sourceId,
+ via: tier === 'env' ? 'GBRAIN_SOURCE' : '.gbrain-source',
+ sourceIds: federatedSetFor(rows, sourceId) ?? [sourceId],
+ optedOut: rows.filter((row) => parseSourceConfig(row.config).federated === false).map((row) => row.id),
+ };
+}
+
+async function liveSourceRows(engine: BrainEngine): Promise<Array<{ id: string; config: unknown; archived?: boolean }>> {
try {
- rows = await engine.executeRaw<{ id: string; config: unknown; archived?: boolean }>(
+ return await engine.executeRaw<{ id: string; config: unknown; archived?: boolean }>(
`SELECT id, config, archived FROM sources WHERE archived = false ORDER BY id`,
);
} catch {
- rows = await engine.executeRaw<{ id: string; config: unknown }>(
+ return await engine.executeRaw<{ id: string; config: unknown }>(
`SELECT id, config FROM sources ORDER BY id`,
);
}
+}
+
+function federatedSetFor(
+ rows: Array<{ id: string; config: unknown; archived?: boolean }>,
+ sourceId: string,
+): string[] | undefined {
// #2928: an EXPLICITLY isolated anchor (`sources unfederate` /
// `--no-federated` → config.federated = false) opted out of cross-source
// read mixing — never widen it into the federated set (which would drag
diff --git a/src/core/sync-failure-ledger.ts b/src/core/sync-failure-ledger.ts
index 7db8b886ba..362347601a 100644
--- a/src/core/sync-failure-ledger.ts
+++ b/src/core/sync-failure-ledger.ts
@@ -215,6 +215,9 @@ export function classifyErrorCode(errorMsg: string): string {
// it the blocked-run breakdown also printed a bare `UNKNOWN: 1`.
if (/rename reconcile failed|RENAME_RECONCILE/i.test(errorMsg)) return 'RENAME_RECONCILE';
+ // #5032: a ':' file name on Windows (src/commands/sync/imports.ts).
+ if (/^colon_slug_windows_write_through:/.test(errorMsg)) return 'COLON_SLUG_WINDOWS_WRITE_THROUGH';
+
// SLUG_MISMATCH: thrown by importFromFile() at src/core/import-file.ts.
if (/slug.*does not match|SLUG_MISMATCH/i.test(errorMsg)) return 'SLUG_MISMATCH';
diff --git a/src/core/takes-quality-eval/pricing.ts b/src/core/takes-quality-eval/pricing.ts
index 956e6ba40a..8c29b40d4c 100644
--- a/src/core/takes-quality-eval/pricing.ts
+++ b/src/core/takes-quality-eval/pricing.ts
@@ -36,6 +36,7 @@ const SUPPORTED_MODELS = [
'openai:gpt-5',
'openai:gpt-5.2',
'openai:gpt-5.5',
+ 'anthropic:claude-opus-5-5',
'anthropic:claude-opus-5',
'anthropic:claude-opus-4-8',
'anthropic:claude-opus-4-7',
diff --git a/src/core/think/index.ts b/src/core/think/index.ts
index f79e9979ae..44541d92c9 100644
--- a/src/core/think/index.ts
+++ b/src/core/think/index.ts
@@ -447,17 +447,28 @@ async function persistCitations(
engine: BrainEngine,
synthesisPageId: number,
citations: ParsedCitation[],
+ scope: { sourceId?: string; allowedSources?: string[] } = {},
): Promise<{ inserted: number; warnings: string[] }> {
const warnings: string[] = [];
+ // #5426: the same slug can exist in several sources. Bind each citation to
+ // a page in the sources the synthesis drew from (preferring its own source),
+ // never to a same-slug page elsewhere in the brain. Unscoped only for an
+ // unscoped think.
+ const sources = scope.allowedSources?.length ? scope.allowedSources : scope.sourceId ? [scope.sourceId] : null;
// Resolve unique slugs to page_ids
const slugToPageId = new Map<string, number>();
for (const c of citations) {
if (c.row_num === null) continue; // page-level, skip
if (slugToPageId.has(c.page_slug)) continue;
- const rows = await engine.executeRaw<{ id: number }>(
- `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,
- [c.page_slug],
- );
+ const rows = sources
+ ? await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE slug = $1 AND source_id = ANY($2::text[]) ORDER BY (source_id = $3) DESC, id LIMIT 1`,
+ [c.page_slug, sources, scope.sourceId ?? ''],
+ )
+ : await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM pages WHERE slug = $1 LIMIT 1`,
+ [c.page_slug],
+ );
if (rows[0]) slugToPageId.set(c.page_slug, rows[0].id);
}
const evidenceInputs: SynthesisEvidenceInput[] = [];
@@ -1000,6 +1011,7 @@ export function stripGapsSection(answer: string): string {
export async function persistSynthesis(
engine: BrainEngine,
result: ThinkResult,
+ scope: { sourceId?: string; allowedSources?: string[] } = {},
): Promise<{ slug: string; evidenceInserted: number; warnings: string[] }> {
// #1698: never persist an empty synthesis. Returned signal (NOT a throw, F3) so
// the MCP `think` op can return the gather result + warning instead of a bare error
@@ -1039,9 +1051,9 @@ export async function persistSynthesis(
pages_gathered: result.pagesGathered,
takes_gathered: result.takesGathered,
},
- });
+ }, scope.sourceId ? { sourceId: scope.sourceId } : undefined);
- const persisted = await persistCitations(engine, page.id, result.citations);
+ const persisted = await persistCitations(engine, page.id, result.citations, scope);
return { slug, evidenceInserted: persisted.inserted, warnings: persisted.warnings };
}
diff --git a/src/core/transcripts/claude-code.ts b/src/core/transcripts/claude-code.ts
index 30bed43432..e886d8aca1 100644
--- a/src/core/transcripts/claude-code.ts
+++ b/src/core/transcripts/claude-code.ts
@@ -13,7 +13,7 @@ import type {
ParseSessionsOpts,
TranscriptAdapter,
} from './types.ts';
-import { TRANSCRIPT_JSONL_HARD_CAP } from './types.ts';
+import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';
import { parseClaudeSessionFile, SPEC_TARGET } from './claude-code-jsonl.ts';
import { basename } from 'node:path';
import { closeSync, openSync, readSync } from 'node:fs';
@@ -183,12 +183,12 @@ export const claudeCodeAdapter: TranscriptAdapter = {
harness: 'claude-code',
sessionId,
cwd: r.cwd,
- startedAt: r.startedAt || undefined,
+ startedAt: utcTimestamp(r.startedAt) || undefined,
raw: { sessionId, cwd: r.cwd ?? null, source_path: path },
},
messages: r.turns.map((t) => ({
role: t.role,
- timestamp: t.timestamp,
+ timestamp: utcTimestamp(t.timestamp),
text: t.text,
})),
};
diff --git a/src/core/transcripts/claude-export.ts b/src/core/transcripts/claude-export.ts
index bd59b47c16..04807e20d2 100644
--- a/src/core/transcripts/claude-export.ts
+++ b/src/core/transcripts/claude-export.ts
@@ -20,6 +20,7 @@ import type {
TranscriptMessage,
} from './types.ts';
import { loadExportConversations } from './export-json.ts';
+import { utcTimestamp } from './types.ts';
export const CLAUDE_EXPORT_SPEC_TARGET: HostSpecTarget = {
id: 'claude-ai-export-2026-08',
@@ -70,7 +71,7 @@ export const claudeExportAdapter: TranscriptAdapter = {
if (!text) continue;
messages.push({
role,
- timestamp: typeof r.created_at === 'string' ? r.created_at : '',
+ timestamp: utcTimestamp(r.created_at),
text,
});
}
@@ -88,8 +89,7 @@ export const claudeExportAdapter: TranscriptAdapter = {
harness: 'claude-export',
sessionId,
title: typeof c.name === 'string' && c.name ? c.name : undefined,
- startedAt:
- (typeof c.created_at === 'string' && c.created_at) || messages[0].timestamp || undefined,
+ startedAt: utcTimestamp(c.created_at) || messages[0].timestamp || undefined,
raw: {
conversation_uuid: sessionId,
name: typeof c.name === 'string' ? c.name : null,
diff --git a/src/core/transcripts/codex.ts b/src/core/transcripts/codex.ts
index 8a79ad4873..5bc1dc35a8 100644
--- a/src/core/transcripts/codex.ts
+++ b/src/core/transcripts/codex.ts
@@ -24,7 +24,7 @@ import type {
TranscriptAdapter,
TranscriptMessage,
} from './types.ts';
-import { TRANSCRIPT_JSONL_HARD_CAP } from './types.ts';
+import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';
/**
* Head window kept when a rollout exceeds the parse budget. Only needs to
@@ -102,7 +102,7 @@ export function mapCodexLine(entry: unknown): CodexLineResult {
if (typeof entry !== 'object' || entry === null) return { kind: 'skip' };
const e = entry as Record<string, unknown>;
const payload = (typeof e.payload === 'object' && e.payload !== null ? e.payload : {}) as Record<string, unknown>;
- const lineTs = typeof e.timestamp === 'string' ? e.timestamp : '';
+ const lineTs = utcTimestamp(e.timestamp);
if (e.type === 'session_meta') {
return {
kind: 'session',
@@ -115,7 +115,7 @@ export function mapCodexLine(entry: unknown): CodexLineResult {
(typeof payload.session_id === 'string' && payload.session_id) ||
undefined,
cwd: typeof payload.cwd === 'string' ? payload.cwd : undefined,
- startedAt: typeof payload.timestamp === 'string' ? payload.timestamp : lineTs || undefined,
+ startedAt: typeof payload.timestamp === 'string' ? utcTimestamp(payload.timestamp) : lineTs || undefined,
cliVersion: typeof payload.cli_version === 'string' ? payload.cli_version : undefined,
modelProvider: typeof payload.model_provider === 'string' ? payload.model_provider : undefined,
};
diff --git a/src/core/transcripts/openclaw.ts b/src/core/transcripts/openclaw.ts
index f7fdc4d644..71aa55bdbf 100644
--- a/src/core/transcripts/openclaw.ts
+++ b/src/core/transcripts/openclaw.ts
@@ -17,7 +17,7 @@ import type {
TranscriptAdapter,
TranscriptMessage,
} from './types.ts';
-import { TRANSCRIPT_JSONL_HARD_CAP } from './types.ts';
+import { TRANSCRIPT_JSONL_HARD_CAP, utcTimestamp } from './types.ts';
export const OPENCLAW_SPEC_TARGET: HostSpecTarget = {
id: 'openclaw-session-2026-08',
@@ -87,7 +87,7 @@ export function mapOpenclawLine(entry: unknown): OpenclawLineResult {
kind: 'session',
id: typeof e.id === 'string' ? e.id : undefined,
cwd: typeof e.cwd === 'string' ? e.cwd : undefined,
- startedAt: typeof e.timestamp === 'string' ? e.timestamp : undefined,
+ startedAt: typeof e.timestamp === 'string' ? utcTimestamp(e.timestamp) : undefined,
};
}
if (e.type === 'compaction') return { kind: 'boundary' };
@@ -114,12 +114,7 @@ export function mapOpenclawLine(entry: unknown): OpenclawLineResult {
}
text = text.trim();
if (!text) return toolCalls.length > 0 ? { kind: 'skip', toolCalls } : { kind: 'skip' };
- const timestamp =
- typeof m.timestamp === 'string' && m.timestamp
- ? m.timestamp
- : typeof e.timestamp === 'string'
- ? e.timestamp
- : '';
+ const timestamp = utcTimestamp(typeof m.timestamp === 'string' && m.timestamp ? m.timestamp : e.timestamp);
return { kind: 'message', message: { role, timestamp, text }, ...(toolCalls.length > 0 ? { toolCalls } : {}) };
}
diff --git a/src/core/transcripts/render.ts b/src/core/transcripts/render.ts
index 63fd2f2285..718fd53d6e 100644
--- a/src/core/transcripts/render.ts
+++ b/src/core/transcripts/render.ts
@@ -37,7 +37,7 @@ import { sanitizeForJsonb } from '../batch-rows.ts';
import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';
import { BUILTIN_PATTERNS } from '../conversation-parser/builtins.ts';
import type { ParsedSession, TranscriptMessage } from './types.ts';
-import { buildTranscriptSlug, transcriptFullId } from './types.ts';
+import { buildTranscriptSlug, transcriptFullId, utcTimestamp } from './types.ts';
// ── Shared line format (imessage-slack builtin) ─────────────────────────────
@@ -217,7 +217,7 @@ export function redactSession(
/** `2026-08-01T10:00:05.000Z` → `(2026-08-01 10:00 AM)` (UTC), matching the builtin. */
function anchorTimestamp(iso: string): string {
const d = new Date(iso);
- const day = iso.slice(0, 10);
+ const day = Number.isNaN(d.getTime()) ? iso.slice(0, 10) : d.toISOString().slice(0, 10);
let h = d.getUTCHours();
const ampm = h >= 12 ? 'PM' : 'AM';
h = h % 12 || 12;
@@ -312,7 +312,7 @@ export function renderSessionParts(
`session ${meta.sessionId} carries no timestamps — refusing to fabricate provenance`,
);
}
- const dateIso = firstTs;
+ const dateIso = utcTimestamp(firstTs);
const baseSlug = buildTranscriptSlug(meta.harness, dateIso, {
sessionId: meta.sessionId,
title: meta.title,
diff --git a/src/core/transcripts/types.ts b/src/core/transcripts/types.ts
index 789860b687..1b09669b64 100644
--- a/src/core/transcripts/types.ts
+++ b/src/core/transcripts/types.ts
@@ -150,6 +150,21 @@ export function transcriptFullId(sourceId: string): string {
/** Max slugified-title length inside an export slug (keeps slugs readable). */
const TITLE_SLUG_MAX = 48;
+/**
+ * Normalize an adapter's source timestamp to UTC (gbrain-evals N12-2). A
+ * string carrying an explicit offset ('2026-08-10T22:30:00-07:00') becomes
+ * its UTC ISO instant, so the date and the hour downstream come from the
+ * same instant. Everything else passes through unchanged: UTC strings stay
+ * byte-identical (no churn for existing imports), and unparseable or
+ * zone-less strings keep their current behavior. Non-strings become ''.
+ */
+export function utcTimestamp(v: unknown): string {
+ if (typeof v !== 'string') return '';
+ if (!/[+-]\d{2}:?\d{2}$/.test(v.trim())) return v;
+ const ms = Date.parse(v);
+ return Number.isNaN(ms) ? v : new Date(ms).toISOString();
+}
+
/**
* The one slug builder for every imported conversation page.
*
diff --git a/src/core/types.ts b/src/core/types.ts
index d6d815097a..e0470d5050 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1411,9 +1411,9 @@ export interface CodeEdgeInput {
/**
* v0.20.0 Cathedral II: result row from code edge queries (getCallersOf,
- * getCalleesOf, getEdgesByChunk). `resolved=true` means the row came from
- * code_edges_chunk (to_chunk_id is a known chunk); `resolved=false` means
- * code_edges_symbol (to_chunk_id is null).
+ * getCalleesOf, getEdgesByChunk). `resolved=true`: a code_edges_chunk row, or a
+ * code_edges_symbol row stamped with edge_metadata.resolved_chunk_id (N13-2).
+ * `resolved=false`: an unresolved code_edges_symbol row (to_chunk_id null).
*/
export interface CodeEdgeResult {
id: number;
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 220881b286..9e413b0d4e 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -165,6 +165,12 @@ export interface DispatchOpts {
* caller params. See OperationContext.localFederatedSourceIds.
*/
localFederatedSourceIds?: string[];
+ /**
+ * #5081: explicit-read admission for a stdio connection bound by
+ * GBRAIN_SOURCE or a .gbrain-source pin. Stdio transport only; see
+ * OperationContext.explicitReadBinding.
+ */
+ explicitReadBinding?: OperationContext['explicitReadBinding'];
/**
* `gbrain serve --source-guard` (plugin lanes): when set, write/admin ops
* are blocked unless the source resolution tier proves the binding is
@@ -485,6 +491,7 @@ export function buildOperationContext(
sourceId: opts.sourceId ?? 'default',
...(sessionId ? { sessionId } : {}),
...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),
+ ...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
auth: opts.auth,
};
diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.ts
index 62ef4f49e3..fe06ede53a 100644
--- a/src/mcp/resolve-ipc-binding.ts
+++ b/src/mcp/resolve-ipc-binding.ts
@@ -34,6 +34,7 @@ import { assembleTurnContext } from '../core/context/turn-context.ts';
import { makeContextPackIpcHandler } from './context-pack-handler.ts';
import { logTurnContextDeliveryFireAndForget } from '../core/context/volunteer-events.ts';
import { persistenceSocketPathForConfig, startPersistenceIpcServer, type PersistenceIpcProvider, type PersistenceIpcBinding } from '../core/persistence/ipc.ts';
+import { residentPersistenceConfig } from '../core/persistence/local-client.ts';
export interface ResolveIpcBinding {
/** The bound listener, or null when binding was skipped/failed (best-effort). */
@@ -92,8 +93,10 @@ export async function bindResolveIpcForServe(
const resolveSocket = resolveSocketPathForConfig(cfg);
if (!resolveSocket) return NULL_BINDING;
- if (persistenceProvider && cfg?.engine === 'pglite') {
- const persistenceSocket = persistenceSocketPathForConfig(cfg);
+ // The owner socket follows the brain the engine opened, which may be a mount (#5237).
+ const owner = residentPersistenceConfig(cfg);
+ if (persistenceProvider && owner?.engine === 'pglite') {
+ const persistenceSocket = persistenceSocketPathForConfig(owner);
if (persistenceSocket) {
try { persistence = await startPersistenceIpcServer(persistenceSocket, persistenceProvider); }
catch {
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index f96df71f56..48f8c5ee2f 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -14,7 +14,7 @@ import { getBrainHotMemoryMeta } from '../core/facts/meta-hook.ts';
import { loadConfig } from '../core/config.ts';
import { gcSessionContextState } from '../core/context/session-state.ts';
import { bindResolveIpcForServe } from './resolve-ipc-binding.ts';
-import { createPersistenceIpcProvider } from '../core/persistence/provider.ts';
+import { createPersistenceIpcProvider, residentPersistenceConfig } from '../core/persistence/provider.ts';
import { resolveMcpInstructions } from './instructions.ts';
import { installCapabilitiesResource, mcpAdministrationGuidance } from './capabilities.ts';
import { createSkillResources } from './skill-resources.ts';
@@ -27,7 +27,12 @@ import { assertStdioSourceBindable } from './source-preflight.ts';
export async function resolveMcpStdioSourceScope(
engine: BrainEngine,
cwd: string = process.cwd(),
-): Promise<{ sourceId: string; localFederatedSourceIds?: string[]; tier: import('../core/source-resolver.ts').SourceTier }> {
+): Promise<{
+ sourceId: string;
+ localFederatedSourceIds?: string[];
+ explicitReadBinding?: import('../core/ops/contract.ts').ExplicitReadBinding;
+ tier: import('../core/source-resolver.ts').SourceTier;
+}> {
// Degraded mode (db-availability 4c): short-circuit WITHOUT touching the
// engine. This site runs before EVERY dispatch and its catch below
// swallows errors into sourceId 'default' — letting it hit a degraded
@@ -47,12 +52,16 @@ export async function resolveMcpStdioSourceScope(
: { sourceId: 'default', tier: 'seed_default' };
}
try {
- const { resolveSourceWithTier, localFederatedSourceIds } = await import('../core/source-resolver.ts');
+ const { resolveSourceWithTier, localFederatedSourceIds, explicitReadBinding } = await import('../core/source-resolver.ts');
const resolved = await resolveSourceWithTier(engine, null, cwd);
const federated = await localFederatedSourceIds(engine, resolved.source_id, resolved.tier);
+ // #5081: the admission set is optional; a failed lookup must not discard
+ // the resolved binding (the catch below would fall back to 'default').
+ const binding = await explicitReadBinding(engine, resolved.source_id, resolved.tier).catch(() => undefined);
return {
sourceId: resolved.source_id,
...(federated ? { localFederatedSourceIds: federated } : {}),
+ ...(binding ? { explicitReadBinding: binding } : {}),
tier: resolved.tier,
};
} catch {
@@ -327,6 +336,9 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
...(sourceScope.localFederatedSourceIds
? { localFederatedSourceIds: sourceScope.localFederatedSourceIds }
: {}),
+ ...(sourceScope.explicitReadBinding
+ ? { explicitReadBinding: sourceScope.explicitReadBinding }
+ : {}),
// --source-guard (plugin lanes): thread the winning resolution tier so
// dispatch can fail-close ambient-tier writes. Off (undefined) unless
// the serve was started with the flag.
@@ -362,7 +374,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpS
ipcBinding = await bindResolveIpcForServe(
engine,
(await resolveMcpStdioSourceScope(engine)).sourceId,
- await createPersistenceIpcProvider(engine, config ?? { engine: engine.kind }),
+ await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind }),
);
// v0.45.7 ambient recall: age out stale session cursors once per serve boot
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 12045ca232..c9461bc94c 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.60.27.0 -->
+<!-- gbrain-template-stamp: 0.60.28.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/ai/anthropic-model-ids.test.ts b/test/ai/anthropic-model-ids.test.ts
index d3c00f139e..426f785a4d 100644
--- a/test/ai/anthropic-model-ids.test.ts
+++ b/test/ai/anthropic-model-ids.test.ts
@@ -47,7 +47,7 @@ describe('compareAnthropicVersions', () => {
describe('newerAnthropicModel', () => {
test('returns the newest priced same-family recipe id when the model is older', () => {
expect(newerAnthropicModel('anthropic:claude-sonnet-4-6')?.id).toBe('claude-sonnet-5');
- expect(newerAnthropicModel('anthropic:claude-opus-4-7')?.id).toBe('claude-opus-5');
+ expect(newerAnthropicModel('anthropic:claude-opus-4-7')?.id).toBe('claude-opus-5-5');
});
test('dated and undated forms of the current version get no hint', () => {
@@ -59,7 +59,8 @@ describe('newerAnthropicModel', () => {
for (const id of [
'anthropic:claude-sonnet-5',
'anthropic:claude-sonnet-6',
- 'anthropic:claude-opus-5-2',
+ 'anthropic:claude-opus-5-5',
+ 'anthropic:claude-opus-5-6',
'anthropic:claude-fable-5',
'openai:gpt-5.6',
'not-a-model',
diff --git a/test/all-sources-sentinel.test.ts b/test/all-sources-sentinel.test.ts
index 7284b216da..0e5c707fcc 100644
--- a/test/all-sources-sentinel.test.ts
+++ b/test/all-sources-sentinel.test.ts
@@ -160,9 +160,11 @@ describe('__all__ is never narrower than an unqualified read', () => {
expect(federatedSearchScope(ctx, '__all__')).toEqual({
sourceIds: ['default', 'src-a', 'src-b'],
});
- // Transport federation preserves unqualified reads; it does not grant an
- // arbitrary explicit source to a caller without a durable source grant.
- expect(() => federatedSearchScope(ctx, 'src-a')).toThrow('outside your granted sources');
+ // #5081 (CEO-A12): an explicit source inside the transport's federated
+ // set is admitted (never wider than the unqualified read above); any
+ // other explicit source is still refused.
+ expect(federatedSearchScope(ctx, 'src-a')).toEqual({ sourceId: 'src-a' });
+ expect(() => federatedSearchScope(ctx, 'src-z')).toThrow('outside your granted sources');
});
test('remote scalar scope stays pinned when no transport federation exists', () => {
diff --git a/test/apply-migrations-safety.serial.test.ts b/test/apply-migrations-safety.serial.test.ts
index b2a1c2500b..ed83b006f9 100644
--- a/test/apply-migrations-safety.serial.test.ts
+++ b/test/apply-migrations-safety.serial.test.ts
@@ -207,7 +207,7 @@ await runApplyMigrations(process.argv.slice(2));
writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nprintf '%s\\n' "$*" >> '${calls}'\nif [ "$1" = autopilot ]; then exit 99; fi\nexit 0\n`, { mode: 0o755 });
const result = await runCli(['apply-migrations', '--yes', '--migration', '0.11.0'], {
home, cwd: home,
- env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_NO_AUTOPILOT_INSTALL: undefined },
+ env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_JOB_CHILD_CLI: join(bin, 'gbrain'), GBRAIN_NO_AUTOPILOT_INSTALL: undefined },
});
expect(readFileSync(calls, 'utf8')).not.toContain('autopilot');
expect(result.exitCode).toBe(0);
@@ -231,7 +231,7 @@ await runApplyMigrations(process.argv.slice(2));
const args = ['apply-migrations', '--yes', '--migration', '0.11.0', ...(disable === 'flag' ? ['--no-autopilot-install'] : [])];
const result = await runCli(args, {
home, cwd: home,
- env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_NO_AUTOPILOT_INSTALL: disable === 'env' ? '1' : undefined },
+ env: { PATH: `${bin}:${process.env.PATH ?? ''}`, GBRAIN_JOB_CHILD_CLI: join(bin, 'gbrain'), GBRAIN_NO_AUTOPILOT_INSTALL: disable === 'env' ? '1' : undefined },
});
expect(result.exitCode).toBe(0);
expect(entries(ledger).at(-1)!.status).toBe('complete');
diff --git a/test/autopilot-install-id.test.ts b/test/autopilot-install-id.test.ts
new file mode 100644
index 0000000000..e58c0cf460
--- /dev/null
+++ b/test/autopilot-install-id.test.ts
@@ -0,0 +1,280 @@
+/**
+ * #5195 (T4, ENG-O11): every brain gets its own autopilot job name.
+ *
+ * The default brain (`~/.gbrain`) keeps the shared pre-#5195 names; any other
+ * brain derives `<name>-<suffix>` names from a random install id recorded in
+ * `<brain>/autopilot-install-id` as `{ id, realpath, created_at }`. These pin
+ * the id's copy/move semantics, the concurrent first install, the default-brain
+ * rule, the test-seam override, and crontab-line ownership. The install-target
+ * behavior (all four targets, two brains, legacy replacement) is pinned end to
+ * end in test/e2e/autopilot-multi-brain.serial.test.ts.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'fs';
+import { spawn, spawnSync } from 'child_process';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+import {
+ type AutopilotJob,
+ autopilotInstallIdPath,
+ autopilotLaunchdLabel,
+ autopilotWrapperOwner,
+ ensureAutopilotInstallId,
+ isDefaultBrainHome,
+ resolveAutopilotInstallId,
+ resolveAutopilotJob,
+} from '../src/core/autopilot-paths.ts';
+import { cronLineBelongsToBrain, generateSelfDisableGuard } from '../src/commands/autopilot.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+
+/**
+ * Bun's os.homedir() is fixed at process start, so the default-brain rule
+ * (which compares against homedir()/.gbrain, as configDir() does) is checked
+ * in a child process started with the HOME under test.
+ */
+function jobIn(env: Record<string, string | undefined>, mint = false): AutopilotJob & { isDefault: boolean } {
+ const script = `import { resolveAutopilotJob, isDefaultBrainHome } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\n` +
+ `process.stdout.write(JSON.stringify({ ...resolveAutopilotJob({ mint: ${mint} }), isDefault: isDefaultBrainHome() }));\n`;
+ const childEnv: Record<string, string> = {};
+ for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined) childEnv[k] = v;
+ const r = spawnSync(process.execPath, ['-e', script], { env: childEnv, encoding: 'utf-8' });
+ if (r.status !== 0) throw new Error(`child failed: ${r.stderr}`);
+ return JSON.parse(r.stdout);
+}
+
+async function withHosts(fn: (root: string) => Promise<void> | void): Promise<void> {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5195-')));
+ mkdirSync(join(root, 'home'), { recursive: true });
+ try {
+ await withEnv({ HOME: join(root, 'home'), GBRAIN_AUTOPILOT_LABEL: undefined }, () => fn(root));
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+}
+
+describe('#5195 default brain keeps the shared names', () => {
+ test('GBRAIN_HOME unset, or pointing at $HOME, is the default brain', async () => {
+ await withHosts(async (root) => {
+ const home = join(root, 'home');
+ for (const gbrainHome of [undefined, home]) {
+ const job = jobIn({ HOME: home, GBRAIN_HOME: gbrainHome }, true);
+ expect(job.isDefault).toBe(true);
+ expect(job.kind).toBe('default');
+ expect(job.launchdLabel).toBe('com.gbrain.autopilot');
+ expect(job.systemdUnit).toBe('gbrain-autopilot.service');
+ expect(job.startScriptPath).toBe(join(home, '.gbrain', 'start-autopilot.sh'));
+ expect(job.cronMarker).toBeNull();
+ expect(job.logPath).toBe(join(home, '.gbrain', 'autopilot.log'));
+ expect(job.installIdPath).toBeNull();
+ expect(existsSync(join(home, '.gbrain', 'autopilot-install-id'))).toBe(false);
+ }
+ });
+ });
+
+ test('a symlinked GBRAIN_HOME that resolves to ~/.gbrain is still the default brain', async () => {
+ await withHosts(async (root) => {
+ mkdirSync(join(root, 'home', '.gbrain'), { recursive: true });
+ const { symlinkSync } = await import('fs');
+ symlinkSync(join(root, 'home'), join(root, 'alias'));
+ expect(jobIn({ HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'alias') }).isDefault).toBe(true);
+ expect(jobIn({ HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'other') }).isDefault).toBe(false);
+ });
+ });
+});
+
+describe('#5195 non-default brains get their own names from the install id', () => {
+ test('two brains on one host get distinct suffixed names, all four targets', async () => {
+ await withHosts(async (root) => {
+ const a = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => resolveAutopilotJob({ mint: true }));
+ const b = await withEnv({ GBRAIN_HOME: join(root, 'brain-b') }, () => resolveAutopilotJob({ mint: true }));
+ for (const job of [a, b]) {
+ expect(job.kind).toBe('suffixed');
+ expect(job.suffix).toMatch(/^[0-9a-f]{8}$/);
+ expect(job.launchdLabel).toBe(`com.gbrain.autopilot.${job.suffix}`);
+ expect(job.systemdUnit).toBe(`gbrain-autopilot-${job.suffix}.service`);
+ expect(job.startScriptPath).toBe(join(job.homeDir, `start-autopilot-${job.suffix}.sh`));
+ expect(job.cronMarker).toBe(`# gbrain-autopilot:${job.suffix}`);
+ expect(job.logPath).toBe(join(job.homeDir, 'autopilot.log'));
+ }
+ expect(a.suffix).not.toBe(b.suffix);
+ expect(a.launchdLabel).not.toBe(b.launchdLabel);
+ expect(a.systemdUnit).not.toBe(b.systemdUnit);
+ });
+ });
+
+ test('the record holds { id, realpath, created_at } and a reinstall reuses it', async () => {
+ await withHosts(async (root) => {
+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => {
+ const id = ensureAutopilotInstallId();
+ const rec = JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8'));
+ expect(rec.id).toBe(id);
+ expect(rec.realpath).toBe(join(root, 'brain-a', '.gbrain'));
+ expect(Number.isNaN(Date.parse(rec.created_at))).toBe(false);
+ expect(ensureAutopilotInstallId()).toBe(id);
+ });
+ });
+ });
+
+ test('read-only resolution never mints: an uninstalled brain owns no named job', async () => {
+ await withHosts(async (root) => {
+ await withEnv({ GBRAIN_HOME: join(root, 'never-installed') }, () => {
+ const job = resolveAutopilotJob();
+ expect(job.kind).toBe('unassigned');
+ expect(job.suffix).toBeNull();
+ // A configDir() that does not exist yet resolves with `resolve`.
+ expect(resolveAutopilotInstallId().relation).toBe('none');
+ expect(existsSync(join(root, 'never-installed'))).toBe(false);
+ });
+ });
+ });
+
+ test('cp -r of a brain mints a new id on install (the original still exists)', async () => {
+ await withHosts(async (root) => {
+ const original = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => ensureAutopilotInstallId());
+ cpSync(join(root, 'brain-a'), join(root, 'brain-copy'), { recursive: true });
+ await withEnv({ GBRAIN_HOME: join(root, 'brain-copy') }, () => {
+ expect(resolveAutopilotInstallId().relation).toBe('copied');
+ expect(resolveAutopilotJob().kind).toBe('unassigned');
+ const copy = ensureAutopilotInstallId();
+ expect(copy).not.toBe(original);
+ expect(JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8')).realpath).toBe(join(root, 'brain-copy', '.gbrain'));
+ });
+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => {
+ expect(ensureAutopilotInstallId()).toBe(original);
+ });
+ });
+ });
+
+ test('mv of a brain keeps its id and job, and records the new path', async () => {
+ await withHosts(async (root) => {
+ const before = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => resolveAutopilotJob({ mint: true }));
+ renameSync(join(root, 'brain-a'), join(root, 'brain-moved'));
+ await withEnv({ GBRAIN_HOME: join(root, 'brain-moved') }, () => {
+ expect(resolveAutopilotInstallId().relation).toBe('moved');
+ expect(resolveAutopilotJob().suffix).toBe(before.suffix);
+ const after = resolveAutopilotJob({ mint: true });
+ expect(after.suffix).toBe(before.suffix);
+ expect(after.launchdLabel).toBe(before.launchdLabel);
+ expect(JSON.parse(readFileSync(autopilotInstallIdPath(), 'utf-8')).realpath).toBe(join(root, 'brain-moved', '.gbrain'));
+ expect(resolveAutopilotInstallId().relation).toBe('same');
+ });
+ });
+ });
+
+ test('concurrent first installs agree on one id', async () => {
+ await withHosts(async (root) => {
+ const gbrainHome = join(root, 'brain-race');
+ const script = `import { ensureAutopilotInstallId } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\nprocess.stdout.write(ensureAutopilotInstallId());\n`;
+ const scriptPath = join(root, 'race.ts');
+ writeFileSync(scriptPath, script);
+ const runs = Array.from({ length: 6 }, () => new Promise<string>((done, fail) => {
+ const child = spawn(process.execPath, [scriptPath], { env: { ...process.env, GBRAIN_HOME: gbrainHome, HOME: join(root, 'home') } });
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (d) => { out += d; });
+ child.stderr.on('data', (d) => { err += d; });
+ child.on('close', (code) => (code === 0 ? done(out.trim()) : fail(new Error(`exit ${code}: ${err}`))));
+ }));
+ const ids = await Promise.all(runs);
+ expect(new Set(ids).size).toBe(1);
+ expect(ids[0]).toMatch(/^[0-9a-f]{32}$/);
+ const leftovers = (await import('fs')).readdirSync(join(gbrainHome, '.gbrain')).filter(f => f.endsWith('.tmp'));
+ expect(leftovers).toEqual([]);
+ });
+ }, 60_000);
+
+ test('concurrent installs of a freshly copied brain settle on one new id', async () => {
+ await withHosts(async (root) => {
+ const original = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => ensureAutopilotInstallId());
+ cpSync(join(root, 'brain-a'), join(root, 'brain-copy'), { recursive: true });
+ const script = `import { ensureAutopilotInstallId } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\nprocess.stdout.write(ensureAutopilotInstallId());\n`;
+ const scriptPath = join(root, 'race-copy.ts');
+ writeFileSync(scriptPath, script);
+ const ids = await Promise.all(Array.from({ length: 6 }, () => new Promise<string>((done, fail) => {
+ const child = spawn(process.execPath, [scriptPath], { env: { ...process.env, GBRAIN_HOME: join(root, 'brain-copy'), HOME: join(root, 'home') } });
+ let out = '';
+ let err = '';
+ child.stdout.on('data', (d) => { out += d; });
+ child.stderr.on('data', (d) => { err += d; });
+ child.on('close', (code) => (code === 0 ? done(out.trim()) : fail(new Error(`exit ${code}: ${err}`))));
+ })));
+ expect(new Set(ids).size).toBe(1);
+ expect(ids[0]).not.toBe(original);
+ const recorded = JSON.parse(readFileSync(join(root, 'brain-copy', '.gbrain', 'autopilot-install-id'), 'utf-8'));
+ expect(recorded.id).toBe(ids[0]);
+ expect(existsSync(join(root, 'brain-copy', '.gbrain', 'autopilot-install-id.lock'))).toBe(false);
+ });
+ }, 60_000);
+
+ test('the GBRAIN_AUTOPILOT_LABEL test seam still wins over the suffix', async () => {
+ await withHosts(async (root) => {
+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a'), GBRAIN_AUTOPILOT_LABEL: 'com.gbrain.autopilot.test.seam' }, () => {
+ const job = resolveAutopilotJob({ mint: true });
+ expect(job.suffix).not.toBeNull();
+ expect(job.launchdLabel).toBe('com.gbrain.autopilot.test.seam');
+ expect(autopilotLaunchdLabel(job.suffix)).toBe('com.gbrain.autopilot.test.seam');
+ });
+ });
+ });
+
+ test("the wrapper's self-disable lines name this brain's own label and unit", async () => {
+ await withHosts(async (root) => {
+ await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => {
+ const job = resolveAutopilotJob({ mint: true });
+ expect(generateSelfDisableGuard('/data/brain', 'macos', job)).toContain(`gui/$(id -u)/com.gbrain.autopilot.${job.suffix}`);
+ expect(generateSelfDisableGuard('/data/brain', 'linux-systemd', job)).toContain(`disable --now gbrain-autopilot-${job.suffix}.service`);
+ });
+ });
+ });
+});
+
+describe('#5195 crontab line ownership', () => {
+ test('marked lines belong to their suffix; unmarked lines to the brain whose wrapper they name, else the default brain', async () => {
+ await withHosts(async (root) => {
+ const home = join(root, 'home');
+ const def = jobIn({ HOME: home, GBRAIN_HOME: undefined });
+ expect(def.kind).toBe('default');
+ const a = await withEnv({ GBRAIN_HOME: join(root, 'brain-a') }, () => resolveAutopilotJob({ mint: true }));
+ const b = await withEnv({ GBRAIN_HOME: join(root, 'brain-b') }, () => resolveAutopilotJob({ mint: true }));
+ const marked = `*/5 * * * * '${a.wrapperPath}' >> '${a.logPath}' 2>&1 ${a.cronMarker}`;
+ const legacyA = `*/5 * * * * '${a.wrapperPath}' >> '${home}/.gbrain/autopilot.log' 2>&1`;
+ const legacyDefault = `*/5 * * * * '${home}/.gbrain/autopilot-run.sh' >> '${home}/.gbrain/autopilot.log' 2>&1`;
+ const direct = '*/5 * * * * gbrain autopilot --repo /data/brain';
+ const monitor = '*/10 * * * * gbrain autopilot --status --json >> health.log';
+
+ expect(cronLineBelongsToBrain(marked, a)).toBe(true);
+ expect(cronLineBelongsToBrain(marked, b)).toBe(false);
+ expect(cronLineBelongsToBrain(marked, def)).toBe(false);
+
+ expect(cronLineBelongsToBrain(legacyA, a)).toBe(true);
+ expect(cronLineBelongsToBrain(legacyA, b)).toBe(false);
+ expect(cronLineBelongsToBrain(legacyA, def)).toBe(false);
+
+ expect(cronLineBelongsToBrain(legacyDefault, def)).toBe(true);
+ expect(cronLineBelongsToBrain(legacyDefault, a)).toBe(false);
+
+ expect(cronLineBelongsToBrain(direct, def)).toBe(true);
+ expect(cronLineBelongsToBrain(direct, a)).toBe(false);
+
+ expect(cronLineBelongsToBrain(monitor, def)).toBe(false);
+ expect(cronLineBelongsToBrain(`# ${legacyDefault}`, def)).toBe(false);
+ });
+ });
+
+ test('wrapper ownership: own, dangling (moved brain), another live brain', async () => {
+ await withHosts(async (root) => {
+ mkdirSync(join(root, 'brain-b', '.gbrain'), { recursive: true });
+ writeFileSync(join(root, 'brain-b', '.gbrain', 'autopilot-run.sh'), '#!/bin/sh\n');
+ const home = join(root, 'brain-a', '.gbrain');
+ expect(autopilotWrapperOwner(join(home, 'autopilot-run.sh'), home).owner).toBe('own');
+ expect(autopilotWrapperOwner(join(root, 'gone', '.gbrain', 'autopilot-run.sh'), home).owner).toBe('dangling');
+ expect(autopilotWrapperOwner(join(root, 'brain-b', '.gbrain', 'autopilot-run.sh'), home))
+ .toEqual({ owner: 'other', home: join(root, 'brain-b', '.gbrain') });
+ expect(autopilotWrapperOwner(null, home).owner).toBe('unknown');
+ });
+ });
+});
diff --git a/test/backup-git-env.test.ts b/test/backup-git-env.test.ts
new file mode 100644
index 0000000000..3e04ad3c60
--- /dev/null
+++ b/test/backup-git-env.test.ts
@@ -0,0 +1,37 @@
+/** #5794: the backup probe's git env is an allowlist, never the whole process env. */
+import { describe, expect, test } from 'bun:test';
+import { backupGitEnv } from '../src/core/backup/repository.ts';
+import { buildGitEnv } from '../src/core/git-remote.ts';
+
+const source = {
+ HOME: '/home/example', PATH: '/usr/bin', XDG_CONFIG_HOME: '/home/example/.config', SSH_AUTH_SOCK: '/tmp/agent.sock',
+ GIT_CONFIG_GLOBAL: '/home/example/.gitconfig-work', HTTPS_PROXY: 'http://proxy.example:8080', https_proxy: 'http://proxy.example:8080',
+ HTTP_PROXY: 'http://proxy.example:8080', http_proxy: 'http://proxy.example:8080', NO_PROXY: 'localhost', no_proxy: 'localhost',
+ USERPROFILE: 'C:\\Users\\example', APPDATA: 'C:\\Users\\example\\AppData\\Roaming', SystemRoot: 'C:\\Windows',
+ GIT_DIR: '/elsewhere/.git', GIT_WORK_TREE: '/elsewhere', GIT_ASKPASS: '/usr/bin/askpass', GIT_TERMINAL_PROMPT: '1', OPENAI_API_KEY: 'example-key',
+};
+
+describe('backup probe git env (#5794)', () => {
+ test('passes the user config, credential and proxy variables on POSIX', () => {
+ const env = backupGitEnv(source, 'linux');
+ expect(Object.keys(env).sort()).toEqual(['GCM_INTERACTIVE', 'GIT_ASKPASS', 'GIT_CONFIG_GLOBAL', 'GIT_TERMINAL_PROMPT', 'HOME', 'HTTPS_PROXY', 'HTTP_PROXY',
+ 'NO_PROXY', 'PATH', 'SSH_ASKPASS', 'SSH_AUTH_SOCK', 'XDG_CONFIG_HOME', 'http_proxy', 'https_proxy', 'no_proxy'].sort());
+ expect(env).toMatchObject({ HOME: '/home/example', PATH: '/usr/bin', SSH_AUTH_SOCK: '/tmp/agent.sock', ...buildGitEnv('linux') });
+ });
+
+ test('adds the Windows profile variables only on Windows', () => {
+ expect(backupGitEnv(source, 'win32')).toMatchObject({ USERPROFILE: source.USERPROFILE, APPDATA: source.APPDATA, SystemRoot: source.SystemRoot, ...buildGitEnv('win32') });
+ expect(backupGitEnv(source, 'linux').USERPROFILE).toBeUndefined();
+ });
+
+ test('never passes repository-redirecting variables or secrets, and the no-prompt overrides win', () => {
+ for (const platform of ['linux', 'darwin', 'win32'] as const) {
+ const env = backupGitEnv(source, platform);
+ expect(env.GIT_DIR).toBeUndefined();
+ expect(env.GIT_WORK_TREE).toBeUndefined();
+ expect(env.OPENAI_API_KEY).toBeUndefined();
+ expect(env.GIT_TERMINAL_PROMPT).toBe('0');
+ }
+ expect(backupGitEnv(source, 'linux').GIT_ASKPASS).toBe('/bin/false');
+ });
+});
diff --git a/test/backup-verification.serial.test.ts b/test/backup-verification.serial.test.ts
index c159a1aa57..2546957d81 100644
--- a/test/backup-verification.serial.test.ts
+++ b/test/backup-verification.serial.test.ts
@@ -11,6 +11,7 @@ import { checkBackupCoverage } from '../src/commands/doctor/checks/backup-covera
import { pushStatusPathForRoot } from '../src/core/workspace-push.ts';
import { assessBackupRepository, BACKUP_REMOTE_PROBE_CAP, BACKUP_REMOTE_BUDGET_MS, BACKUP_REMOTE_TIMEOUT_MS } from '../src/core/backup/repository.ts';
import { makeGitFixture } from './helpers/git-fixture.ts';
+import { withEnv } from './helpers/with-env.ts';
let tmp: string;
let oldHome: string | undefined;
@@ -279,3 +280,19 @@ test('retained evidence is invalidated by local identity, source, commit, remote
expect(result.verification?.state).not.toBe('verified');
}
}, 15_000);
+
+test('the remote probe reads the user git config through HOME, so an insteadOf rewrite reaches the remote (#5794)', async () => {
+ const { root, remote } = await repository();
+ const alias = 'https://example.invalid/private-backup.git';
+ git(root, 'remote', 'set-url', 'origin', alias);
+ const userHome = join(tmp, 'user-home');
+ mkdirSync(userHome);
+ writeFileSync(join(userHome, '.gitconfig'), `[url "${remote}"]\n\tinsteadOf = ${alias}\n`);
+ const head = git(root, 'rev-parse', 'HEAD');
+ await withEnv({ HOME: userHome, GIT_CONFIG_GLOBAL: undefined, XDG_CONFIG_HOME: undefined,
+ GIT_DIR: join(tmp, 'not-a-repository'), GIT_WORK_TREE: join(tmp, 'not-a-worktree') }, async () => {
+ const result = await assessBackupRepository(root, 'source_repo', 'source-id', now, { remaining: 1 });
+ expect(result.verification).toMatchObject({ state: 'verified', local_commit: head, remote_commit: head });
+ expect(result.state).toBe('ok');
+ });
+}, 15_000);
diff --git a/test/brain-pdf-frontmatter-strip.test.ts b/test/brain-pdf-frontmatter-strip.test.ts
new file mode 100644
index 0000000000..d4ae5508bc
--- /dev/null
+++ b/test/brain-pdf-frontmatter-strip.test.ts
@@ -0,0 +1,58 @@
+/**
+ * #5772: brain-pdf stripped frontmatter with a GNU-only sed range that BSD sed
+ * (macOS) rejects (empty PDF) and that GNU sed also got wrong: a body `---`
+ * rule restarted the range and deleted everything after it, and a page
+ * without frontmatter kept only its first line. These run the strip step as
+ * written in skills/brain-pdf/SKILL.md (and its generated plugin copy).
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { spawnSync } from 'child_process';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+const REPO = resolve(import.meta.dir, '..');
+
+/** The skill's strip step: the line that writes "$CLEAN", plus its guard. */
+function stripStep(skillPath: string): string {
+ const lines = readFileSync(join(REPO, skillPath), 'utf-8').split('\n');
+ const i = lines.findIndex(l => l.includes('"$RAW" > "$CLEAN"'));
+ if (i < 0) throw new Error(`no strip step in ${skillPath}`);
+ return lines.slice(i, i + 2).filter(l => l.includes('"$CLEAN"')).join('\n');
+}
+
+function strip(skillPath: string, page: string): { out: string; status: number | null; stderr: string } {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5772-'));
+ try {
+ writeFileSync(join(dir, 'raw.md'), page);
+ const r = spawnSync('bash', ['-c', `${stripStep(skillPath)}\ncat "$CLEAN"`], {
+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', RAW: join(dir, 'raw.md'), CLEAN: join(dir, 'clean.md'), SLUG: 'notes/x' },
+ encoding: 'utf-8',
+ });
+ return { out: r.stdout, status: r.status, stderr: r.stderr };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+for (const skill of ['skills/brain-pdf/SKILL.md', 'plugin/skills/brain-pdf/SKILL.md']) {
+ describe(`#5772 brain-pdf frontmatter strip (${skill})`, () => {
+ test('removes only the leading frontmatter block; a body --- rule and what follows survive', () => {
+ const r = strip(skill, '---\ntitle: X\ntype: note\n---\n# X\n\npara1\n\n---\n\npara2 after hr\n');
+ expect(r.status).toBe(0);
+ expect(r.out).toBe('# X\n\npara1\n\n---\n\npara2 after hr\n');
+ });
+
+ test('a page without frontmatter keeps every line', () => {
+ const page = '# Plain page\n\nline two\n\nline three\n';
+ expect(strip(skill, page).out).toBe(page);
+ });
+
+ test('a page that is only frontmatter stops instead of rendering an empty PDF', () => {
+ const r = strip(skill, '---\ntitle: X\n---\n');
+ expect(r.status).toBe(1);
+ expect(r.stderr).toContain('nothing to render for notes/x');
+ });
+ });
+}
diff --git a/test/bundle-files-segments.test.ts b/test/bundle-files-segments.test.ts
new file mode 100644
index 0000000000..470d1a024c
--- /dev/null
+++ b/test/bundle-files-segments.test.ts
@@ -0,0 +1,50 @@
+/**
+ * #5776: skill publication's bundle reader checked the whole relative path
+ * for a backslash, which is the separator on Windows, so every nested bundle
+ * file was rejected there and the shared-skills projection never completed.
+ * The check is per path segment now. The win32 cases run on every OS through
+ * path.win32; the readBundleFile case runs natively in the Windows
+ * security-regressions job.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'fs';
+import { join, posix, win32 } from 'path';
+import { tmpdir } from 'os';
+
+import { bundleRelativePathIsSafe, readBundleFile } from '../src/core/persistence/bundle-files.ts';
+
+describe('#5776 bundle paths are checked per segment', () => {
+ test('a nested Windows path is safe', () => {
+ const rel = win32.relative('C:\\brain\\skills', 'C:\\brain\\skills\\sub\\nested.md');
+ expect(rel).toBe('sub\\nested.md');
+ expect(bundleRelativePathIsSafe(rel, win32.sep)).toBe(true);
+ });
+
+ test('unsafe segments are still refused on Windows', () => {
+ expect(bundleRelativePathIsSafe('sub\\a:b.md', win32.sep)).toBe(false);
+ expect(bundleRelativePathIsSafe('sub\\a\u0001b.md', win32.sep)).toBe(false);
+ expect(bundleRelativePathIsSafe('sub\\a/b.md', win32.sep)).toBe(false);
+ expect(bundleRelativePathIsSafe('sub\\\\b.md', win32.sep)).toBe(false);
+ });
+
+ test('POSIX keeps refusing a backslash inside a file name, and the depth bound holds', () => {
+ expect(bundleRelativePathIsSafe('sub/nested.md', posix.sep)).toBe(true);
+ expect(bundleRelativePathIsSafe('sub/a\\b.md', posix.sep)).toBe(false);
+ expect(bundleRelativePathIsSafe('sub/a:b.md', posix.sep)).toBe(false);
+ expect(bundleRelativePathIsSafe(Array.from({ length: 16 }, () => 'd').join('/'), posix.sep)).toBe(true);
+ expect(bundleRelativePathIsSafe(Array.from({ length: 17 }, () => 'd').join('/'), posix.sep)).toBe(false);
+ });
+
+ test('readBundleFile reads a nested file on this platform', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5776-')));
+ try {
+ mkdirSync(join(root, 'sub'), { recursive: true });
+ writeFileSync(join(root, 'sub', 'nested.md'), 'nested body');
+ const read = readBundleFile(join(root, 'sub', 'nested.md'), root);
+ expect(read?.bytes.toString('utf-8')).toBe('nested body');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/chunker-version-gate.test.ts b/test/chunker-version-gate.test.ts
index 75d9a10792..8ef52e2c35 100644
--- a/test/chunker-version-gate.test.ts
+++ b/test/chunker-version-gate.test.ts
@@ -15,7 +15,7 @@ import { describe, test, expect } from 'bun:test';
import { CHUNKER_VERSION } from '../src/core/chunkers/code.ts';
describe('Layer 12 — CHUNKER_VERSION constant', () => {
- test('bumped to 7 for the compatible Bash grammar (#5082)', () => {
+ test('bumped to 8 for function-valued declarations (N13-1, after #5082 at 7)', () => {
// v3: v0.19.0 Chonkie parity (tokenizer + small-sibling merge).
// v4: v0.20.0 Cathedral II (qualified names + parent scope + doc_comment
// + fence extraction + chunk-grain FTS). Folded into content_hash
@@ -25,14 +25,16 @@ describe('Layer 12 — CHUNKER_VERSION constant', () => {
// v6: #4511 mergeSmallSiblings stopped erasing symbol_name on short
// definitions; the bump re-chunks previously-merged files so the
// lost symbols come back.
- expect(CHUNKER_VERSION).toBe(7);
+ // v7: #5082 compatible Bash grammar.
+ // v8: N13-1 `const f = () => …` definitions keep their own named chunk.
+ expect(CHUNKER_VERSION).toBe(8);
});
test('is stable across imports (not recomputed at call time)', async () => {
const a = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;
const b = (await import('../src/core/chunkers/code.ts')).CHUNKER_VERSION;
expect(a).toBe(b);
- expect(a).toBe(7);
+ expect(a).toBe(8);
});
});
diff --git a/test/chunkers/code-merge-defs.test.ts b/test/chunkers/code-merge-defs.test.ts
index f9b7fad1e4..ecba680983 100644
--- a/test/chunkers/code-merge-defs.test.ts
+++ b/test/chunkers/code-merge-defs.test.ts
@@ -66,6 +66,30 @@ describe('#4511 — short flat definitions keep their symbol names', () => {
expect(named[0]!.metadata.symbolType).toBe('function');
});
+ // gbrain-evals N13-1: `const name = (...) => ...` is a named function
+ // definition even though its node is a lexical declaration (a mergeable
+ // run form). 9 of 50 pathe functions were folded into nameless chunks.
+ test('typescript: short const arrow functions keep their names (N13-1)', async () => {
+ const src = [
+ 'const ALPHABET = "abcdefghijklmnopqrstuvwxyz";', '',
+ 'const int2alpha = (int: number): string => {', ' let alpha = "";', ' while (int > 0) {', ' alpha = ALPHABET[(int - 1) % 26] + alpha;', ' int = Math.floor((int - 1) / 26);', ' }', ' return alpha;', '};', '',
+ 'const alpha2int = (str: string): number => {', ' let int = 0;', ' for (const char of str) int = int * 26 + ALPHABET.indexOf(char) + 1;', ' return int;', '};', '',
+ 'let legacy = function (v: number) { return v; };', '',
+ 'export function roundTrip(n: number): number {', ' return alpha2int(int2alpha(n));', '}', '',
+ ].join('\n');
+ const chunks = await chunkCodeText(src, 'sample.ts');
+ const names = chunks.map((c) => c.metadata.symbolName);
+ expect(names).toEqual(expect.arrayContaining(['int2alpha', 'alpha2int', 'legacy', 'roundTrip']));
+ expect(chunks.some((c) => c.metadata.symbolType === 'merged' && /int2alpha =|alpha2int =|legacy =/.test(c.text))).toBe(false);
+ });
+
+ test('javascript: const value runs still merge (only function values are protected)', async () => {
+ const src = Array.from({ length: 6 }, (_, i) => `const K${i} = ${i};`).join('\n') + '\n';
+ const chunks = await chunkCodeText(src, 'consts.js');
+ expect(chunks).toHaveLength(1);
+ expect(chunks[0]!.metadata.symbolType).toBe('merged');
+ });
+
test('import runs still merge (the pass keeps its stated purpose)', async () => {
const src = Array.from({ length: 8 }, (_, i) => `import mod_${i}`).join('\n') + '\n';
const chunks = await chunkCodeText(src, 'imports.py');
@@ -77,6 +101,10 @@ describe('#4511 — short flat definitions keep their symbol names', () => {
expect(CHUNKER_VERSION).toBeGreaterThanOrEqual(6);
});
+ test('CHUNKER_VERSION bumped to 8 so files with merged arrow functions re-chunk (N13-1)', () => {
+ expect(CHUNKER_VERSION).toBeGreaterThanOrEqual(8);
+ });
+
test('merge guard is a derived view of code-def DEF_TYPES (single shared list)', () => {
// Same array object via both import paths — not a hand-copied duplicate.
expect(DEF_TYPES_VIA_CODE_DEF).toBe(DEF_TYPES);
diff --git a/test/chunkers/code.test.ts b/test/chunkers/code.test.ts
index 2ef4d541cf..05c27cbdcb 100644
--- a/test/chunkers/code.test.ts
+++ b/test/chunkers/code.test.ts
@@ -10,8 +10,8 @@ import { describe, test, expect } from 'bun:test';
import { chunkCodeText, detectCodeLanguage, CHUNKER_VERSION } from '../../src/core/chunkers/code.ts';
describe('CHUNKER_VERSION', () => {
- test('#5082 Bash grammar refresh bumped to 7', () => {
- expect(CHUNKER_VERSION).toBe(7);
+ test('N13-1 function-valued declarations bumped to 8 (after #5082 Bash grammar refresh at 7)', () => {
+ expect(CHUNKER_VERSION).toBe(8);
});
});
diff --git a/test/code-intel/n13-edge-resolution.test.ts b/test/code-intel/n13-edge-resolution.test.ts
new file mode 100644
index 0000000000..71adcd2680
--- /dev/null
+++ b/test/code-intel/n13-edge-resolution.test.ts
@@ -0,0 +1,108 @@
+/**
+ * gbrain-evals N13-2 / N13-3, on every backend (PGLite always; Postgres
+ * when a safe DATABASE_URL is set, and in the E2E lane through
+ * test/e2e/code-intel-n13-postgres.test.ts).
+ *
+ * N13-2: the within-file resolver stamps edge_metadata.resolved_chunk_id
+ * on a code_edges_symbol row, but getCallersOf / getCalleesOf /
+ * getEdgesByChunk reported resolved: false because the flag came only from
+ * the table the row lived in.
+ *
+ * N13-3: code_blast refused a Python function as unsupported_language when
+ * a Go function shared its bare name — the language gate read one
+ * arbitrary chunk carrying the qualified name.
+ *
+ * Synthetic data only.
+ */
+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 { importCodeFile } from '../../src/core/import-file.ts';
+import { resolveSymbolEdgesIncremental } from '../../src/core/chunkers/symbol-resolver.ts';
+import { runRecursiveWalk } from '../../src/core/code-intel/recursive-walk.ts';
+import { handleToolCall } from '../../src/mcp/server.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+
+for (const kind of testBackends()) {
+ describe(`code-intel edge resolution and language gate (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ }, 120_000);
+ afterAll(async () => {
+ await close?.();
+ });
+ beforeEach(async () => {
+ await engine.executeRaw(`DELETE FROM pages WHERE slug LIKE 'src/%' OR slug LIKE 'gate/%'`);
+ });
+
+ test('N13-2: an edge the resolver resolved reports resolved: true on every read', async () => {
+ await importCodeFile(engine, 'src/sample.ts',
+ 'export function helper(): number {\n return 1;\n}\n\nexport function caller(): number {\n return helper() + 1;\n}\n',
+ { noEmbed: true });
+ const stats = await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });
+ expect(stats.edges_resolved).toBeGreaterThanOrEqual(1);
+
+ const callers = await engine.getCallersOf('helper', { sourceId: 'default' });
+ const edge = callers.find((e) => e.from_symbol_qualified === 'caller');
+ expect(edge?.edge_metadata.resolved_chunk_id).toEqual(expect.any(Number));
+ expect(edge?.resolved).toBe(true);
+
+ const callees = await engine.getCalleesOf('caller', { sourceId: 'default' });
+ expect(callees.find((e) => e.to_symbol_qualified === 'helper')?.resolved).toBe(true);
+
+ const byChunk = await engine.getEdgesByChunk(edge!.from_chunk_id, { direction: 'out' });
+ expect(byChunk.find((e) => e.to_symbol_qualified === 'helper')?.resolved).toBe(true);
+
+ const op: any = await handleToolCall(engine, 'code_callers', { symbol: 'helper' });
+ const opEdge = op.callers.find((e: any) => e.from_symbol_qualified === 'caller');
+ expect(opEdge.resolved).toBe(true);
+ });
+
+ test('N13-2 control: an edge the resolver left unresolved stays resolved: false', async () => {
+ await importCodeFile(engine, 'src/lonely.ts',
+ 'export function lonely(): number {\n return missingThing() + 1;\n}\n', { noEmbed: true });
+ await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });
+ const callees = await engine.getCalleesOf('lonely', { sourceId: 'default' });
+ const edge = callees.find((e) => e.to_symbol_qualified === 'missingThing');
+ expect(edge).toBeDefined();
+ expect(edge?.resolved).toBe(false);
+ });
+
+ test('N13-3: a Python function sharing a Go function name walks; Go callers stay out', async () => {
+ await importCodeFile(engine, 'gate/shared.go',
+ 'package main\n\nfunc shared_helper() int {\n\treturn 2\n}\n\nfunc go_user() int {\n\treturn shared_helper()\n}\n',
+ { noEmbed: true });
+ await importCodeFile(engine, 'gate/shared.py',
+ 'def shared_helper():\n return 2\n\n\ndef py_user():\n return shared_helper()\n', { noEmbed: true });
+ await resolveSymbolEdgesIncremental(engine, { sourceId: 'default' });
+
+ const r = await runRecursiveWalk(engine, 'shared_helper', { direction: 'callers', sourceId: 'default' });
+ expect(r.result).toBe('ok');
+ if (r.result !== 'ok') return;
+ const symbols = r.depth_groups.flatMap((g) => g.nodes.map((n) => n.symbol));
+ expect(symbols).toContain('py_user');
+ expect(symbols).not.toContain('go_user');
+
+ const op: any = await handleToolCall(engine, 'code_blast', { symbol: 'shared_helper' });
+ expect(op.result).not.toBe('unsupported_language');
+ });
+
+ test('N13-3 control: a Go-only function is still unsupported_language', async () => {
+ await importCodeFile(engine, 'gate/only.go',
+ 'package main\n\nfunc go_only() int {\n\treturn 3\n}\n\nfunc go_only_user() int {\n\treturn go_only()\n}\n',
+ { noEmbed: true });
+ const r = await runRecursiveWalk(engine, 'go_only', { direction: 'callers', sourceId: 'default' });
+ expect(r.result).toBe('unsupported_language');
+ });
+ });
+}
diff --git a/test/colon-slug-windows-5032.test.ts b/test/colon-slug-windows-5032.test.ts
new file mode 100644
index 0000000000..d4f36ce9fd
--- /dev/null
+++ b/test/colon-slug-windows-5032.test.ts
@@ -0,0 +1,262 @@
+/**
+ * #5032 — colon slugs (`calendar:abc`) are writable again (PR #5044's grammar,
+ * pinned in test/file-upload-security.test.ts), and on Windows, where `:` in a
+ * file name names an alternate data stream, gbrain refuses rather than mangles:
+ *
+ * - a put_page whose canonical file name would contain `:` refuses before
+ * admission with `colon_slug_windows_write_through`, naming the slug;
+ * - the same slug written database-only (no repo configured) succeeds;
+ * - the publication step refuses the same target (a write admitted on another
+ * host and published by a Windows owner);
+ * - managed sync skips each committed colon file with a named refusal and
+ * imports the rest instead of failing the run;
+ * - macOS and Linux are unchanged: the colon file is written.
+ *
+ * Off Windows the Windows cases run with `process.platform` forced to win32;
+ * on the `windows-latest` security-regressions job they run natively.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { prepareFileTarget } from '../src/core/persistence/page-prepare.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { nativeLockCapability } from '../src/core/persistence/native-lock.ts';
+import { printManagedSyncNotes } from '../src/commands/sync-diagnostics.ts';
+import { performSync } from '../src/commands/sync/perform.ts';
+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NATIVE_WINDOWS = process.platform === 'win32';
+// The Windows runner's TEMP is an 8.3 short path (RUNNER~1); git reports the long
+// form, so the fixture starts from the native realpath to keep the two comparable.
+const home = mkdtempSync(join(realpathSync.native(tmpdir()), 'gbrain-5032-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const putPage = operations.find((op) => op.name === 'put_page')!;
+const CONTENT = '---\ntitle: Calendar event\ntype: note\n---\n\nA calendar event.\n';
+
+async function asWindows<T>(fn: () => Promise<T>): Promise<T> {
+ if (NATIVE_WINDOWS) return fn();
+ const original = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { ...original, value: 'win32' });
+ try { return await fn(); } finally { Object.defineProperty(process, 'platform', original); }
+}
+
+function ctxOf(engine: BrainEngine, sourceId: string): OperationContext {
+ return {
+ engine, config: { engine: engine.kind } as OperationContext['config'],
+ logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: false, sourceId,
+ };
+}
+
+async function addSource(engine: BrainEngine, root: string | null): Promise<string> {
+ const id = `c${randomUUID().replace(/-/g, '').slice(0, 20)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
+ return id;
+}
+
+function git(root: string, ...args: string[]): string {
+ return execFileSync('git', ['-c', 'core.protectNTFS=false', '-C', root, ...args], { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] }).trim();
+}
+
+beforeAll(async () => {
+ // Load the native writer-lock addon for the real platform before any test
+ // forces win32 (the binding is chosen by process.platform and cached).
+ await nativeLockCapability();
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+ await closePostgres?.();
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('#5032 put_page with a colon slug', () => {
+ test('Windows: a write-through write refuses before admission with colon_slug_windows_write_through', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `wt-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ const error = await asWindows(() => putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT }))
+ .then(() => null, (e: unknown) => e);
+ expect(error).toBeInstanceOf(OperationError);
+ expect((error as OperationError).toJSON()).toMatchObject({
+ error: 'colon_slug_windows_write_through',
+ message: "Page calendar:abc has a ':' in its file name, which Windows cannot store.",
+ suggestion: `Use a slug without ':' (for example calendar-abc), or write calendar:abc from a macOS or Linux host that owns source ${sourceId}.`,
+ docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through',
+ });
+ expect(await engine.getPage('calendar:abc', { sourceId })).toBeNull();
+ expect(await engine.executeRaw('SELECT id FROM persistence_requests WHERE source_id=$1', [sourceId])).toEqual([]);
+ }), 60_000);
+
+ test('Windows: a database-only write of the same slug succeeds', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const sourceId = await addSource(engine, null);
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT }));
+ expect((await engine.getPage('calendar:abc', { sourceId }))?.compiled_truth).toContain('A calendar event.');
+ }), 60_000);
+
+ test('Windows: a live database-only page (derive-phase path, no file) keeps updating', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `dbonly-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ const seeded = await importFromContent(engine, 'atoms/cal:abc', CONTENT, { sourceId, noEmbed: true });
+ expect(seeded.status).toBe('imported');
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), {
+ slug: 'atoms/cal:abc', content: CONTENT.replace('A calendar event.', 'An updated event.'), force: true,
+ }));
+ expect((await engine.getPage('atoms/cal:abc', { sourceId }))?.compiled_truth).toContain('An updated event.');
+ }), 60_000);
+
+ test('Windows: a read-only mirror source stores a colon slug database-only instead of refusing (#5409)', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `mirror-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only":true}'::jsonb WHERE id=$1`, [sourceId]);
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT }));
+ expect((await engine.getPage('calendar:abc', { sourceId }))?.compiled_truth).toContain('A calendar event.');
+ await engine.executeRaw(`UPDATE sources SET config = config || '{"mirror_read_only":false}'::jsonb WHERE id=$1`, [sourceId]);
+ await asWindows(() => putPage.handler(ctxOf(engine, sourceId), {
+ slug: 'calendar:abc', content: CONTENT.replace('A calendar event.', 'An updated event.'), force: true,
+ }));
+ expect((await engine.getPage('calendar:abc', { sourceId }))?.compiled_truth).toContain('An updated event.');
+ }), 60_000);
+
+ test('Windows: publication refuses a colon file target admitted elsewhere', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `pub-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ const binding = await claimWorktree(engine, sourceId, root);
+ const row = { source_id: sourceId, worktree_id: binding.worktree_id, slug: 'calendar:abc' };
+ await expect(asWindows(() => prepareFileTarget(engine, row, null, CONTENT))).rejects.toMatchObject({
+ code: 'colon_slug_windows_write_through',
+ });
+ expect(await prepareFileTarget(engine, { ...row, slug: 'calendar-abc' }, null, CONTENT)).toBeDefined();
+ }), 60_000);
+
+ test.skipIf(NATIVE_WINDOWS)('macOS and Linux: the colon slug is written through to its file, unchanged', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = engines[0];
+ const root = join(home, `nix-${randomUUID()}`); mkdirSync(root);
+ const sourceId = await addSource(engine, root);
+ await putPage.handler(ctxOf(engine, sourceId), { slug: 'calendar:abc', content: CONTENT });
+ expect(await engine.getPage('calendar:abc', { sourceId })).not.toBeNull();
+ expect(existsSync(join(root, 'calendar:abc.md'))).toBe(true);
+ }), 60_000);
+});
+
+describe('#5032 managed sync of committed colon files on Windows', () => {
+ test('each colon file gets a named refusal; the rest import and the run completes', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const root = join(home, `sync-${randomUUID()}`); mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes', 'plain.md'), '---\ntitle: Plain\n---\nAn ordinary note.\n');
+ git(root, 'add', '-A');
+ // Commit the colon file through the index only: Windows cannot create it
+ // in a checkout, and the Windows clone this models never has it on disk.
+ const blob = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: CONTENT, encoding: 'utf8' }).trim();
+ git(root, 'update-index', '--add', '--cacheinfo', `100644,${blob},notes/calendar:abc.md`);
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'colon');
+ git(root, 'update-index', '--skip-worktree', 'notes/calendar:abc.md');
+ const head = git(root, 'rev-parse', 'HEAD');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = await addSource(engine, root);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+
+ const result = await asWindows(() => performManagedSync(engine, { sourceId, noPull: true }));
+ expect(result.status).toBe('first_sync');
+ expect(result.fileRefusals).toEqual([{
+ path: 'notes/calendar:abc.md', code: 'colon_slug_windows_write_through',
+ message: "notes/calendar:abc.md has a ':' in its name, which Windows cannot store; sync skipped it.",
+ suggestion: `Rename it without ':' on a macOS or Linux checkout and commit, then run gbrain sync --source ${sourceId} --no-pull.`,
+ docs: 'docs/guides/write-refusals.md#colon_slug_windows_write_through',
+ }]);
+ expect(await engine.getPage('notes/plain', { sourceId })).not.toBeNull();
+ const [source] = await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [sourceId]);
+ expect(source.last_commit).toBe(head);
+ const lines: string[] = [];
+ printManagedSyncNotes(result, (line) => lines.push(line));
+ expect(lines).toContain(` Refused colon_slug_windows_write_through: ${result.fileRefusals![0].message} ${result.fileRefusals![0].suggestion} (docs/guides/write-refusals.md#colon_slug_windows_write_through)`);
+ }
+ }), 180_000);
+});
+
+describe('#5032 managed sync of a rename away from a colon file on Windows', () => {
+ // The colon page was imported by a macOS or Linux owner; that first sync
+ // cannot run on a native Windows runner, so this case is POSIX-only.
+ test.skipIf(NATIVE_WINDOWS)('both sides are refused and the page keeps its identity; no duplicate page appears', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const root = join(home, `rename-${randomUUID()}`); mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes', 'calendar:abc.md'), CONTENT);
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'colon');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = await addSource(engine, root);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).toBe('first_sync');
+ const [before] = await engine.executeRaw<{ id: number; slug: string }>(
+ "SELECT id,slug FROM pages WHERE source_id=$1 AND source_path='notes/calendar:abc.md' AND deleted_at IS NULL", [sourceId]);
+ expect(before).toBeDefined();
+
+ git(root, 'mv', 'notes/calendar:abc.md', 'notes/calendar-abc.md');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'rename');
+ const result = await asWindows(() => performManagedSync(engine, { sourceId, noPull: true }));
+ expect(result.fileRefusals?.map((refusal) => refusal.path).sort()).toEqual(['notes/calendar-abc.md', 'notes/calendar:abc.md']);
+ const live = await engine.executeRaw<{ id: number; slug: string }>('SELECT id,slug FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [sourceId]);
+ expect(live).toEqual([{ id: before.id, slug: before.slug }]);
+ }
+ }), 180_000);
+});
+
+describe('#5032 unmanaged incremental sync of a committed colon file on Windows', () => {
+ test('the colon file is a named per-file failure; the other files import', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+ const engine = engines[0];
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try {
+ const root = join(home, `legacy-${randomUUID()}`); mkdirSync(join(root, 'notes'), { recursive: true });
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'notes', 'first.md'), '---\ntitle: First\n---\nThe first note.\n');
+ git(root, 'add', '-A');
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'first');
+ const sourceId = await addSource(engine, root);
+ expect((await performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true })).status).toBe('first_sync');
+
+ writeFileSync(join(root, 'notes', 'second.md'), '---\ntitle: Second\n---\nThe second note.\n');
+ git(root, 'add', '-A');
+ const blob = execFileSync('git', ['-C', root, 'hash-object', '-w', '--stdin'], { input: CONTENT, encoding: 'utf8' }).trim();
+ git(root, 'update-index', '--add', '--cacheinfo', `100644,${blob},notes/calendar:abc.md`);
+ git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'colon');
+ git(root, 'update-index', '--skip-worktree', 'notes/calendar:abc.md');
+
+ const result = await asWindows(() => performSync(engine, { repoPath: root, sourceId, noPull: true, noEmbed: true, noExtract: true }));
+ expect(result.status).toBe('blocked_by_failures');
+ expect(result.failedFiles).toBe(1);
+ expect(await engine.getPage('notes/second', { sourceId })).not.toBeNull();
+ const failure = loadSyncFailures().find((row) => row.path === 'notes/calendar:abc.md');
+ expect(failure?.error).toStartWith("colon_slug_windows_write_through: notes/calendar:abc.md has a ':' in its name");
+ expect(failure?.code).toBe('COLON_SLUG_WINDOWS_WRITE_THROUGH');
+ } finally {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ }
+ }), 120_000);
+});
diff --git a/test/compile-view.test.ts b/test/compile-view.test.ts
index e3a20efc96..180268ff0d 100644
--- a/test/compile-view.test.ts
+++ b/test/compile-view.test.ts
@@ -18,6 +18,7 @@ import {
type CompileViewInput,
} from '../src/core/context/compile-view.ts';
import { loadSensitivityConfig } from '../src/core/context/sensitivity-scan.ts';
+import { isPrivatePage } from '../src/core/search/private-visibility.ts';
import * as tokenBudget from '../src/core/search/token-budget.ts';
import type { Page, PageFilters, GetPageOpts } from '../src/core/types.ts';
@@ -60,6 +61,7 @@ function makeEngine(pages: Page[]): CompileViewEngine {
async listPages(filters: PageFilters = {}) {
let rows = pages.slice();
if (filters.sourceId) rows = rows.filter((p) => p.source_id === filters.sourceId);
+ if (filters.excludePrivate) rows = rows.filter((p) => !isPrivatePage(p));
if (filters.slugPrefix) rows = rows.filter((p) => p.slug.startsWith(filters.slugPrefix!));
if (filters.tag) {
rows = rows.filter((p) => {
@@ -271,6 +273,20 @@ describe('compileView — recency arm (adversarial review: newest-first + tie-dr
});
});
+describe('compileView — private pages', () => {
+ test('a visibility: private page never reaches the compiled file on any arm (N8 context-path audit)', async () => {
+ const secret = { visibility: 'private', tags: ['compile-context'] };
+ const engine = makeEngine([
+ page('people/public-person', { title: 'Public Person' }),
+ page('people/secret-person', { title: 'SECRETTITLE', compiled_truth: 'SECRETBODY line.', frontmatter: secret }),
+ page('notes/recent-secret', { title: 'RECENTSECRET', frontmatter: { visibility: 'private' }, updated_at: new Date('2026-08-02T00:00:00.000Z') }),
+ ]);
+ const out = await compileView(input(engine));
+ expect(out.text).toContain('people/public-person');
+ for (const marker of ['SECRETTITLE', 'SECRETBODY', 'secret-person', 'RECENTSECRET']) expect(out.text).not.toContain(marker);
+ });
+});
+
describe('compileView — source isolation + read errors', () => {
test('duplicate slug across sources compiles the requested source body', async () => {
const pages = [
diff --git a/test/context-engine-checkpoint.serial.test.ts b/test/context-engine-checkpoint.serial.test.ts
index 83ee215f40..2f9b12bec6 100644
--- a/test/context-engine-checkpoint.serial.test.ts
+++ b/test/context-engine-checkpoint.serial.test.ts
@@ -340,67 +340,35 @@ describe('checkpoint compaction (cathedral 5)', () => {
});
it('F5/CK9 drift guard: hook.ts sanitizeSessionId, corpus-segments safeIdComponent, and sanitizeEngineSessionId map an identical probe set to IDENTICAL keys', async () => {
- const { runHook } = await import('../src/commands/hook.ts');
+ const { sanitizeSessionId } = await import('../src/commands/hook.ts');
const { segmentFileName, parseSegmentFileName } = await import('../src/core/context/corpus-segments.ts');
- // hook.ts's copy is module-private; its stop lane names the live-buffer
- // file `${sanitizeSessionId(id)}.txt` — the filename IS the mapping seam
- // (same seam test/hook-command.serial.test.ts already pins for one id).
- const savedEnv: Record<string, string | undefined> = {};
- for (const k of ['GBRAIN_HOOKS', 'GBRAIN_HOOK_LANE', 'GBRAIN_STOP_PUSH']) savedEnv[k] = process.env[k];
- delete process.env.GBRAIN_HOOKS;
- delete process.env.GBRAIN_HOOK_LANE;
- process.env.GBRAIN_STOP_PUSH = '0'; // stop-push arm skips instantly
- const ws = mkdtempSync(join(tmpdir(), 'gb-ckpt-drift-ws-'));
- try {
- let probeN = 0;
- const hookKey = async (probe: unknown): Promise<string> => {
- const marker = `drift-probe-${++probeN}-marker`;
- const code = await runHook(['stop'], {
- stdin: JSON.stringify({ session_id: probe, last_assistant_message: marker }),
- cwd: ws, // non-bootstrap workspace: no push machinery runs
- spawnPush: () => { /* never spawns */ },
- disableTelemetry: true,
- });
- expect(code).toBe(0);
- const liveDir = join(home!, '.gbrain', 'transcripts', 'live');
- const hit = readdirSync(liveDir).filter(
- (f) => f.endsWith('.txt') && readFileSync(join(liveDir, f), 'utf8').includes(marker),
- );
- expect(hit).toHaveLength(1);
- return hit[0].slice(0, -'.txt'.length);
- };
- // Third copy (corpus-segments safeIdComponent) read back through its
- // exported filename builder + parser.
- const segKey = (probe: string): string => {
- const parsed = parseSegmentFileName(segmentFileName(probe, 'a'.repeat(24)));
- expect(parsed).not.toBeNull();
- return parsed!.sessionId;
- };
-
- const probes = ['oc:sess/2026-08', 'a b', '../x', 'UPPER', 'L'.repeat(300)];
- for (const probe of probes) {
- const engineKey = sanitizeEngineSessionId(probe);
- expect(engineKey).not.toBeNull(); // every probe keeps a safe residue
- expect(await hookKey(probe)).toBe(engineKey!);
- expect(segKey(probe)).toBe(engineKey!);
- }
-
- // Deliberate divergence, pinned so it can only change LOUDLY: degenerate
- // ids map to hook.ts's 'unknown' sentinel but to engine null — compact()
- // treats a shared-'unknown' bucket as ABSENT (cross-session pollution),
- // per the hook.ts compact lane's own sentinel check.
- expect(sanitizeEngineSessionId('...')).toBeNull();
- expect(await hookKey('...')).toBe('unknown');
- expect(sanitizeEngineSessionId(1234)).toBeNull();
- expect(await hookKey(1234)).toBe('unknown');
- } finally {
- rmSync(ws, { recursive: true, force: true });
- for (const [k, v] of Object.entries(savedEnv)) {
- if (v === undefined) delete process.env[k];
- else process.env[k] = v;
- }
+ // hook.ts's copy is exported for this guard (#5558 removed the stop-lane
+ // live-buffer file that used to expose the mapping).
+ // Third copy (corpus-segments safeIdComponent) read back through its
+ // exported filename builder + parser.
+ const segKey = (probe: string): string => {
+ const parsed = parseSegmentFileName(segmentFileName(probe, 'a'.repeat(24)));
+ expect(parsed).not.toBeNull();
+ return parsed!.sessionId;
+ };
+
+ const probes = ['oc:sess/2026-08', 'a b', '../x', 'UPPER', 'L'.repeat(300)];
+ for (const probe of probes) {
+ const engineKey = sanitizeEngineSessionId(probe);
+ expect(engineKey).not.toBeNull(); // every probe keeps a safe residue
+ expect(sanitizeSessionId(probe)).toBe(engineKey!);
+ expect(segKey(probe)).toBe(engineKey!);
}
+
+ // Deliberate divergence, pinned so it can only change LOUDLY: degenerate
+ // ids map to hook.ts's 'unknown' sentinel but to engine null — compact()
+ // treats a shared-'unknown' bucket as ABSENT (cross-session pollution),
+ // per the hook.ts compact lane's own sentinel check.
+ expect(sanitizeEngineSessionId('...')).toBeNull();
+ expect(sanitizeSessionId('...')).toBe('unknown');
+ expect(sanitizeEngineSessionId(1234)).toBeNull();
+ expect(sanitizeSessionId(1234)).toBe('unknown');
});
});
diff --git a/test/conversation-parser/parse.test.ts b/test/conversation-parser/parse.test.ts
index a0ffde5147..e9fafe409b 100644
--- a/test/conversation-parser/parse.test.ts
+++ b/test/conversation-parser/parse.test.ts
@@ -768,6 +768,30 @@ describe('bold-name-no-time pattern (Circleback/Granola/Zoom, no timestamp)', ()
expect(r.messages[0].timestamp).toBe('1970-01-01T00:00:00Z');
});
+ // gbrain-evals N12-1: a status note with three one-off bold labels is
+ // not a conversation. Full-body density (3/26 ≈ 0.115) clears the floor,
+ // so the gate is structural: three or more turns with no speaker ever
+ // speaking twice is a list of labels, not an exchange.
+ test('REGRESSION (N12-1): a status note with one-off bold labels is no_match', () => {
+ const filler = Array.from({ length: 22 }, (_, i) => `Paragraph ${i + 1}: the team agreed in principle and will review the plan this week.`);
+ const body = ['# Project status', '', '**Status:** green', '**Owner:** Alice Example', '**Next step:** ship the draft', '', ...filler, ''].join('\n');
+ const r = parseConversation(body, { noFallback: true, noPolish: true, page: { frontmatter: { date: '2026-04-01' } } } as any);
+ expect(r.phase).toBe('no_match');
+ expect(r.messages).toEqual([]);
+ });
+
+ test('N12-1 control: a three-person exchange where someone speaks twice still parses', () => {
+ const body = [
+ '**Alice Example:** shall we start?',
+ '**Bob Example:** ready.',
+ '**Carol Example:** me too.',
+ '**Alice Example:** great, first item.',
+ ].join('\n');
+ const r = parseConversation(body, { fallbackDate: '2026-04-01' });
+ expect(r.matched_pattern_id).toBe('bold-name-no-time');
+ expect(r.messages).toHaveLength(4);
+ });
+
// REGRESSION: must NOT shadow bold-paren-time. A `**Name** (00:00): text`
// line has its colon OUTSIDE the bold markers, so it must still parse via
// bold-paren-time (the safety is the regex, not declaration order).
diff --git a/test/cross-lane-5081-5032.test.ts b/test/cross-lane-5081-5032.test.ts
new file mode 100644
index 0000000000..d7df880f52
--- /dev/null
+++ b/test/cross-lane-5081-5032.test.ts
@@ -0,0 +1,96 @@
+/**
+ * ENG-O14 cross-lane journey: #5081 with #5032. A stdio connection bound by
+ * GBRAIN_SOURCE=work reads a colon-slug page from a federated source by naming
+ * it (#5081), still cannot write into that source (read admission confers no
+ * write right), and its own colon-slug writes follow #5032: refused before
+ * admission on Windows when the write source writes through to files,
+ * database-only writes succeed, and macOS and Linux are unchanged.
+ *
+ * Off Windows the Windows case runs with `process.platform` forced to win32;
+ * on the windows-latest security-regressions job it runs natively.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { nativeLockCapability } from '../src/core/persistence/native-lock.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import { resolveMcpStdioSourceScope } from '../src/mcp/server.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const NATIVE_WINDOWS = process.platform === 'win32';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-5081-5032-'));
+const workRoot = join(home, 'work');
+let engine: PGLiteEngine;
+const PAGE = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n\n${title} body.\n`;
+
+async function asWindows<T>(fn: () => Promise<T>): Promise<T> {
+ if (NATIVE_WINDOWS) return fn();
+ const original = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { ...original, value: 'win32' });
+ try { return await fn(); } finally { Object.defineProperty(process, 'platform', original); }
+}
+
+async function boundOpts(): Promise<DispatchOpts> {
+ const scope = await withEnv({ GBRAIN_SOURCE: 'work' }, () => resolveMcpStdioSourceScope(engine, home));
+ return {
+ remote: true, transport: 'stdio', takesHoldersAllowList: ['world'], sourceId: scope.sourceId,
+ ...(scope.explicitReadBinding ? { explicitReadBinding: scope.explicitReadBinding } : {}),
+ };
+}
+
+async function call(name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(engine, name, params, await boundOpts());
+ return { isError: result.isError === true, body: JSON.parse(result.content[0].text) };
+}
+
+beforeAll(async () => {
+ await nativeLockCapability();
+ mkdirSync(workRoot);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('work', 'work', $1, '{}'::jsonb)`, [workRoot]);
+ await engine.executeRaw(`INSERT INTO sources (id, name, local_path, config) VALUES ('notes', 'notes', NULL, '{"federated": true}'::jsonb)`);
+ const seeded = await importFromContent(engine, 'calendar:standup', PAGE('Standup'), { sourceId: 'notes', noEmbed: true });
+ expect(seeded.status).toBe('imported');
+}, 60_000);
+
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); });
+ rmSync(home, { recursive: true, force: true });
+});
+
+describe('ENG-O14 #5081 + #5032', () => {
+ test('the bound connection reads a federated colon-slug page by naming its source', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError, body } = await call('get_page', { slug: 'calendar:standup', source_id: 'notes' });
+ expect(isError).toBe(false);
+ expect(body.source_id).toBe('notes');
+ expect((await call('get_page', { slug: 'calendar:standup' })).isError).toBe(true);
+ }));
+
+ test('read admission confers no write right into the admitted source', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError, body } = await call('put_page', { slug: 'calendar:retro', content: PAGE('Retro'), source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.error).toBe('permission_denied');
+ expect(await engine.getPage('calendar:retro', { sourceId: 'notes' })).toBeNull();
+ }));
+
+ test('Windows: a colon-slug write into the write-through bound source is refused before admission', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError, body } = await asWindows(() => call('put_page', { slug: 'calendar:planning', content: PAGE('Planning') }));
+ expect(isError).toBe(true);
+ expect(body.error).toBe('colon_slug_windows_write_through');
+ expect(body.docs).toBe('docs/guides/write-refusals.md#colon_slug_windows_write_through');
+ expect(await engine.getPage('calendar:planning', { sourceId: 'work' })).toBeNull();
+ }));
+
+ test.skipIf(NATIVE_WINDOWS)('macOS and Linux: the same write lands in the bound source and its file', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { isError } = await call('put_page', { slug: 'calendar:planning', content: PAGE('Planning') });
+ expect(isError).toBe(false);
+ expect(await engine.getPage('calendar:planning', { sourceId: 'work' })).not.toBeNull();
+ expect(existsSync(join(workRoot, 'calendar:planning.md'))).toBe(true);
+ }));
+});
diff --git a/test/doctor-atom-provenance-drift.test.ts b/test/doctor-atom-provenance-drift.test.ts
index b02a7cc1da..04d2cae6ad 100644
--- a/test/doctor-atom-provenance-drift.test.ts
+++ b/test/doctor-atom-provenance-drift.test.ts
@@ -24,6 +24,8 @@ import { resetPgliteState } from './helpers/reset-pglite.ts';
import { computeAtomProvenanceDriftCheck } from '../src/commands/doctor.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { doctorFileSource } from './helpers/doctor-source.ts';
+import { WAVE_CHECKS, checkHealthUnknown } from '../src/commands/doctor/wave-checks.ts';
+import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';
let engine: PGLiteEngine;
@@ -199,6 +201,10 @@ describe('computeAtomProvenanceDriftCheck', () => {
expect(c.status).toBe('warn');
expect(c.message).toContain('atom_provenance_drift check failed');
expect(c.message).toContain('relation "pages" does not exist');
+ // As a wave check, a failed inspection is unknown health, never a stale-atoms finding with a zero count.
+ expect(checkHealthUnknown(c)).toBe(true);
+ const spec = WAVE_CHECKS.find(s => s.id === 'atom_provenance_drift')!;
+ expect(bannerFindingLine({ spec, check: c, state: 'unknown' })).toBe('[AGENT] atom_provenance_drift: could not be checked (health unknown)');
});
it('does not count transcript-minted (file-bound) atoms as drift (#4806)', async () => {
@@ -360,4 +366,20 @@ describe('computeAtomProvenanceDriftCheck', () => {
expect(c.message).toContain('0 whose source page is gone');
expect(c.message).toContain('30 slug-unbound');
}, 60_000);
+
+ it('counts a managed atom by its stripped provisional hash and names the stale-atoms repair (#5770)', async () => {
+ await seedSource('src-managed', 'original body');
+ const original = await hashOf('src-managed');
+ for (let i = 0; i < 30; i++) {
+ await engine.putPage(`atoms/2026-01-01/managed-${String(i).padStart(6, '0')}`, { type: 'atom', title: `managed ${i}`, compiled_truth: 'claim body',
+ frontmatter: { type: 'atom', source_slug: 'src-managed', source_hash: `pending:${original}`, managed_extraction: true, extracted_at: new Date().toISOString() } });
+ }
+ const healthy = await computeAtomProvenanceDriftCheck(engine);
+ expect(healthy.details).toMatchObject({ total_atoms: 30, drifted: 0 });
+ await seedSource('src-managed', 'edited body');
+ const c = await computeAtomProvenanceDriftCheck(engine);
+ expect(c.status).toBe('warn');
+ expect(c.details).toMatchObject({ drifted: 30, source_changed: 30 });
+ expect(c.message).toContain('gbrain repair stale-atoms');
+ }, 60_000);
});
diff --git a/test/doctor-legacy-job-authority.test.ts b/test/doctor-legacy-job-authority.test.ts
new file mode 100644
index 0000000000..a2a290d2a4
--- /dev/null
+++ b/test/doctor-legacy-job-authority.test.ts
@@ -0,0 +1,101 @@
+/**
+ * #5157 DX-O3(a): doctor `legacy_job_authority` counts exactly the claim
+ * gate's population (live rows with SQL NULL or unsupported authority, keyed
+ * or not), splits authorizable from unsupported, reports terminal keyed SQL
+ * NULL rows separately, and the post-upgrade banner names the read-only
+ * recovery preview when live rows exist.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { assertNoUnreviewedJobs } from '../src/core/minions/submission-authority.ts';
+import { legacyJobAuthorityBannerNote, legacyJobAuthorityCheck, legacyJobAuthorityEntry } from '../src/commands/doctor/checks/legacy-job-authority.ts';
+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });
+
+async function row(status: string, authority: string | null, key?: string): Promise<number> {
+ const job = await queue.add('fixture', { n: Math.random() }, key ? { idempotency_key: key } : {});
+ if (status === 'active') {
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 't', lock_until = now() + interval '1 hour', claim_generation = claim_generation + 1 WHERE id = $1`, [job.id]);
+ } else if (status !== 'waiting') {
+ await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [job.id, status]);
+ }
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [job.id, authority]);
+ return job.id;
+}
+async function gateCount(): Promise<number> {
+ try { await assertNoUnreviewedJobs(engine); return 0; }
+ catch (error) { return Number(/(\d+) legacy jobs/.exec((error as Error).message)![1]); }
+}
+
+describe('legacy_job_authority doctor check', () => {
+ test('a brain without legacy rows is ok', async () => {
+ await queue.add('fixture', {});
+ const check = await legacyJobAuthorityCheck(engine);
+ expect(check).toMatchObject({ name: 'legacy_job_authority', status: 'ok', message: 'No queued job predates submission authority.' });
+ expect(await legacyJobAuthorityBannerNote(engine)).toBeNull();
+ });
+
+ test('terminal keyed SQL NULL rows are reported separately and need no operator step', async () => {
+ await row('completed', null, 'k1');
+ await row('dead', null, 'k2');
+ await row('failed', null);
+ const check = await legacyJobAuthorityCheck(engine);
+ expect(check.status).toBe('ok');
+ expect(check.details).toMatchObject({ live: 0, terminal_keyed: { completed: 1, dead: 1 }, terminal_keyed_total: 2 });
+ expect(check.message).toContain('2 finished job row(s) from before the upgrade');
+ expect(await gateCount()).toBe(0);
+ expect(await legacyJobAuthorityBannerNote(engine)).toBeNull();
+ });
+
+ test('live rows fail with the gate count, the authorizable/unsupported split and the filled recovery', async () => {
+ await row('waiting', null, 'keyed');
+ await row('waiting', null);
+ await row('paused', null);
+ const active = await row('active', null);
+ const jsonbNull = await row('delayed', 'null');
+ const future = await row('waiting', '{"version":2,"kind":"application"}');
+ await row('completed', null, 'old');
+ await queue.add('fixture', { healthy: true });
+ const check = await legacyJobAuthorityCheck(engine);
+ expect(check.status).toBe('fail');
+ expect(check.details).toMatchObject({
+ live: 6, authorizable_total: 4, unsupported: 2, authorizable: { waiting: 2, paused: 1, active: 1 },
+ unsupported_ids: [jsonbNull, future], active_ids: [active], terminal_keyed_total: 1,
+ });
+ expect(check.details!.live).toBe(await gateCount());
+ expect(check.message).toContain('6 queued job(s) predate submission authority and block every worker (4 authorizable with SQL NULL authority, 2 unsupported)');
+ expect(check.message).toContain('Stop producers (gbrain serve, gbrain autopilot) and workers');
+ expect(check.message).toContain(`cancel active jobs (gbrain jobs cancel ${active})`);
+ expect(check.message).toContain('preview with gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"');
+ expect(check.message).toContain('apply with the printed --expect <hash> --yes, then restart them');
+ expect(check.message).toContain(`gbrain jobs cancel ${jsonbNull}; gbrain jobs cancel ${future}`);
+ expect(check.message).toContain('docs/guides/repair.md#legacy-job-authority');
+ const [fromEntry] = await legacyJobAuthorityEntry.run({ engine } as never) as Array<{ name: string }>;
+ expect(fromEntry!.name).toBe('legacy_job_authority');
+ });
+
+ test('the post-upgrade banner names the read-only preview, never an applying command', async () => {
+ await row('waiting', null, 'keyed');
+ await row('paused', 'null');
+ const lines = await postUpgradeRecoveryBanner(engine, 'host (pglite, id test-brain)');
+ const text = lines.join('\n');
+ expect(text).toContain('[AGENT] legacy_job_authority: 2 queued job(s) from before v0.50 block every worker.');
+ expect(text).toContain('preview with: gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"');
+ expect(text).toContain('1 unsupported row(s) need matching versions or gbrain jobs cancel <id>');
+ expect(text).not.toContain('--yes');
+ expect(text).not.toContain('--apply');
+ for (const line of lines.filter(Boolean)) expect(line).toStartWith('[AGENT]');
+ }, 120_000);
+});
diff --git a/test/e2e/autopilot-multi-brain.serial.test.ts b/test/e2e/autopilot-multi-brain.serial.test.ts
new file mode 100644
index 0000000000..c0fe307844
--- /dev/null
+++ b/test/e2e/autopilot-multi-brain.serial.test.ts
@@ -0,0 +1,326 @@
+/**
+ * #5195 — two brains on one host each get their own autopilot job, on every
+ * install target, end to end.
+ *
+ * Before the fix every brain installed under one shared name
+ * (`com.gbrain.autopilot`, `gbrain-autopilot.service`, `~/.gbrain/start-autopilot.sh`,
+ * one unmarked crontab line), so a second brain's install replaced the first
+ * brain's job, logs interleaved in `~/.gbrain/autopilot.log`, and either
+ * brain's uninstall removed the shared job.
+ *
+ * Hermetic like test/e2e/autopilot-linux-lifecycle.serial.test.ts: `crontab`,
+ * `systemctl` and `launchctl` are PATH shims in a tempdir (crontab round-trips
+ * a state file; the others record argv), HOME is a temp root, and each brain
+ * is a GBRAIN_HOME under it with a hand-seeded keyless PGLite config. The CLI
+ * is SPAWNED (Bun's execSync snapshots env at startup, #2747). The macos
+ * target is forced with `--target macos`, so its plist arm runs on Linux too.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, resolve } from 'path';
+
+const REPO_ROOT = resolve(import.meta.dir, '..', '..');
+const CLI = join(REPO_ROOT, 'src', 'cli.ts');
+
+let root: string;
+let home: string;
+let repoDir: string;
+let shimDir: string;
+let cronState: string;
+let sysctlLog: string;
+let launchctlLog: string;
+let baseEnv: Record<string, string>;
+
+const FOREIGN = "*/10 * * * * /usr/local/bin/backup.sh --label 'nightly backup' # keep me\n";
+
+function shim(name: string, body: string): void {
+ writeFileSync(join(shimDir, name), body);
+ chmodSync(join(shimDir, name), 0o755);
+}
+
+function seedBrain(gbrainHome: string): void {
+ const dir = join(gbrainHome, '.gbrain');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ database_path: join(dir, 'brain.pglite'),
+ embedding_disabled: true,
+ }) + '\n');
+}
+
+function run(gbrainHome: string | null, args: string[]): { status: number | null; out: string } {
+ const env = { ...baseEnv };
+ if (gbrainHome) env.GBRAIN_HOME = gbrainHome;
+ const r = spawnSync(process.execPath, ['run', CLI, 'autopilot', ...args], {
+ cwd: REPO_ROOT, env, encoding: 'utf-8', timeout: 120_000, killSignal: 'SIGKILL',
+ });
+ return { status: r.status, out: (r.stdout ?? '') + (r.stderr ?? '') };
+}
+
+function install(gbrainHome: string | null, target: string): { status: number | null; out: string } {
+ return run(gbrainHome, ['--install', '--force', '--target', target, '--repo', repoDir]);
+}
+
+function status(gbrainHome: string | null): Record<string, any> {
+ const r = run(gbrainHome, ['--status', '--json']);
+ const line = r.out.split('\n').map(l => l.trim()).filter(l => l.startsWith('{')).pop();
+ if (!line) throw new Error(`no status JSON:\n${r.out}`);
+ return JSON.parse(line);
+}
+
+function suffixOf(gbrainHome: string): string {
+ return JSON.parse(readFileSync(join(gbrainHome, '.gbrain', 'autopilot-install-id'), 'utf-8')).id.slice(0, 8);
+}
+
+const lines = (p: string) => (existsSync(p) ? readFileSync(p, 'utf-8').split('\n').filter(Boolean) : []);
+const unitDir = () => join(home, '.config', 'systemd', 'user');
+const agentsDir = () => join(home, 'Library', 'LaunchAgents');
+
+let brainA: string;
+let brainB: string;
+let brainC: string;
+
+beforeAll(() => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-5195-e2e-')));
+ home = join(root, 'home');
+ repoDir = join(root, 'repo');
+ shimDir = join(root, 'shims');
+ cronState = join(root, 'cron-state.txt');
+ sysctlLog = join(root, 'systemctl.log');
+ launchctlLog = join(root, 'launchctl.log');
+ for (const d of [home, repoDir, shimDir]) mkdirSync(d, { recursive: true });
+ shim('crontab', `#!/bin/sh
+if [ "$1" = "-l" ]; then if [ -f '${cronState}' ]; then cat '${cronState}'; exit 0; else exit 1; fi; fi
+cat "$1" > '${cronState}'
+`);
+ shim('systemctl', `#!/bin/sh\nprintf '%s\\n' "$*" >> '${sysctlLog}'\nexit 0\n`);
+ shim('launchctl', `#!/bin/sh\nprintf '%s\\n' "$*" >> '${launchctlLog}'\nexit 0\n`);
+ shim('gbrain', '#!/bin/sh\nexit 0\n');
+ writeFileSync(cronState, FOREIGN);
+ baseEnv = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) baseEnv[k] = v;
+ Object.assign(baseEnv, {
+ HOME: home,
+ XDG_CONFIG_HOME: join(home, '.config'),
+ PATH: `${shimDir}:${process.env.PATH ?? ''}`,
+ GBRAIN_SKIP_STARTUP_HOOKS: '1',
+ });
+ for (const k of ['GBRAIN_HOME', 'GBRAIN_AUTOPILOT_LABEL', 'DATABASE_URL', 'GBRAIN_DATABASE_URL', 'OPENCLAW_HOME',
+ 'VOYAGE_API_KEY', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'GOOGLE_API_KEY', 'RENDER', 'RAILWAY_ENVIRONMENT', 'FLY_APP_NAME']) {
+ delete baseEnv[k];
+ }
+ brainA = join(root, 'brain-a');
+ brainB = join(root, 'brain-b');
+ brainC = join(root, 'brain-c');
+ for (const b of [brainA, brainB, brainC]) seedBrain(b);
+ seedBrain(home);
+});
+
+afterAll(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('#5195 two brains on one host keep separate autopilot jobs', () => {
+ test('linux-cron: two marked lines, per-brain logs; uninstall removes only its own line', () => {
+ expect(install(brainA, 'linux-cron').status).toBe(0);
+ expect(install(brainB, 'linux-cron').status).toBe(0);
+ const sa = suffixOf(brainA);
+ const sb = suffixOf(brainB);
+ expect(sa).not.toBe(sb);
+ const table = readFileSync(cronState, 'utf-8');
+ expect(table.startsWith(FOREIGN)).toBe(true);
+ expect(table).toContain(`*/5 * * * * '${brainA}/.gbrain/autopilot-run.sh' >> '${brainA}/.gbrain/autopilot.log' 2>&1 # gbrain-autopilot:${sa}`);
+ expect(table).toContain(`*/5 * * * * '${brainB}/.gbrain/autopilot-run.sh' >> '${brainB}/.gbrain/autopilot.log' 2>&1 # gbrain-autopilot:${sb}`);
+
+ // A reinstall of A keeps one line for A (the existence check is per brain).
+ const again = install(brainA, 'linux-cron');
+ expect(again.out).toContain('Crontab entry already exists');
+ expect(readFileSync(cronState, 'utf-8')).toBe(table);
+
+ const sA = status(brainA);
+ expect(sA.installed).toBe(true);
+ expect(sA.install_target).toBe('linux-cron');
+ expect(sA.job.suffix).toBe(sa);
+ expect(sA.job.cron_marker).toBe(`# gbrain-autopilot:${sa}`);
+ expect(sA.job.install_id_path).toBe(join(brainA, '.gbrain', 'autopilot-install-id'));
+ expect(sA.job.log_path).toBe(join(brainA, '.gbrain', 'autopilot.log'));
+ expect(sA.job.wrapper_path).toBe(join(brainA, '.gbrain', 'autopilot-run.sh'));
+
+ expect(run(brainA, ['--uninstall']).status).toBe(0);
+ const after = readFileSync(cronState, 'utf-8');
+ expect(after).not.toContain(`gbrain-autopilot:${sa}`);
+ expect(after).toContain(`gbrain-autopilot:${sb}`);
+ expect(after.startsWith(FOREIGN)).toBe(true);
+ expect(status(brainA).installed).toBe(false);
+ expect(status(brainB).installed).toBe(true);
+ expect(run(brainB, ['--uninstall']).status).toBe(0);
+ expect(readFileSync(cronState, 'utf-8').trim()).toBe(FOREIGN.trim());
+ }, 240_000);
+
+ test('linux-systemd: two units, each logs under its own brain; uninstall disables only its unit', () => {
+ rmSync(sysctlLog, { force: true });
+ expect(install(brainA, 'linux-systemd').status).toBe(0);
+ expect(install(brainB, 'linux-systemd').status).toBe(0);
+ const ua = `gbrain-autopilot-${suffixOf(brainA)}.service`;
+ const ub = `gbrain-autopilot-${suffixOf(brainB)}.service`;
+ expect(readdirSync(unitDir()).sort()).toEqual([ua, ub].sort());
+ const unitA = readFileSync(join(unitDir(), ua), 'utf-8');
+ expect(unitA).toContain(`ExecStart=${brainA}/.gbrain/autopilot-run.sh`);
+ expect(unitA).toContain(`StandardOutput=append:${brainA}/.gbrain/autopilot.log`);
+ expect(lines(sysctlLog)).toContain(`--user enable --now ${ua}`);
+ expect(lines(sysctlLog)).toContain(`--user enable --now ${ub}`);
+ expect(readFileSync(join(brainA, '.gbrain', 'autopilot-run.sh'), 'utf-8')).toContain(`systemctl --user disable --now ${ua}`);
+
+ const sB = status(brainB);
+ expect(sB.install_target).toBe('linux-systemd');
+ expect(sB.job.systemd_unit).toBe(ub);
+
+ rmSync(sysctlLog, { force: true });
+ expect(run(brainA, ['--uninstall']).status).toBe(0);
+ expect(existsSync(join(unitDir(), ua))).toBe(false);
+ expect(existsSync(join(unitDir(), ub))).toBe(true);
+ expect(lines(sysctlLog)).toEqual([`--user disable --now ${ua}`, '--user daemon-reload']);
+ expect(run(brainB, ['--uninstall']).status).toBe(0);
+ }, 240_000);
+
+ test('ephemeral-container: one start script per brain, inside that brain', () => {
+ expect(install(brainA, 'ephemeral-container').status).toBe(0);
+ expect(install(brainB, 'ephemeral-container').status).toBe(0);
+ const scriptA = join(brainA, '.gbrain', `start-autopilot-${suffixOf(brainA)}.sh`);
+ const scriptB = join(brainB, '.gbrain', `start-autopilot-${suffixOf(brainB)}.sh`);
+ expect(readFileSync(scriptA, 'utf-8')).toContain(`nohup '${brainA}/.gbrain/autopilot-run.sh' > '${brainA}/.gbrain/autopilot.log' 2>&1 &`);
+ expect(readFileSync(scriptB, 'utf-8')).toContain(`> '${brainB}/.gbrain/autopilot.log'`);
+ expect(existsSync(join(home, '.gbrain', 'start-autopilot.sh'))).toBe(false);
+ expect(status(brainA).install_target).toBe('ephemeral-container');
+ expect(run(brainA, ['--uninstall']).status).toBe(0);
+ expect(existsSync(scriptA)).toBe(false);
+ expect(existsSync(scriptB)).toBe(true);
+ expect(run(brainB, ['--uninstall']).status).toBe(0);
+ }, 240_000);
+
+ test('macos (launchd): one plist per brain label; uninstall unloads only its own', () => {
+ rmSync(launchctlLog, { force: true });
+ expect(install(brainA, 'macos').status).toBe(0);
+ expect(install(brainB, 'macos').status).toBe(0);
+ const la = `com.gbrain.autopilot.${suffixOf(brainA)}`;
+ const lb = `com.gbrain.autopilot.${suffixOf(brainB)}`;
+ expect(readdirSync(agentsDir()).sort()).toEqual([`${la}.plist`, `${lb}.plist`].sort());
+ const plistA = readFileSync(join(agentsDir(), `${la}.plist`), 'utf-8');
+ expect(plistA).toContain(`<key>Label</key><string>${la}</string>`);
+ expect(plistA).toContain(`<key>StandardOutPath</key><string>${brainA}/.gbrain/autopilot.log</string>`);
+ expect(lines(launchctlLog)).toContain(`load ${join(agentsDir(), `${lb}.plist`)}`);
+ expect(readFileSync(join(brainA, '.gbrain', 'autopilot-run.sh'), 'utf-8')).toContain(`gui/$(id -u)/${la}`);
+
+ expect(run(brainA, ['--uninstall']).status).toBe(0);
+ expect(existsSync(join(agentsDir(), `${la}.plist`))).toBe(false);
+ expect(existsSync(join(agentsDir(), `${lb}.plist`))).toBe(true);
+ expect(run(brainB, ['--uninstall']).status).toBe(0);
+ }, 240_000);
+});
+
+describe('#5195 legacy shared-name jobs and moved brains', () => {
+ test('status flags a legacy shared unit that runs this brain; install replaces it and says so', () => {
+ mkdirSync(unitDir(), { recursive: true });
+ mkdirSync(join(brainC, '.gbrain'), { recursive: true });
+ writeFileSync(join(brainC, '.gbrain', 'autopilot-run.sh'), '#!/bin/sh\n', { mode: 0o755 });
+ writeFileSync(join(unitDir(), 'gbrain-autopilot.service'), `[Unit]\nDescription=GBrain Autopilot\n[Service]\nExecStart=${brainC}/.gbrain/autopilot-run.sh\n`);
+
+ const before = status(brainC);
+ expect(before.installed).toBe(true);
+ expect(before.job.needs_reinstall).toBe('legacy_shared_job');
+ expect(before.job.installed_definition.legacy_shared_name).toBe(true);
+ // The default brain does not claim a shared job that runs another live brain.
+ const defaultView = status(null);
+ expect(defaultView.installed).toBe(false);
+ expect(defaultView.job.shared_job_of_other_brain.home).toBe(join(brainC, '.gbrain'));
+ // ...and its uninstall leaves that job alone, naming the right command.
+ const defaultUninstall = run(null, ['--uninstall']);
+ expect(defaultUninstall.out).toContain(`GBRAIN_HOME='${brainC}' gbrain autopilot --uninstall`);
+ expect(existsSync(join(unitDir(), 'gbrain-autopilot.service'))).toBe(true);
+ // ...and its install refuses rather than taking that brain's job over.
+ const refused = install(null, 'linux-systemd');
+ expect(refused.status).toBe(1);
+ expect(refused.out).toContain('autopilot job gbrain-autopilot.service runs the brain at');
+ expect(refused.out).toContain(`GBRAIN_HOME='${brainC}' gbrain autopilot --install`);
+
+ const r = install(brainC, 'linux-systemd');
+ expect(r.status).toBe(0);
+ expect(r.out).toContain('Replaced the shared systemd unit gbrain-autopilot.service, which ran this brain');
+ expect(existsSync(join(unitDir(), 'gbrain-autopilot.service'))).toBe(false);
+ expect(existsSync(join(unitDir(), `gbrain-autopilot-${suffixOf(brainC)}.service`))).toBe(true);
+ expect(status(brainC).job.needs_reinstall).toBeNull();
+ expect(run(brainC, ['--uninstall']).status).toBe(0);
+ }, 240_000);
+
+ test('a pre-upgrade brain with no install id still sees and removes its legacy shared launchd job', () => {
+ const brainD = join(root, 'brain-d');
+ seedBrain(brainD);
+ writeFileSync(join(brainD, '.gbrain', 'autopilot-run.sh'), '#!/bin/sh\n', { mode: 0o755 });
+ mkdirSync(agentsDir(), { recursive: true });
+ const plist = join(agentsDir(), 'com.gbrain.autopilot.plist');
+ writeFileSync(plist, `<plist><dict><key>Label</key><string>com.gbrain.autopilot</string><key>ProgramArguments</key><array>\n <string>${brainD}/.gbrain/autopilot-run.sh</string>\n </array></dict></plist>`);
+ expect(existsSync(join(brainD, '.gbrain', 'autopilot-install-id'))).toBe(false);
+ rmSync(launchctlLog, { force: true });
+ const r = run(brainD, ['--uninstall']);
+ expect(r.status).toBe(0);
+ expect(r.out).toContain('Removed launchd service: com.gbrain.autopilot');
+ expect(existsSync(plist)).toBe(false);
+ expect(lines(launchctlLog)).toContain(`unload ${plist}`);
+ }, 120_000);
+
+ test('an unmarked legacy crontab line naming this brain is replaced by its marked line', () => {
+ const legacy = `*/5 * * * * '${brainC}/.gbrain/autopilot-run.sh' >> '${home}/.gbrain/autopilot.log' 2>&1`;
+ writeFileSync(cronState, FOREIGN + legacy + '\n');
+ expect(status(brainC).job.needs_reinstall).toBe('legacy_shared_job');
+ const r = install(brainC, 'linux-cron');
+ expect(r.status).toBe(0);
+ const table = readFileSync(cronState, 'utf-8');
+ expect(table).not.toContain(legacy);
+ expect(table).toContain(`# gbrain-autopilot:${suffixOf(brainC)}`);
+ expect(table.split('\n').filter(l => l.includes('autopilot-run.sh'))).toHaveLength(1);
+ expect(run(brainC, ['--uninstall']).status).toBe(0);
+ expect(readFileSync(cronState, 'utf-8').trim()).toBe(FOREIGN.trim());
+ }, 240_000);
+
+ test('mv keeps one job: status flags the missing wrapper, reinstall repoints the same job', () => {
+ expect(install(brainB, 'linux-cron').status).toBe(0);
+ const sb = suffixOf(brainB);
+ const moved = join(root, 'brain-b-moved');
+ renameSync(brainB, moved);
+ // The seeded config names its PGLite file by absolute path; repoint it, or
+ // the install's engine connect would recreate the old directory (which
+ // would then read as a copy, correctly, and mint a new id).
+ seedBrain(moved);
+ const s = status(moved);
+ expect(s.installed).toBe(true);
+ expect(s.job.suffix).toBe(sb);
+ expect(s.job.needs_reinstall).toBe('wrapper_missing');
+ expect(s.job.installed_definition.wrapper_exists).toBe(false);
+
+ expect(install(moved, 'linux-cron').status).toBe(0);
+ expect(suffixOf(moved)).toBe(sb);
+ const table = readFileSync(cronState, 'utf-8');
+ const own = table.split('\n').filter(l => l.includes(`gbrain-autopilot:${sb}`));
+ expect(own).toHaveLength(1);
+ expect(own[0]).toContain(`'${moved}/.gbrain/autopilot-run.sh'`);
+ expect(status(moved).job.needs_reinstall).toBeNull();
+ expect(run(moved, ['--uninstall']).status).toBe(0);
+ }, 240_000);
+
+ test('cp -r gives the copy its own job; the original keeps its own', () => {
+ expect(install(brainA, 'linux-cron').status).toBe(0);
+ const copy = join(root, 'brain-a-copy');
+ spawnSync('cp', ['-r', brainA, copy]);
+ expect(status(copy).installed).toBe(false);
+ expect(install(copy, 'linux-cron').status).toBe(0);
+ expect(suffixOf(copy)).not.toBe(suffixOf(brainA));
+ const autopilotLines = readFileSync(cronState, 'utf-8').split('\n').filter(l => l.includes('autopilot-run.sh'));
+ expect(autopilotLines).toHaveLength(2);
+ expect(run(copy, ['--uninstall']).status).toBe(0);
+ expect(status(brainA).installed).toBe(true);
+ expect(run(brainA, ['--uninstall']).status).toBe(0);
+ }, 240_000);
+});
diff --git a/test/e2e/code-intel-n13-postgres.test.ts b/test/e2e/code-intel-n13-postgres.test.ts
new file mode 100644
index 0000000000..ab4f7ec92d
--- /dev/null
+++ b/test/e2e/code-intel-n13-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../code-intel/n13-edge-resolution.test.ts'));
diff --git a/test/e2e/fix-wave-5-integration.test.ts b/test/e2e/fix-wave-5-integration.test.ts
new file mode 100644
index 0000000000..ef5519f482
--- /dev/null
+++ b/test/e2e/fix-wave-5-integration.test.ts
@@ -0,0 +1,4 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+// Fix wave 5 cross-lane journeys (ENG-O14): the PostgreSQL arm of test/fix-wave-5-integration.test.ts.
+await registerPostgresTests(() => import('../fix-wave-5-integration.test.ts'));
diff --git a/test/e2e/frontmatter-migration.test.ts b/test/e2e/frontmatter-migration.test.ts
index 7be99ea12b..79407a8364 100644
--- a/test/e2e/frontmatter-migration.test.ts
+++ b/test/e2e/frontmatter-migration.test.ts
@@ -42,6 +42,7 @@ let brainRootA: string;
let brainRootB: string;
let engine: PGLiteEngine;
let originalHome: string | undefined;
+let originalGbrainHome: string | undefined;
const originalContents = new Map<string, string>();
beforeAll(async () => {
@@ -90,12 +91,15 @@ beforeAll(async () => {
);
__setTestEngineOverride(engine);
- // Redirect ~/.gbrain/migrations/ output. The orchestrator's gbrainDir()
- // helper reads process.env.HOME at call time, so the override takes
- // effect even though Bun's os.homedir() does not observe mid-process
- // mutations.
+ // Redirect ~/.gbrain/migrations/ output. The orchestrator resolves it via
+ // gbrainPath(): GBRAIN_HOME is a PARENT dir with '.gbrain' appended, so
+ // GBRAIN_HOME=tmpHome routes the audit JSON and pending-host-work to
+ // `tmpHome/.gbrain/migrations/`. HOME moves too so any HOME-based read
+ // stays inside the tmpdir.
originalHome = process.env.HOME;
+ originalGbrainHome = process.env.GBRAIN_HOME;
process.env.HOME = tmpHome;
+ process.env.GBRAIN_HOME = tmpHome;
});
afterAll(async () => {
@@ -103,6 +107,8 @@ afterAll(async () => {
if (engine) await engine.disconnect();
if (originalHome === undefined) delete process.env.HOME;
else process.env.HOME = originalHome;
+ if (originalGbrainHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = originalGbrainHome;
rmSync(workdir, { recursive: true, force: true });
});
diff --git a/test/e2e/journey-atoms-sync-race-postgres.test.ts b/test/e2e/journey-atoms-sync-race-postgres.test.ts
new file mode 100644
index 0000000000..da00c46637
--- /dev/null
+++ b/test/e2e/journey-atoms-sync-race-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../journey-atoms-sync-race.test.ts'));
diff --git a/test/e2e/managed-extract-atoms.test.ts b/test/e2e/managed-extract-atoms.test.ts
index 7ee891dcd7..667d5a004f 100644
--- a/test/e2e/managed-extract-atoms.test.ts
+++ b/test/e2e/managed-extract-atoms.test.ts
@@ -1,7 +1,7 @@
import { afterAll, beforeAll, describe, test } from 'bun:test';
import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
-import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority } from '../helpers/managed-atoms-contract.ts';
+import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation, atomRetirementCases, exerciseManagedAtomRetirement } from '../helpers/managed-atoms-contract.ts';
(process.env.DATABASE_URL ? describe : describe.skip)('managed atom PostgreSQL caller parity', () => {
let fixture: Awaited<ReturnType<typeof isolatedPersistencePostgres>>;
@@ -13,4 +13,6 @@ import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManage
for (const scenario of atomContractCases) test(scenario, () => exerciseManagedAtoms(fixture.engine, scenario), 60_000);
for (const scenario of atomBatchCases) test(`batch ${scenario}`, () => exerciseManagedAtomBatch(fixture.engine, scenario), 60_000);
for (const scenario of atomAuthorityCases) test(`authority ${scenario} rejects normal and dry runs before providers`, () => exerciseManagedAtomAuthority(fixture.engine, scenario), 60_000);
+ test('reconciles stale atom pages and files', () => exerciseManagedAtomReconciliation(fixture.engine), 60_000);
+ for (const scenario of atomRetirementCases) test(`retirement ${scenario}`, () => exerciseManagedAtomRetirement(fixture.engine, scenario), 60_000);
});
diff --git a/test/e2e/managed-write-single-attribution-postgres.test.ts b/test/e2e/managed-write-single-attribution-postgres.test.ts
new file mode 100644
index 0000000000..5c4115c99d
--- /dev/null
+++ b/test/e2e/managed-write-single-attribution-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../managed-write-single-attribution.test.ts'));
diff --git a/test/e2e/minions-legacy-coalesce-postgres.test.ts b/test/e2e/minions-legacy-coalesce-postgres.test.ts
new file mode 100644
index 0000000000..0b7dbeb18b
--- /dev/null
+++ b/test/e2e/minions-legacy-coalesce-postgres.test.ts
@@ -0,0 +1,56 @@
+/**
+ * #5157 / #5114 on real Postgres: the same coalesce matrix the PGLite unit
+ * test runs (`test/minions-legacy-coalesce.test.ts`), plus a real concurrent
+ * insert race over a released legacy key.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { runMigrations } from '../../src/core/migrate.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { prepareRemoteJob } from '../../src/core/minions/submission-authority.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { PATHS, runCoalesceMatrix } from '../helpers/legacy-coalesce-matrix.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const suite = hasDatabase() ? describe : describe.skip;
+suite('Postgres legacy coalesce rule (#5157)', () => {
+ let sandbox: string, root: string;
+ const ctx = (): OperationContext => ({
+ engine: getEngine(), config: {} as OperationContext['config'], remote: true, sourceId: 'default', dryRun: false,
+ logger: { info() {}, warn() {}, error() {} },
+ auth: { token: 'test-only', clientId: 'coalesce-test-client', principal: { kind: 'oauth_client', id: 'coalesce-test-client' }, scopes: ['admin'], sourceId: 'default' },
+ });
+ beforeAll(async () => {
+ sandbox = mkdtempSync(join(tmpdir(), 'gbrain-pg-legacy-coalesce-'));
+ root = join(sandbox, 'repo'); mkdirSync(root); execFileSync('git', ['init', '-q', root]);
+ await withEnv({ GBRAIN_HOME: sandbox }, async () => { await setupDB(); await runMigrations(getEngine()); });
+ }, 120_000);
+ afterAll(async () => { await teardownDB(); if (sandbox) rmSync(sandbox, { recursive: true, force: true }); });
+ beforeEach(async () => {
+ await getEngine().executeRaw('DELETE FROM minion_jobs');
+ await getEngine().executeRaw("DELETE FROM oauth_clients WHERE client_id = 'coalesce-test-client'");
+ await getEngine().executeRaw("UPDATE sources SET local_path = $1, config = '{}'::jsonb, archived = false WHERE id = 'default'", [root]);
+ await getEngine().executeRaw("INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, scope, source_id) VALUES ('coalesce-test-client', 'fixture-hash', 'example-client', 'admin', 'default')");
+ });
+
+ test('variant x path x status x caller matches PGLite', async () => {
+ const cells = await runCoalesceMatrix(getEngine(), () => prepareRemoteJob(ctx(), 'lint', {}));
+ expect(cells).toBe(4 * Object.values(PATHS).reduce((n, p) => n + p.statuses.length * p.callers.length, 0));
+ }, 300_000);
+
+ test('concurrent resubmissions over one dead legacy key insert exactly one fresh job', async () => {
+ const queue = new MinionQueue(getEngine());
+ const old = await queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:race' });
+ await getEngine().executeRaw("UPDATE minion_jobs SET status = 'dead', submission_authority = NULL WHERE id = $1", [old.id]);
+ const results = await Promise.all(Array.from({ length: 6 }, () => queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:race' })));
+ const ids = new Set(results.map(job => job.id));
+ expect(ids.size).toBe(1);
+ expect(ids.has(old.id)).toBe(false);
+ const rows = await getEngine().executeRaw<{ id: number }>("SELECT id FROM minion_jobs WHERE idempotency_key = 'dream:synth-v2:race'");
+ expect(rows.map(r => r.id)).toEqual([...ids]);
+ }, 60_000);
+});
diff --git a/test/e2e/minions-legacy-journey-postgres.test.ts b/test/e2e/minions-legacy-journey-postgres.test.ts
new file mode 100644
index 0000000000..96820da4b1
--- /dev/null
+++ b/test/e2e/minions-legacy-journey-postgres.test.ts
@@ -0,0 +1,24 @@
+/**
+ * #5157 restored-operation journey on real Postgres (DX-O15(a),
+ * DX-O3(f)(g)); the PGLite run is `test/minions-legacy-journey.test.ts`.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { runLegacyJourney, runUnsupportedRowRecovery } from '../helpers/legacy-journey.ts';
+
+
+const suite = hasDatabase() ? describe : describe.skip;
+suite('Postgres legacy job recovery journey (#5157)', () => {
+ beforeAll(async () => { await setupDB(); }, 120_000);
+ afterAll(async () => { await teardownDB(); });
+ beforeEach(async () => { await getEngine().executeRaw('DELETE FROM minion_jobs'); });
+
+ test('/ingest 409 -> printed commands verbatim -> 202, worker runs, search finds the memory', async () => {
+ const { commands } = await runLegacyJourney(getEngine());
+ expect(commands).toHaveLength(6);
+ }, 120_000);
+
+ test('an unsupported non-NULL row needs its own printed cancel before a worker starts', async () => {
+ expect(await runUnsupportedRowRecovery(getEngine())).toHaveLength(3);
+ }, 120_000);
+});
diff --git a/test/e2e/persistence-large-manifest-50k.test.ts b/test/e2e/persistence-large-manifest-50k.test.ts
new file mode 100644
index 0000000000..0444584c19
--- /dev/null
+++ b/test/e2e/persistence-large-manifest-50k.test.ts
@@ -0,0 +1,91 @@
+/**
+ * #5790 scale record: a 50,000-file worktree on both engines. Records the
+ * duration and peak RSS of `sources add`, `claim` and writer transfer prepare
+ * and accept with the fixture's total bytes. No duration gate (DX-O10); the
+ * stored manifest and peak RSS growth carry ceilings set from measurement.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { cpSync, mkdtempSync, rmSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { isPhysicalRootMetadata } from '../../src/core/persistence/physical-root.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { claimWorktree, getWorktreeBinding } from '../../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../../src/core/persistence/source-lifecycle.ts';
+import { runPersistenceAdministration } from '../../src/core/persistence/administration.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase } from '../helpers/test-backends.ts';
+import { reviewedWriterIntent } from '../helpers/writer-admin-intent.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { writeLargeWorktree } from '../helpers/large-worktree.ts';
+
+const FILES = 50_000;
+const STORED_MANIFEST_CEILING_BYTES = 4096;
+const PEAK_RSS_GROWTH_CEILING_MB = 1024;
+const databaseUrl = requirePostgresTestDatabase();
+const directory = mkdtempSync(join(tmpdir(), 'gbrain-50k-manifest-'));
+const template = join(directory, 'template');
+let totalBytes = 0;
+beforeAll(() => { totalBytes = writeLargeWorktree(template, FILES); }, 300_000);
+afterAll(() => rmSync(directory, { recursive: true, force: true }), 300_000);
+
+const peakRssMb = () => process.resourceUsage().maxRSS / 1024;
+async function measured<T>(run: () => Promise<T>): Promise<{ value: T; ms: number; peak_rss_mb: number }> {
+ const started = performance.now();
+ const value = await run();
+ return { value, ms: Math.round(performance.now() - started), peak_rss_mb: Math.round(peakRssMb()) };
+}
+const copy = (to: string) => cpSync(template, to, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) });
+
+for (const backend of ['postgres', 'pglite'] as const) describe(`50,000-file worktree (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });
+
+ test('sources add, claim and writer transfer commit with a compact manifest', async () => {
+ const home = join(directory, backend);
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const rssBefore = peakRssMb();
+ const added = join(home, 'added'), claimed = join(home, 'claimed'), successor = join(home, 'successor');
+ copy(added); copy(claimed); copy(successor);
+ const add = await measured(() => runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'scale-added', path: added }));
+ expect(add.value).toMatchObject({ state: 'committed' });
+ await engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', ['scale-claimed', claimed]);
+ });
+ const claim = await measured(() => claimWorktree(engine, 'scale-claimed', claimed));
+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>
+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) }) as Promise<any>;
+ const prepare = await measured(() => administer('writer_transfer_prepare', { source_id: 'scale-claimed' }));
+ expect(prepare.value.manifest.file_count).toBe(FILES);
+ const accept = await measured(() => administer('writer_transfer_accept', { source_id: 'scale-claimed', path: successor,
+ expected_epoch: prepare.value.owner_epoch, manifest: prepare.value.manifest.digest }));
+ expect(accept.value).toMatchObject({ transferred: true });
+ expect((await getWorktreeBinding(engine, 'scale-claimed'))!.local_path).toBe(successor);
+ const rows = await engine.executeRaw<{ manifest: unknown }>('SELECT manifest FROM persistence_worktrees WHERE manifest IS NOT NULL');
+ expect(rows).toHaveLength(2);
+ for (const { manifest } of rows) {
+ const stored = typeof manifest === 'string' ? JSON.parse(manifest) : manifest as Record<string, unknown>;
+ expect(stored).toMatchObject({ file_count: FILES });
+ expect(stored.files).toBeUndefined();
+ expect(Buffer.byteLength(JSON.stringify(stored))).toBeLessThan(STORED_MANIFEST_CEILING_BYTES);
+ }
+ const record = { backend, files: FILES, total_bytes: totalBytes,
+ add: { ms: add.ms, peak_rss_mb: add.peak_rss_mb }, claim: { ms: claim.ms, peak_rss_mb: claim.peak_rss_mb },
+ transfer_prepare: { ms: prepare.ms, peak_rss_mb: prepare.peak_rss_mb }, transfer_accept: { ms: accept.ms, peak_rss_mb: accept.peak_rss_mb },
+ peak_rss_growth_mb: Math.round(peakRssMb() - rssBefore) };
+ console.log(`[5790-scale] ${JSON.stringify(record)}`);
+ expect(record.peak_rss_growth_mb).toBeLessThan(PEAK_RSS_GROWTH_CEILING_MB);
+ });
+ }, 600_000);
+});
diff --git a/test/e2e/persistence-large-manifest-postgres.test.ts b/test/e2e/persistence-large-manifest-postgres.test.ts
new file mode 100644
index 0000000000..5521dc5f7b
--- /dev/null
+++ b/test/e2e/persistence-large-manifest-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../persistence-large-manifest.test.ts'));
diff --git a/test/e2e/preview-approval-postgres.test.ts b/test/e2e/preview-approval-postgres.test.ts
new file mode 100644
index 0000000000..cb2957075e
--- /dev/null
+++ b/test/e2e/preview-approval-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../preview-approval.test.ts'));
diff --git a/test/e2e/projection-drain-postgres.test.ts b/test/e2e/projection-drain-postgres.test.ts
new file mode 100644
index 0000000000..a8e1bd0bf2
--- /dev/null
+++ b/test/e2e/projection-drain-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../projection-drain.test.ts'));
diff --git a/test/e2e/reflex-private-visibility-postgres.test.ts b/test/e2e/reflex-private-visibility-postgres.test.ts
new file mode 100644
index 0000000000..31b01db4f8
--- /dev/null
+++ b/test/e2e/reflex-private-visibility-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../reflex-private-visibility.test.ts'));
diff --git a/test/e2e/repair-extractor-facts-postgres.test.ts b/test/e2e/repair-extractor-facts-postgres.test.ts
new file mode 100644
index 0000000000..7ea3840231
--- /dev/null
+++ b/test/e2e/repair-extractor-facts-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-extractor-facts.test.ts'));
diff --git a/test/e2e/repair-stale-atoms-postgres.test.ts b/test/e2e/repair-stale-atoms-postgres.test.ts
new file mode 100644
index 0000000000..f2c34ae578
--- /dev/null
+++ b/test/e2e/repair-stale-atoms-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../repair-stale-atoms.test.ts'));
diff --git a/test/e2e/sources-mirror-read-only-postgres.test.ts b/test/e2e/sources-mirror-read-only-postgres.test.ts
new file mode 100644
index 0000000000..7c880440d7
--- /dev/null
+++ b/test/e2e/sources-mirror-read-only-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sources-mirror-read-only.test.ts'));
diff --git a/test/embed-concurrency-pool-clamp.test.ts b/test/embed-concurrency-pool-clamp.test.ts
new file mode 100644
index 0000000000..516fd06dbf
--- /dev/null
+++ b/test/embed-concurrency-pool-clamp.test.ts
@@ -0,0 +1,54 @@
+/**
+ * #5183: `embed --stale` wedged (no progress, no error, 0% CPU) when
+ * GBRAIN_EMBED_CONCURRENCY (default 20) exceeded the Postgres client pool:
+ * every worker holds a connection, so extra workers waited on the pool
+ * forever. Embed concurrency is now clamped to the pool on Postgres.
+ */
+
+import { describe, test, expect, spyOn } from 'bun:test';
+import { readFileSync } from 'fs';
+import { resolve } from 'path';
+
+import { _resetEmbedConcurrencyClampWarningForTest, resolveEmbedConcurrency } from '../src/commands/embed.ts';
+
+describe('#5183 embed concurrency never exceeds the Postgres pool', () => {
+ test('an explicit setting above the pool is clamped, with one warning per process', () => {
+ _resetEmbedConcurrencyClampWarningForTest();
+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: '20' }, 12)).toBe(12);
+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: '20' }, 12)).toBe(12);
+ const lines = err.mock.calls.map(c => String(c[0])).filter(l => l.includes('[embed]'));
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('GBRAIN_EMBED_CONCURRENCY=20 is above the connection pool (12); using 12 workers');
+ expect(lines[0]).toContain('GBRAIN_POOL_SIZE');
+ } finally {
+ err.mockRestore();
+ }
+ });
+
+ test('the default 20 is clamped to the pool silently (the pool-2 guidance case)', () => {
+ _resetEmbedConcurrencyClampWarningForTest();
+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ expect(resolveEmbedConcurrency('postgres', undefined, {}, 2)).toBe(2);
+ expect(err.mock.calls.filter(c => String(c[0]).includes('[embed]'))).toHaveLength(0);
+ } finally {
+ err.mockRestore();
+ }
+ });
+
+ test('unchanged when the pool is large enough, on PGLite, and for a lower paced cap', () => {
+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: '8' }, 12)).toBe(8);
+ expect(resolveEmbedConcurrency('pglite', undefined, {}, 2)).toBe(20);
+ expect(resolveEmbedConcurrency('postgres', 4, {}, 12)).toBe(4);
+ expect(resolveEmbedConcurrency('postgres', undefined, { GBRAIN_EMBED_CONCURRENCY: 'junk' }, 50)).toBe(20);
+ });
+
+ test('both embed loops use the clamped value', () => {
+ // test-reads-source-ok[structural]: both embed loops must take the clamped value; the loops need a live Postgres pool to observe.
+ const src = readFileSync(resolve(import.meta.dir, '..', 'src', 'commands', 'embed.ts'), 'utf-8');
+ expect(src.match(/const CONCURRENCY = resolveEmbedConcurrency\(engine\.kind, staleOpts\?\.paceMaxConcurrency\);/g)).toHaveLength(2);
+ expect(src).not.toMatch(/parseInt\(process\.env\.GBRAIN_EMBED_CONCURRENCY/);
+ });
+});
diff --git a/test/embedding-key-source-cli.serial.test.ts b/test/embedding-key-source-cli.serial.test.ts
new file mode 100644
index 0000000000..85b5af887c
--- /dev/null
+++ b/test/embedding-key-source-cli.serial.test.ts
@@ -0,0 +1,44 @@
+/**
+ * #5137 through the real CLI entrypoint: the key-shadow warning prints once
+ * per process from ordinary commands, never from `gbrain hook`, carries no
+ * key bytes, and `gbrain config unset <key>` (the documented fix for an
+ * intended env key) stops it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const ENV_KEY = 'sk-test-ENVKEYexample0123456789abcdefWXYZ';
+const CONFIG_KEY = 'sk-test-CONFIGKEYexample9876543210fedcbaQRST';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-key-shadow-cli-'));
+const configFile = join(home, '.gbrain', 'config.json');
+const opts = { home, env: { OPENAI_API_KEY: ENV_KEY } };
+const leaked = (text: string) => [ENV_KEY, CONFIG_KEY, ENV_KEY.slice(0, 16), CONFIG_KEY.slice(-12)].filter(fragment => text.includes(fragment));
+const warnings = (stderr: string) => stderr.split('\n').filter(line => line.includes('differs from openai_api_key'));
+
+beforeAll(() => {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(configFile, JSON.stringify({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite'), openai_api_key: CONFIG_KEY }));
+});
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+test('an ordinary command warns once on stderr and leaks no key bytes; a hook command never warns', async () => {
+ const command = await runCli(['engine', '--help'], opts);
+ expect(command.exitCode).toBe(0);
+ expect(warnings(command.stderr)).toEqual([expect.stringContaining('[gbrain] warning: OPENAI_API_KEY in this process\'s environment differs from openai_api_key')]);
+ expect(leaked(command.stdout + command.stderr)).toEqual([]);
+ const hook = await runCli(['hook', '--help'], opts);
+ expect(warnings(hook.stderr)).toEqual([]);
+ expect(leaked(hook.stdout + hook.stderr)).toEqual([]);
+}, 120_000);
+
+test('`gbrain config unset openai_api_key` keeps the env key in effect and stops the warning', async () => {
+ const unset = await runCli(['config', 'unset', 'openai_api_key'], opts);
+ expect(unset.exitCode).toBe(0);
+ expect(leaked(unset.stdout + unset.stderr)).toEqual([]);
+ expect(JSON.parse(readFileSync(configFile, 'utf8')).openai_api_key).toBeUndefined();
+ const after = await runCli(['engine', '--help'], opts);
+ expect(warnings(after.stderr)).toEqual([]);
+}, 120_000);
diff --git a/test/embedding-key-source.test.ts b/test/embedding-key-source.test.ts
new file mode 100644
index 0000000000..32ff68524b
--- /dev/null
+++ b/test/embedding-key-source.test.ts
@@ -0,0 +1,181 @@
+/**
+ * #5137: env provider keys keep winning over config keys, but a different
+ * config key shadowed by the environment is reported once per process, doctor
+ * `embedding_key_source` reports the same, and the first embedding 401/403
+ * prints embedding_auth_failed naming the key source. No key value or
+ * fragment reaches any output.
+ */
+import { afterAll, afterEach, 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 { mergedProviderEnv, providerKeyShadows, providerKeySource } from '../src/core/ai/provider-env.ts';
+import { _setKeyWarningSinkForTests, credentialEnvName, embeddingAuthFailedError, warnShadowedProviderKeys } from '../src/core/ai/key-warnings.ts';
+import { getRecipe } from '../src/core/ai/recipes/index.ts';
+import { redactProviderKeys } from '../src/core/ai/key-redact.ts';
+import { configureGateway, embed, resetGateway } from '../src/core/ai/gateway.ts';
+import { embeddingKeySource } from '../src/commands/doctor/checks/embedding-health.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const ENV_KEY = 'sk-test-ENVKEYexample0123456789abcdefWXYZ';
+const CONFIG_KEY = 'sk-test-CONFIGKEYexample9876543210fedcbaQRST';
+const fragments = (key: string) => [key, key.slice(0, 16), key.slice(-12)];
+const cfg = (extra: Partial<GBrainConfig> = {}) => ({ engine: 'pglite', openai_api_key: CONFIG_KEY, ...extra }) as GBrainConfig;
+const leaks = (text: string) => [...fragments(ENV_KEY), ...fragments(CONFIG_KEY)].filter(fragment => text.includes(fragment));
+
+const lines: string[] = [];
+afterEach(() => { _setKeyWarningSinkForTests(); lines.length = 0; resetGateway(); });
+
+describe('providerKeyShadows (pure)', () => {
+ test('reports an env value that differs from the config key, by name only', () => {
+ expect(providerKeyShadows(cfg(), { OPENAI_API_KEY: ENV_KEY })).toEqual([{ variable: 'OPENAI_API_KEY', config_key: 'openai_api_key' }]);
+ expect(providerKeyShadows(cfg(), { OPENAI_API_KEY: CONFIG_KEY })).toEqual([]);
+ expect(providerKeyShadows(cfg(), { OPENAI_API_KEY: '' })).toEqual([]);
+ expect(providerKeyShadows(cfg(), {})).toEqual([]);
+ expect(providerKeyShadows(null, { OPENAI_API_KEY: ENV_KEY })).toEqual([]);
+ expect(mergedProviderEnv(cfg(), { OPENAI_API_KEY: ENV_KEY }).OPENAI_API_KEY).toBe(ENV_KEY);
+ });
+
+ test('the GEMINI alias counts as the env key for google_api_key; TypeSafe has no config key, so its alias never warns', () => {
+ const google = cfg({ google_api_key: CONFIG_KEY } as Partial<GBrainConfig>);
+ expect(providerKeyShadows(google, { GEMINI_API_KEY: ENV_KEY })).toEqual([{ variable: 'GEMINI_API_KEY', config_key: 'google_api_key' }]);
+ expect(providerKeyShadows(google, { GOOGLE_GENERATIVE_AI_API_KEY: ENV_KEY, GEMINI_API_KEY: CONFIG_KEY }))
+ .toEqual([{ variable: 'GOOGLE_GENERATIVE_AI_API_KEY', config_key: 'google_api_key' }]);
+ expect(providerKeyShadows(cfg(), { JEV_TYPESAFE_API_KEY: ENV_KEY })).toEqual([]);
+ expect(providerKeyShadows(cfg(), { TYPESAFE_API_KEY: ENV_KEY, JEV_TYPESAFE_API_KEY: CONFIG_KEY })).toEqual([]);
+ });
+
+ test('providerKeySource names where the key in effect comes from', () => {
+ expect(providerKeySource(cfg(), { OPENAI_API_KEY: ENV_KEY }, 'OPENAI_API_KEY')).toEqual({ kind: 'env', variable: 'OPENAI_API_KEY', config_key: 'openai_api_key', shadows_config: true });
+ expect(providerKeySource(cfg(), {}, 'OPENAI_API_KEY')).toEqual({ kind: 'config', variable: 'OPENAI_API_KEY', config_key: 'openai_api_key' });
+ expect(providerKeySource(null, {}, 'ZEROENTROPY_API_KEY')).toEqual({ kind: 'missing', variable: 'ZEROENTROPY_API_KEY' });
+ });
+});
+
+describe('the shadow warning', () => {
+ test('prints once per process, names the variable, the config key, which is in effect and both fixes, and no key bytes', () => {
+ _setKeyWarningSinkForTests(line => lines.push(line));
+ warnShadowedProviderKeys(cfg(), { OPENAI_API_KEY: ENV_KEY });
+ warnShadowedProviderKeys(cfg(), { OPENAI_API_KEY: ENV_KEY });
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain('OPENAI_API_KEY in this process\'s environment differs from openai_api_key in');
+ expect(lines[0]).toContain('the environment value is in effect');
+ expect(lines[0]).toContain('remove OPENAI_API_KEY from the environment of the process that reported this');
+ expect(lines[0]).toContain('for a daemon its service definition) and restart that process');
+ expect(lines[0]).toContain('run `gbrain config unset openai_api_key`, which also stops this warning');
+ expect(leaks(lines[0])).toEqual([]);
+ });
+
+ test('a matching or absent env key prints nothing', () => {
+ _setKeyWarningSinkForTests(line => lines.push(line));
+ warnShadowedProviderKeys(cfg(), { OPENAI_API_KEY: CONFIG_KEY });
+ expect(lines).toEqual([]);
+ });
+});
+
+describe('doctor embedding_key_source', () => {
+ test('warns on a shadowed key, names the embedding key source, scopes itself to doctor\'s environment, and leaks no key', () => {
+ const check = embeddingKeySource(cfg({ embedding_model: 'openai:text-embedding-3-small' }), { OPENAI_API_KEY: ENV_KEY }, '/home/example/.gbrain/config.json');
+ expect(check.status).toBe('warn');
+ expect(check.message).toContain('The embedding key in effect is OPENAI_API_KEY from this environment.');
+ expect(check.message).toContain('differs from openai_api_key in /home/example/.gbrain/config.json');
+ expect(check.message).toContain('This check sees only the environment `gbrain doctor` runs in');
+ expect(check.details).toMatchObject({ shadows: [{ variable: 'OPENAI_API_KEY', config_key: 'openai_api_key', in_effect: 'env' }],
+ embedding_key: { kind: 'env', variable: 'OPENAI_API_KEY', config_key: 'openai_api_key' }, docs: 'docs/guides/repair.md#embedding-key-source' });
+ expect(leaks(JSON.stringify(check))).toEqual([]);
+ });
+
+ test('names the real credential for Azure and LiteLLM, and follows GBRAIN_EMBEDDING_MODEL over the file model', () => {
+ expect(credentialEnvName(getRecipe('azure-openai')?.auth_env)).toBe('AZURE_OPENAI_API_KEY');
+ expect(credentialEnvName(getRecipe('litellm')?.auth_env)).toBe('LITELLM_API_KEY');
+ const check = embeddingKeySource(cfg({ embedding_model: 'openai:text-embedding-3-small' }),
+ { GBRAIN_EMBEDDING_MODEL: 'voyage:voyage-4', VOYAGE_API_KEY: ENV_KEY }, '/home/example/.gbrain/config.json');
+ expect(check.message).toContain('The embedding key in effect is VOYAGE_API_KEY from this environment.');
+ expect(check.details).toMatchObject({ embedding_model: 'voyage:voyage-4' });
+ const azure = embeddingAuthFailedError(getRecipe('azure-openai')!, 401, cfg({ azure_openai_api_key: CONFIG_KEY } as Partial<GBrainConfig>), {}, '/home/example/.gbrain/config.json');
+ expect(azure.message).toContain('the key in effect is azure_openai_api_key in /home/example/.gbrain/config.json (AZURE_OPENAI_API_KEY is not set)');
+ expect(azure.message).not.toContain('AZURE_OPENAI_ENDPOINT');
+ const entra = embeddingAuthFailedError(getRecipe('azure-openai')!, 403, cfg({ azure_openai_api_key: CONFIG_KEY } as Partial<GBrainConfig>), { AZURE_OPENAI_USE_ENTRA: '1' }, '/home/example/.gbrain/config.json');
+ expect(entra.message).toContain('Azure Entra mode is on (AZURE_OPENAI_USE_ENTRA)');
+ expect(entra.suggestion).toContain('az login');
+ expect(entra.suggestion).not.toContain('azure_openai_api_key');
+ });
+
+ test('is ok without a shadow and reports a config-plane embedding key', () => {
+ const check = embeddingKeySource(cfg({ embedding_model: 'openai:text-embedding-3-small' }), {}, '/home/example/.gbrain/config.json');
+ expect(check.status).toBe('ok');
+ expect(check.message).toContain('The embedding key in effect is openai_api_key in /home/example/.gbrain/config.json.');
+ expect(leaks(JSON.stringify(check))).toEqual([]);
+ });
+});
+
+test('redactProviderKeys removes a key in effect, a masked echo and a key fragment, and keeps ordinary text', () => {
+ const text = `Incorrect API key provided: ${ENV_KEY}. Also seen: sk-test-****************WXYZ and ${ENV_KEY.slice(4, 20)} for model text-embedding-3-small.`;
+ const redacted = redactProviderKeys(text, { OPENAI_API_KEY: ENV_KEY, OPENAI_BASE_URL: 'http://127.0.0.1:1/v1' });
+ expect(leaks(redacted)).toEqual([]);
+ expect(redacted).not.toContain('****');
+ expect(redacted).toContain('<REDACTED:OPENAI_API_KEY>');
+ expect(redacted).toContain('for model text-embedding-3-small.');
+});
+
+describe('embedding_auth_failed against a provider that rejects the env key', () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-key-source-'));
+ let server: ReturnType<typeof Bun.serve>;
+ const requests: string[] = [];
+ beforeAll(() => {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', openai_api_key: CONFIG_KEY }));
+ server = Bun.serve({ port: 0, hostname: '127.0.0.1', async fetch(req) {
+ const key = (req.headers.get('authorization') ?? '').replace(/^Bearer /, '');
+ requests.push(key === CONFIG_KEY ? 'config' : key === ENV_KEY ? 'env' : 'other');
+ if (key !== CONFIG_KEY) {
+ return Response.json({ error: { message: `Incorrect API key provided: ${key}. You passed ${key.slice(0, 16)}...${key.slice(-12)} (sk-test-****${key.slice(-4)}).`, type: 'invalid_request_error', code: 'invalid_api_key' } }, { status: 401 });
+ }
+ const body = await req.json() as { input: string[] };
+ return Response.json({ object: 'list', model: 'text-embedding-3-small', usage: { prompt_tokens: 1, total_tokens: 1 },
+ data: body.input.map((_, index) => ({ object: 'embedding', index, embedding: Array.from({ length: 1536 }, (_, i) => (i % 7) + 1) })) });
+ } });
+ });
+ afterAll(() => { server.stop(true); rmSync(home, { recursive: true, force: true }); });
+
+ const configureFromEnv = async () => {
+ const { loadConfigFileOnly } = await import('../src/core/config.ts');
+ configureGateway({ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536,
+ env: { ...mergedProviderEnv(loadConfigFileOnly(), process.env), OPENAI_BASE_URL: `http://127.0.0.1:${server.port}/v1` } });
+ };
+
+ test('the first 401 prints one error naming the env key source and its fixes; following the fix makes the embedding succeed', async () => {
+ _setKeyWarningSinkForTests(line => lines.push(line));
+ let failure: unknown;
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: ENV_KEY }, async () => {
+ await configureFromEnv();
+ failure = await embed(['example text'], { maxRetries: 0 }).then(() => null, error => error);
+ expect(await embed(['second example'], { maxRetries: 0 }).then(() => null, error => error)).toBeInstanceOf(Error);
+ });
+ expect(failure).toBeInstanceOf(Error);
+ expect(requests).toContain('env');
+ expect(leaks(String((failure as Error).message))).toEqual([]);
+ expect(leaks(JSON.stringify({ error: (failure as Error).message, ...(failure as object) }))).toEqual([]);
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toStartWith('[gbrain] Error [embedding_auth_failed]: The OpenAI embedding provider rejected its key (HTTP 401); the key in effect is OPENAI_API_KEY from this process\'s environment, which differs from openai_api_key in');
+ expect(lines[0]).toContain('Fix: To use the config key, remove OPENAI_API_KEY from the environment of the process that reported this');
+ expect(lines[0]).toContain('run `gbrain config unset openai_api_key`');
+ expect(lines[0]).toContain('Docs: docs/guides/write-refusals.md#embedding_auth_failed');
+ expect(leaks(lines.join('\n'))).toEqual([]);
+
+ await withEnv({ GBRAIN_HOME: home, OPENAI_API_KEY: undefined }, async () => {
+ await configureFromEnv();
+ const [vector] = await embed(['example text'], { maxRetries: 0 });
+ expect(vector).toHaveLength(1536);
+ });
+ expect(requests.at(-1)).toBe('config');
+ }, 60_000);
+
+ test('a rejected config key names the config key and its fix', () => {
+ const error = embeddingAuthFailedError({ id: 'openai', name: 'OpenAI', auth_env: { required: ['OPENAI_API_KEY'] } }, 403, cfg(), {}, '/home/example/.gbrain/config.json');
+ expect(error.toJSON()).toMatchObject({ error: 'embedding_auth_failed', docs: 'docs/guides/write-refusals.md#embedding_auth_failed',
+ message: 'The OpenAI embedding provider rejected its key (HTTP 403); the key in effect is openai_api_key in /home/example/.gbrain/config.json (OPENAI_API_KEY is not set).',
+ suggestion: 'Run `gbrain config set openai_api_key <valid key>` and restart any daemon that uses it. Then run `gbrain embed --stale` to embed what was saved while the key was rejected.' });
+ });
+});
diff --git a/test/embedding-rejection-refund.serial.test.ts b/test/embedding-rejection-refund.serial.test.ts
new file mode 100644
index 0000000000..b28b47db86
--- /dev/null
+++ b/test/embedding-rejection-refund.serial.test.ts
@@ -0,0 +1,89 @@
+/**
+ * Wave-3 connector follow-up #11: an embedding request the provider rejects
+ * (HTTP 400/413/422) kept its maximum debit against the `gbrain migrate
+ * embeddings --max-cost-usd` authorization, so a migration could stop early at
+ * the cap. Only token-limit rejections released their reservation. A rejection
+ * is now released only for providers whose documentation says rejected
+ * requests are not billed (Google); every other provider keeps the debit.
+ *
+ * Each case runs at exactly the cap: the authorization covers one request at
+ * its maximum input size, so the request after a rejection is admitted only if
+ * the rejection was released.
+ *
+ * Serial: the gateway transport and configuration are process-global.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, embed, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { isUnbilledEmbeddingRejection } from '../src/core/ai/errors.ts';
+import { planEmbeddingMigration, readMigrationState, runSchemaTransition } from '../src/core/embedding-migration.ts';
+import { authorizeMigrationBudget } from '../src/core/embedding-migration-budget.ts';
+import { withAIInvocationGuard, type AIInvocation } from '../src/core/ai/invocation-guard.ts';
+
+const RATE_PER_MTOK = 1_000;
+const TEXT = 'Synthetic rejected chunk. '.repeat(20);
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ __setEmbedTransportForTests(null);
+ resetGateway();
+ await engine.disconnect();
+}, 60_000);
+
+function rejection(status: number): Error {
+ return Object.assign(new Error('Synthetic invalid request: input rejected'), { statusCode: status });
+}
+
+async function atExactCap(model: string, dims: number, env: Record<string, string>, status: number) {
+ await runSchemaTransition(engine, dims);
+ await engine.executeRaw("DELETE FROM config WHERE key LIKE 'embedding_migration.%'");
+ await engine.setConfig('pricing.overrides', JSON.stringify({ [model]: RATE_PER_MTOK }));
+ resetGateway();
+ configureGateway({ embedding_model: model, embedding_dimensions: dims, env });
+ const vector = () => Array.from({ length: dims }, () => 0.1);
+ let reject = true;
+ __setEmbedTransportForTests(async ({ values }: { values: string[] }) => {
+ if (reject) throw rejection(status);
+ return { values, warnings: [], embeddings: values.map(vector), usage: { tokens: 10 } };
+ });
+ // The cap is exactly one request at its maximum input size.
+ let maxInputTokens = 0;
+ await withAIInvocationGuard(async (call: AIInvocation) => { maxInputTokens = call.maxInputTokens!; return { settle: async () => {} }; },
+ () => embed([TEXT], { embeddingModel: model, dimensions: dims })).catch(() => {});
+ expect(maxInputTokens).toBeGreaterThan(0);
+ const cap = maxInputTokens * RATE_PER_MTOK / 1_000_000;
+ const debit = await authorizeMigrationBudget(engine, await planEmbeddingMigration(engine, { to: model, dim: dims }), cap);
+ await expect(withAIInvocationGuard(debit, () => embed([TEXT], { embeddingModel: model, dimensions: dims }))).rejects.toThrow();
+ const afterRejection = (await readMigrationState(engine)).state!.budget!;
+ reject = false;
+ const next = await withAIInvocationGuard(debit, () => embed([TEXT], { embeddingModel: model, dimensions: dims })).then(() => 'embedded', (e: Error) => e.message);
+ return { cap, afterRejection, next };
+}
+
+describe('embedding rejection refund', () => {
+ test('Google (documented unbilled): a 400 rejection is released and the next request fits the exact cap', async () => {
+ const r = await atExactCap('google:gemini-embedding-001', 768, { GOOGLE_GENERATIVE_AI_API_KEY: 'synthetic-only' }, 400);
+ expect(r.afterRejection.debited_usd).toBe(0);
+ expect(r.next).toBe('embedded');
+ });
+
+ test('OpenAI (no such statement): a 400 rejection keeps its debit and the next request is refused at the cap', async () => {
+ const r = await atExactCap('openai:text-embedding-3-small', 8, { OPENAI_API_KEY: 'synthetic-only' }, 400);
+ expect(r.afterRejection.debited_usd).toBeCloseTo(r.cap, 12);
+ expect(r.next).toContain('Migration authorization exhausted');
+ });
+
+ test('only request-shaped rejections from documented providers qualify', () => {
+ for (const status of [400, 413, 422]) expect(isUnbilledEmbeddingRejection('google', rejection(status))).toBe(true);
+ for (const status of [401, 403, 429, 500]) expect(isUnbilledEmbeddingRejection('google', rejection(status))).toBe(false);
+ for (const provider of ['openai', 'voyage', 'mistral', 'azure-openai']) expect(isUnbilledEmbeddingRejection(provider, rejection(400))).toBe(false);
+ expect(isUnbilledEmbeddingRejection('google', new Error('no status'))).toBe(false);
+ });
+});
diff --git a/test/error-catalogue.test.ts b/test/error-catalogue.test.ts
new file mode 100644
index 0000000000..a5ee5d977d
--- /dev/null
+++ b/test/error-catalogue.test.ts
@@ -0,0 +1,69 @@
+/**
+ * Fix wave 5 error catalogue (DX-O1 / DX-O2 / ENG-O12): every catalogue
+ * entry's docs anchor exists in its guide, and a catalogue refusal carries its
+ * code, one-sentence message, hint and docs pointer on both wire shapes
+ * (`OperationError.toJSON()` for CLI `--json` and MCP; the StructuredError
+ * envelope for CLI-only surfaces).
+ */
+import { describe, expect, test } from 'bun:test';
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { ERROR_CATALOGUE, catalogueError, catalogueStructuredError, type CatalogueName } from '../src/core/error-catalogue.ts';
+import { serializeError } from '../src/core/errors.ts';
+
+const ROOT = join(import.meta.dir, '..');
+
+/** GitHub's heading anchor: lowercase, punctuation dropped, spaces to hyphens. */
+function headingAnchor(heading: string): string {
+ return heading.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');
+}
+
+function anchorsOf(path: string): Set<string> {
+ const text = readFileSync(join(ROOT, path), 'utf8').replace(/^```[\s\S]*?^```/gm, '');
+ const anchors = new Set<string>();
+ for (const [, heading] of text.matchAll(/^#{1,6}\s+(.+)$/gm)) anchors.add(headingAnchor(heading!));
+ for (const [, id] of text.matchAll(/<a id="([^"]+)"><\/a>/g)) anchors.add(id!);
+ return anchors;
+}
+
+describe('error catalogue docs anchors', () => {
+ test('every entry points at docs/guides/repair.md or write-refusals.md and its anchor exists', () => {
+ const names = Object.keys(ERROR_CATALOGUE) as CatalogueName[];
+ expect(names.length).toBeGreaterThan(0);
+ for (const name of names) {
+ const [path, anchor] = ERROR_CATALOGUE[name].docs.split('#');
+ expect(['docs/guides/repair.md', 'docs/guides/write-refusals.md']).toContain(path!);
+ expect(anchor, `${name} has no anchor`).toBeTruthy();
+ expect(anchorsOf(path!).has(anchor!), `${name}: ${path}#${anchor} does not exist`).toBe(true);
+ }
+ });
+
+ test('the anchor resolver rejects a heading that does not exist', () => {
+ expect(anchorsOf('docs/guides/repair.md').has('preview-changed')).toBe(true);
+ expect(anchorsOf('docs/guides/repair.md').has('no-such-wave-5-heading')).toBe(false);
+ });
+
+ test('the DX-O2 codes are catalogued with their stable codes, and the legacy refusal keeps permission_denied', () => {
+ for (const code of ['legacy_jobs_active', 'legacy_job_selection_invalid', 'preview_changed', 'projection_owner_resident',
+ 'colon_slug_windows_write_through', 'embedding_auth_failed'] as const) {
+ expect(ERROR_CATALOGUE[code].code).toBe(code);
+ }
+ expect(ERROR_CATALOGUE.legacy_job_authority).toEqual({ code: 'permission_denied', docs: 'docs/guides/repair.md#legacy-job-authority' });
+ expect(ERROR_CATALOGUE.colon_slug_windows_write_through.docs).toStartWith('docs/guides/write-refusals.md#');
+ });
+});
+
+describe('catalogue refusals on the wire', () => {
+ test('OperationError.toJSON carries code, message, hint as suggestion and the anchor as docs', () => {
+ const error = catalogueError('projection_owner_resident', 'A resident owner holds this PGLite brain.', 'Stop it first: gbrain serve --stop');
+ expect(error.toJSON()).toMatchObject({ error: 'projection_owner_resident', message: 'A resident owner holds this PGLite brain.',
+ suggestion: 'Stop it first: gbrain serve --stop', docs: 'docs/guides/repair.md#projection-owner-resident' });
+ expect(JSON.parse(JSON.stringify(catalogueError('legacy_job_authority', 'm.', 'h')))).toMatchObject({ error: 'permission_denied', docs: 'docs/guides/repair.md#legacy-job-authority' });
+ });
+
+ test('the StructuredError envelope names them hint and docs_url', () => {
+ const error = catalogueStructuredError('legacy_job_selection_invalid', 'SelectionInvalid', 'Unknown --select key "state".', 'gbrain jobs authorize-legacy --select "status=waiting"');
+ expect(serializeError(error)).toEqual({ class: 'SelectionInvalid', code: 'legacy_job_selection_invalid', message: 'Unknown --select key "state".',
+ hint: 'gbrain jobs authorize-legacy --select "status=waiting"', docs_url: 'docs/guides/repair.md#legacy-job-selection-invalid' });
+ });
+});
diff --git a/test/explicit-read-admission-5081.test.ts b/test/explicit-read-admission-5081.test.ts
new file mode 100644
index 0000000000..33285efcb8
--- /dev/null
+++ b/test/explicit-read-admission-5081.test.ts
@@ -0,0 +1,308 @@
+/**
+ * #5081 — a stdio connection bound by GBRAIN_SOURCE (or a .gbrain-source pin)
+ * may name a federated source in an explicit `source_id` read.
+ *
+ * Pre-fix, `resolveRequestedScope` denied every explicit id outside the
+ * scalar bound source, because `localFederatedSourceIds` returns undefined
+ * for the explicit tiers. The fix (ENG-O6): the stdio transport computes
+ * `explicitReadBinding` (bound source + non-archived `federated === true`
+ * sources; just the bound source when it opted out, E-T2) and
+ * `federatedSearchScope` alone passes it to `resolveRequestedScope` as the
+ * explicit-read admission set. Unqualified reads stay scalar; image, loops
+ * and code-intel keep denying; `requireWritablePage` is unchanged.
+ *
+ * Contexts are built by the real stdio scope resolver
+ * (`resolveMcpStdioSourceScope`) and calls go through `dispatchToolCall`, the
+ * same path `gbrain serve` uses. The subprocess transport test lives in
+ * test/serve-stdio-bound-explicit-read.test.ts.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { noGrantFederatedScope } from '../src/core/source-resolver.ts';
+import type { AuthInfo, OperationContext } from '../src/core/operations.ts';
+import { requireWritablePage, resolveCodeIntelScope } from '../src/core/ops/context.ts';
+import { dispatchToolCall, buildOperationContext, type DispatchOpts } from '../src/mcp/dispatch.ts';
+import { resolveMcpStdioSourceScope } from '../src/mcp/server.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { encodeDeepResearchId } from '../src/core/deep-research-id.ts';
+
+let engine: PGLiteEngine;
+let outsideCwd: string;
+const SOURCES = ['default', 'work', 'notes', 'private', 'iso'] as const;
+const MARKER = 'zebratelescope';
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ outsideCwd = mkdtempSync(join(tmpdir(), 'gbrain-5081-cwd-'));
+ // Seeded 'default' is federated=true. work: the bound anchor (federated
+ // unset). notes: federated. private: never federated. iso: opted out.
+ const configs: Record<string, string> = {
+ work: '{}', notes: '{"federated": true}', private: '{}', iso: '{"federated": false}',
+ };
+ for (const [id, config] of Object.entries(configs)) {
+ await engine.executeRaw(
+ `INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)`,
+ [id, mkdtempSync(join(tmpdir(), `gbrain-5081-${id}-`)), config],
+ );
+ }
+ for (const id of SOURCES) {
+ const result = await importFromContent(engine, `topics/${id}-topic`,
+ serializeMarkdown({}, `the ${MARKER} lives in ${id}`, '', { type: 'note', title: `Topic in ${id}`, tags: [] }),
+ { sourceId: id, noEmbed: true, forceRechunk: true });
+ expect(result.status).toBe('imported');
+ }
+ await engine.setConfig('search.mcp_keyword_only', 'true');
+}, 60_000);
+
+afterAll(async () => {
+ if (engine) await engine.disconnect();
+}, 60_000);
+
+/** Dispatch options exactly as src/mcp/server.ts builds them for one call. */
+async function stdioOpts(env: Record<string, string | undefined>, cwd = outsideCwd): Promise<DispatchOpts> {
+ const scope = await withEnv(env, () => resolveMcpStdioSourceScope(engine, cwd));
+ return {
+ remote: true,
+ transport: 'stdio',
+ takesHoldersAllowList: ['world'],
+ sourceId: scope.sourceId,
+ ...(scope.localFederatedSourceIds ? { localFederatedSourceIds: scope.localFederatedSourceIds } : {}),
+ ...(scope.explicitReadBinding ? { explicitReadBinding: scope.explicitReadBinding } : {}),
+ };
+}
+
+const bound = (id = 'work') => stdioOpts({ GBRAIN_SOURCE: id });
+
+async function call(opts: DispatchOpts, name: string, params: Record<string, unknown>) {
+ const result = await dispatchToolCall(engine, name, params, opts);
+ return { isError: result.isError === true, body: JSON.parse(result.content[0].text) };
+}
+
+function sourcesOf(body: unknown): string[] {
+ const rows = Array.isArray(body) ? body : ((body as { results?: unknown[] }).results ?? []);
+ return [...new Set(rows.map((row) => (row as { source_id: string }).source_id))].sort();
+}
+
+/** Each fixture page is `topics/<source>-topic`, so a slug names its source. */
+function sourcesOfSlugs(slugs: string[]): string[] {
+ return [...new Set(slugs.map((slug) => slug.replace(/^topics\/(.*)-topic$/, '$1')))].sort();
+}
+
+const reads: Array<[name: string, params: (sourceId: string) => Record<string, unknown>, sources: (body: any) => string[]]> = [
+ ['search', (s) => ({ query: MARKER, source_id: s }), sourcesOf],
+ ['query', (s) => ({ query: MARKER, expand: false, source_id: s }), sourcesOf],
+ ['get_page', (s) => ({ slug: `topics/${s}-topic`, source_id: s }), (b) => [b.source_id]],
+ ['list_pages', (s) => ({ source_id: s }), sourcesOf],
+ ['resolve_slugs', (s) => ({ partial: 'topics', source_id: s }), (b) => sourcesOfSlugs(b)],
+ ['recall', (s) => ({ query: MARKER, source_id: s }), (b) => sourcesOfSlugs(b.results.map((r: { slug: string }) => r.slug))],
+];
+
+describe('#5081 — transport computes the explicit-read binding', () => {
+ test('GBRAIN_SOURCE binding: bound source + federated sources; unqualified scope stays scalar', async () => {
+ const scope = await withEnv({ GBRAIN_SOURCE: 'work' }, () => resolveMcpStdioSourceScope(engine, outsideCwd));
+ expect(scope.tier).toBe('env');
+ expect(scope.localFederatedSourceIds).toBeUndefined();
+ expect(scope.explicitReadBinding).toEqual({
+ sourceId: 'work', via: 'GBRAIN_SOURCE', sourceIds: ['work', 'default', 'notes'], optedOut: ['iso'],
+ });
+ });
+
+ test('E-T2: an isolated anchor (federated: false) admits only itself', async () => {
+ const scope = await withEnv({ GBRAIN_SOURCE: 'iso' }, () => resolveMcpStdioSourceScope(engine, outsideCwd));
+ expect(scope.explicitReadBinding?.sourceIds).toEqual(['iso']);
+ });
+
+ test('.gbrain-source pin produces a dotfile binding', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5081-pin-'));
+ writeFileSync(join(dir, '.gbrain-source'), 'work\n');
+ const scope = await withEnv({ GBRAIN_SOURCE: undefined }, () => resolveMcpStdioSourceScope(engine, dir));
+ expect(scope.tier).toBe('dotfile');
+ expect(scope.explicitReadBinding?.via).toBe('.gbrain-source');
+ expect(scope.explicitReadBinding?.sourceIds).toEqual(['work', 'default', 'notes']);
+ });
+
+ test('an unbound stdio connection gets no binding (its federated widening is unchanged)', async () => {
+ const scope = await withEnv({ GBRAIN_SOURCE: undefined }, () => resolveMcpStdioSourceScope(engine, outsideCwd));
+ expect(scope.explicitReadBinding).toBeUndefined();
+ expect(scope.localFederatedSourceIds).toEqual(['default', 'notes']);
+ });
+});
+
+describe('#5081 — explicit reads from a GBRAIN_SOURCE-bound stdio connection', () => {
+ for (const [name, params, sources] of reads) {
+ test(`${name}: an explicit federated source is admitted and returns only that source`, async () => {
+ const { isError, body } = await call(await bound(), name, params('notes'));
+ expect(isError).toBe(false);
+ expect(sources(body)).toEqual(['notes']);
+ });
+
+ test(`${name}: a source that is not federated is denied with the bound-connection hint`, async () => {
+ const { isError, body } = await call(await bound(), name, params('private'));
+ expect(isError).toBe(true);
+ expect(['permission_denied', 'scope_denied']).toContain(body.error);
+ expect(body.suggestion).toBe(
+ 'This connection is bound to source work (GBRAIN_SOURCE). private is not federated; the brain owner can run '
+ + '`gbrain sources federate private` on the brain host, or start this connection without GBRAIN_SOURCE.',
+ );
+ });
+ }
+
+ test('fetch accepts the id of an admitted explicit search result and hides an unadmitted one', async () => {
+ const { body: results } = await call(await bound(), 'search', { query: MARKER, source_id: 'notes' });
+ const fetched = await call(await bound(), 'fetch', { id: results[0].id });
+ expect(fetched.isError).toBe(false);
+ expect(fetched.body.metadata.source_id).toBe('notes');
+ const hidden = await call(await bound(), 'fetch', { id: encodeDeepResearchId('private', 'topics/private-topic') });
+ expect(hidden.body.error).toBe('page_not_found');
+ });
+
+ test('denials carry the docs anchor', async () => {
+ const { body } = await call(await bound(), 'search', { query: MARKER, source_id: 'private' });
+ expect(body.docs).toBe('docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection');
+ });
+
+ test('a target that opted out is named as opted out', async () => {
+ const { body } = await call(await bound(), 'search', { query: MARKER, source_id: 'iso' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toContain('iso opted out of federation (federated: false)');
+ expect(body.suggestion).toContain('`gbrain sources federate iso`');
+ });
+
+ test('unqualified reads stay scalar on the bound source', async () => {
+ expect(sourcesOf((await call(await bound(), 'search', { query: MARKER })).body)).toEqual(['work']);
+ expect(sourcesOf((await call(await bound(), 'list_pages', {})).body)).toEqual(['work']);
+ const hidden = await call(await bound(), 'get_page', { slug: 'topics/notes-topic' });
+ expect(hidden.isError).toBe(true);
+ });
+
+ test('__all__ is unchanged: it stays on the bound source', async () => {
+ const { body } = await call(await bound(), 'search', { query: MARKER, source_id: '__all__' });
+ expect(sourcesOf(body)).toEqual(['work']);
+ });
+
+ test('E-T2: an isolated anchor is refused with its own opt-out hint', async () => {
+ const { isError, body } = await call(await bound('iso'), 'search', { query: MARKER, source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.suggestion).toBe(
+ 'This connection is bound to source iso (GBRAIN_SOURCE). iso opted out of federation (federated: false), so it '
+ + 'reads no other source; the brain owner can run `gbrain sources federate iso` on the brain host, or start this '
+ + 'connection without GBRAIN_SOURCE.',
+ );
+ const own = await call(await bound('iso'), 'search', { query: MARKER, source_id: 'iso' });
+ expect(sourcesOf(own.body)).toEqual(['iso']);
+ });
+
+ test('.gbrain-source binding names the pin in its hint', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5081-pin-'));
+ writeFileSync(join(dir, '.gbrain-source'), 'work\n');
+ const opts = await stdioOpts({ GBRAIN_SOURCE: undefined }, dir);
+ expect(sourcesOf((await call(opts, 'search', { query: MARKER, source_id: 'notes' })).body)).toEqual(['notes']);
+ const { body } = await call(opts, 'search', { query: MARKER, source_id: 'private' });
+ expect(body.suggestion).toBe(
+ 'This connection is bound to source work (.gbrain-source). private is not federated; the brain owner can run '
+ + '`gbrain sources federate private` on the brain host, or start this connection outside the directory pinned by .gbrain-source.',
+ );
+ });
+});
+
+describe('#5081 — callers that pass no admission set keep denying (ENG-O6 pins)', () => {
+ const ORIGINAL_HINT = 'Request access to this source, or omit source_id to search within your grant.';
+
+ test('search_by_image still denies an explicit federated source', async () => {
+ const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
+ const { isError, body } = await call(await bound(), 'search_by_image', { image_data: png, source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(ORIGINAL_HINT);
+ });
+
+ test('open_loops still denies an explicit federated source', async () => {
+ const { isError, body } = await call(await bound(), 'open_loops', { source_id: 'notes' });
+ expect(isError).toBe(true);
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(ORIGINAL_HINT);
+ });
+
+ test('code-intel scope resolution still denies an explicit federated source', async () => {
+ // The code_* ops are closed to agent callers outright, so pin the resolver they share.
+ const ctx = buildOperationContext(engine, {}, await bound()) as OperationContext;
+ expect(() => resolveCodeIntelScope(ctx, 'notes')).toThrow(expect.objectContaining({
+ code: 'permission_denied', suggestion: ORIGINAL_HINT,
+ }));
+ });
+
+ test('requireWritablePage is unchanged: a page in an admitted source is still not writable or disclosed', async () => {
+ const opts = await bound();
+ const ctx = buildOperationContext(engine, {}, opts) as OperationContext;
+ await expect(requireWritablePage(ctx, 'topics/notes-topic', 'add_link', 'from')).rejects.toMatchObject({
+ code: 'page_not_found',
+ });
+ });
+});
+
+describe('#5081 — HTTP tokens and unbound stdio keep the no-widening rule', () => {
+ async function noGrantOpts(): Promise<DispatchOpts> {
+ const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'default', hasSourceGrant: false } as AuthInfo;
+ return {
+ remote: true, transport: 'http', sourceId: 'default', auth,
+ localFederatedSourceIds: await noGrantFederatedScope(engine, false, 'default'),
+ };
+ }
+
+ test('no-grant token: an explicit federated read is admitted and is a subset of its unqualified read', async () => {
+ const opts = await noGrantOpts();
+ const explicit = sourcesOf((await call(opts, 'search', { query: MARKER, source_id: 'notes' })).body);
+ const unqualified = sourcesOf((await call(opts, 'search', { query: MARKER })).body);
+ expect(explicit).toEqual(['notes']);
+ for (const id of explicit) expect(unqualified).toContain(id);
+ });
+
+ test('no-grant token: a source outside the federated set is denied as not federated', async () => {
+ const { body } = await call(await noGrantOpts(), 'search', { query: MARKER, source_id: 'private' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(
+ 'private is not federated; the brain owner can run `gbrain sources federate private` on the brain host, '
+ + 'or omit source_id to read within this connection\'s sources.',
+ );
+ });
+
+ test('unbound stdio: an explicit federated read is a subset of its unqualified read', async () => {
+ const opts = await stdioOpts({ GBRAIN_SOURCE: undefined });
+ const explicit = sourcesOf((await call(opts, 'search', { query: MARKER, source_id: 'notes' })).body);
+ const unqualified = sourcesOf((await call(opts, 'search', { query: MARKER })).body);
+ expect(explicit).toEqual(['notes']);
+ for (const id of explicit) expect(unqualified).toContain(id);
+ expect((await call(opts, 'search', { query: MARKER, source_id: 'private' })).isError).toBe(true);
+ });
+
+ test('a granted OAuth token is told about its grant, with the filled rescope command', async () => {
+ const auth = {
+ token: '', clientId: 'client-a', scopes: ['read'], sourceId: 'work', allowedSources: ['work'],
+ principal: { kind: 'oauth_client', id: 'client-a' },
+ } as AuthInfo;
+ const opts: DispatchOpts = {
+ remote: true, transport: 'http', sourceId: 'work', auth,
+ localFederatedSourceIds: ['work', 'default', 'notes'],
+ };
+ const { body } = await call(opts, 'search', { query: MARKER, source_id: 'notes' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe(
+ 'Your token is not granted notes; ask the brain owner to grant it '
+ + '(gbrain auth rescope-client client-a --federated-read work,notes).',
+ );
+ });
+
+ test('a granted legacy token is told to ask for a grant', async () => {
+ const auth = { token: '', clientId: 'legacy', scopes: ['read'], sourceId: 'work', hasSourceGrant: true } as AuthInfo;
+ const { body } = await call({ remote: true, transport: 'http', sourceId: 'work', auth }, 'search', { query: MARKER, source_id: 'notes' });
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toBe('Your token is not granted notes; ask the brain owner to grant it.');
+ });
+});
diff --git a/test/file-upload-security.test.ts b/test/file-upload-security.test.ts
index 9319ed3e18..5e4b2a78fc 100644
--- a/test/file-upload-security.test.ts
+++ b/test/file-upload-security.test.ts
@@ -132,6 +132,18 @@ describe('validatePageSlug', () => {
expect(() => validatePageSlug('people/my_file_name')).not.toThrow();
});
+ it('accepts colon-separated namespace parts (#5032)', () => {
+ expect(() => validatePageSlug('calendar:abc123def456')).not.toThrow();
+ expect(() => validatePageSlug('integrations/calendar:event-123')).not.toThrow();
+ });
+
+ it('rejects empty or dot-led colon namespace parts (#5032)', () => {
+ expect(() => validatePageSlug('calendar:')).toThrow(OperationError);
+ expect(() => validatePageSlug(':event')).toThrow(OperationError);
+ expect(() => validatePageSlug('calendar::event')).toThrow(OperationError);
+ expect(() => validatePageSlug('calendar:../event')).toThrow(OperationError);
+ });
+
it('accepts underscore-LED segments the slugifier produces (Hugo _index shape, #4665)', () => {
// slugifySegment('_index') === '_index' — leading underscores survive
// sync, so the op boundary must round-trip them too. Dots stay
diff --git a/test/fix-wave-3-integration.test.ts b/test/fix-wave-3-integration.test.ts
index 2d92e0ede3..49c98ed9be 100644
--- a/test/fix-wave-3-integration.test.ts
+++ b/test/fix-wave-3-integration.test.ts
@@ -40,7 +40,7 @@ import { localHostId, registerLocalWriter, withVerifiedLocalRegistration } from
import { runPersistenceEffects } from '../src/core/persistence/effects.ts';
import { runReconcileApply, runReconcilePreview } from '../src/core/persistence/reconcile.ts';
import { resolveRepairScope } from '../src/core/repair/core.ts';
-import { REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';
+import { AUTO_REPAIR_REGISTRY, repairRunner } from '../src/core/repair/registry.ts';
import { planRepairSteps } from '../src/core/remediation/repairs.ts';
import { runWaveChecks, remoteWaveHandoff, WAVE_CHECKS } from '../src/commands/doctor/wave-checks.ts';
import { writerVersionCheck } from '../src/commands/doctor/checks/writer-version.ts';
@@ -430,7 +430,7 @@ test('check 9: every registered repair kind reaches the remediation plan with it
await disposePersistenceConsumer(engine);
await engine.executeRaw("UPDATE pages SET contextual_retrieval_mode=NULL,chunker_version=1,text_projection_revision=gen_random_uuid() WHERE source_id=$1 AND slug='people/second-example'", [f.id]);
await engine.executeRaw("INSERT INTO op_checkpoints(op,fingerprint,completed_keys,updated_at) VALUES('managed-connector',$1,'[]'::jsonb,now()-interval '9 days')", [`orphan-${randomUUID()}`]);
- const kinds = REPAIR_REGISTRY.map(spec => spec.kind);
+ const kinds = AUTO_REPAIR_REGISTRY.map(spec => spec.kind);
expect(kinds).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints', 'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);
const planned = Object.fromEntries((await planRepairSteps(engine, { noEmbed: true })).map(step => [step.kind, step]));
expect(planned['contextual-mode']).toMatchObject({ paid: false, embeds: 'inline', command: 'gbrain repair contextual-mode --no-embed --apply' });
diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.ts
index 696948d0f0..0c53d5db09 100644
--- a/test/fix-wave-4-integration.test.ts
+++ b/test/fix-wave-4-integration.test.ts
@@ -49,7 +49,7 @@ import { readAllSourceHolds } from '../src/core/connectors/item-holds-store.ts';
import { retryHeld } from '../src/commands/sources-retry-held.ts';
import { planRepairSteps } from '../src/core/remediation/repairs.ts';
import { runRemediate } from '../src/commands/doctor/remediate.ts';
-import { REPAIR_REGISTRY } from '../src/core/repair/registry.ts';
+import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';
import { capture } from './helpers/wave-scenarios.ts';
import { createConnectorFixture, contact, json, options, withGoogleAccount } from './helpers/connector-fixture.ts';
import { addThread, fakeGmail, gmailFetch } from './helpers/connector-holds-fixture.ts';
@@ -149,7 +149,7 @@ test('X4: the v0.32.2 facts adoption on a connector page publishes above the tim
}
}), 240_000);
-test('X6: deactivate refuses while a connector item is held (classic mode cannot read managed holds); after the printed exit it succeeds and the dispatch gate stays open', async () => withEnv(env, async () => {
+test('X6: deactivate carries a held connector item into classic state (wave 5): it stays held after the mode change, the retry-held exit still clears it, and the dispatch gate stays open', async () => withEnv(env, async () => {
const account = '[email protected]';
const gmailConfig = { kind: 'google', g_account: account, g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
for (const engine of engines) {
@@ -166,27 +166,29 @@ test('X6: deactivate refuses while a connector item is held (classic mode cannot
const settle = () => engine.transaction(async tx => { await declarePersistenceProtocol(tx); await tx.executeRaw("UPDATE persistence_effects SET state='committed' WHERE state<>'committed'"); });
await settle();
- const dry = await runPersistenceAdministration(engine, 'writer_deactivate', { dry_run: true }) as { blockers: Array<{ kind: string; source_id?: string; exit: string }>; apply_command?: string };
- const held = dry.blockers.find(b => b.kind === 'connector_holds');
- expect(held).toMatchObject({ source_id: f.id, exit: expect.stringContaining(`gbrain sources retry-held ${f.id}`) });
- expect(dry.apply_command).toBeUndefined();
- await expect(runPersistenceAdministration(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: await writerAdminState(engine) }))
- .rejects.toMatchObject({ code: 'writer_not_quiesced' });
+ // The held item no longer blocks: the dry run names where it will be carried and prints the apply command.
+ const dry = await runPersistenceAdministration(engine, 'writer_deactivate', { dry_run: true }) as {
+ blockers: Array<{ kind: string; source_id?: string }>; apply_command?: string; carried_holds?: Array<{ source_id: string; items: number; state_file: string }> };
+ expect(dry.blockers.filter(b => b.kind === 'connector_holds' && b.source_id === f.id)).toEqual([]);
+ expect(dry.carried_holds).toContainEqual({ source_id: f.id, items: 1, state_file: join(f.dir, '.google-source.json') });
+ const expected = /--expected-state ([a-f0-9]{64})$/.exec(dry.apply_command ?? '')?.[1];
+ expect(expected).toBeDefined();
+ const done = await runPersistenceAdministration(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: expected }) as Record<string, unknown>;
+ expect(done).toMatchObject({ mode: 'classic', deactivated: true });
+ expect(done.carried_holds).toContainEqual({ source_id: f.id, items: 1, state_file: join(f.dir, '.google-source.json') });
+
+ // Classic mode reads the carried hold, and a classic run keeps it held while the upstream error persists.
+ expect((await readAllSourceHolds(engine, { sourceIds: [f.id] }))[0]?.held.map(h => h.key)).toEqual(['a1b2c3d4e5f60302']);
+ await run();
+ expect((await readAllSourceHolds(engine, { sourceIds: [f.id] }))[0]?.held.map(h => h.key)).toEqual(['a1b2c3d4e5f60302']);
- // The printed exit: retry the held thread (recovered upstream) and sync; the hold clears and deactivate proceeds.
+ // The printed exit still works in classic mode: retry the held thread (recovered upstream) and sync; the hold clears.
await retryHeld(engine, f.id);
fx.failThreads.delete('a1b2c3d4e5f60302');
fx.fetched.length = 0;
expect((await run()).status).not.toBe('partial');
- await disposePersistenceConsumer(engine);
expect(fx.fetched).toContain('a1b2c3d4e5f60302');
expect(await readAllSourceHolds(engine, { sourceIds: [f.id] })).toEqual([]);
- await settle();
- const clean = await runPersistenceAdministration(engine, 'writer_deactivate', { dry_run: true }) as { apply_command?: string };
- const expected = /--expected-state ([a-f0-9]{64})$/.exec(clean.apply_command ?? '')?.[1];
- expect(expected).toBeDefined();
- const done = await runPersistenceAdministration(engine, 'writer_deactivate', { admin_intent: 'writer_deactivate', expected_state: expected }) as Record<string, unknown>;
- expect(done).toMatchObject({ mode: 'classic', deactivated: true });
// Lane B's gate survives Lane D's mode change: autopilot keeps dispatching the connector.
expect((await attemptedConnectorSourceIds(engine)).has(f.id)).toBe(true);
@@ -207,7 +209,7 @@ test('X6: deactivate refuses while a connector item is held (classic mode cannot
test('X11: the remediation run reaches every new repair kind, runs the free ones under --max-usd 0 and clears their doctor findings', async () => withEnv(env, async () => {
for (const engine of engines) {
- expect(REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints',
+ expect(AUTO_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(['timeline', 'visibility', 'safe-chunks', 'contextual-mode', 'connector-checkpoints',
'request-indexes', 'connector-fences', 'orphan-bindings', 'embedding-effects']);
// Pending work for Lane A (a dropped index) and Lane D (an orphan binding of a removed source).
await engine.executeRaw('DROP INDEX IF EXISTS persistence_requests_sync_run_open');
diff --git a/test/fix-wave-5-integration.test.ts b/test/fix-wave-5-integration.test.ts
new file mode 100644
index 0000000000..be41dbbea3
--- /dev/null
+++ b/test/fix-wave-5-integration.test.ts
@@ -0,0 +1,364 @@
+/**
+ * Fix wave 5 cross-lane journeys (ENG-O14), PGLite here and PostgreSQL through
+ * test/e2e/fix-wave-5-integration.test.ts. The mounted-resident journeys
+ * (#5237 with #5401 and #5195; #5157 /ingest through a mounted serve) need
+ * real serve children and live in test/fix-wave-5-mounted.serial.test.ts.
+ * Already covered by lane suites on this branch: #5770 with #5777
+ * (journey-atoms-sync-race), #5081 with #5032 (cross-lane-5081-5032) and the
+ * preview-helper contract (preview-approval).
+ *
+ * 1. #5731 restore on an upgraded managed brain with a projection backlog:
+ * the restore publishes, `gbrain projections drain` settles every queued
+ * page, recall and search find the restored fact, and a managed
+ * writeSingleFact for an absent entity stays a separate fact.
+ * 2. explicit_only with both real kinds (stale-atoms, extractor-facts) and
+ * their real doctor findings: `repair --all --apply`, the remediation
+ * plan, `doctor --remediate --include-repairs` and the post-upgrade
+ * banner list each with its preview command and never run it.
+ * 3. #5558 with the stop hook and session-end: two concurrent sessions and
+ * an older binary's buffer; no hook output carries buffered text, and the
+ * sweep still ingests the captured transcript.
+ * 4. #5790 with #5409: a 12,000-file source onboards as a read-only mirror
+ * with a compact manifest; its syncs import database-only and the
+ * checkout stays byte-identical.
+ * Only the providers behind the chat transport are simulated; every step
+ * goes through the real repair, doctor, drain, hook, sweep, lifecycle and
+ * sync entry points.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { operations } from '../src/core/operations.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { extractorFactsCheck } from '../src/commands/doctor/checks/extractor-facts.ts';
+import { drainProjections } from '../src/commands/projections.ts';
+import { projectionBacklog } from '../src/core/page-state/projections.ts';
+import { checkProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { postUpgradeRecoveryBanner } from '../src/commands/doctor/upgrade-banner.ts';
+import { runRemediate, runRemediationPlan } from '../src/commands/doctor/remediate.ts';
+import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';
+import { HOOK_EVENTS, runHook } from '../src/commands/hook.ts';
+import { CORPUS_INGESTED_SUFFIX, runMaintenanceSweep } from '../src/core/sweep.ts';
+import { __setChatTransportForTests, resetGateway, type ChatResult } from '../src/core/ai/gateway.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { worktreeManifest } from '../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { writeLargeWorktree } from './helpers/large-worktree.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { isolatedSharedSkillsEngine } from './helpers/shared-skills-engine.ts';
+import { capture } from './helpers/wave-scenarios.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const ENTITY = 'people/alice-example';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-fix-wave-5-'));
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+const CLAIM = 'Alice Example will send the signed contract by Friday.';
+const CHAT = [
+ '**Alice Example** (2024-03-15 9:00 AM): I will send the signed contract by Friday, the quokka-ledger draft.',
+ '**Bob Demo** (2024-03-15 9:01 AM): Great, thanks.',
+].join('\n');
+
+/** Runs `gbrain repair <args> --json` in-process and returns its first result. */
+async function repair(engine: BrainEngine, args: string[]) {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, [...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as { results: Array<{ apply_command: string; outcomes?: Record<string, number>; residuals: Record<string, number> }>;
+ explicit_kinds?: Array<{ kind: string; preview_command: string }> };
+}
+
+/** A page row plus its file in the claimed worktree, as a synced page has. */
+async function filedPage(engine: BrainEngine, root: string, slug: string, page: { type: string; title: string; compiled_truth: string }) {
+ const row = await engine.putPage(slug, page as never, { sourceId: 'default' });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${slug}.md`, row.id]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ mkdirSync(join(root, slug.split('/')[0]), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+}
+
+/** A real managed write of the page, then the pre-fix projection's effect on its extractor facts in the same transaction. */
+async function prefixExpire(engine: BrainEngine, ctx: OperationContext, slug: string): Promise<void> {
+ const receipt = await submitPageMutation(ctx, { operation: 'add_timeline_entry',
+ params: { request_id: randomUUID(), slug, date: '2026-03-01', summary: 'a pre-fix publication', source: 'operator' } }) as { request_id: string };
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw('UPDATE persistence_requests SET completed_at=now(), consumer_version=NULL WHERE request_id=$1::uuid', [receipt.request_id]);
+ await tx.executeRaw(`UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id='default' AND source_markdown_slug=$1
+ AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL`, [slug]);
+ }));
+}
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+
+ describe(`#5731 restore with managed writeSingleFact and the #5401 drain (${backend})`, () => {
+ test('restore, drain, recall and search find the restored fact; an absent entity stays separate', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const slug = 'conversations/synthetic-chat';
+ const extractor = async () => [{ fact: CLAIM, kind: 'commitment' as const, entity_slug: ENTITY,
+ confidence: 1, notability: 'high' as const, source: 'test', visibility: 'private' as const }];
+ expect((await runExtractConversationFactsCore(engine, { sourceId: 'default', overrideDisabled: true, extractor, types: ['conversation'] })).facts_inserted).toBe(1);
+ const [original] = await engine.executeRaw<{ id: number }>("SELECT id::int AS id FROM facts WHERE source_markdown_slug=$1 AND fact=$2", [slug, CLAIM]);
+ await prefixExpire(engine, ctx, slug);
+ const recall = operations.find(op => op.name === 'recall')!;
+ const recalled = async () => (await recall.handler(ctx, { entity: ENTITY }) as { facts: Array<{ fact_id: string }> }).facts.map(f => Number(f.fact_id));
+ expect(await recalled()).not.toContain(original.id);
+
+ // The upgrade across v0.51 left every page's text projection queued (the protocol activation backlog); half of it the
+ // resident last failed, so it waits out the resident's 30-second retry cooldown and only the drain takes it now.
+ await disposePersistenceConsumer(engine);
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='default'");
+ await tx.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,CASE WHEN p.slug LIKE 'notes/backlog-%' AND right(p.slug,1) IN ('0','2','4','6','8') THEN 'rebuild_failed' ELSE 'protocol_activation' END
+ FROM pages p JOIN sources s ON s.id=p.source_id
+ WHERE p.source_id='default' AND p.deleted_at IS NULL ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason`);
+ }));
+ const queued = (await projectionBacklog(engine)).pending;
+ expect(queued).toBe(152);
+ const cooling = (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM page_projection_jobs WHERE reason='rebuild_failed'"))[0].n;
+ expect(cooling).toBe(75);
+ const before = await checkProjectionReadiness(engine);
+ expect(before.status).toBe('warn');
+ expect(before.message).toContain('Run `gbrain projections drain`');
+
+ const doctor = await extractorFactsCheck(engine);
+ expect(doctor.details).toMatchObject({ evidenced: 2, ambiguous: 0 });
+ const preview = await repair(engine, ['extractor-facts']);
+ const applied = await repair(engine, preview.results[0].apply_command.split(' ').slice(2));
+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });
+ // The repair CLI exits; its in-process owner may have rebuilt part of the backlog while idle. The drain takes the rest.
+ await disposePersistenceConsumer(engine);
+ const left = (await projectionBacklog(engine)).pending;
+ expect(left).toBeGreaterThanOrEqual(cooling);
+ const drained = await drainProjections(engine);
+ expect(drained).toMatchObject({ failed: [], remaining: 0 });
+ expect(drained.rebuilt + drained.superseded).toBe(left);
+ expect(await checkProjectionReadiness(engine)).toMatchObject({ status: 'ok' });
+ expect(await engine.executeRaw(`SELECT slug FROM pages WHERE source_id='default' AND deleted_at IS NULL
+ AND text_projection_revision IS DISTINCT FROM knowledge_revision`)).toEqual([]);
+ expect(await recalled()).toContain(original.id);
+ const searched = await recall.handler(ctx, { query: 'quokka-ledger' }) as { results?: Array<{ slug: string }> };
+ expect(searched.results?.map(r => r.slug)).toContain(slug);
+
+ const absent = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'Carol Absent', kind: 'commitment' });
+ expect(absent).toMatchObject({ status: 'inserted', entity_slug: 'carol-absent' });
+ expect(absent.id).not.toBe(original.id);
+ expect(await recalled()).toContain(original.id);
+ expect((await extractorFactsCheck(engine)).status).toBe('ok');
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ await filedPage(engine, root, ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example' });
+ await filedPage(engine, root, 'conversations/synthetic-chat', { type: 'conversation', title: 'Synthetic chat', compiled_truth: CHAT });
+ for (let i = 0; i < 150; i++) await engine.putPage(`notes/backlog-${i}`, { type: 'note', title: `Backlog ${i}`, compiled_truth: `Backlog note ${i}.` }, { sourceId: 'default' });
+ } });
+ }, 180_000);
+ });
+
+ describe(`explicit_only across repair --all, the remediation plan, remediate and the banner (${backend})`, () => {
+ test('both real kinds are listed with their preview command and never run', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ // 30 atoms of a deleted page (stale-atoms, origin_gone) and two expired extractor facts (extractor-facts, ambiguous when unmanaged).
+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'A page that was deleted.' }, { sourceId: 'default' });
+ for (let i = 0; i < 30; i++) {
+ await engine.putPage(`atoms/gone/claim-${i}`, { type: 'atom', title: `Claim ${i}`, compiled_truth: `Claim ${i} body.`,
+ frontmatter: { source_slug: 'notes/gone', source_hash: 'abcdef0123456789', extracted_at: '2026-09-01T00:00:00Z' } } as never, { sourceId: 'default' });
+ }
+ await engine.softDeletePage('notes/gone', { sourceId: 'default' });
+ await engine.putPage('conversations/expired', { type: 'note', title: 'Expired', compiled_truth: 'Alice: I will send the deck.' }, { sourceId: 'default' });
+ for (const fact of ['Alice sends the deck', 'Alice books the venue']) {
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session, row_num, source_markdown_slug, expired_at)
+ VALUES ('default', $1, $2, 'commitment', 'private', 'cli:extract-conversation-facts:sess', 'sess', NULL, 'conversations/expired', now())`, [ENTITY, fact]);
+ }
+ const liveAtoms = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE type='atom' AND deleted_at IS NULL"))[0].n;
+ const activeFacts = async () => (await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE source_markdown_slug='conversations/expired' AND expired_at IS NULL"))[0].n;
+ const untouched = async () => { expect(await liveAtoms()).toBe(30); expect(await activeFacts()).toBe(0); };
+ const previews = { 'stale-atoms': 'gbrain repair stale-atoms', 'extractor-facts': 'gbrain repair extractor-facts' };
+
+ // The post-upgrade banner names both findings with the kind's read-only preview.
+ const banner = await postUpgradeRecoveryBanner(engine, 'host');
+ expect(banner).toContain('[AGENT] atom_provenance_drift: 30 (explicit_kind_required; preview with: gbrain repair stale-atoms)');
+ expect(banner).toContain('[AGENT] extractor_facts_expired: 2 (explicit_kind_required; preview with: gbrain repair extractor-facts)');
+ expect(banner.join('\n')).not.toMatch(/--apply|--yes/);
+
+ // gbrain repair --all --apply runs every automatic kind, lists the explicit ones and exits 0.
+ const all = await capture(() => runRepairCommand(engine, ['--all', '--apply', '--json']));
+ const allBody = JSON.parse(all.out) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string }> };
+ expect(allBody.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));
+ expect(allBody.explicit_kinds.map(n => [n.kind, n.code, n.preview_command])).toEqual(Object.entries(previews).map(([kind, cmd]) => [kind, 'explicit_kind_required', cmd]));
+ expect(all.exit).toBe(0);
+ await untouched();
+
+ // gbrain doctor --remediation-plan lists them apart from the repair steps, with no apply command.
+ const plan = JSON.parse((await capture(() => runRemediationPlan(engine, ['--remediation-plan', '--no-embed', '--json']))).out) as {
+ repair_steps: Array<{ kind: string; command: string }>; explicit_repairs: Array<{ kind: string; preview_command: string }> };
+ expect(plan.repair_steps.map(step => step.kind).filter(kind => kind in previews)).toEqual([]);
+ expect(plan.explicit_repairs.map(n => [n.kind, n.preview_command])).toEqual(Object.entries(previews));
+ const planText = (await capture(() => runRemediationPlan(engine, ['--remediation-plan', '--no-embed']))).out;
+ expect(planText).toContain(' stale-atoms: gbrain repair stale-atoms');
+ expect(planText).toContain(' extractor-facts: gbrain repair extractor-facts');
+ expect(planText).not.toMatch(/gbrain repair (stale-atoms|extractor-facts) --apply/);
+
+ // gbrain doctor --remediate --include-repairs never runs them; each finding says explicit_kind_required with the preview.
+ const run = JSON.parse((await capture(() => runRemediate(engine, ['--remediate', '--yes', '--include-repairs', '--no-embed', '--max-usd', '0', '--json']))).out) as {
+ repairs?: Array<{ kind: string }>; findings: Array<{ check_id: string; class: string; repair_kind?: string; command?: string }> };
+ expect((run.repairs ?? []).map(r => r.kind).filter(kind => kind in previews)).toEqual([]);
+ expect(run.findings.filter(f => f.class === 'explicit_kind_required').map(f => [f.check_id, f.repair_kind, f.command])).toEqual([
+ ['atom_provenance_drift', 'stale-atoms', previews['stale-atoms']], ['extractor_facts_expired', 'extractor-facts', previews['extractor-facts']]]);
+ await untouched();
+
+ // Named, each previews the same set it was listed for.
+ expect((await repair(engine, ['stale-atoms'])).results[0].residuals).toEqual({ origin_gone: 30, origin_changed: 0 });
+ expect((await repair(engine, ['extractor-facts'])).results[0].residuals).toMatchObject({ evidenced: 0, ambiguous: 2 });
+ await untouched();
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ }), 240_000);
+ });
+
+ describe(`#5558 with the stop hook and session-end capture (${backend})`, () => {
+ test('no hook output carries buffered text, and session capture still ingests the transcript', async () => {
+ const hookHome = mkdtempSync(join(home, 'hooks-'));
+ const ws = join(hookHome, 'ws'), projects = join(hookHome, 'projects'), live = join(hookHome, '.gbrain', 'transcripts', 'live');
+ mkdirSync(ws, { recursive: true }); mkdirSync(join(projects, 'p1'), { recursive: true }); mkdirSync(live, { recursive: true });
+ const transcript = (id: string, text: string) => {
+ const path = join(projects, 'p1', `${id}.jsonl`);
+ writeFileSync(path, [JSON.stringify({ type: 'user', isSidechain: false, message: { role: 'user', content: text } }),
+ JSON.stringify({ type: 'assistant', isSidechain: false, message: { role: 'assistant', content: [{ type: 'text', text: `Noted: ${text}` }] } })].join('\n') + '\n');
+ return path;
+ };
+ const secrets = ['session-a-stop-marker', 'session-b-stop-marker', 'older-binary-buffer-marker'];
+ // A buffer an older binary left behind for a third session.
+ writeFileSync(join(live, 'older.txt'), JSON.stringify({ ts: '2026-09-30T09:00:00Z', session_id: 'older', exchange: secrets[2] }) + '\n');
+ const sessions = { 'sess-a': transcript('sess-a', 'I moved the zebra-capture-marker launch to Thursday.'), 'sess-b': transcript('sess-b', 'Unrelated planning for the other agent.') };
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await withEnv({ GBRAIN_HOME: hookHome, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_SOURCE: undefined, GBRAIN_HOOKS: undefined,
+ GBRAIN_STOP_PUSH: undefined, GBRAIN_MEMORABLE: undefined, CLAUDE_CODE_REMOTE: undefined }, async () => {
+ const outputs: Record<string, string> = {};
+ const hook = async (event: string, sessionId: string, extra: Record<string, unknown> = {}) => {
+ let out = '';
+ const code = await runHook([event], { write: (s: string) => { out += s; }, cwd: ws, spawnPush: () => {}, spawnBackupCheck: () => {}, transcriptRoot: projects,
+ stdin: JSON.stringify({ session_id: sessionId, cwd: ws, transcript_path: sessions[sessionId as keyof typeof sessions], source: 'resume', ...extra }) });
+ expect(code).toBe(0);
+ outputs[`${event}:${sessionId}`] = (outputs[`${event}:${sessionId}`] ?? '') + out;
+ };
+ // Both sessions run concurrently on one host; each stop carries its last assistant message.
+ await Promise.all([hook('stop', 'sess-a', { last_assistant_message: secrets[0] }), hook('stop', 'sess-b', { last_assistant_message: secrets[1] })]);
+ expect(readdirSync(live)).toEqual(['older.txt']);
+ for (const event of HOOK_EVENTS.filter(e => e !== 'session-end')) for (const id of ['sess-b', 'sess-a']) await hook(event, id);
+ await hook('session-end', 'sess-a');
+ for (const [key, out] of Object.entries(outputs)) {
+ for (const secret of secrets) expect(`${key}: ${out}`).not.toContain(secret);
+ if (key.endsWith('sess-b')) expect(out).not.toContain('zebra-capture-marker');
+ }
+
+ // Session capture: session-end wrote A's transcript to the corpus, and the sweep ingests it.
+ const corpus = join(hookHome, '.gbrain', 'transcripts', 'corpus');
+ const files = readdirSync(corpus).filter(name => name.endsWith('.txt'));
+ expect(files.some(name => name.startsWith('sess-a'))).toBe(true);
+ for (const name of files) for (const secret of secrets) expect(readFileSync(join(corpus, name), 'utf8')).not.toContain(secret);
+ await engine.setConfig('dream.synthesize.session_corpus_dir', corpus);
+ const prompts: string[] = [];
+ __setChatTransportForTests(async (req: unknown): Promise<ChatResult> => {
+ const prompt = JSON.stringify(req);
+ prompts.push(prompt);
+ const facts = prompt.includes('zebra-capture-marker') ? [{ fact: 'The zebra launch moved to Thursday.', kind: 'event', entity: null, confidence: 1, notability: 'high' }] : [];
+ return { text: JSON.stringify({ facts }),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ });
+ const swept = await runMaintenanceSweep(engine, { sourceId: 'default', capabilities: { embeddings: { available: false },
+ extraction: { available: true, provider: 'anthropic' }, search: 'keyword-only', mode: 'keyed' } });
+ expect(swept.corpusIngested).toBeGreaterThanOrEqual(1);
+ expect(prompts.some(prompt => prompt.includes('zebra-capture-marker'))).toBe(true);
+ for (const prompt of prompts) for (const secret of secrets) expect(prompt).not.toContain(secret);
+ expect(files.filter(name => name.startsWith('sess-a')).every(name => existsSync(join(corpus, name + CORPUS_INGESTED_SUFFIX)))).toBe(true);
+ const facts = await engine.executeRaw<{ fact: string }>("SELECT fact FROM facts WHERE fact LIKE '%zebra launch%'");
+ expect(facts.length).toBeGreaterThanOrEqual(1);
+ });
+ } finally { __setChatTransportForTests(null); resetGateway(); await disposePersistenceConsumer(engine); await close(); }
+ }, 120_000);
+ });
+
+ describe(`#5790 with #5409: a 12k-file read-only mirror (${backend})`, () => {
+ test('a 12,000-file source onboards as a read-only mirror; its syncs stay database-only', async () => {
+ const mirrorHome = mkdtempSync(join(home, 'mirror-'));
+ const { engine, close } = await isolatedSharedSkillsEngine(databaseUrl);
+ try {
+ await withEnv({ GBRAIN_HOME: mirrorHome, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const id = 'large-mirror', root = join(mirrorHome, 'checkout');
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const commit = (message: string) => { git('add', '-A'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); };
+ writeLargeWorktree(root, 12_000);
+ writeFileSync(join(root, 'TODOS.md'), '# Todos\n\n- keep the mirror pullable\n');
+ mkdirSync(join(root, 'journal'));
+ for (const day of ['2026-09-29', '2026-09-30']) writeFileSync(join(root, 'journal', `${day}.md`), `# ${day}\n\nA journal entry without frontmatter.\n`);
+ git('init', '-q'); commit('upstream');
+ const tracked = () => git('status', '--porcelain', '--untracked-files=no');
+
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: id, path: root })).toMatchObject({ state: 'committed' });
+ const [manifest] = await engine.executeRaw<{ manifest: Record<string, unknown> | string }>(`SELECT w.manifest FROM persistence_worktrees w
+ JOIN persistence_source_bindings b ON b.worktree_id=w.id WHERE b.source_id=$1`, [id]);
+ const stored = typeof manifest.manifest === 'string' ? JSON.parse(manifest.manifest) : manifest.manifest;
+ expect(stored).toMatchObject({ digest: worktreeManifest(root).digest, file_count: 12_003 });
+ expect(stored.files).toBeUndefined();
+ const lines: string[] = [];
+ const log = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runSources(engine, ['mirror-readonly', id]); } finally { console.log = log; }
+ expect(lines.join('\n')).toContain(`Source "${id}" is now a read-only mirror`);
+
+ // The full import costs ~80 ms per file on PGLite (~16 minutes at 12k), so the bulk folder is excluded from import with the
+ // operator's own knob; discovery still walks the whole 12k-file tree, and the checkout stays byte-identical throughout.
+ await engine.setConfig('sync.exclude', 'notes/');
+ const first = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ await disposePersistenceConsumer(engine);
+ expect(first).toMatchObject({ status: 'first_sync' });
+ expect(first.failureCodes ?? []).toEqual([]);
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [id]))[0].n).toBe(3);
+ expect(tracked()).toBe('');
+ expect(worktreeManifest(root).digest).toBe(stored.digest);
+
+ // A database-only tag makes the page's canonical form differ from its bytes; an upstream edit then syncs database-only.
+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.addTag('todos', 'kept-in-brain', { sourceId: id })));
+ writeFileSync(join(root, 'TODOS.md'), '# Todos\n\n- keep the mirror pullable\n- and syncing\n');
+ commit('upstream edit');
+ const next = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, noExtract: true });
+ await disposePersistenceConsumer(engine);
+ expect(next).toMatchObject({ filesImported: 1 });
+ expect(tracked()).toBe('');
+ expect(readFileSync(join(root, 'TODOS.md'), 'utf8')).not.toContain('kept-in-brain');
+ const snapshot = (await engine.readPageSnapshot('todos', { sourceId: id }))!;
+ expect(snapshot.page.compiled_truth).toContain('and syncing');
+ expect(snapshot.tags).toContain('kept-in-brain');
+ const [receipt] = await engine.executeRaw<{ outcome: Record<string, unknown> }>(
+ "SELECT outcome FROM persistence_requests WHERE source_id=$1 AND slug='todos' AND state='committed' ORDER BY sequence DESC LIMIT 1", [id]);
+ expect(receipt.outcome).toMatchObject({ storage: 'database_only', write_through: { written: false, skipped: 'mirror_read_only' } });
+ // The checkout still matches the stored 12k-file manifest, so later lifecycle steps (rebind, transfer) keep their proof.
+ git('reset', '-q', '--hard', 'HEAD~1');
+ expect(worktreeManifest(root).digest).toBe(stored.digest);
+ });
+ } finally { await disposePersistenceConsumer(engine); await close(); }
+ }, 240_000);
+ });
+}
diff --git a/test/fix-wave-5-mounted.serial.test.ts b/test/fix-wave-5-mounted.serial.test.ts
new file mode 100644
index 0000000000..b561297bd1
--- /dev/null
+++ b/test/fix-wave-5-mounted.serial.test.ts
@@ -0,0 +1,239 @@
+/**
+ * Fix wave 5 cross-lane journeys on a mounted PGLite brain (ENG-O14), with
+ * real `gbrain serve` and CLI subprocesses under a sandboxed HOME and a
+ * non-default GBRAIN_HOME (so #5195 gives this brain its own autopilot job):
+ *
+ * - #5237 + #5401 + #5195: a resident serve started in a `.gbrain-mount`
+ * project owns the mount; `gbrain projections drain` refuses with
+ * projection_owner_resident naming the mount and printing stop/drain/
+ * restart steps with this brain's autopilot names; a CLI write commits
+ * through the mounted owner; the printed manual-serve steps drain it.
+ * - #5157 + #5237: `POST /ingest` on `gbrain serve --http` in that project
+ * returns 409 with the hint for a legacy live row of the mount, and after
+ * the printed recovery commands it returns 202.
+ *
+ * Serial: real serve children bind sockets and hold PGLite locks; each is
+ * stopped in afterEach. A real launchd/systemd job is not installed: the
+ * install id is minted the way `gbrain autopilot --install` mints it.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { createServer } from 'node:net';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createEngine } from '../src/core/engine-factory.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { persistenceSocketPathForConfig } from '../src/core/persistence/ipc.ts';
+import { ensureAutopilotInstallId, resolveAutopilotJob } from '../src/core/autopilot-paths.ts';
+import { argv } from './helpers/legacy-journey.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+const CLI = join(REPO_ROOT, 'src', 'cli.ts');
+const MOUNT = 'example-mount';
+
+let root: string, userHome: string, brainHome: string, hostDb: string, mountDb: string, project: string;
+let serve: ReturnType<typeof Bun.spawn> | null = null;
+let serveStderr = '';
+let job: { launchdLabel: string; systemdUnit: string };
+
+function env(): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) out[key] = value;
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'GBRAIN_AUTOPILOT_LABEL', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']) delete out[key];
+ return { ...out, HOME: userHome, GBRAIN_HOME: brainHome, GBRAIN_MOUNTS_PATH: join(brainHome, '.gbrain', 'mounts.json'),
+ GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300' };
+}
+
+async function withBrain<T>(path: string, run: (engine: BrainEngine) => Promise<T>): Promise<T> {
+ const config = { engine: 'pglite' as const, database_path: path };
+ const engine = await createEngine(config);
+ await engine.connect(config);
+ try { return await run(engine); } finally { await engine.disconnect(); }
+}
+
+async function freePort(): Promise<number> {
+ return new Promise((resolvePort, reject) => {
+ const server = createServer();
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => { const { port } = server.address() as { port: number }; server.close(() => resolvePort(port)); });
+ });
+}
+
+/** Starts `gbrain serve [args]` in the project and waits until `ready` holds. */
+async function startServe(args: string[], ready: () => Promise<boolean>) {
+ serveStderr = '';
+ serve = Bun.spawn(['bun', 'run', CLI, 'serve', ...args], { cwd: project, env: env(), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ void (async () => {
+ const reader = (serve!.stderr as ReadableStream<Uint8Array>).getReader();
+ const decoder = new TextDecoder();
+ try { while (true) { const { value, done } = await reader.read(); if (done) break; serveStderr += decoder.decode(value, { stream: true }); } } catch { /* child gone */ }
+ })();
+ const deadline = Date.now() + 120_000;
+ while (!(await ready())) {
+ if (serve.exitCode !== null) throw new Error(`serve exited early (${serve.exitCode})\n${serveStderr}`);
+ if (Date.now() > deadline) throw new Error(`serve never became ready\n${serveStderr}`);
+ await Bun.sleep(150);
+ }
+}
+
+async function stopServe() {
+ if (!serve) return;
+ if (serve.exitCode === null) { serve.kill('SIGTERM'); await Promise.race([serve.exited, Bun.sleep(15_000)]); }
+ if (serve.exitCode === null) { serve.kill('SIGKILL'); await serve.exited; }
+ serve = null;
+}
+
+async function cli(args: string[], extra: Record<string, string> = {}) {
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd: project, env: { ...env(), ...extra }, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const timer = setTimeout(() => proc.kill('SIGKILL'), 120_000);
+ try {
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+ } finally { clearTimeout(timer); }
+}
+
+/** Runs a printed `gbrain …` command verbatim from the project. */
+async function printed(command: string) {
+ const args = argv(command);
+ expect(args[0]).toBe('gbrain');
+ return cli(args.slice(1));
+}
+
+const mountSocket = () => persistenceSocketPathForConfig({ engine: 'pglite', database_path: mountDb })!;
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-w5m-'));
+ userHome = join(root, 'u');
+ brainHome = join(root, 'h');
+ hostDb = join(root, 'hdb');
+ mountDb = join(root, 'mdb');
+ project = join(root, 'p');
+ for (const dir of [userHome, join(brainHome, '.gbrain'), project, join(root, 'mount-clone')]) mkdirSync(dir, { recursive: true });
+ writeFileSync(join(brainHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: hostDb }));
+ writeFileSync(join(brainHome, '.gbrain', 'mounts.json'), JSON.stringify({ version: 1, mounts: [
+ { id: MOUNT, path: join(root, 'mount-clone'), engine: 'pglite', database_path: mountDb, enabled: true },
+ ] }), { mode: 0o600 });
+ const dotfile = join(project, '.gbrain-mount');
+ writeFileSync(dotfile, `${MOUNT}\n`);
+ chmodSync(dotfile, 0o644);
+ for (const path of [hostDb, mountDb]) await withBrain(path, engine => engine.initSchema());
+ // #5195: this non-default home gets its own autopilot job once installed; mint its id as the installer does.
+ job = await withEnv({ HOME: userHome, GBRAIN_HOME: brainHome, GBRAIN_AUTOPILOT_LABEL: undefined }, async () => {
+ ensureAutopilotInstallId();
+ const resolved = resolveAutopilotJob();
+ expect(resolved.kind).toBe('suffixed');
+ return resolved;
+ });
+}, 240_000);
+
+afterEach(stopServe, 30_000);
+afterAll(() => { rmSync(root, { recursive: true, force: true }); });
+
+describe('#5237 + #5401 + #5195 on a mounted PGLite resident', () => {
+ test('drain refuses naming the mount with per-brain stop steps; a CLI write commits through the owner; the printed steps drain it', async () => {
+ // An upgraded mount with a queued projection backlog.
+ await withBrain(mountDb, async engine => {
+ for (let i = 0; i < 5; i++) await engine.putPage(`notes/backlog-${i}`, { type: 'note', title: `Backlog ${i}`, compiled_truth: `Backlog note ${i}.` }, { sourceId: 'default' });
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='default'");
+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,'protocol_activation' FROM pages p JOIN sources s ON s.id=p.source_id
+ WHERE p.deleted_at IS NULL ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision`);
+ });
+ await startServe([], async () => existsSync(mountSocket()));
+
+ const refused = await cli(['projections', 'drain', '--json']);
+ expect(refused.exitCode).toBe(2);
+ const body = JSON.parse(refused.stdout) as { error: string; message: string; suggestion: string };
+ expect(body.error).toBe('projection_owner_resident');
+ expect(body.message).toContain(`The PGLite brain at ${mountDb} is held by gbrain serve (pid ${serve!.pid})`);
+ expect(body.suggestion).toContain(`gbrain doctor --brain ${MOUNT}`);
+ expect(body.suggestion).toContain(`launchctl bootout gui/$(id -u)/${job.launchdLabel} && { gbrain projections drain --brain ${MOUNT};`);
+ expect(body.suggestion).toContain(`systemctl --user stop ${job.systemdUnit} && { gbrain projections drain --brain ${MOUNT}; systemctl --user start ${job.systemdUnit}; }`);
+ expect(body.suggestion).not.toMatch(/com\.gbrain\.autopilot[ .]plist|gbrain-autopilot\.service/);
+
+ const put = await cli(['put', 'notes/mounted-example', '--content', '# Mounted example\n\nWritten through the resident owner.']);
+ expect(put.stderr).not.toContain('owner_unavailable');
+ expect(put.exitCode).toBe(0);
+
+ // The printed manual-serve steps, verbatim: stop it, run the drain, start gbrain serve again.
+ const manual = /a manual gbrain serve: stop it \(kill (\d+)\), run (gbrain projections drain --brain \S+), then start gbrain serve again/.exec(body.suggestion);
+ expect(manual?.[1]).toBe(String(serve!.pid));
+ await stopServe();
+ const drained = await printed(`${manual![2]} --json`);
+ expect(drained.exitCode).toBe(0);
+ expect(JSON.parse(drained.stdout)).toMatchObject({ failed: [], remaining: 0 });
+ await startServe([], async () => existsSync(mountSocket()));
+ await stopServe();
+
+ await withBrain(mountDb, async engine => {
+ expect(await engine.getPage('notes/mounted-example', { sourceId: 'default' })).not.toBeNull();
+ expect(await engine.executeRaw(`SELECT slug FROM pages WHERE deleted_at IS NULL AND text_projection_revision IS DISTINCT FROM knowledge_revision`)).toEqual([]);
+ });
+ await withBrain(hostDb, async engine => { expect(await engine.getPage('notes/mounted-example', { sourceId: 'default' })).toBeNull(); });
+ }, 300_000);
+});
+
+describe('#5157 /ingest through a mounted serve owner', () => {
+ test('a legacy live row of the mount gives 409 with the hint; after the printed recovery commands /ingest returns 202', async () => {
+ // `gbrain auth` opens the host config's brain even inside a .gbrain-mount project, while the mounted serve verifies
+ // tokens against the mount; so the token is minted with a config that names the mount's datastore.
+ const tokenHome = join(root, 'token-home');
+ mkdirSync(join(tokenHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(tokenHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: mountDb }));
+ const created = await cli(['auth', 'create', 'w5-journey', '--scopes', 'read,write'], { GBRAIN_HOME: tokenHome });
+ expect(created.exitCode).toBe(0);
+ const token = (created.stdout.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];
+ expect(token).not.toBe('');
+ const port = await freePort();
+ const base = `http://127.0.0.1:${port}`;
+ const http = () => startServe(['--http', '--bind', '127.0.0.1', '--port', String(port)],
+ async () => { try { return (await fetch(`${base}/health`)).ok; } catch { return false; } });
+ const ingest = (content: string) => fetch(`${base}/ingest`, { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'text/markdown' }, body: content });
+ const content = '# Mounted capture\n\nThe mounted-ingest-marker note survives the v0.50 upgrade.';
+
+ // The capture was queued before the upgrade; the upgrade left its row with SQL NULL authority.
+ await http();
+ const first = await ingest(content);
+ expect(first.status).toBe(202);
+ const jobId = (await first.json() as { job_id: number }).job_id;
+ await stopServe();
+ await withBrain(mountDb, engine => engine.executeRaw("UPDATE minion_jobs SET status='waiting', submission_authority=NULL WHERE id=$1", [jobId]));
+
+ await http();
+ const refused = await ingest(content);
+ expect(refused.status).toBe(409);
+ const body = await refused.json() as { error: string; message: string; hint: string; docs_url: string };
+ expect(body).toMatchObject({ error: 'permission_denied', docs_url: 'docs/guides/repair.md#legacy-job-authority' });
+ expect(body.message).toContain(`job ${jobId} (ingest_capture, waiting)`);
+ expect(body.hint).toStartWith('Stop producers (gbrain serve, gbrain autopilot) and workers');
+
+ const commands: string[] = [];
+ await stopServe();
+ commands.push('stop gbrain serve');
+ const preview = /preview with (gbrain jobs authorize-legacy --select "[^"]+")/.exec(body.hint)?.[1];
+ expect(preview).toBeDefined();
+ const previewed = await printed(preview!);
+ expect(previewed.exitCode).toBe(0);
+ expect(previewed.stdout).toContain('(SQL NULL authority, authorizable): 1');
+ commands.push(preview!);
+ const apply = /Apply exactly this set: (.+)$/m.exec(previewed.stdout)?.[1];
+ expect(apply).toMatch(/--expect [a-f0-9]{64} --yes$/);
+ expect((await printed(apply!)).exitCode).toBe(0);
+ commands.push(apply!);
+ await http();
+ commands.push('restart gbrain serve');
+ const accepted = await ingest(content);
+ expect(accepted.status).toBe(202);
+ expect((await accepted.json() as { job_id: number }).job_id).toBe(jobId);
+ expect(commands.length).toBeLessThanOrEqual(6);
+ await stopServe();
+
+ await withBrain(mountDb, async engine => {
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs WHERE submission_authority IS NULL'))[0].n).toBe(0);
+ });
+ await withBrain(hostDb, async engine => {
+ expect((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM minion_jobs'))[0].n).toBe(0);
+ });
+ }, 300_000);
+});
diff --git a/test/fixtures/goldens/cli/dispatch-phase.json b/test/fixtures/goldens/cli/dispatch-phase.json
index 9a5e3aee69..04ccea0843 100644
--- a/test/fixtures/goldens/cli/dispatch-phase.json
+++ b/test/fixtures/goldens/cli/dispatch-phase.json
@@ -1108,6 +1108,25 @@
"thinClient": "none",
"thinClientRoutedSubcommands": []
},
+ "projections": {
+ "hasSwitchCase": false,
+ "phase": "pre-connect-own-engine",
+ "preConnectRules": [
+ {
+ "condition": "command === 'projections'",
+ "connectsEngine": true,
+ "refusesThinClient": false,
+ "routesThinClient": false,
+ "terminates": true,
+ "thinClientCheck": false,
+ "unconditionalFor": [
+ "projections"
+ ]
+ }
+ ],
+ "thinClient": "refuse",
+ "thinClientRoutedSubcommands": []
+ },
"protocol": {
"hasSwitchCase": false,
"phase": "pre-connect",
@@ -1807,6 +1826,16 @@
"thinClientCheck": false,
"unconditionalFor": []
},
+ {
+ "commands": [],
+ "condition": "command !== 'hook'",
+ "connectsEngine": false,
+ "refusesThinClient": false,
+ "routesThinClient": false,
+ "terminates": false,
+ "thinClientCheck": false,
+ "unconditionalFor": []
+ },
{
"commands": [
"ask"
diff --git a/test/fixtures/goldens/cli/engine-free-db-down.json b/test/fixtures/goldens/cli/engine-free-db-down.json
index b0fa02da90..b5e9c0dc05 100644
--- a/test/fixtures/goldens/cli/engine-free-db-down.json
+++ b/test/fixtures/goldens/cli/engine-free-db-down.json
@@ -273,13 +273,13 @@
"Usage: gbrain hook <event>",
"",
"Events (wired into .claude/settings.local.json by gbrain bootstrap):",
- " session-start print the greeting digest (MEMORY.md sections, last session,",
- " push status, hook health) to stdout",
+ " session-start print the greeting digest (MEMORY.md sections, push status,",
+ " hook health) to stdout",
" user-prompt read hook JSON on stdin, request per-turn context from a",
" running 'gbrain serve' over IPC, print additionalContext JSON",
" (--harness <claude-code|codex|opencode> sets the feedback-loop",
" channel; default claude-code, unknown values fall back to the default)",
- " stop append to the per-session live buffer",
+ " stop bank the writeback backstop and spawn the workspace push",
" session-end ingest the session transcript into the dream corpus",
" (secret-scanned), prune old corpus files, push the workspace",
" compact (PreCompact) bank the window's standing entities into the",
diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.json
index c81055b782..3ac9d41398 100644
--- a/test/fixtures/goldens/cli/help-and-errors.json
+++ b/test/fixtures/goldens/cli/help-and-errors.json
@@ -25,6 +25,7 @@
" upgrade Self-update",
" check-update [--json] Check for new versions",
" repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",
+ " projections drain [--limit n] Rebuild queued text projections now [--json]",
" doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)",
" integrations [subcommand] Manage integration recipes (senses + reflexes)",
"",
@@ -230,6 +231,7 @@
" upgrade Self-update",
" check-update [--json] Check for new versions",
" repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",
+ " projections drain [--limit n] Rebuild queued text projections now [--json]",
" doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)",
" integrations [subcommand] Manage integration recipes (senses + reflexes)",
"",
@@ -435,6 +437,7 @@
" upgrade Self-update",
" check-update [--json] Check for new versions",
" repair [<kind>] [--apply] Preview/apply residual repairs (timeline, visibility, safe-chunks)",
+ " projections drain [--limit n] Rebuild queued text projections now [--json]",
" doctor [--json] [--fast] [--probe-pglite] Health check (resolver, skills, pgvector, RLS, embeddings; --probe-pglite runs the scratch-store probe)",
" integrations [subcommand] Manage integration recipes (senses + reflexes)",
"",
diff --git a/test/fixtures/goldens/cli/membership-sets.json b/test/fixtures/goldens/cli/membership-sets.json
index 2bfc9201ee..2db3c0b660 100644
--- a/test/fixtures/goldens/cli/membership-sets.json
+++ b/test/fixtures/goldens/cli/membership-sets.json
@@ -152,6 +152,7 @@
"pages",
"pglite-repair",
"post-upgrade",
+ "projections",
"protocol",
"providers",
"publish",
@@ -235,6 +236,7 @@
"pages",
"pglite-repair",
"post-upgrade",
+ "projections",
"protocol",
"reindex",
"reinit-pglite",
@@ -302,6 +304,7 @@
"migrate",
"orphans",
"pages",
+ "projections",
"repair",
"repair-jsonb",
"retrieval-upgrade",
@@ -338,6 +341,7 @@
"migrate",
"orphans",
"pages",
+ "projections",
"quarantine",
"repair",
"repair-jsonb",
diff --git a/test/fixtures/goldens/doctor/early-stop-connection-failure.json b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
index 60174e785d..c9dc322bcf 100644
--- a/test/fixtures/goldens/doctor/early-stop-connection-failure.json
+++ b/test/fixtures/goldens/doctor/early-stop-connection-failure.json
@@ -213,6 +213,9 @@
"status": "ok"
},
{
+ "details": {
+ "health": "unknown"
+ },
"message": "atom provenance query returned no rows",
"name": "atom_provenance_drift",
"status": "warn"
@@ -242,6 +245,21 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"message": "Prepared statements disabled (PgBouncer-safe)",
"name": "pgbouncer_prepare",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
index ba73856cce..e18e630c06 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-connect-error.json
@@ -174,6 +174,21 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"details": {
"fix_hint": "Connection refused. If this is a Supabase direct URL (db.<ref>...:5432), switch to the transaction pooler (port 6543): gbrain db-repair can rewrite it. Run: gbrain db-repair",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
index 708731aab1..81fa2dd6a1 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-fast.json
@@ -174,6 +174,21 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"message": "Skipping DB checks (--fast mode, URL present from config-file)",
"name": "connection",
diff --git a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
index de529a7e28..2d4b0ed931 100644
--- a/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
+++ b/test/fixtures/goldens/doctor/early-stop-null-engine-no-config.json
@@ -169,6 +169,21 @@
"name": "home_dir_in_worktree",
"status": "ok"
},
+ {
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"message": "No database configured (filesystem checks only). Set GBRAIN_DATABASE_URL or run `gbrain init`.",
"name": "connection",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index abca8293a3..f2d51150a4 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -291,6 +291,22 @@
"name": "default_source_local_path",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "openai_api_key",
+ "kind": "missing",
+ "variable": "OPENAI_API_KEY"
+ },
+ "embedding_model": "openai:text-embedding-3-large",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (OPENAI_API_KEY or openai_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Connected, 0 pages",
@@ -657,6 +673,19 @@
"name": "stale_embedding_effects",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "extractor-facts"
+ },
+ "message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",
+ "name": "extractor_facts_expired",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Sampled 0 pages; no bare-tweet phrases or external links.",
@@ -812,6 +841,23 @@
"name": "facts_health",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_ids": [],
+ "authorizable": {},
+ "authorizable_total": 0,
+ "docs": "docs/guides/repair.md#legacy-job-authority",
+ "live": 0,
+ "terminal_keyed": {},
+ "terminal_keyed_total": 0,
+ "unsupported": 0,
+ "unsupported_ids": []
+ },
+ "message": "No queued job predates submission authority.",
+ "name": "legacy_job_authority",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No image assets indexed yet",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fast.json b/test/fixtures/goldens/doctor/json-pglite-fast.json
index b0b717946c..0f2b0cb79b 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fast.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fast.json
@@ -202,6 +202,22 @@
"name": "home_dir_in_worktree",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Skipping DB checks (--fast mode, URL present from config-file-path)",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 057441e99c..d3975d0980 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -291,6 +291,22 @@
"name": "default_source_local_path",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Connected, 0 pages",
@@ -657,6 +673,19 @@
"name": "stale_embedding_effects",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "extractor-facts"
+ },
+ "message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",
+ "name": "extractor_facts_expired",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Sampled 0 pages; no bare-tweet phrases or external links.",
@@ -812,6 +841,23 @@
"name": "facts_health",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_ids": [],
+ "authorizable": {},
+ "authorizable_total": 0,
+ "docs": "docs/guides/repair.md#legacy-job-authority",
+ "live": 0,
+ "terminal_keyed": {},
+ "terminal_keyed_total": 0,
+ "unsupported": 0,
+ "unsupported_ids": []
+ },
+ "message": "No queued job predates submission authority.",
+ "name": "legacy_job_authority",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No image assets indexed yet",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index e9223514af..3d3b4b6be5 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -297,6 +297,22 @@
"name": "default_source_local_path",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Connected, 0 pages",
@@ -663,6 +679,19 @@
"name": "stale_embedding_effects",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "ambiguous": 0,
+ "docs": "docs/guides/repair.md#explicit-only-repair-kinds",
+ "evidenced": 0,
+ "excluded": 0,
+ "repair": "extractor-facts"
+ },
+ "message": "No conversation-extractor fact is left expired by the pre-v0.60.11.0 projection.",
+ "name": "extractor_facts_expired",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "Sampled 0 pages; no bare-tweet phrases or external links.",
@@ -823,6 +852,23 @@
"name": "facts_health",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "active_ids": [],
+ "authorizable": {},
+ "authorizable_total": 0,
+ "docs": "docs/guides/repair.md#legacy-job-authority",
+ "live": 0,
+ "terminal_keyed": {},
+ "terminal_keyed_total": 0,
+ "unsupported": 0,
+ "unsupported_ids": []
+ },
+ "message": "No queued job predates submission authority.",
+ "name": "legacy_job_authority",
+ "status": "ok"
+ },
{
"category": "brain",
"message": "No image assets indexed yet",
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
index 3302f2e430..1bc6294faf 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable-fast.json
@@ -208,6 +208,22 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Skipping DB checks (--fast mode, URL present from config-file)",
diff --git a/test/fixtures/goldens/doctor/json-postgres-unreachable.json b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
index 2e387c6b42..7272aee15e 100644
--- a/test/fixtures/goldens/doctor/json-postgres-unreachable.json
+++ b/test/fixtures/goldens/doctor/json-postgres-unreachable.json
@@ -207,6 +207,22 @@
"name": "pglite_leftovers",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "docs": "docs/guides/repair.md#embedding-key-source",
+ "embedding_key": {
+ "config_key": "voyage_api_key",
+ "kind": "missing",
+ "variable": "VOYAGE_API_KEY"
+ },
+ "embedding_model": "voyage:voyage-4",
+ "shadows": []
+ },
+ "message": "No embedding key is set here (VOYAGE_API_KEY or voyage_api_key). No environment variable overrides a different config-plane provider key. This check sees only the environment `gbrain doctor` runs in; a daemon (gbrain serve, autopilot) has its own, and reports a mismatch in its log with a startup warning or embedding_auth_failed.",
+ "name": "embedding_key_source",
+ "status": "ok"
+ },
{
"category": "ops",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 6f952e24e8..cf14433975 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -201,6 +201,10 @@
"category": "ops",
"name": "orphan_clones"
},
+ {
+ "category": "brain",
+ "name": "embedding_key_source"
+ },
{
"category": "ops",
"name": "pglite_data_dir"
@@ -209,6 +213,10 @@
"category": "brain",
"name": "pglite_scratch_probe"
},
+ {
+ "category": "brain",
+ "name": "text_projection_readiness"
+ },
{
"category": "ops",
"name": "connection"
@@ -233,10 +241,6 @@
"category": "meta",
"name": "pages_upsert_arbiter"
},
- {
- "category": "brain",
- "name": "text_projection_readiness"
- },
{
"category": "ops",
"name": "persistence_capacity"
@@ -369,6 +373,10 @@
"category": "ops",
"name": "stale_embedding_effects"
},
+ {
+ "category": "brain",
+ "name": "extractor_facts_expired"
+ },
{
"category": "brain",
"name": "integrity"
@@ -469,6 +477,10 @@
"category": "brain",
"name": "facts_health"
},
+ {
+ "category": "ops",
+ "name": "legacy_job_authority"
+ },
{
"category": "ops",
"name": "index_audit"
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index 5da9850d31..5944223737 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -5371,6 +5371,7 @@
"dryRun: boolean",
"emitResponseMeta?: ((key: string, value: unknown) => void) | undefined",
"engine: BrainEngine",
+ "explicitReadBinding?: ExplicitReadBinding | undefined",
"jobId?: number | undefined",
"localFederatedSourceIds?: string[] | undefined",
"logger: Logger",
@@ -5512,7 +5513,7 @@
"kind": "function",
"name": "resolveRequestedScope",
"signature": [
- "(ctx: OperationContext, sourceIdParam: string | undefined, allSourcesParam?: boolean) => { sourceId?: string; sourceIds?: string[]; }"
+ "(ctx: OperationContext, sourceIdParam: string | undefined, allSourcesParam?: boolean, explicitReads?: readonly string[]) => { sourceId?: string; sourceIds?: string[]; }"
]
},
{
@@ -6924,7 +6925,7 @@
"kind": "function",
"name": "persistSynthesis",
"signature": [
- "(engine: BrainEngine, result: ThinkResult) => Promise<{ slug: string; evidenceInserted: number; warnings: string[]; }>"
+ "(engine: BrainEngine, result: ThinkResult, scope?: { sourceId?: string; allowedSources?: string[]; }) => Promise<{ slug: string; evidenceInserted: number; warnings: string[]; }>"
]
},
{
diff --git a/test/frontmatter-fix-slug-5053.test.ts b/test/frontmatter-fix-slug-5053.test.ts
new file mode 100644
index 0000000000..632a38158b
--- /dev/null
+++ b/test/frontmatter-fix-slug-5053.test.ts
@@ -0,0 +1,85 @@
+/**
+ * #5053 — `frontmatter validate --fix` passed the ABSOLUTE file path to the
+ * fixer, whose slug check then saw every declared `slug:` as a mismatch and
+ * deleted it (re-keying the page on the next import). Both callers of
+ * `autoFixFrontmatter` now pass the path the slug derives from: validate
+ * passes the brain-root-relative path (or the basename outside a brain), and
+ * `writeBrainPage` passes the path relative to its source.
+ */
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { writeBrainPage } from '../src/core/brain-writer.ts';
+
+// A NESTED_QUOTES error gives --fix something to repair, so the fixer runs.
+const page = (slug: string) => `---\ntype: note\ntitle: "a "quoted" title"\nslug: ${slug}\n---\n\nbody\n`;
+
+let scratch: string;
+let brain: string;
+
+beforeEach(() => {
+ scratch = mkdtempSync(join(tmpdir(), 'fm-5053-'));
+ brain = join(scratch, 'brain');
+ mkdirSync(join(brain, '.git'), { recursive: true });
+ mkdirSync(join(brain, 'notes'), { recursive: true });
+});
+
+afterEach(() => { rmSync(scratch, { recursive: true, force: true }); });
+
+function validateFix(target: string): string {
+ const result = spawnSync(process.execPath, ['run', 'src/cli.ts', 'frontmatter', 'validate', target, '--fix'], {
+ encoding: 'utf8', cwd: process.cwd(),
+ env: { ...process.env, GBRAIN_HOME: join(scratch, 'home'), DATABASE_URL: '', GBRAIN_DATABASE_URL: '' },
+ });
+ return (result.stdout ?? '') + (result.stderr ?? '');
+}
+
+describe('#5053 frontmatter validate --fix', () => {
+ test('a correct slug survives --fix while the real error is repaired', () => {
+ const file = join(brain, 'notes', 'foo-bar.md');
+ writeFileSync(file, page('notes/foo-bar'));
+ const output = validateFix(file);
+ const fixed = readFileSync(file, 'utf8');
+ expect(fixed).toContain('slug: notes/foo-bar');
+ expect(fixed).not.toContain('"a "quoted" title"');
+ expect(output).not.toContain('Removed mismatched slug');
+ }, 60_000);
+
+ test('a legacy-identity slug whose slugified spelling matches the path survives (#3772)', () => {
+ const file = join(brain, 'notes', 'foo-bar.md');
+ writeFileSync(file, page('Notes/Foo Bar'));
+ validateFix(file);
+ expect(readFileSync(file, 'utf8')).toContain('slug: Notes/Foo Bar');
+ }, 60_000);
+
+ test('a truly mismatched slug is still removed', () => {
+ const file = join(brain, 'notes', 'foo-bar.md');
+ writeFileSync(file, page('other/thing'));
+ validateFix(file);
+ expect(readFileSync(file, 'utf8')).not.toContain('slug:');
+ }, 60_000);
+
+ test('a file outside any brain root keeps a slug that matches its basename', () => {
+ const loose = join(scratch, 'loose');
+ mkdirSync(loose);
+ const file = join(loose, 'note.md');
+ writeFileSync(file, page('note'));
+ validateFix(file);
+ expect(readFileSync(file, 'utf8')).toContain('slug: note');
+ }, 60_000);
+});
+
+describe('#5053 writeBrainPage autoFix', () => {
+ test('derives the slug relative to its source: a correct slug survives, a mismatched one is removed', () => {
+ const backupRoot = join(scratch, 'backups');
+ const kept = writeBrainPage(join(brain, 'notes', 'foo-bar.md'), page('notes/foo-bar'), { sourcePath: brain, autoFix: true, backupRoot });
+ expect(kept.fixes.map((fix) => fix.code)).not.toContain('SLUG_MISMATCH');
+ expect(readFileSync(join(brain, 'notes', 'foo-bar.md'), 'utf8')).toContain('slug: notes/foo-bar');
+
+ const removed = writeBrainPage(join(brain, 'notes', 'other.md'), page('notes/foo-bar'), { sourcePath: brain, autoFix: true, backupRoot });
+ expect(removed.fixes.map((fix) => fix.code)).toContain('SLUG_MISMATCH');
+ expect(readFileSync(join(brain, 'notes', 'other.md'), 'utf8')).not.toContain('slug:');
+ });
+});
diff --git a/test/google-loop-detect.test.ts b/test/google-loop-detect.test.ts
index 29f975f8ad..512c775275 100644
--- a/test/google-loop-detect.test.ts
+++ b/test/google-loop-detect.test.ts
@@ -396,6 +396,58 @@ const CASES: CorpusCase[] = [
],
expect: null,
},
+ // ── Grace runs from the oldest unanswered message (gbrain-evals N7-1) ─────
+ // First sight of a thread (backfill, sync gap): a fresh nudge must not
+ // restart the clock on a request that has waited past the window.
+ {
+ name: 'request 40h + nudge 5h, first sight → unanswered_inbound (clock starts at the request)',
+ messages: [
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40, body: 'Can you send the deck?' }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 5, body: 'Bumping this. Any news?' }),
+ ],
+ expect: { type: 'unanswered_inbound', counterparty: '[email protected]' },
+ },
+ {
+ name: 'my ask 100h + my follow-up 10h, first sight → unanswered_outbound (clock starts at the ask)',
+ messages: [
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Could you confirm the date?' }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10, sent: true, body: 'Following up on this. Any update?' }),
+ ],
+ expect: { type: 'unanswered_outbound', counterparty: '[email protected]' },
+ },
+ {
+ name: 'fresh request 10h + nudge 2h → none (the whole run is inside grace)',
+ messages: [
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10 }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 2 }),
+ ],
+ expect: null,
+ },
+ {
+ name: 'inbound 40h, my reply 30h, their nudge 5h → none (the run starts after my reply)',
+ messages: [
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 40 }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 30, sent: true, body: 'Will do.' }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 5 }),
+ ],
+ expect: null,
+ },
+ {
+ name: 'CC-only mail 40h + direct ask 5h → none (the reply is owed from the To: message)',
+ messages: [
+ msg({ from: '[email protected]', to: ['[email protected]'], cc: ['[email protected]'], ageHours: 40 }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 5 }),
+ ],
+ expect: null,
+ },
+ {
+ name: 'my FYI 100h + my question 10h → none (the ask is fresh)',
+ messages: [
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 100, sent: true, body: 'Notes attached.' }),
+ msg({ from: '[email protected]', to: ['[email protected]'], ageHours: 10, sent: true, body: 'Can you review?' }),
+ ],
+ expect: null,
+ },
];
describe('detectThreadLoop precision corpus', () => {
diff --git a/test/harness-token-receipt.test.ts b/test/harness-token-receipt.test.ts
new file mode 100644
index 0000000000..18a30e1da5
--- /dev/null
+++ b/test/harness-token-receipt.test.ts
@@ -0,0 +1,123 @@
+/** #5775: an inline-token install names where the token lives and how to replace it, never the token. */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { installHarnessConnection } from '../src/core/harness/install.ts';
+import { writeCredentials, type HarnessCredentials } from '../src/core/harness/credentials.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+const roots: string[] = [];
+const temp = () => { const p = mkdtempSync(join(tmpdir(), 'gbrain-token-receipt-')); roots.push(p); return p; };
+afterEach(() => { for (const p of roots.splice(0)) rmSync(p, { recursive: true, force: true }); });
+const TOKEN = 'fixture-access-private-value';
+const creds = (): HarnessCredentials => ({ version: 1, mcp_url: 'https://brain.example.com/mcp', issuer_url: 'https://brain.example.com', client_id: 'gbrain_cl_fixture',
+ access_token: TOKEN, client_secret: 'fixture-client-private-value', profile: 'memory-writer', source_id: 'default', expires_at: Date.now() / 1000 + 3600 });
+const CONFIG = { codex: 'config.toml', 'claude-code': 'claude.json', opencode: 'opencode.jsonc' } as const;
+const RELOAD = { codex: 'Start a new Codex session and inspect /mcp.', 'claude-code': 'Restart Claude Code and inspect /mcp.', opencode: 'Restart opencode and inspect its MCP connections.' } as const;
+
+describe('inline bearer token receipt (#5775)', () => {
+ for (const harness of ['codex', 'claude-code', 'opencode'] as const) test(`${harness} receipt names storage, renewal and exposure recovery without the token`, async () => {
+ const dir = temp(), configPath = join(dir, CONFIG[harness]), handoff = join(dir, 'handoff.json');
+ const receipt = await installHarnessConnection(creds(), { harness, configPath, credentialsFile: handoff, name: 'example-brain' }) as Record<string, any>;
+ const renew = `gbrain connect https://brain.example.com/mcp --harness ${harness} --credentials-file ${handoff} --name example-brain --install --fresh-token`;
+ expect(receipt).toMatchObject({ status: 'installed', token_storage: 'inline', config_path: configPath, renew_command: renew });
+ expect(receipt.if_exposed).toEqual({
+ steps: [
+ 'On the brain host, preview: gbrain mcp admin invalidate-tokens gbrain_cl_fixture --url https://brain.example.com/mcp --admin-token-file <owner-admin-token-file> --json',
+ 'Apply with the previewed revision: gbrain mcp admin invalidate-tokens gbrain_cl_fixture --yes --if-version <revision> --url https://brain.example.com/mcp --admin-token-file <owner-admin-token-file> --json',
+ `Write a freshly exchanged token here: ${renew}`,
+ RELOAD[harness],
+ ],
+ docs_url: 'docs/mcp/ADMIN.md#invalidate-tokens-revoke-or-delete',
+ });
+ expect(receipt.token_warning).toBeUndefined();
+ expect(readFileSync(configPath, 'utf8')).toContain(TOKEN);
+ expect(JSON.stringify(receipt)).not.toContain(TOKEN);
+ expect(readFileSync(join(dir, `.gbrain-connection-${harness}-example-brain.json`), 'utf8')).not.toContain(TOKEN);
+ });
+
+ test('exposure recovery exchanges a new token instead of reinstalling the cached one', async () => {
+ const dir = temp(), configPath = join(dir, 'config.toml');
+ const issued = 'fixture-fresh-token-value-0001';
+ let exchanges = 0;
+ const server = Bun.serve({ port: 0, fetch: () => { exchanges++; return Response.json({ access_token: issued, token_type: 'Bearer', expires_in: 3600 }); } });
+ try {
+ const c = { ...creds(), issuer_url: `http://127.0.0.1:${server.port}` };
+ await installHarnessConnection(c, { harness: 'codex', configPath });
+ expect(exchanges).toBe(0);
+ expect(readFileSync(configPath, 'utf8')).toContain(TOKEN);
+ await installHarnessConnection(c, { harness: 'codex', configPath, freshToken: true });
+ expect(exchanges).toBe(1);
+ expect(readFileSync(configPath, 'utf8')).toContain(issued);
+ expect(readFileSync(configPath, 'utf8')).not.toContain(TOKEN);
+ } finally { server.stop(true); }
+ });
+
+ test('a handoff without a client secret points recovery at a new handoff', async () => {
+ const dir = temp(), configPath = join(dir, 'config.toml');
+ const { client_secret: _secret, ...staticCreds } = creds();
+ const receipt = await installHarnessConnection(staticCreds, { harness: 'codex', configPath }) as Record<string, any>;
+ expect(receipt.if_exposed.steps[2]).toBe('This handoff cannot exchange a new token; get a new private handoff from the brain owner (gbrain mcp grant on the brain host), then run: '
+ + 'gbrain connect https://brain.example.com/mcp --harness codex --credentials-file <private-handoff-file> --install');
+ });
+
+ test('a configuration inside a Git working tree warns with the fix until it is ignored', async () => {
+ const repo = temp(), configPath = join(repo, '.codex', 'config.toml');
+ execFileSync('git', ['init', '--quiet', repo]);
+ mkdirSync(join(repo, '.codex'));
+ const first = await installHarnessConnection(creds(), { harness: 'codex', configPath }) as Record<string, any>;
+ expect(first.renew_command).toBe('gbrain connect https://brain.example.com/mcp --harness codex --credentials-file <private-handoff-file> --install --fresh-token');
+ expect(first.token_warning).toBe(`${configPath} is inside the Git working tree ${execFileSync('git', ['-C', repo, 'rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim()}, `
+ + "so committing there would publish this bearer token. Add .codex/config.toml to that repository's .gitignore or move the configuration; if it was already committed, follow if_exposed.");
+ writeFileSync(join(repo, '.gitignore'), '.codex/config.toml\n');
+ const ignored = await installHarnessConnection(creds(), { harness: 'codex', configPath }) as Record<string, any>;
+ expect(ignored.token_warning).toBeUndefined();
+ });
+
+ test('connect --install human output says where the token lives and never prints it', async () => {
+ const dir = temp(), handoff = join(dir, 'handoff.json');
+ writeCredentials(handoff, { ...creds(), harness: 'codex' });
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) env[key] = value;
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL']) delete env[key];
+ Object.assign(env, { HOME: dir, GBRAIN_HOME: dir, CODEX_HOME: join(dir, '.codex'), GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1' });
+ const proc = Bun.spawn(['bun', 'run', join(REPO_ROOT, 'src', 'cli.ts'), 'connect', 'https://brain.example.com/mcp', '--harness', 'codex', '--credentials-file', handoff, '--install'],
+ { cwd: dir, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ expect(code).toBe(0);
+ const configPath = join(dir, '.codex', 'config.toml');
+ expect(JSON.parse(stdout)).toMatchObject({ status: 'installed', token_storage: 'inline', config_path: configPath });
+ expect(stderr).toContain(`The bearer token is stored inline in ${configPath}; this output never prints it. Renew it with: gbrain connect https://brain.example.com/mcp --harness codex --credentials-file ${handoff} --install --fresh-token`);
+ expect(stderr).toContain('If it was exposed: On the brain host, preview: gbrain mcp admin invalidate-tokens gbrain_cl_fixture');
+ expect(stderr).toContain('docs/mcp/ADMIN.md#invalidate-tokens-revoke-or-delete');
+ expect(stdout + stderr).not.toContain(TOKEN);
+ expect(readFileSync(configPath, 'utf8')).toContain(TOKEN);
+ }, 60_000);
+
+ test('connect --install --fresh-token is accepted by the CLI and installs a newly exchanged token', async () => {
+ const dir = temp(), handoff = join(dir, 'handoff.json');
+ const issued = 'fixture-fresh-token-value-0002';
+ let exchanges = 0;
+ const server = Bun.serve({ port: 0, fetch: () => { exchanges++; return Response.json({ access_token: issued, token_type: 'Bearer', expires_in: 3600 }); } });
+ try {
+ const origin = `http://127.0.0.1:${server.port}`;
+ writeCredentials(handoff, { ...creds(), harness: 'codex', issuer_url: origin, mcp_url: `${origin}/mcp` });
+ const env: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) env[key] = value;
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL']) delete env[key];
+ Object.assign(env, { HOME: dir, GBRAIN_HOME: dir, CODEX_HOME: join(dir, '.codex'), GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1' });
+ const proc = Bun.spawn(['bun', 'run', join(REPO_ROOT, 'src', 'cli.ts'), 'connect', `${origin}/mcp`, '--harness', 'codex', '--credentials-file', handoff, '--install', '--fresh-token', '--json'],
+ { cwd: dir, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ expect({ code, stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(stdout)).toMatchObject({ status: 'installed', token_storage: 'inline' });
+ expect(exchanges).toBe(1);
+ const config = readFileSync(join(dir, '.codex', 'config.toml'), 'utf8');
+ expect(config).toContain(issued);
+ expect(config).not.toContain(TOKEN);
+ expect(stdout + stderr).not.toContain(issued);
+ } finally { server.stop(true); }
+ }, 60_000);
+});
diff --git a/test/helpers/large-worktree.ts b/test/helpers/large-worktree.ts
new file mode 100644
index 0000000000..b63bc70ee8
--- /dev/null
+++ b/test/helpers/large-worktree.ts
@@ -0,0 +1,33 @@
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+/**
+ * Writes `count` small Markdown files under `root` with realistic path lengths,
+ * so a per-file manifest map passes the 1 MiB metadata bound near 10k files.
+ * Returns the total content bytes written.
+ */
+export function writeLargeWorktree(root: string, count: number): number {
+ let bytes = 0;
+ for (let i = 0; i < count; i++) {
+ const dir = join(root, 'notes', `batch-${String(Math.floor(i / 500)).padStart(3, '0')}`);
+ if (i % 500 === 0) mkdirSync(dir, { recursive: true });
+ const body = `---\ntitle: Example ${i}\ntype: note\n---\n\nGeneric example body ${i}.\n`;
+ writeFileSync(join(dir, `example-note-${String(i).padStart(6, '0')}.md`), body);
+ bytes += Buffer.byteLength(body);
+ }
+ return bytes;
+}
+
+/** Commits a large worktree and returns a local bare repository cloned from it. */
+export function largeBareRepository(directory: string, count: number): string {
+ const work = join(directory, 'bare-work'), bare = join(directory, 'large.git');
+ mkdirSync(work, { recursive: true });
+ writeLargeWorktree(work, count);
+ const git = (cwd: string, args: string[]) => execFileSync('git', ['-c', '[email protected]', '-c', 'user.name=t', ...args], { cwd, stdio: 'ignore' });
+ git(work, ['init', '--quiet']);
+ git(work, ['add', '-A']);
+ git(work, ['commit', '--quiet', '-m', 'fixture']);
+ git(directory, ['clone', '--quiet', '--bare', work, bare]);
+ return bare;
+}
diff --git a/test/helpers/legacy-coalesce-matrix.ts b/test/helpers/legacy-coalesce-matrix.ts
new file mode 100644
index 0000000000..318a283879
--- /dev/null
+++ b/test/helpers/legacy-coalesce-matrix.ts
@@ -0,0 +1,181 @@
+/**
+ * #5157 / #5114 coalesce matrix, shared by the PGLite unit test and the
+ * Postgres E2E test so both engines run the same table.
+ *
+ * Every case submits once through `MinionQueue.add` to create a row with the
+ * right name, payload, hash and key, rewrites that row's status and
+ * authority to the case's variant, then submits the same request again on
+ * one of the five coalesce paths and checks the outcome.
+ */
+import { expect } from 'bun:test';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { APPLICATION_AUTHORITY, coalesceDecision, type SubmissionAuthority } from '../../src/core/minions/submission-authority.ts';
+import type { MinionJobInput } from '../../src/core/minions/types.ts';
+import { OperationError } from '../../src/core/ops/contract.ts';
+
+export type AuthorityVariant = 'sql_null' | 'jsonb_null' | 'malformed' | 'future';
+export type CoalescePath = 'idempotency' | 'param' | 'pending' | 'waiting' | 'race';
+export type Outcome = 'coalesce' | 'release' | 'deny-legacy' | 'deny-cross';
+export type Caller = 'application' | 'remote';
+export interface RemoteSubmission { data: Record<string, unknown>; authority: SubmissionAuthority }
+
+export const AUTHORITY_VARIANTS: Record<AuthorityVariant, string | null> = {
+ sql_null: null,
+ jsonb_null: 'null',
+ malformed: '{"version":1}',
+ future: '{"version":2,"kind":"application"}',
+};
+export const ALL_STATUSES = ['dead', 'cancelled', 'completed', 'failed', 'waiting', 'active', 'delayed', 'waiting-children', 'paused'] as const;
+type Status = typeof ALL_STATUSES[number];
+
+/** The statuses each path can select as a coalesce target, and the callers it serves. */
+export const PATHS: Record<CoalescePath, { statuses: readonly Status[]; callers: readonly Caller[] }> = {
+ idempotency: { statuses: ALL_STATUSES, callers: ['application', 'remote'] },
+ race: { statuses: ALL_STATUSES, callers: ['application', 'remote'] },
+ // Param coalescing is application-only by design (queue.ts coalesceActive).
+ param: { statuses: ['waiting'], callers: ['application'] },
+ pending: { statuses: ['waiting', 'active'], callers: ['application', 'remote'] },
+ waiting: { statuses: ['waiting'], callers: ['application', 'remote'] },
+};
+
+export const LEGACY_DOCS = 'docs/guides/repair.md#legacy-job-authority';
+
+export function expectedOutcome(variant: AuthorityVariant, status: Status, caller: Caller): Outcome {
+ if (variant !== 'sql_null') return 'deny-cross';
+ if (status === 'dead' || status === 'cancelled') return 'release';
+ if ((status === 'completed' || status === 'failed') && caller === 'application') return 'coalesce';
+ return 'deny-legacy';
+}
+
+/**
+ * Hides the first idempotency-key read inside each transaction, so the
+ * fast path misses and the INSERT's ON CONFLICT lands on the race path
+ * exactly as a concurrent winner would.
+ */
+export function racingEngine(engine: BrainEngine): BrainEngine {
+ const bind = <T extends object>(target: T, prop: string | symbol) => {
+ const value = Reflect.get(target, prop);
+ return typeof value === 'function' ? value.bind(target) : value;
+ };
+ return new Proxy(engine, {
+ get(target, prop) {
+ if (prop !== 'transaction') return bind(target, prop);
+ return <T>(fn: (tx: BrainEngine) => Promise<T>) => target.transaction(tx => {
+ let hidden = false;
+ return fn(new Proxy(tx, {
+ get(t, p) {
+ if (p !== 'executeRaw') return bind(t, p);
+ return (sql: string, params?: unknown[]) => {
+ if (!hidden && /FROM minion_jobs WHERE idempotency_key = \$1$/.test(sql.trim())) { hidden = true; return Promise.resolve([]); }
+ return t.executeRaw(sql, params);
+ };
+ },
+ }));
+ });
+ },
+ });
+}
+
+function optsFor(path: CoalescePath): Partial<MinionJobInput> {
+ switch (path) {
+ case 'idempotency': case 'race': return { idempotency_key: 'matrix-key' };
+ case 'param': return { coalesce_params: true };
+ case 'pending': return { maxPending: 1 };
+ case 'waiting': return { maxWaiting: 1 };
+ }
+}
+
+async function setVariant(engine: BrainEngine, id: number, status: Status, variant: AuthorityVariant): Promise<void> {
+ // The queue protocol trigger only lets a claim make a row active, and only
+ // with authority present, so claim first and rewrite the authority after.
+ if (status === 'active') {
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 'matrix', lock_until = now() + interval '1 hour',
+ claim_generation = claim_generation + 1 WHERE id = $1`, [id]);
+ } else {
+ await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [id, status]);
+ }
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [id, AUTHORITY_VARIANTS[variant]]);
+}
+
+async function rejection(fn: () => Promise<unknown>): Promise<OperationError> {
+ try { await fn(); } catch (error) { return error as OperationError; }
+ throw new Error('expected a refusal');
+}
+
+/** Runs one case and asserts its outcome; returns the outcome it observed. */
+export async function runCoalesceCase(
+ engine: BrainEngine,
+ remote: () => Promise<RemoteSubmission>,
+ c: { variant: AuthorityVariant; status: Status; caller: Caller; path: CoalescePath },
+): Promise<Outcome> {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ const submission = c.caller === 'remote' ? await remote() : { data: { matrix: true, sourceId: 'default' }, authority: APPLICATION_AUTHORITY };
+ const name = c.caller === 'remote' ? 'lint' : 'matrix-job';
+ const opts = optsFor(c.path);
+ const trusted = { submissionAuthority: submission.authority };
+ const first = await new MinionQueue(engine).add(name, submission.data, opts, trusted);
+ await setVariant(engine, first.id, c.status, c.variant);
+ const [{ count: before }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');
+ const queue = new MinionQueue(c.path === 'race' ? racingEngine(engine) : engine);
+ const expected = expectedOutcome(c.variant, c.status, c.caller);
+ const label = JSON.stringify(c);
+
+ const [raw] = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT *, submission_authority IS NULL AS legacy_authority_is_null FROM minion_jobs WHERE id = $1', [first.id]);
+ let decided: Outcome;
+ try { decided = coalesceDecision(raw!, submission.authority); }
+ catch (error) { decided = (error as OperationError).docs === LEGACY_DOCS ? 'deny-legacy' : 'deny-cross'; }
+ expect(decided, `${label} decision`).toBe(expected);
+
+ if (expected === 'deny-legacy' || expected === 'deny-cross') {
+ const error = await rejection(() => queue.add(name, submission.data, opts, trusted));
+ expect(error, label).toBeInstanceOf(OperationError);
+ expect(error.code, label).toBe('permission_denied');
+ if (expected === 'deny-legacy') {
+ expect(error.docs, label).toBe(LEGACY_DOCS);
+ expect(error.suggestion, label).toContain(c.status === 'active' ? `gbrain jobs cancel ${first.id}` : 'gbrain jobs authorize-legacy --select');
+ expect(error.message, label).toContain(`job ${first.id} (${name}, ${c.status})`);
+ } else {
+ expect(error.message, label).toContain('coalescing across');
+ expect(error.docs, label).toBeUndefined();
+ }
+ } else {
+ const result = await queue.add(name, submission.data, opts, trusted);
+ const [old] = await engine.executeRaw<{ idempotency_key: string | null; data: Record<string, unknown> | string }>(
+ 'SELECT idempotency_key, data FROM minion_jobs WHERE id = $1', [first.id]);
+ if (expected === 'coalesce') {
+ expect(result.id, label).toBe(first.id);
+ expect(result.coalesced, label).toBe(true);
+ } else {
+ expect(result.id, label).not.toBe(first.id);
+ expect(result.coalesced, label).toBeFalsy();
+ expect(result.submission_authority, label).toEqual(submission.authority);
+ const data = typeof old!.data === 'string' ? JSON.parse(old!.data) : old!.data;
+ expect(old!.idempotency_key, label).toBeNull();
+ expect(data.__released_idempotency_key, label).toBe('matrix-key');
+ const [{ count: after }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');
+ expect(Number(after), label).toBe(Number(before) + 1);
+ return expected;
+ }
+ }
+ const [{ count: after }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');
+ expect(Number(after), `${label} inserted nothing`).toBe(Number(before));
+ return expected;
+}
+
+/** Every (variant x path x status x caller) cell; returns how many cells ran. */
+export async function runCoalesceMatrix(engine: BrainEngine, remote: () => Promise<RemoteSubmission>): Promise<number> {
+ let cells = 0;
+ for (const variant of Object.keys(AUTHORITY_VARIANTS) as AuthorityVariant[]) {
+ for (const [path, spec] of Object.entries(PATHS) as Array<[CoalescePath, typeof PATHS[CoalescePath]]>) {
+ for (const status of spec.statuses) {
+ for (const caller of spec.callers) {
+ await runCoalesceCase(engine, remote, { variant, status, caller, path });
+ cells++;
+ }
+ }
+ }
+ }
+ return cells;
+}
diff --git a/test/helpers/legacy-journey.ts b/test/helpers/legacy-journey.ts
new file mode 100644
index 0000000000..2f44d27b40
--- /dev/null
+++ b/test/helpers/legacy-journey.ts
@@ -0,0 +1,224 @@
+/**
+ * #5157 restored-operation journey (CEO-A4, DX-O3(f)(g), DX-O15(a)), shared
+ * by the PGLite unit test and the Postgres E2E test.
+ *
+ * A brain upgraded across v0.50 holds terminal and live legacy keyed rows,
+ * an unkeyed live SQL NULL row and an active row the upgrade orphaned.
+ * Terminal rows need no operator step. `POST /ingest` returns 409 with a
+ * hint; the journey then runs the commands the product prints, verbatim,
+ * through the real `gbrain jobs` dispatcher, counts them, and proves
+ * restored operation: `/ingest` returns 202, a worker starts and completes
+ * the queued synthesize and ingest work, and `search` finds the memory.
+ */
+import { expect } from 'bun:test';
+import express from 'express';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { mountWebhooks } from '../../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../../src/commands/serve-http.ts';
+import { runJobs } from '../../src/commands/jobs.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../../src/core/cli-force-exit.ts';
+import { makeIngestCaptureHandler } from '../../src/core/minions/handlers/ingest-capture.ts';
+import { MinionQueue } from '../../src/core/minions/queue.ts';
+import { MinionWorker } from '../../src/core/minions/worker.ts';
+import { assertNoUnreviewedJobs } from '../../src/core/minions/submission-authority.ts';
+import { legacyJobAuthorityCheck } from '../../src/commands/doctor/checks/legacy-job-authority.ts';
+import { operations } from '../../src/core/operations.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+
+export const JOURNEY_CLIENT = 'journey-client';
+
+/** A minimal `gbrain serve --http` stand-in: the real /ingest route on an ephemeral port. */
+export async function startIngestServer(engine: BrainEngine): Promise<{ base: string; stop(): Promise<void> }> {
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, {
+ engine,
+ resourceVerifier: {
+ verifyAccessToken: async (token: string) => ({ token, clientId: JOURNEY_CLIENT, clientName: 'example-client', scopes: ['read', 'write'], sourceId: 'default', expiresAt: Math.floor(Date.now() / 1000) + 3600 }),
+ },
+ resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass,
+ githubWebhookLimiter: pass,
+ broadcastEvent: () => {},
+ } as unknown as ServeHttpContext);
+ const server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ return {
+ base: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
+ stop: () => new Promise<void>(resolve => server.close(() => resolve())),
+ };
+}
+
+export function postIngest(base: string, content: string) {
+ return fetch(`${base}/ingest`, { method: 'POST', headers: { authorization: 'Bearer test-only', 'content-type': 'text/markdown' }, body: content });
+}
+
+/** Splits one printed `gbrain ...` command into argv, honoring double quotes. */
+export function argv(command: string): string[] {
+ return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map(m => m[1] ?? m[2]!);
+}
+
+/** Runs a printed `gbrain jobs …` command verbatim through the real dispatcher. */
+export async function runPrinted(engine: BrainEngine, command: string): Promise<{ out: string; err: string; exit: number }> {
+ const args = argv(command);
+ expect(args.slice(0, 2)).toEqual(['gbrain', 'jobs']);
+ const out: string[] = [], err: string[] = [];
+ const log = console.log, error = console.error;
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.join(' ')); };
+ _resetCliExitVerdictForTests();
+ try { await runJobs(engine, args.slice(2)); } finally { console.log = log; console.error = error; }
+ const exit = currentExitCode();
+ _resetCliExitVerdictForTests();
+ process.exitCode = 0;
+ return { out: out.join('\n'), err: err.join('\n'), exit };
+}
+
+/** Rewrites rows to what an upgrade across v0.50 leaves behind (the protocol trigger forbids inserting them). */
+async function legacy(engine: BrainEngine, id: number, status?: string): Promise<void> {
+ if (status === 'active') {
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 'pre-upgrade', lock_until = now() + interval '1 hour',
+ claim_generation = claim_generation + 1 WHERE id = $1`, [id]);
+ } else if (status) {
+ await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [id, status]);
+ }
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [id]);
+}
+
+async function drain(engine: BrainEngine, ids: number[]): Promise<Record<number, string>> {
+ const queue = new MinionQueue(engine);
+ const worker = new MinionWorker(engine, { pollInterval: 10, healthCheckInterval: 0, stalledInterval: 60_000 });
+ worker.register('ingest_capture', makeIngestCaptureHandler(engine));
+ worker.register('synthesize', async () => ({ synthesized: true }));
+ const running = worker.start();
+ const statuses = async () => Object.fromEntries(await Promise.all(ids.map(async id => [id, (await queue.getJob(id))?.status ?? 'missing'])));
+ for (let i = 0; i < 400; i++) {
+ if (Object.values(await statuses()).every(status => status === 'completed' || status === 'failed')) break;
+ await new Promise(r => setTimeout(r, 25));
+ }
+ worker.stop();
+ await running;
+ return statuses();
+}
+
+export interface JourneyResult { commands: string[] }
+
+/** `gbrain search <query>` through the search operation, as a trusted local caller; returns hit slugs. */
+async function searchSlugs(engine: BrainEngine, query: string): Promise<string[]> {
+ const op = operations.find(o => o.name === 'search')!;
+ const ctx: OperationContext = { engine, config: {} as OperationContext['config'], dryRun: false, remote: false, sourceId: 'default', logger: { info() {}, warn() {}, error() {} } };
+ const result = await op.handler(ctx, { query }) as unknown;
+ const rows = (Array.isArray(result) ? result : (result as { results?: unknown[] }).results ?? []) as Array<{ slug?: string }>;
+ return rows.map(row => String(row.slug));
+}
+
+export async function runLegacyJourney(engine: BrainEngine): Promise<JourneyResult> {
+ const queue = new MinionQueue(engine);
+ const trusted = { allowProtectedSubmit: true };
+ const content = '# Journey capture\n\nThe zebra-journey-marker note survives the v0.50 upgrade.';
+
+ // The capture was queued before the upgrade: its row holds the capture's key.
+ let serve = await startIngestServer(engine);
+ const first = await postIngest(serve.base, content);
+ expect(first.status).toBe(202);
+ const captureId = (await first.json() as { job_id: number }).job_id;
+ await legacy(engine, captureId);
+ const completed = await queue.add('synthesize', { day: 1 }, { idempotency_key: 'dream:synth-v2:journey-done' }, trusted);
+ await legacy(engine, completed.id, 'completed');
+ const dead = await queue.add('synthesize', { day: 2 }, { idempotency_key: 'dream:synth-v2:journey-dead' }, trusted);
+ await legacy(engine, dead.id, 'dead');
+ const unkeyed = await queue.add('synthesize', { day: 3 }, {}, trusted);
+ await legacy(engine, unkeyed.id);
+ const orphan = await queue.add('embed', { orphaned: true });
+ await legacy(engine, orphan.id, 'active');
+
+ // Terminal legacy keys need no operator step for application callers.
+ expect((await queue.add('synthesize', { day: 1 }, { idempotency_key: 'dream:synth-v2:journey-done' }, trusted)).id).toBe(completed.id);
+ const resubmitted = await queue.add('synthesize', { day: 2 }, { idempotency_key: 'dream:synth-v2:journey-dead' }, trusted);
+ expect(resubmitted.id).not.toBe(dead.id);
+
+ // Live rows: doctor names the recovery, workers are blocked, and /ingest says 409, never 500.
+ expect((await legacyJobAuthorityCheck(engine)).status).toBe('fail');
+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');
+ const refused = await postIngest(serve.base, content);
+ expect(refused.status).toBe(409);
+ const body = await refused.json() as { error: string; hint: string; docs_url: string };
+ expect(body.error).toBe('permission_denied');
+ expect(body.docs_url).toBe('docs/guides/repair.md#legacy-job-authority');
+
+ const commands: string[] = [];
+ // 1. Stop producers and workers: the hint's first instruction.
+ expect(body.hint).toStartWith('Stop producers (gbrain serve, gbrain autopilot) and workers');
+ await serve.stop();
+ commands.push('stop gbrain serve');
+ // 2. Cancel the active job the hint names.
+ const cancel = /cancel active jobs \((gbrain jobs cancel \d+)\)/.exec(body.hint)?.[1];
+ expect(cancel).toBe(`gbrain jobs cancel ${orphan.id}`);
+ expect((await runPrinted(engine, cancel!)).exit).toBe(0);
+ commands.push(cancel!);
+ // 3. Preview with the hint's filled --select.
+ const preview = /preview with (gbrain jobs authorize-legacy --select "[^"]+")/.exec(body.hint)?.[1];
+ expect(preview).toBe('gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"');
+ const previewed = await runPrinted(engine, preview!);
+ expect(previewed.exit).toBe(0);
+ expect(previewed.out).toContain('(SQL NULL authority, authorizable): 2');
+ commands.push(preview!);
+ // 4. Apply with the printed --expect.
+ const apply = /Apply exactly this set: (.+)$/m.exec(previewed.out)?.[1];
+ expect(apply).toMatch(/--expect [a-f0-9]{64} --yes$/);
+ expect((await runPrinted(engine, apply!)).exit).toBe(0);
+ commands.push(apply!);
+ // 5. Restart serve.
+ serve = await startIngestServer(engine);
+ commands.push('restart gbrain serve');
+
+ await assertNoUnreviewedJobs(engine);
+ expect((await legacyJobAuthorityCheck(engine)).status).toBe('ok');
+ const accepted = await postIngest(serve.base, content);
+ expect(accepted.status).toBe(202);
+ expect((await accepted.json() as { job_id: number }).job_id).toBe(captureId);
+ await serve.stop();
+
+ // A worker starts and completes the queued synthesize and capture work.
+ const statuses = await drain(engine, [captureId, unkeyed.id, resubmitted.id]);
+ expect(statuses).toEqual({ [captureId]: 'completed', [unkeyed.id]: 'completed', [resubmitted.id]: 'completed' });
+
+ // 6. search finds the ingested memory.
+ const hits = await searchSlugs(engine, 'zebra-journey-marker');
+ commands.push('gbrain search zebra-journey-marker');
+ expect(hits.some(slug => slug.startsWith('inbox/'))).toBe(true);
+ expect(commands.length).toBeLessThanOrEqual(6);
+ return { commands };
+}
+
+/**
+ * DX-O3(g): an unsupported non-NULL row keeps workers blocked after the
+ * SQL NULL rows are authorized; its own printed step (local cancel) clears
+ * it and a worker starts.
+ */
+export async function runUnsupportedRowRecovery(engine: BrainEngine): Promise<string[]> {
+ const queue = new MinionQueue(engine);
+ const trusted = { allowProtectedSubmit: true };
+ const legacyRow = await queue.add('synthesize', { day: 4 }, {}, trusted);
+ await legacy(engine, legacyRow.id);
+ const future = await queue.add('synthesize', { day: 5 }, {}, trusted);
+ await engine.executeRaw(`UPDATE minion_jobs SET submission_authority = '{"version":2,"kind":"application"}'::jsonb WHERE id = $1`, [future.id]);
+
+ const doctor = await legacyJobAuthorityCheck(engine);
+ const commands: string[] = [];
+ const preview = /preview with (gbrain jobs authorize-legacy --select "[^"]+")/.exec(doctor.message)![1]!;
+ const previewed = await runPrinted(engine, preview);
+ expect(previewed.out).toContain(`Unsupported non-NULL authority (not authorizable; cancel locally): ${future.id}`);
+ commands.push(preview);
+ const apply = /Apply exactly this set: (.+)$/m.exec(previewed.out)![1]!;
+ expect((await runPrinted(engine, apply)).exit).toBe(0);
+ commands.push(apply);
+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('1 legacy jobs');
+ const cancel = new RegExp(`gbrain jobs cancel ${future.id}\\b`).exec(doctor.message)![0];
+ expect((await runPrinted(engine, cancel)).exit).toBe(0);
+ commands.push(cancel);
+ await assertNoUnreviewedJobs(engine);
+ expect(await drain(engine, [legacyRow.id])).toEqual({ [legacyRow.id]: 'completed' });
+ return commands;
+}
diff --git a/test/helpers/managed-atoms-contract.ts b/test/helpers/managed-atoms-contract.ts
index c3b2c0b3eb..f204661c52 100644
--- a/test/helpers/managed-atoms-contract.ts
+++ b/test/helpers/managed-atoms-contract.ts
@@ -1,5 +1,5 @@
import { expect } from 'bun:test';
-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { BrainEngine } from '../../src/core/engine.ts';
@@ -14,7 +14,7 @@ import { retryManagedAtomBatch } from '../../src/core/persistence/atom-retry.ts'
import type { WriteRequest } from '../../src/core/persistence/model.ts';
import { withSubmissionAuthority } from '../../src/core/minions/submission-authority.ts';
import { serializePageToMarkdown } from '../../src/core/markdown.ts';
-import { sha256 } from '../../src/core/persistence/digest.ts';
+import { digest, sha256 } from '../../src/core/persistence/digest.ts';
import { purgeStaleCheckpoints } from '../../src/core/op-checkpoint.ts';
import { __setChatTransportForTests } from '../../src/core/ai/gateway.ts';
import { MinionWorker } from '../../src/core/minions/worker.ts';
@@ -224,6 +224,254 @@ export async function exerciseManagedAtoms(engine: BrainEngine, scenario: Case):
} finally { await disposePersistenceConsumer(engine); await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); __setChatTransportForTests(null); rmSync(home, { recursive: true, force: true }); }
}
+export async function exerciseManagedAtomReconciliation(engine: BrainEngine): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-reconcile-'));
+ const root = join(home, 'repo');
+ const sourceId = 'managed-atom-reconcile';
+ const slug = 'notes/example';
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const writeSource = async (revision: number) => {
+ const page = await engine.putPage(slug, { type: 'source', title: 'Example', compiled_truth: `A careful project record at revision ${revision}. `.repeat(40) }, { sourceId });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(page, []));
+ return page;
+ };
+ let page = await writeSource(1);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ let titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return {
+ text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ blocks: [], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic',
+ };
+ };
+ const extract = () => runPhaseExtractAtoms(engine, { sourceId, _transcripts: [],
+ _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat });
+ expect((await extract()).status).toBe('ok');
+ const first = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL ORDER BY slug", [sourceId]);
+ expect(first).toHaveLength(2);
+ const retired = first.find(atom => atom.slug.includes('/patience-compounds-'))!;
+ for (const atom of first) {
+ const path = join(root, `${atom.slug}.md`);
+ expect(existsSync(path)).toBe(true);
+ rmSync(path);
+ }
+ writeFileSync(join(root, `${retired.slug}.md`), 'Uncoordinated operator content.');
+
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ page = await writeSource(2);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ titles = ['Patience compounds over years', 'Hire slowly'];
+ const failed = await extract();
+ expect(failed.status).toBe('warn');
+ expect(calls).toBe(2);
+ const completion = (failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!;
+ rmSync(join(root, `${retired.slug}.md`));
+ await disposePersistenceConsumer(engine);
+ expect(await retryManagedAtomBatch(engine, sourceId, completion.request_id, 'reviewed-retirement')).toMatchObject({ status: 'completed', model_rerun: false });
+ expect(calls).toBe(2);
+
+ const second = await engine.executeRaw<{ slug: string }>("SELECT slug FROM pages WHERE source_id=$1 AND type='atom' AND deleted_at IS NULL ORDER BY slug", [sourceId]);
+ expect(second).toHaveLength(2);
+ for (const atom of second) expect(existsSync(join(root, `${atom.slug}.md`))).toBe(true);
+ expect(second.map(atom => atom.slug)).not.toContain(retired.slug);
+ expect(existsSync(join(root, `${retired.slug}.md`))).toBe(false);
+ expect((await engine.getPage(retired.slug, { sourceId, includeDeleted: true }))?.deleted_at).not.toBeNull();
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
+export const atomRetirementCases = ['marker_and_republish', 'edit_back', 'user_deleted', 'prefix_pin', 'generation_key_and_purge', 'partial_retry', 'partial_then_revert'] as const;
+
+/** #5770 / ENG-O7: retirement markers, republication of retired slugs, the regeneration generation and its purge exclusion. */
+export async function exerciseManagedAtomRetirement(engine: BrainEngine, scenario: typeof atomRetirementCases[number]): Promise<void> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-retire-'));
+ const root = join(home, 'repo');
+ const sourceId = `atom-retire-${scenario.replaceAll('_', '-')}`;
+ const slug = 'notes/example';
+ const bodies = ['A careful project record at revision one. ', 'A careful project record at revision two. ', 'A careful project record at revision three. ']
+ .map(line => line.repeat(40));
+ const unmanaged = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ };
+ const atomsOf = async () => engine.executeRaw<{ slug: string; deleted: boolean; frontmatter: Record<string, unknown> }>(
+ `SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter FROM pages WHERE source_id=$1 AND type='atom' ORDER BY slug`, [sourceId]);
+ const atom = async (title: string) => (await atomsOf()).find(row => row.slug.includes(`/${title}-`));
+ try {
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const writeSource = async (body: string) => {
+ const written = await engine.putPage(slug, { type: 'source', title: 'Example', compiled_truth: body }, { sourceId });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(written, []));
+ return written;
+ };
+ let page = await writeSource(bodies[0]);
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ let titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return { text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ const extract = () => runPhaseExtractAtoms(engine, { sourceId, _transcripts: [],
+ _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat });
+ const edit = async (body: string, next: string[]) => { page = await unmanaged(() => writeSource(body)); titles = next; };
+ expect((await extract()).status).toBe('ok');
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const settledState = async (requestId: string) => {
+ for (let attempt = 0; attempt < 300; attempt++) {
+ const [row] = await engine.executeRaw<{ state: string }>('SELECT state FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);
+ if (row && !['queued', 'running', 'recovering'].includes(row.state)) return row.state;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error(`request ${requestId} did not settle`);
+ };
+ const generation = async () => (await engine.executeRaw<{ generation: string }>(
+ "SELECT completed_keys->0->>'generation' AS generation FROM op_checkpoints WHERE op='managed-atoms-generation' AND fingerprint=$1", [String(page.id)]))[0]?.generation;
+
+ if (scenario === 'marker_and_republish') {
+ await edit(bodies[1], ['Patience compounds over years', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const retired = (await atom('patience-compounds'))!;
+ expect(retired.deleted).toBe(true);
+ expect(retired.frontmatter.retired_by).toBe('managed-reextract');
+ expect(Number.isNaN(Date.parse(String(retired.frontmatter.retired_at)))).toBe(false);
+ expect(existsSync(join(root, `${retired.slug}.md`))).toBe(false);
+ await edit(bodies[2], ['Patience compounds', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const restored = (await atom('patience-compounds'))!;
+ expect(restored.slug).toBe(retired.slug);
+ expect(restored.deleted).toBe(false);
+ expect(restored.frontmatter).not.toHaveProperty('retired_by');
+ expect(existsSync(join(root, `${restored.slug}.md`))).toBe(true);
+ expect((await atom('patience-compounds-over-years'))?.deleted).toBe(true);
+ expect(calls).toBe(3);
+ }
+
+ if (scenario === 'edit_back') {
+ const first = (await atom('patience-compounds'))!;
+ await edit(bodies[1], ['Patience compounds over years', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ expect((await atom('patience-compounds'))?.deleted).toBe(true);
+ expect(await generation()).toBe('1');
+ await edit(bodies[0], ['Patience compounds', 'Hire slowly']);
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);
+ expect((await extract()).status).toBe('ok');
+ expect(calls).toBe(3);
+ const back = (await atom('patience-compounds'))!;
+ expect(back).toMatchObject({ slug: first.slug, deleted: false });
+ expect((await atom('patience-compounds-over-years'))?.deleted).toBe(true);
+ expect(await discoverExtractablePages(engine, sourceId)).toEqual([]);
+ }
+
+ if (scenario === 'user_deleted') {
+ const removed = (await atom('patience-compounds'))!;
+ await unmanaged(() => engine.softDeletePage(removed.slug, { sourceId }));
+ await edit(bodies[1], ['Patience compounds', 'Hire slowly']);
+ expect((await extract()).status).not.toBe('ok');
+ const after = (await atom('patience-compounds'))!;
+ expect(after.deleted).toBe(true);
+ expect(after.frontmatter).not.toHaveProperty('retired_by');
+ }
+
+ if (scenario === 'prefix_pin') {
+ const next = await unmanaged(async () => {
+ const written = await writeSource(bodies[1]);
+ for (const [name, hash] of [['legacy-prefix', written.content_hash!.slice(0, 16)], ['legacy-full', written.content_hash!]] as const) {
+ await engine.putPage(`atoms/2026-01-01/${name}`, { type: 'atom', title: name, compiled_truth: `Legacy atom ${name}.`,
+ frontmatter: { source_slug: slug, source_hash: hash } }, { sourceId });
+ }
+ return written;
+ });
+ page = next;
+ titles = ['Patience compounds', 'Hire slowly'];
+ expect((await extract()).status).toBe('ok');
+ expect((await atomsOf()).find(row => row.slug.endsWith('/legacy-prefix'))?.deleted).toBe(false);
+ expect((await atomsOf()).find(row => row.slug.endsWith('/legacy-full'))?.deleted).toBe(true);
+ }
+
+ if (scenario === 'partial_retry') {
+ await edit(bodies[1], ['Patience compounds', 'Queue patiently', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const queued = (await atom('queue-patiently'))!;
+ await edit(bodies[2], ['Patience compounds over years', 'Hire slowly']);
+ writeFileSync(join(root, `${queued.slug}.md`), 'Uncoordinated operator content.');
+ const failed = await extract();
+ const completion = (failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!;
+ expect(await settledState(completion.request_id)).not.toBe('committed');
+ expect((await atom('patience-compounds'))).toMatchObject({ deleted: true, frontmatter: { retired_by: 'managed-reextract' } });
+ expect((await atom('queue-patiently'))?.deleted).toBe(false);
+ rmSync(join(root, `${queued.slug}.md`));
+ await disposePersistenceConsumer(engine);
+ expect(await retryManagedAtomBatch(engine, sourceId, completion.request_id, 'reviewed-retirement')).toMatchObject({ status: 'completed', model_rerun: false });
+ expect(await retryManagedAtomBatch(engine, sourceId, completion.request_id, 'reviewed-retirement')).toMatchObject({ status: 'completed', replayed: true, model_rerun: false });
+ expect(calls).toBe(3);
+ expect((await atom('queue-patiently'))).toMatchObject({ deleted: true, frontmatter: { retired_by: 'managed-reextract' } });
+ expect((await atom('patience-compounds'))?.deleted).toBe(true);
+ }
+
+ if (scenario === 'partial_then_revert') {
+ await edit(bodies[1], ['Patience compounds', 'Queue patiently', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ const queued = (await atom('queue-patiently'))!;
+ await edit(bodies[2], ['Patience compounds over years', 'Hire slowly']);
+ writeFileSync(join(root, `${queued.slug}.md`), 'Uncoordinated operator content.');
+ const failed = await extract();
+ expect(await settledState((failed.details?.write_requests as Array<{ request_id: string }>).at(-1)!.request_id)).not.toBe('committed');
+ expect((await atom('patience-compounds'))?.deleted).toBe(true);
+ rmSync(join(root, `${queued.slug}.md`));
+ await disposePersistenceConsumer(engine);
+ await extract();
+ expect(calls).toBe(3);
+ await edit(bodies[1], ['Patience compounds', 'Queue patiently', 'Hire slowly']);
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);
+ expect((await extract()).status).toBe('ok');
+ expect(calls).toBe(4);
+ expect((await atom('patience-compounds'))?.deleted).toBe(false);
+ expect((await atom('patience-compounds-over-years'))?.deleted).toBe(true);
+ }
+
+ if (scenario === 'generation_key_and_purge') {
+ const legacyKey = digest(['managed-atoms-v1', incarnation, 'page', slug, page.id, page.content_hash]);
+ expect((await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-atoms' AND fingerprint=$1", [legacyKey]))).toHaveLength(1);
+ expect(await generation()).toBeUndefined();
+ await edit(bodies[1], ['Patience compounds over years', 'Hire slowly']);
+ expect((await extract()).status).toBe('ok');
+ expect(await generation()).toBe('1');
+ await engine.executeRaw("UPDATE op_checkpoints SET updated_at=now() - interval '30 days' WHERE op IN ('managed-atoms-generation','managed-atoms')");
+ await purgeStaleCheckpoints(engine, 7);
+ expect(await generation()).toBe('1');
+ }
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ rmSync(home, { recursive: true, force: true });
+ }
+}
+
export const atomBatchCases = ['partial_publication', 'missing_after_provenance', 'changed_after_provenance', 'completion_rollback'] as const;
export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: typeof atomBatchCases[number]): Promise<void> {
@@ -360,7 +608,7 @@ export async function exerciseManagedAtomBatch(engine: BrainEngine, scenario: ty
}
}
-export const atomAuthorityCases = ['remote_job', 'stdio', 'missing_source', 'archived_source', 'missing_owner', 'inactive_owner', 'foreign_owner', 'revoked_writer', 'source_grant', 'read_only_grant', 'operation_grant', 'slug_grant'] as const;
+export const atomAuthorityCases = ['remote_job', 'stdio', 'missing_source', 'archived_source', 'missing_owner', 'inactive_owner', 'foreign_owner', 'revoked_writer', 'source_grant', 'read_only_grant', 'operation_grant', 'delete_operation_grant', 'slug_grant'] as const;
export async function exerciseManagedAtomAuthority(engine: BrainEngine, scenario: typeof atomAuthorityCases[number]): Promise<void> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-managed-atom-authority-'));
@@ -372,7 +620,7 @@ export async function exerciseManagedAtomAuthority(engine: BrainEngine, scenario
await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
await engine.putPage('notes/example', { type: 'source', title: 'Example', compiled_truth: 'A project record. '.repeat(40) }, { sourceId });
const page = (await engine.getPage('notes/example', { sourceId }))!;
- const grant: LocalGrant = { sourceIds: scenario === 'source_grant' ? ['another-source'] : ['*'], operations: scenario === 'operation_grant' ? ['submit_job'] : null,
+ const grant: LocalGrant = { sourceIds: scenario === 'source_grant' ? ['another-source'] : ['*'], operations: scenario === 'operation_grant' ? ['submit_job'] : scenario === 'delete_operation_grant' ? ['submit_job', 'put_page'] : null,
scopes: scenario === 'read_only_grant' ? ['read'] : ['read', 'write'], slugPrefixes: scenario === 'slug_grant' ? ['atoms/'] : null };
const registration = await registerLocalWriter(engine, scenario === 'stdio' ? 'stdio' : 'cli', grant);
if (scenario.endsWith('_owner')) {
diff --git a/test/hold-carry-classic-state.test.ts b/test/hold-carry-classic-state.test.ts
new file mode 100644
index 0000000000..9bf404100e
--- /dev/null
+++ b/test/hold-carry-classic-state.test.ts
@@ -0,0 +1,90 @@
+/**
+ * Wave-5 follow-up: `sources writer deactivate` carries managed connector holds
+ * into each source's classic state file. These pin the two edges the
+ * integrated scenario (fix-wave-4-integration X6) does not reach:
+ * - a source whose worktree another host owns is not written from here
+ * (its classic state lives on that host); deactivation keeps refusing;
+ * - a hold copied by an earlier deactivation that then aborted, and was
+ * resolved in managed mode since, is cleared on the next carry instead of
+ * coming back as held in classic mode.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+import { randomUUID } from 'crypto';
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { carryHoldsToClassicState, holdCarryBlocked, planHoldCarry } from '../src/core/connectors/item-holds-store.ts';
+import { carryLegacyFailCounts } from '../src/core/connectors/item-holds.ts';
+import { connectorCheckpointKey, connectorIdentity } from '../src/core/persistence/connector-identity.ts';
+
+let engine: PGLiteEngine;
+let dir: string;
+const config = { kind: 'google', g_account: '[email protected]', g_services: 'gmail', g_access: 'env', g_token_env: 'CONNECTOR_TEST_TOKEN' };
+const HOST = randomUUID();
+const held = () => carryLegacyFailCounts(undefined, { 'thread-1': 3 }, id => id, '2026-10-01T00:00:00.000Z');
+const stateFile = () => join(dir, '.google-source.json');
+
+async function setManagedHolds(holds: unknown): Promise<void> {
+ const [row] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='gmail-a'");
+ const key = connectorCheckpointKey('gmail-a', row.incarnation, connectorIdentity('google', config, dir));
+ await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-connector'");
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-connector',$1,$2::text::jsonb)`,
+ [key, JSON.stringify([{ state: { history_id: 'h1', item_holds: holds } }])]);
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ dir = mkdtempSync(join(tmpdir(), 'gbrain-hold-carry-'));
+ await engine.executeRaw('INSERT INTO sources (id, name, local_path, config) VALUES ($1, $1, $2, $3::text::jsonb)', ['gmail-a', dir, JSON.stringify(config)]);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+}, 60_000);
+
+beforeEach(async () => {
+ rmSync(stateFile(), { force: true });
+ await engine.executeRaw('DELETE FROM persistence_source_bindings');
+ await engine.executeRaw('DELETE FROM persistence_worktrees');
+});
+
+describe('carrying connector holds into classic state', () => {
+ test('a locally owned source takes its managed holds, other classic fields kept', async () => {
+ await setManagedHolds(held());
+ writeFileSync(stateFile(), JSON.stringify({ gmail_history_id: 'classic-cursor' }));
+ const carried = await carryHoldsToClassicState(engine, HOST);
+ expect(carried).toEqual([{ source_id: 'gmail-a', items: 1, state_file: stateFile() }]);
+ const classic = JSON.parse(readFileSync(stateFile(), 'utf-8'));
+ expect(classic.gmail_history_id).toBe('classic-cursor');
+ expect(classic.item_holds).toEqual(JSON.parse(JSON.stringify(held())));
+ });
+
+ test('a hold copied by an aborted deactivation and resolved since is cleared, not resurrected', async () => {
+ writeFileSync(stateFile(), JSON.stringify({ gmail_history_id: 'classic-cursor', item_holds: held() }));
+ await setManagedHolds({ version: 1, items: {} });
+ expect(await carryHoldsToClassicState(engine, HOST)).toEqual([]);
+ const classic = JSON.parse(readFileSync(stateFile(), 'utf-8'));
+ expect(classic).toEqual({ gmail_history_id: 'classic-cursor' });
+ });
+
+ test('a source whose worktree another host owns blocks and is never written from here', async () => {
+ await setManagedHolds(held());
+ const [incarnation] = await engine.executeRaw<{ incarnation: string }>("SELECT incarnation::text AS incarnation FROM sources WHERE id='gmail-a'");
+ const other = randomUUID();
+ const [worktree] = await engine.executeRaw<{ id: string }>('INSERT INTO persistence_worktrees (owner_host_id) VALUES ($1::uuid) RETURNING id::text', [other]);
+ await engine.executeRaw('INSERT INTO persistence_source_bindings (source_id, source_incarnation, worktree_id) VALUES ($1, $2::uuid, $3::uuid)',
+ ['gmail-a', incarnation.incarnation, worktree.id]);
+ const [plan] = await planHoldCarry(engine, HOST);
+ expect(plan).toMatchObject({ source_id: 'gmail-a', items: 1, owner_host: other });
+ expect(holdCarryBlocked(plan)).toBe(true);
+ await expect(carryHoldsToClassicState(engine, HOST)).rejects.toThrow(/cannot take its held items on this host/);
+ expect(existsSync(stateFile())).toBe(false);
+ // The owning host carries them.
+ expect(holdCarryBlocked((await planHoldCarry(engine, other))[0])).toBe(false);
+ });
+});
diff --git a/test/hook-command.serial.test.ts b/test/hook-command.serial.test.ts
index 0ac989ce83..9b73768493 100644
--- a/test/hook-command.serial.test.ts
+++ b/test/hook-command.serial.test.ts
@@ -24,6 +24,7 @@ import {
DIGEST_MEMORY_CAP_BYTES,
memoryDigest,
PUSH_ANNOUNCE_REFIRE_MS,
+ HOOK_EVENTS,
type HookHeartbeatEntry,
} from '../src/commands/hook.ts';
import { pushStatusPathForRoot } from '../src/core/workspace-push.ts';
@@ -599,7 +600,7 @@ describe('session-start', () => {
expect(out.get()).not.toContain('run gbrain doctor');
});
- test('last-session line + stale push-status surfaced [B4]', async () => {
+ test('stale push-status surfaced; no buffered session text at session start [B4, #5558]', async () => {
const liveDir = join(home(), 'transcripts', 'live');
mkdirSync(liveDir, { recursive: true });
writeFileSync(join(liveDir, 'prev.txt'), JSON.stringify({ ts: '2026-08-07T09:00:00Z', session_id: 'prev', exchange: 'wrapped up the acme-example memo' }) + '\n');
@@ -609,13 +610,31 @@ describe('session-start', () => {
const ws = join(tmp, 'ws');
mkdirSync(ws, { recursive: true });
const out = collectStdout();
- await runHook(['session-start'], { ...out.io, stdin: '', cwd: ws });
+ await runHook(['session-start'], { ...out.io, stdin: JSON.stringify({ session_id: 'prev', cwd: ws }), cwd: ws });
const text = out.get();
- expect(text).toContain('Last session activity');
- expect(text).toContain('acme-example memo');
+ expect(text).not.toContain('Last session activity');
+ expect(text).not.toContain('acme-example memo');
expect(text).toContain('>48h ago');
});
+ test('#5558: no hook event surfaces another session\'s text (every event, every buffer shape)', async () => {
+ const liveDir = join(home(), 'transcripts', 'live');
+ mkdirSync(liveDir, { recursive: true });
+ const secrets = ['private-json-exchange-marker', 'private-raw-line-marker', 'private-own-session-marker'];
+ writeFileSync(join(liveDir, 'other-agent.txt'), JSON.stringify({ ts: '2026-09-30T09:00:00Z', session_id: 'other-agent', exchange: secrets[0] }) + '\n');
+ writeFileSync(join(liveDir, 'unknown.txt'), secrets[1] + '\n');
+ writeFileSync(join(liveDir, 'me.txt'), JSON.stringify({ ts: '2026-09-30T09:01:00Z', session_id: 'me', exchange: secrets[2] }) + '\n');
+ const ws = join(tmp, 'ws');
+ mkdirSync(ws, { recursive: true });
+ for (const event of HOOK_EVENTS) {
+ for (const stdin of ['', JSON.stringify({ session_id: 'me', cwd: ws, source: 'compact' })]) {
+ const out = collectStdout();
+ await runHook([event], { ...out.io, stdin, cwd: ws, spawnPush: () => {}, transcriptRoot: join(tmp, 'projects') });
+ for (const secret of secrets) expect(out.get()).not.toContain(secret);
+ }
+ }
+ });
+
test('parser-drift status file surfaced at session start [G3]', async () => {
const statusPath = await hookStatusPath();
writeFileSync(statusPath, JSON.stringify({ ts: new Date().toISOString(), error: 'parser_drift', bytes: 1234 }));
@@ -630,7 +649,7 @@ describe('session-start', () => {
// ── stop [G15] ──────────────────────────────────────────────────────────────
describe('stop', () => {
- test('appends to the per-session buffer (sanitized id) and GCs stale buffers', async () => {
+ test('writes no session buffer and GCs stale buffers left by older binaries [#5558]', async () => {
const liveDir = join(home(), 'transcripts', 'live');
mkdirSync(liveDir, { recursive: true });
const stale = join(liveDir, 'stale.txt');
@@ -638,16 +657,14 @@ describe('stop', () => {
const old = (Date.now() - 8 * 24 * 3600 * 1000) / 1000;
utimesSync(stale, old, old);
- expect(
- await runHook(['stop'], {
- stdin: JSON.stringify({ session_id: 'abc/../def', last_assistant_message: 'the widget-co answer' }),
- }),
- ).toBe(0);
- const files = readdirSync(liveDir);
- expect(files).toContain('abc-..-def.txt'); // '/' sanitized, no traversal possible
- expect(files).not.toContain('stale.txt');
- const body = readFileSync(join(liveDir, 'abc-..-def.txt'), 'utf8');
- expect(body).toContain('the widget-co answer');
+ for (const session_id of ['abc/../def', undefined]) {
+ expect(
+ await runHook(['stop'], {
+ stdin: JSON.stringify({ session_id, last_assistant_message: 'the widget-co answer' }),
+ }),
+ ).toBe(0);
+ }
+ expect(readdirSync(liveDir)).toEqual([]);
expect((await lastHeartbeat())?.outcome).toBe('ok');
});
});
@@ -1210,9 +1227,8 @@ describe('stop-hook per-turn push [D3]', () => {
await runHook(['stop'], stopIo(repo, spawned));
expect(spawned).toEqual([]);
expect((await lastHeartbeat())?.reason).toBe('push_clean');
- // the live-buffer append still happened (stop's original contract)
- const bufDir = join(home(), 'transcripts', 'live');
- expect(readdirSync(bufDir).some((n) => n.includes('sess-stop-push'))).toBe(true);
+ // #5558: stop no longer writes a live buffer
+ expect(existsSync(join(home(), 'transcripts', 'live', 'sess-stop-push.txt'))).toBe(false);
});
test('corrupt per-root state file is treated as due (fail-open)', async () => {
diff --git a/test/jobs-authorize-legacy-select.test.ts b/test/jobs-authorize-legacy-select.test.ts
new file mode 100644
index 0000000000..2a99f9d5df
--- /dev/null
+++ b/test/jobs-authorize-legacy-select.test.ts
@@ -0,0 +1,252 @@
+/**
+ * #5157 Taste T3: `gbrain jobs authorize-legacy --select <filter>` previews
+ * every matching SQL NULL row with a hash, and `--expect <hash> --yes`
+ * authorizes exactly that set through the shared preview-approval helper.
+ * Also pins the coded refusals that replaced the module's plain Errors
+ * (DX-O2) and that the command is CLI-only (ENG-O13).
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { applyLegacySelection, authorizeLegacyJobs, parseLegacyJobIds, previewLegacySelection } from '../src/core/minions/authorize-legacy.ts';
+import { parseLegacyJobSelection } from '../src/core/minions/legacy-selection.ts';
+import { assertNoUnreviewedJobs } from '../src/core/minions/submission-authority.ts';
+import { PREVIEW_APPROVAL_OP } from '../src/core/persistence/preview-approval.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { operations } from '../src/core/operations.ts';
+import { runJobs } from '../src/commands/jobs.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { argv } from './helpers/legacy-journey.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [PREVIEW_APPROVAL_OP]);
+});
+afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });
+
+async function legacy(name: string, status = 'waiting', authority: string | null = null): Promise<number> {
+ const job = await queue.add(name, { n: Math.random() }, {}, { allowProtectedSubmit: true });
+ if (status !== 'waiting') await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [job.id, status]);
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [job.id, authority]);
+ return job.id;
+}
+async function authorities(): Promise<Record<number, unknown>> {
+ const rows = await engine.executeRaw<{ id: number; submission_authority: unknown }>('SELECT id, submission_authority FROM minion_jobs ORDER BY id');
+ return Object.fromEntries(rows.map(r => [r.id, r.submission_authority]));
+}
+async function refusal(fn: () => unknown): Promise<OperationError> {
+ try { await fn(); } catch (error) { expect(error).toBeInstanceOf(OperationError); return error as OperationError; }
+ throw new Error('expected a refusal');
+}
+async function cli(args: string[]): Promise<{ out: string; err: string; exit: number }> {
+ const out: string[] = [], err: string[] = [];
+ const log = console.log, error = console.error;
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ console.error = (...a: unknown[]) => { err.push(a.join(' ')); };
+ try { await runJobs(engine, args); } finally { console.log = log; console.error = error; }
+ return { out: out.join('\n'), err: err.join('\n'), exit: currentExitCode() };
+}
+
+describe('--select grammar', () => {
+ test('status and name keys with | alternatives', () => {
+ expect(parseLegacyJobSelection('status=waiting|paused,name=synthesize|ingest_capture', 'authorize-legacy'))
+ .toEqual({ statuses: ['waiting', 'paused'], names: ['synthesize', 'ingest_capture'] });
+ expect(parseLegacyJobSelection('name=synthesize', 'authorize-legacy')).toEqual({ statuses: [], names: ['synthesize'] });
+ });
+
+ test('an unknown key or value refuses with legacy_job_selection_invalid listing the valid ones', async () => {
+ for (const raw of ['state=waiting', 'status=active', 'status=bogus', 'status=waiting,status=paused', 'status=', 'status=waiting|', '', undefined]) {
+ const error = await refusal(() => parseLegacyJobSelection(raw, 'authorize-legacy'));
+ expect(error.code, String(raw)).toBe('legacy_job_selection_invalid');
+ expect(error.message).toContain('status and name');
+ expect(error.message).toContain('waiting|delayed|waiting-children|paused|completed|failed');
+ expect(error.suggestion).toBe('gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture"');
+ expect(error.docs).toBe('docs/guides/repair.md#legacy-job-selection-invalid');
+ }
+ });
+});
+
+describe('authorize-legacy --select preview and apply', () => {
+ test('preview lists every matching SQL NULL id with a hash and changes nothing', async () => {
+ const a = await legacy('synthesize');
+ const b = await legacy('synthesize', 'paused');
+ const c = await legacy('ingest_capture');
+ const unsupported = await legacy('synthesize', 'waiting', '{"version":2,"kind":"application"}');
+ await queue.add('synthesize', { fresh: true }, {}, { allowProtectedSubmit: true });
+ const before = await authorities();
+ const preview = await previewLegacySelection(engine, parseLegacyJobSelection('status=waiting|paused,name=synthesize', 'authorize-legacy'));
+ expect(preview.summary).toEqual({ total: 2, by_name: { synthesize: { waiting: 1, paused: 1 } }, first_ids: [a, b] });
+ expect(preview.unsupported_ids).toEqual([unsupported]);
+ expect(preview.preview_hash).toMatch(/^[a-f0-9]{64}$/);
+ expect(preview.apply_command).toBe(`gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize" --expect ${preview.preview_hash} --yes`);
+ expect(await authorities()).toEqual(before);
+ expect(c).toBeGreaterThan(0);
+ });
+
+ test('apply authorizes exactly the previewed set, not rows that match later', async () => {
+ const a = await legacy('synthesize');
+ const selection = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const preview = await previewLegacySelection(engine, selection);
+ const late = await legacy('synthesize');
+ const result = await applyLegacySelection(engine, selection, preview.preview_hash!, true);
+ expect(result.authorized_ids).toEqual([a]);
+ const now = await authorities();
+ expect(now[a]).toEqual({ version: 1, kind: 'application' });
+ expect(now[late]).toBeNull();
+ // The approved set is consumed: replaying the same hash refuses.
+ expect((await refusal(() => applyLegacySelection(engine, selection, preview.preview_hash!, true))).code).toBe('preview_changed');
+ });
+
+ test('a stale or unknown hash refuses with preview_changed and authorizes nothing', async () => {
+ const a = await legacy('synthesize');
+ const selection = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const preview = await previewLegacySelection(engine, selection);
+ await engine.executeRaw('UPDATE minion_jobs SET priority = priority + 1 WHERE id = $1', [a]);
+ const stale = await refusal(() => applyLegacySelection(engine, selection, preview.preview_hash!, true));
+ expect(stale.code).toBe('preview_changed');
+ expect(stale.message).toContain(preview.preview_hash!);
+ expect(stale.suggestion).toBe('Re-run the preview: gbrain jobs authorize-legacy --select "status=waiting"');
+ expect(stale.docs).toBe('docs/guides/repair.md#preview-changed');
+ const unknown = await refusal(() => applyLegacySelection(engine, selection, 'b'.repeat(64), true));
+ expect(unknown.message).toBe(`The preview changed since ${'b'.repeat(64)}; re-run gbrain jobs authorize-legacy --select "status=waiting" and use the new hash.`);
+ // A hash previewed for another filter does not apply under this one.
+ const other = parseLegacyJobSelection('status=waiting,name=synthesize', 'authorize-legacy');
+ const otherPreview = await previewLegacySelection(engine, other);
+ expect((await refusal(() => applyLegacySelection(engine, selection, otherPreview.preview_hash!, true))).code).toBe('preview_changed');
+ expect((await authorities())[a]).toBeNull();
+ });
+
+ test('two filters that select the same rows keep separate approvals (Codex review)', async () => {
+ const a = await legacy('example-job');
+ const broad = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const narrow = parseLegacyJobSelection('status=waiting,name=example-job', 'authorize-legacy');
+ const first = await previewLegacySelection(engine, broad);
+ const second = await previewLegacySelection(engine, narrow);
+ expect(first.snapshot!.snapshot_digest).toBe(second.snapshot!.snapshot_digest);
+ expect(first.preview_hash).not.toBe(second.preview_hash);
+ expect((await applyLegacySelection(engine, broad, first.preview_hash!, true)).authorized_ids).toEqual([a]);
+ });
+
+ test('active jobs refuse with legacy_jobs_active listing up to 10 cancel commands', async () => {
+ await legacy('synthesize');
+ const active: number[] = [];
+ for (let i = 0; i < 11; i++) {
+ const job = await queue.add('busy', { i });
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 't', lock_until = now() + interval '1 hour', claim_generation = claim_generation + 1 WHERE id = $1`, [job.id]);
+ active.push(job.id);
+ }
+ const error = await refusal(() => previewLegacySelection(engine, parseLegacyJobSelection('status=waiting', 'authorize-legacy')));
+ expect(error.code).toBe('legacy_jobs_active');
+ expect(error.message).toContain('11 job(s) are active');
+ expect(error.suggestion).toContain('Stop producers (gbrain serve, gbrain autopilot) and workers');
+ for (const id of active.slice(0, 10)) expect(error.suggestion).toMatch(new RegExp(`gbrain jobs cancel ${id}\\b`));
+ expect(error.suggestion).not.toMatch(new RegExp(`gbrain jobs cancel ${active[10]}\\b`));
+ expect(error.suggestion).toContain('gbrain jobs list --status active');
+ expect(error.docs).toBe('docs/guides/repair.md#legacy-jobs-active');
+ });
+
+ test('17.8k-scale selection previews with a summary and applies in one transaction', async () => {
+ await engine.executeRaw(`INSERT INTO minion_jobs (name, status, data, submission_authority)
+ SELECT CASE WHEN g % 10 = 0 THEN 'ingest_capture' ELSE 'synthesize' END, 'waiting', jsonb_build_object('g', g), '{"version":1,"kind":"application"}'::jsonb
+ FROM generate_series(1, 17800) g`);
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL');
+ const selection = parseLegacyJobSelection('status=waiting', 'authorize-legacy');
+ const preview = await previewLegacySelection(engine, selection);
+ expect(preview.summary.total).toBe(17800);
+ expect(preview.summary.by_name).toEqual({ synthesize: { waiting: 16020 }, ingest_capture: { waiting: 1780 } });
+ expect(preview.summary.first_ids).toHaveLength(20);
+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');
+ const result = await applyLegacySelection(engine, selection, preview.preview_hash!, true);
+ expect(result.authorized).toBe(17800);
+ await assertNoUnreviewedJobs(engine);
+ }, 120_000);
+});
+
+describe('coded refusals on the --ids path (DX-O2)', () => {
+ test('missing ids, non-SQL-NULL rows and a stale digest carry codes, hints and anchors', async () => {
+ const missing = await refusal(() => parseLegacyJobIds(undefined));
+ expect(missing.code).toBe('legacy_job_selection_invalid');
+ expect(missing.suggestion).toContain('gbrain jobs authorize-legacy --ids 12,34');
+ const future = await legacy('synthesize', 'waiting', '{"version":2,"kind":"application"}');
+ const unsupported = await refusal(() => authorizeLegacyJobs(engine, [future]));
+ expect(unsupported.message).toContain('SQL NULL');
+ expect(unsupported.suggestion).toContain(`gbrain jobs cancel ${future}`);
+ const id = await legacy('synthesize');
+ const stale = await refusal(() => authorizeLegacyJobs(engine, [id], 'a'.repeat(64), true));
+ expect(stale.code).toBe('preview_changed');
+ expect(stale.message).toContain('snapshot changed');
+ expect(stale.suggestion).toBe(`Re-run the preview: gbrain jobs authorize-legacy --ids ${id}`);
+ const flags = await refusal(() => authorizeLegacyJobs(engine, [id], 'a'.repeat(64), false));
+ expect(flags.suggestion).toBe(`gbrain jobs authorize-legacy --ids ${id} --expect ${'a'.repeat(64)} --yes`);
+ });
+});
+
+describe('CLI transport (ENG-O12) and CLI-only pin (ENG-O13)', () => {
+ test('human preview summarizes and marks paid job names; --json carries the full rows', async () => {
+ const a = await legacy('synthesize');
+ await legacy('lint', 'paused');
+ await legacy('ingest_capture', 'paused');
+ const human = await cli(['authorize-legacy', '--select', 'status=waiting|paused']);
+ expect(human.exit).toBe(0);
+ expect(human.out).toContain('Legacy jobs matching status=waiting|paused (SQL NULL authority, authorizable): 3');
+ expect(human.out).toContain(' synthesize: waiting 1 [may make paid provider calls]');
+ expect(human.out).toContain(' ingest_capture: paused 1 [may make paid provider calls]');
+ expect(human.out).toContain(' lint: paused 1');
+ expect(human.out).not.toContain('lint: paused 1 [may');
+ expect(human.out).toMatch(/Apply exactly this set: gbrain jobs authorize-legacy --select "status=waiting\|paused" --expect [a-f0-9]{64} --yes/);
+ const json = JSON.parse((await cli(['authorize-legacy', '--select', 'status=waiting|paused', '--json'])).out);
+ expect(json.snapshot.jobs.map((job: { id: number }) => job.id)).toContain(a);
+ expect(json.paid_job_names).toEqual(['ingest_capture', 'synthesize']);
+ const applied = await cli(['authorize-legacy', '--select', 'status=waiting|paused', '--expect', json.preview_hash, '--yes']);
+ expect(applied.out).toContain('Authorized 3 legacy job(s) matching status=waiting|paused.');
+ });
+
+ test('--dry-run next to --expect/--yes previews and authorizes nothing (Codex review)', async () => {
+ const a = await legacy('synthesize');
+ const json = JSON.parse((await cli(['authorize-legacy', '--select', 'status=waiting', '--json'])).out);
+ const dry = await cli(['authorize-legacy', '--select', 'status=waiting', '--expect', json.preview_hash, '--yes', '--dry-run']);
+ expect(dry.out).toContain('Nothing was changed.');
+ expect((await authorities())[a]).toBeNull();
+ });
+
+ test('the printed recovery still selects a parent that a required cancel moved to waiting (Codex review)', async () => {
+ const parent = await legacy('fanout', 'waiting');
+ const child = await queue.add('busy', {}, { parent_job_id: parent });
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 't', lock_until = now() + interval '1 hour', claim_generation = claim_generation + 1 WHERE id = $1`, [child.id]);
+ const gate = await refusal(() => assertNoUnreviewedJobs(engine));
+ const preview = /preview with (gbrain jobs authorize-legacy --select "[^"]+")/.exec(gate.suggestion!)![1]!;
+ await queue.cancelJob(child.id);
+ expect((await queue.getJob(parent))?.status).toBe('waiting');
+ const printed = await cli(argv(preview).slice(2));
+ expect(printed.out).toContain('(SQL NULL authority, authorizable): 1');
+ });
+
+ test('a refusal prints the toJSON envelope with --json and exits 1', async () => {
+ const result = await cli(['authorize-legacy', '--select', 'state=waiting', '--json']);
+ expect(result.exit).toBe(1);
+ expect(JSON.parse(result.out)).toMatchObject({
+ error: 'legacy_job_selection_invalid',
+ suggestion: 'gbrain jobs authorize-legacy --select "status=waiting|paused,name=synthesize|ingest_capture"',
+ docs: 'docs/guides/repair.md#legacy-job-selection-invalid',
+ });
+ expect(result.err).toContain('Error [legacy_job_selection_invalid]: Unknown --select key "state"');
+ expect(result.err).toContain('Docs: docs/guides/repair.md#legacy-job-selection-invalid');
+ });
+
+ test('no operation exposes legacy authorization or bulk cancel to MCP or remediation', () => {
+ const names = operations.map(op => op.name);
+ expect(names.filter(name => /legacy|authorize_job|cancel_jobs/.test(name))).toEqual([]);
+ const cancel = operations.find(op => op.name === 'cancel_job')!;
+ expect(Object.keys(cancel.params)).toEqual(['id']);
+ });
+});
diff --git a/test/jobs-cancel-select.test.ts b/test/jobs-cancel-select.test.ts
new file mode 100644
index 0000000000..ec60ef70ad
--- /dev/null
+++ b/test/jobs-cancel-select.test.ts
@@ -0,0 +1,159 @@
+/**
+ * DX-T2 / ENG-O5: `gbrain jobs cancel --select <filter>` previews and hashes
+ * the complete cancellation closure (selected rows plus parent transitions),
+ * cancels exactly that set through cancelJobs with `--expect <hash> --yes`,
+ * and refuses a selection that would cascade to a descendant outside it.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { applyLegacyCancel, previewLegacyCancel } from '../src/core/minions/legacy-cancel.ts';
+import { parseLegacyJobSelection } from '../src/core/minions/legacy-selection.ts';
+import { assertNoUnreviewedJobs } from '../src/core/minions/submission-authority.ts';
+import { PREVIEW_APPROVAL_OP } from '../src/core/persistence/preview-approval.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { runJobs } from '../src/commands/jobs.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+
+let engine: PGLiteEngine;
+let queue: MinionQueue;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ queue = new MinionQueue(engine);
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM op_checkpoints WHERE op = $1', [PREVIEW_APPROVAL_OP]);
+});
+afterEach(() => { _resetCliExitVerdictForTests(); process.exitCode = 0; });
+
+const sel = (raw: string) => parseLegacyJobSelection(raw, 'cancel');
+async function job(name: string, opts: { parent?: number; authority?: string | null; status?: string } = {}): Promise<number> {
+ const added = await queue.add(name, { n: Math.random() }, opts.parent ? { parent_job_id: opts.parent } : {});
+ if (opts.status) await engine.executeRaw('UPDATE minion_jobs SET status = $2 WHERE id = $1', [added.id, opts.status]);
+ if (opts.authority !== undefined) await engine.executeRaw('UPDATE minion_jobs SET submission_authority = $2::text::jsonb WHERE id = $1', [added.id, opts.authority]);
+ return added.id;
+}
+async function statuses(): Promise<Record<number, string>> {
+ const rows = await engine.executeRaw<{ id: number; status: string }>('SELECT id, status FROM minion_jobs ORDER BY id');
+ return Object.fromEntries(rows.map(r => [r.id, r.status]));
+}
+async function refusal(fn: () => unknown): Promise<OperationError> {
+ try { await fn(); } catch (error) { expect(error).toBeInstanceOf(OperationError); return error as OperationError; }
+ throw new Error('expected a refusal');
+}
+
+describe('jobs cancel --select', () => {
+ test('preview lists and hashes the closure, including parent transitions, and changes nothing', async () => {
+ const parent = await job('fanout');
+ const child = await job('legacy-child', { parent, authority: null });
+ const loner = await job('legacy-loner', { authority: 'null' });
+ const keep = await job('legacy-child', { authority: null, status: 'completed' });
+ const before = await statuses();
+ const preview = await previewLegacyCancel(engine, sel('status=waiting'));
+ expect(preview.summary.first_ids).toEqual([child, loner]);
+ expect(preview.unsupported_ids).toEqual([loner]);
+ expect(preview.parent_transitions).toEqual([{ id: parent, from: 'waiting-children', to: 'waiting' }]);
+ expect(preview.apply_command).toBe(`gbrain jobs cancel --select "status=waiting" --expect ${preview.preview_hash} --yes`);
+ expect(await statuses()).toEqual(before);
+ expect(before[keep]).toBe('completed');
+ });
+
+ test('apply cancels exactly the previewed set, applies the parent transition and unblocks workers', async () => {
+ const parent = await job('fanout');
+ const child = await job('legacy-child', { parent, authority: null });
+ const loner = await job('legacy-loner', { authority: 'null' });
+ const preview = await previewLegacyCancel(engine, sel('status=waiting'));
+ const late = await job('legacy-late', { authority: null, status: 'paused' });
+ await expect(assertNoUnreviewedJobs(engine)).rejects.toThrow('legacy jobs');
+ const result = await applyLegacyCancel(engine, sel('status=waiting'), preview.preview_hash!, true);
+ expect(result.cancelled_ids).toEqual([child, loner]);
+ const now = await statuses();
+ expect(now[child]).toBe('cancelled');
+ expect(now[loner]).toBe('cancelled');
+ expect(now[parent]).toBe('waiting');
+ expect(now[late]).toBe('paused');
+ expect((await refusal(() => applyLegacyCancel(engine, sel('status=waiting'), preview.preview_hash!, true))).code).toBe('preview_changed');
+ await engine.executeRaw('DELETE FROM minion_jobs WHERE id = $1', [late]);
+ await assertNoUnreviewedJobs(engine);
+ });
+
+ test('a stale hash refuses with preview_changed and cancels nothing', async () => {
+ const a = await job('legacy', { authority: null });
+ const preview = await previewLegacyCancel(engine, sel('status=waiting'));
+ await engine.executeRaw('UPDATE minion_jobs SET priority = priority + 1, updated_at = now() + interval \'1 second\' WHERE id = $1', [a]);
+ const error = await refusal(() => applyLegacyCancel(engine, sel('status=waiting'), preview.preview_hash!, true));
+ expect(error.code).toBe('preview_changed');
+ expect(error.message).toBe(`The preview changed since ${preview.preview_hash}; re-run gbrain jobs cancel --select "status=waiting" and use the new hash.`);
+ expect((await statuses())[a]).toBe('waiting');
+ });
+
+ test('a mixed-authority tree refuses: the application child is outside the selection', async () => {
+ const parent = await job('legacy-parent');
+ const appChild = await job('worker-step', { parent });
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = $1', [parent]);
+ const error = await refusal(() => previewLegacyCancel(engine, sel('status=waiting-children')));
+ expect(error.code).toBe('legacy_job_selection_invalid');
+ expect(error.message).toBe(`Cancelling the selection would also cancel 1 descendant job(s) outside it: ${appChild}.`);
+ expect(error.suggestion).toContain(`gbrain jobs cancel ${appChild}`);
+ expect((await statuses())[appChild]).toBe('waiting');
+ });
+
+ test('an outside-set legacy descendant refuses until the filter selects it', async () => {
+ const parent = await job('legacy-parent');
+ const child = await job('legacy-child', { parent });
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL WHERE id = ANY($1::int[])', [[parent, child]]);
+ const error = await refusal(() => previewLegacyCancel(engine, sel('name=legacy-parent')));
+ expect(error.message).toContain(`outside it: ${child}.`);
+ const widened = await previewLegacyCancel(engine, sel('name=legacy-parent|legacy-child'));
+ expect(widened.summary.first_ids).toEqual([parent, child]);
+ await applyLegacyCancel(engine, sel('name=legacy-parent|legacy-child'), widened.preview_hash!, true);
+ expect(await statuses()).toEqual({ [parent]: 'cancelled', [child]: 'cancelled' });
+ });
+
+ test('active jobs refuse with legacy_jobs_active', async () => {
+ await job('legacy', { authority: null });
+ const busy = await job('busy');
+ await engine.executeRaw(`UPDATE minion_jobs SET status = 'active', lock_token = 't', lock_until = now() + interval '1 hour', claim_generation = claim_generation + 1 WHERE id = $1`, [busy]);
+ const error = await refusal(() => previewLegacyCancel(engine, sel('status=waiting')));
+ expect(error.code).toBe('legacy_jobs_active');
+ expect(error.suggestion).toContain(`gbrain jobs cancel ${busy}`);
+ });
+
+ test('CLI: preview, --json and apply through runJobs; jobs cancel <id> is unchanged', async () => {
+ const out: string[] = [];
+ const log = console.log, err = console.error;
+ console.log = (...a: unknown[]) => { out.push(a.join(' ')); };
+ console.error = () => {};
+ try {
+ const a = await job('synthesize-legacy', { authority: null });
+ await runJobs(engine, ['cancel', '--select', 'status=waiting']);
+ expect(out.join('\n')).toContain('Legacy jobs matching status=waiting to cancel (missing or unsupported authority): 1');
+ out.length = 0;
+ await runJobs(engine, ['cancel', '--select', 'status=waiting', '--json']);
+ const preview = JSON.parse(out.join('\n'));
+ expect(preview.rows.map((r: { id: number }) => r.id)).toEqual([a]);
+ out.length = 0;
+ await runJobs(engine, ['cancel', '--select', 'status=waiting', '--expect', preview.preview_hash, '--yes', '--dry-run']);
+ expect(out.join('\n')).toContain('Nothing was changed.');
+ expect((await statuses())[a]).toBe('waiting');
+ out.length = 0;
+ await runJobs(engine, ['cancel', '--select', 'status=waiting', '--expect', preview.preview_hash, '--yes']);
+ expect(out.join('\n')).toBe('Cancelled 1 legacy job(s) matching status=waiting.');
+ out.length = 0;
+ await runJobs(engine, ['cancel', '--select', 'status=active', '--json']);
+ expect(JSON.parse(out.join('\n')).error).toBe('legacy_job_selection_invalid');
+ expect(currentExitCode()).toBe(1);
+ const plain = await job('plain');
+ out.length = 0;
+ await runJobs(engine, ['cancel', String(plain)]);
+ expect(out.join('\n')).toBe(`Job #${plain} cancelled.`);
+ } finally {
+ console.log = log; console.error = err;
+ }
+ });
+});
diff --git a/test/journey-atoms-sync-race.test.ts b/test/journey-atoms-sync-race.test.ts
new file mode 100644
index 0000000000..e56e14b8f4
--- /dev/null
+++ b/test/journey-atoms-sync-race.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Cross-lane journey (ENG-O14): #5770 together with #5777, on PGLite and, with
+ * a safe DATABASE_URL, Postgres (test/e2e/journey-atoms-sync-race-postgres.test.ts).
+ *
+ * A managed source page is synced and extracted, edited through sync, caught
+ * in the trailing-commit window of a queued publication (#5777: skipped, not a
+ * sticky source_changed), re-extracted (#5774 retires the stale atom), deleted
+ * and cleaned up by `gbrain repair stale-atoms`, then restored: discovery
+ * offers it again and extraction restores every atom of its current text.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { runPhaseExtractAtoms, discoverExtractablePages } from '../src/core/cycle/extract-atoms.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { loadSyncFailures } from '../src/core/sync-failure-ledger.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const note = (text: string) => `---\ntitle: Example note\ntype: source\n---\n${`${text} `.repeat(40).trim()}\n`;
+
+for (const kind of testBackends()) {
+ describe(`#5770 with #5777 (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-journey-atoms-sync-'));
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ }, 120_000);
+ afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));
+ if (close) await close(); else await engine.disconnect();
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('queued publication, stale-atom preview, source change, retirement, restoration and rediscovery', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const sourceId = `journey-${randomUUID().replace(/-/g, '').slice(0, 12)}`;
+ const root = join(home, sourceId);
+ const slug = 'notes/example';
+ const path = join(root, 'notes/example.md');
+ const git = (...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ const commit = (message: string) => { git('add', 'notes/example.md'); git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message); return git('rev-parse', 'HEAD'); };
+ mkdirSync(join(root, 'notes'), { recursive: true }); git('init', '-q');
+ writeFileSync(path, note('The first project record.')); commit('first');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const unmanaged = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ };
+ let titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return { text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ const extract = async () => {
+ const page = (await engine.getPage(slug, { sourceId }))!;
+ return runPhaseExtractAtoms(engine, { sourceId, _transcripts: [], _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat });
+ };
+ const atoms = async () => Object.fromEntries((await engine.executeRaw<{ slug: string; deleted: boolean; retired_by: string | null }>(
+ "SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter->>'retired_by' AS retired_by FROM pages WHERE source_id=$1 AND type='atom'", [sourceId]))
+ .map(row => [row.slug.replace(/^atoms\/[^/]+\//, '').replace(/-[0-9a-f]+$/, ''), { deleted: row.deleted, retired_by: row.retired_by }]));
+ const repair = async (args: string[]) => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, [...args, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')).results[0] as { apply_command: string; listing: Array<{ class: string }>; outcomes?: Record<string, number> };
+ };
+ const failures = () => loadSyncFailures().filter(row => row.source_id === sourceId);
+
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).toBe('first_sync');
+ expect((await extract()).status).toBe('ok');
+ expect(await atoms()).toEqual({ 'patience-compounds': { deleted: false, retired_by: null }, 'hire-slowly': { deleted: false, retired_by: null } });
+
+ writeFileSync(path, note('The edited project record.')); commit('edit');
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).not.toBe('blocked_by_failures');
+ writeFileSync(path, note('An older record a trailing commit still carries.')); const trailing = commit('trailing'); writeFileSync(path, note('The edited project record.'));
+ const raced = await performManagedSync(engine, { sourceId, noPull: true });
+ expect(raced.status).not.toBe('blocked_by_failures');
+ expect(raced.managedWrite).toBeUndefined();
+ expect(raced.toCommit).toBe(trailing);
+ expect(failures()).toEqual([]);
+ expect((await engine.getPage(slug, { sourceId }))?.compiled_truth).toContain('The edited project record.');
+
+ titles = ['Patience compounds over years', 'Hire slowly'];
+ expect((await extract()).status).toBe('ok');
+ expect(await atoms()).toMatchObject({ 'patience-compounds': { deleted: true, retired_by: 'managed-reextract' },
+ 'patience-compounds-over-years': { deleted: false }, 'hire-slowly': { deleted: false } });
+
+ await unmanaged(() => engine.softDeletePage(slug, { sourceId }));
+ const preview = await repair(['stale-atoms', '--source', sourceId]);
+ expect(preview.listing.map(entry => entry.class)).toEqual(['origin_gone', 'origin_gone']);
+ expect(preview.apply_command).toMatch(/^gbrain repair stale-atoms --source \S+ --apply --expect [0-9a-f]{64}$/);
+ expect((await repair(preview.apply_command.split(' ').slice(2))).outcomes).toEqual({ retired: 2 });
+ expect(await atoms()).toMatchObject({ 'patience-compounds-over-years': { deleted: true, retired_by: 'stale-atoms' },
+ 'hire-slowly': { deleted: true, retired_by: 'stale-atoms' } });
+
+ await unmanaged(() => engine.restorePage(slug, { sourceId }));
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([slug]);
+ titles = ['Patience compounds', 'Hire slowly'];
+ expect((await extract()).status).toBe('ok');
+ expect(calls).toBe(3);
+ expect(await atoms()).toEqual({ 'patience-compounds': { deleted: false, retired_by: null }, 'hire-slowly': { deleted: false, retired_by: null },
+ 'patience-compounds-over-years': { deleted: true, retired_by: 'stale-atoms' } });
+ expect(await discoverExtractablePages(engine, sourceId)).toEqual([]);
+ expect((await performManagedSync(engine, { sourceId, noPull: true })).status).not.toBe('blocked_by_failures');
+ expect(failures()).toEqual([]);
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }), 120_000);
+ });
+}
diff --git a/test/managed-extract-atoms.test.ts b/test/managed-extract-atoms.test.ts
index fdfa7f1e8d..e0b74a4d88 100644
--- a/test/managed-extract-atoms.test.ts
+++ b/test/managed-extract-atoms.test.ts
@@ -9,7 +9,7 @@ import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
import { stopPersistenceConsumer } from '../src/core/persistence/service.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { withEnv } from './helpers/with-env.ts';
-import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority } from './helpers/managed-atoms-contract.ts';
+import { atomContractCases, exerciseManagedAtoms, atomBatchCases, exerciseManagedAtomBatch, atomAuthorityCases, exerciseManagedAtomAuthority, exerciseManagedAtomReconciliation, atomRetirementCases, exerciseManagedAtomRetirement } from './helpers/managed-atoms-contract.ts';
let engine: PGLiteEngine;
beforeAll(async () => {
@@ -52,3 +52,6 @@ test('managed public atom extraction publishes searchable atoms and replays with
});
} finally { await stopPersistenceConsumer(engine); rmSync(home, { recursive: true, force: true }); }
}, 60_000);
+
+test('managed extraction retires stale atom pages and files after a source edit', () => exerciseManagedAtomReconciliation(engine), 60_000);
+for (const scenario of atomRetirementCases) test(`managed atom retirement ${scenario}`, () => exerciseManagedAtomRetirement(engine, scenario), 60_000);
diff --git a/test/managed-write-single-attribution.test.ts b/test/managed-write-single-attribution.test.ts
new file mode 100644
index 0000000000..56aea8d261
--- /dev/null
+++ b/test/managed-write-single-attribution.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Managed `writeSingleFact` attribution (fix wave 5, TODOS "Managed
+ * writeSingleFact keeps unresolved entity attribution"), on PGLite and, with a
+ * safe DATABASE_URL, Postgres (test/e2e/managed-write-single-attribution-postgres.test.ts).
+ *
+ * Protects: on a managed brain, the same commitment remembered for two people
+ * who have no pages lands as two facts, each keeping the resolver's fallback
+ * slug database-only (no row number, no page, no file); the same claim for the
+ * same absent person still deduplicates. The facts backstop (extract_facts)
+ * never opts in: its absent-entity rows stay unattributed, deduplicate within
+ * a batch, and replay without provider calls.
+ * Fails when: the managed fact intent drops the fallback slug for
+ * writeSingleFact (the second person's fact dedups against the first), or the
+ * opt-in leaks into the backstop.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, readdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';
+import { operationsByName } from '../src/core/operations.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const CLAIM = 'Will send the signed contract by Friday.';
+
+for (const backend of testBackends()) {
+ describe(`managed writeSingleFact attribution (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-write-single-attribution-'));
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ }, 120_000);
+ afterEach(async () => {
+ __setChatTransportForTests(null); __setEmbedTransportForTests(null); resetGateway();
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ });
+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); rmSync(dir, { recursive: true, force: true }); });
+
+ /** A fresh source with a claimed worktree, then managed mode on. */
+ async function managedSource(run: (sourceId: string, root: string) => Promise<void>): Promise<void> {
+ const sourceId = `attr-${randomUUID().slice(0, 8)}`;
+ const root = mkdtempSync(join(dir, 'root-'));
+ await withEnv({ GBRAIN_HOME: join(dir, `home-${sourceId}`) }, async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await run(sourceId, root);
+ });
+ }
+ const rows = (sourceId: string) => engine.executeRaw<{ id: number; entity_slug: string | null; row_num: number | null; source_markdown_slug: string | null }>(
+ 'SELECT id::int AS id, entity_slug, row_num, source_markdown_slug FROM facts WHERE source_id=$1 ORDER BY id', [sourceId]);
+
+ test('the same commitment for two people with no pages lands as two facts, each keeping its fallback slug', async () => {
+ await managedSource(async (sourceId, root) => {
+ const remember = (entity: string) => writeSingleFact(engine, sourceId, { fact: CLAIM, provenance: 'fixture', entity, kind: 'commitment' });
+ const alice = await remember('Alice Absent');
+ const bob = await remember('Bob Absent');
+ expect([alice.status, bob.status]).toEqual(['inserted', 'inserted']);
+ expect(bob.id).not.toBe(alice.id);
+ expect([alice.entity_slug, bob.entity_slug]).toEqual(['alice-absent', 'bob-absent']);
+ const again = await remember('Alice Absent');
+ expect(again).toMatchObject({ status: 'duplicate', id: alice.id, entity_slug: 'alice-absent' });
+ expect(await rows(sourceId)).toEqual([
+ { id: alice.id, entity_slug: 'alice-absent', row_num: null, source_markdown_slug: null },
+ { id: bob.id, entity_slug: 'bob-absent', row_num: null, source_markdown_slug: null },
+ ]);
+ const requests = await engine.executeRaw<{ slug: string; flag: string | null }>(`SELECT slug, intent->>'attribute_fallback' AS flag FROM persistence_requests
+ WHERE source_id=$1 AND operation='extract_facts' AND state='committed' AND intent->>'kind'='managed_facts_entity' ORDER BY sequence`, [sourceId]);
+ expect(requests).toEqual([0, 1, 2].map(() => ({ slug: 'memory/unattributed', flag: 'true' })));
+ expect(await engine.getPage('memory/unattributed', { sourceId })).toBeNull();
+ expect(readdirSync(root).filter(name => !name.startsWith('.gbrain'))).toEqual([]);
+ });
+ }, 120_000);
+
+ test('the facts backstop never opts in: absent entities stay unattributed, dedup within the batch, and replay without provider calls', async () => {
+ await managedSource(async sourceId => {
+ let calls = 0;
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: { OPENAI_API_KEY: 'test' } });
+ __setChatTransportForTests(async () => { calls++; return { text: JSON.stringify({ facts: [
+ { fact: CLAIM, kind: 'commitment', entity: 'Alice Absent', confidence: 0.9, notability: 'high' },
+ { fact: CLAIM, kind: 'commitment', entity: 'Bob Absent', confidence: 0.9, notability: 'high' },
+ ] }), blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'test:stub', providerId: 'test' }; });
+ const ctx = { engine, config: { engine: engine.kind, embedding_disabled: true }, remote: false, sourceId, dryRun: false, logger: console };
+ const params = { turn_text: 'Alice Absent and Bob Absent both said they will send the signed contract by Friday.', request_id: randomUUID() };
+ const first = await operationsByName.extract_facts.handler(ctx as never, params) as { inserted: number; duplicate: number; fact_ids: number[] };
+ expect(first).toMatchObject({ inserted: 1, duplicate: 1 });
+ expect(new Set(first.fact_ids).size).toBe(1);
+ expect((await rows(sourceId)).map(row => row.entity_slug)).toEqual([null]);
+ const flags = await engine.executeRaw("SELECT 1 FROM persistence_requests WHERE source_id=$1 AND intent ? 'attribute_fallback'", [sourceId]);
+ expect(flags).toEqual([]);
+ const replay = await operationsByName.extract_facts.handler(ctx as never, params);
+ expect(replay).toEqual(first);
+ expect(calls).toBe(1);
+ });
+ }, 120_000);
+ });
+}
diff --git a/test/mcp-stdio-source-resolution.test.ts b/test/mcp-stdio-source-resolution.test.ts
index 3a6b7ca3bc..0094384b74 100644
--- a/test/mcp-stdio-source-resolution.test.ts
+++ b/test/mcp-stdio-source-resolution.test.ts
@@ -52,7 +52,31 @@ describe('stdio MCP source resolution', () => {
dir,
);
- expect(scope).toEqual({ sourceId: 'team-alpha', tier: 'dotfile' });
+ // #5081: an explicit tier carries the explicit-read binding; no source
+ // in this fixture is federated, so it admits only the bound source.
+ expect(scope).toEqual({
+ sourceId: 'team-alpha',
+ tier: 'dotfile',
+ explicitReadBinding: { sourceId: 'team-alpha', via: '.gbrain-source', sourceIds: ['team-alpha'], optedOut: [] },
+ });
+ });
+ });
+
+ test('#5081: a failed admission lookup keeps the resolved pin instead of falling back to default', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-mcp-source-'));
+ scratchDirs.push(dir);
+ writeSourceDotfile(dir, 'team-alpha');
+ const base = makeEngine(['default', 'team-alpha']);
+ const failing = {
+ ...base,
+ executeRaw: async <T>(sql: string, params?: unknown[]): Promise<T[]> => {
+ if (/SELECT id, config/.test(sql)) throw new Error('sources table unavailable');
+ return base.executeRaw<T>(sql, params);
+ },
+ } as unknown as BrainEngine;
+
+ await withEnv({ GBRAIN_SOURCE: undefined }, async () => {
+ expect(await resolveMcpStdioSourceScope(failing, dir)).toEqual({ sourceId: 'team-alpha', tier: 'dotfile' });
});
});
@@ -67,7 +91,11 @@ describe('stdio MCP source resolution', () => {
dir,
);
- expect(scope).toEqual({ sourceId: 'env-source', tier: 'env' });
+ expect(scope).toEqual({
+ sourceId: 'env-source',
+ tier: 'env',
+ explicitReadBinding: { sourceId: 'env-source', via: 'GBRAIN_SOURCE', sourceIds: ['env-source'], optedOut: [] },
+ });
});
});
});
diff --git a/test/migration-child-cli.test.ts b/test/migration-child-cli.test.ts
new file mode 100644
index 0000000000..5367ed7e3a
--- /dev/null
+++ b/test/migration-child-cli.test.ts
@@ -0,0 +1,81 @@
+/**
+ * #5184: migration children run the CLI that is running the migration, not
+ * whatever `gbrain` PATH resolves to. A PATH `gbrain` can be another version,
+ * or a wrapper that sets its own GBRAIN_HOME / database URL, so backfills
+ * (extract links/timeline, repair-jsonb), smoke checks and the autopilot
+ * install acted on another brain.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+import { gbrainChildCommand, runGbrainSubprocess } from '../src/commands/migrations/in-process.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+
+describe('#5184 gbrainChildCommand', () => {
+ test('a compiled CLI replaces every gbrain command word, including after ||', () => {
+ expect(gbrainChildCommand('gbrain get_stats --json 2>/dev/null || gbrain stats', {}, '/opt/gbrain-1/gbrain', undefined))
+ .toBe("'/opt/gbrain-1/gbrain' get_stats --json 2>/dev/null || '/opt/gbrain-1/gbrain' stats");
+ });
+
+ test('a source run invokes bun with the running cli.ts', () => {
+ expect(gbrainChildCommand('gbrain extract links --source db', {}, '/usr/local/bin/bun', '/repo/src/cli.ts'))
+ .toBe("'/usr/local/bin/bun' '/repo/src/cli.ts' extract links --source db");
+ });
+
+ test('paths with quotes stay one shell word', () => {
+ expect(gbrainChildCommand('gbrain jobs smoke', {}, "/opt/o'brien/gbrain", undefined))
+ .toBe("'/opt/o'\\''brien/gbrain' jobs smoke");
+ });
+
+ test('Windows uses double quotes (execSync runs cmd.exe there)', () => {
+ expect(gbrainChildCommand('gbrain jobs smoke', {}, 'C:\\Program Files\\gbrain\\gbrain.exe', undefined, 'win32'))
+ .toBe('"C:\\Program Files\\gbrain\\gbrain.exe" jobs smoke');
+ });
+
+ test('only command words change: arguments and other commands are left alone', () => {
+ expect(gbrainChildCommand('gbrain jobs submit gbrain-x', {}, '/b/gbrain', undefined)).toBe("'/b/gbrain' jobs submit gbrain-x");
+ expect(gbrainChildCommand("sh -c 'echo gbrain'", {}, '/b/gbrain', undefined)).toBe("sh -c 'echo gbrain'");
+ });
+
+ test('when the running CLI cannot be identified, PATH resolution is kept', () => {
+ expect(gbrainChildCommand('gbrain jobs smoke', {}, '/usr/local/bin/bun', '/repo/test/x.test.ts')).toBe('gbrain jobs smoke');
+ });
+});
+
+describe('#5184 runGbrainSubprocess runs the resolved CLI, not a PATH decoy', () => {
+ test('the child is the resolved CLI even with a different gbrain first on PATH', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5184-'));
+ try {
+ writeFileSync(join(dir, 'gbrain'), '#!/bin/sh\necho "DECOY $@"\n', { mode: 0o755 });
+ const running = join(dir, 'running-cli');
+ writeFileSync(running, '#!/bin/sh\necho "RUNNING $@"\n', { mode: 0o755 });
+ await withEnv({ PATH: `${dir}:${process.env.PATH ?? ''}`, GBRAIN_JOB_CHILD_CLI: running }, () => {
+ expect(runGbrainSubprocess('gbrain extract links --source db').trim()).toBe('RUNNING extract links --source db');
+ });
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('#5184 no migration spawns a name-resolved gbrain', () => {
+ test('every direct execSync of a gbrain command goes through gbrainChildCommand', () => {
+ const dir = join(REPO, 'src', 'commands', 'migrations');
+ const offenders: string[] = [];
+ for (const file of readdirSync(dir).filter(f => f.endsWith('.ts'))) {
+ // test-reads-source-ok[structural]: every migration spawn site, including ones only reachable mid-upgrade, must use the resolved CLI.
+ const src = readFileSync(join(dir, file), 'utf-8');
+ const lines = src.split('\n');
+ lines.forEach((line, i) => {
+ if (/^\s*(\/\/|\*)/.test(line)) return;
+ if (/(?:execSync|spawnSync|execFileSync)\(\s*['"`]gbrain\b/.test(line)) offenders.push(`${file}:${i + 1}`);
+ });
+ }
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/test/migrations-v0_11_0.test.ts b/test/migrations-v0_11_0.test.ts
index 0e1a6d176a..f0870b086d 100644
--- a/test/migrations-v0_11_0.test.ts
+++ b/test/migrations-v0_11_0.test.ts
@@ -28,18 +28,29 @@ const {
} = __testing;
let tmp: string;
+let gbrainHome: string;
let origHome: string | undefined;
+let origGbrainHome: string | undefined;
+// HOME holds the host-agent scopes ($HOME/.claude, $HOME/.openclaw); the
+// gbrain home is a SEPARATE dir so every test also proves that migration
+// state follows GBRAIN_HOME, never $HOME/.gbrain (#5549).
beforeEach(() => {
origHome = process.env.HOME;
+ origGbrainHome = process.env.GBRAIN_HOME;
tmp = mkdtempSync(join(tmpdir(), 'gbrain-v0_11_0-test-'));
+ gbrainHome = mkdtempSync(join(tmpdir(), 'gbrain-v0_11_0-gbrain-home-'));
process.env.HOME = tmp;
+ process.env.GBRAIN_HOME = gbrainHome;
});
afterEach(() => {
if (origHome === undefined) delete process.env.HOME;
else process.env.HOME = origHome;
+ if (origGbrainHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = origGbrainHome;
try { rmSync(tmp, { recursive: true, force: true }); } catch { /* best-effort */ }
+ try { rmSync(gbrainHome, { recursive: true, force: true }); } catch { /* best-effort */ }
});
function writeAgentsMd(dir: string, body: string) {
@@ -259,6 +270,37 @@ describe('cron manifest rewrite — gbrain builtins only', () => {
});
});
+describe('GBRAIN_HOME resolution (#5549)', () => {
+ test('pending-host-work.jsonl lands under GBRAIN_HOME, not $HOME/.gbrain', () => {
+ const path = writeCronJson(join(tmp, '.claude'), [
+ { schedule: '0 */30 * * *', kind: 'agentTurn', skill: 'ea-inbox-sweep' },
+ ]);
+ rewriteCronManifest(path, DEFAULT_OPTS);
+
+ const expected = join(gbrainHome, '.gbrain', 'migrations', 'pending-host-work.jsonl');
+ expect(existsSync(expected)).toBe(true);
+ expect(readFileSync(expected, 'utf-8')).toContain('ea-inbox-sweep');
+ expect(existsSync(join(tmp, '.gbrain'))).toBe(false);
+ });
+
+ test('engine detection reads config.json from GBRAIN_HOME', () => {
+ // Only the GBRAIN_HOME brain is PGLite; $HOME/.gbrain says postgres.
+ // A PGLite brain needs --follow on rewritten builtin cron entries.
+ mkdirSync(join(gbrainHome, '.gbrain'), { recursive: true });
+ writeFileSync(join(gbrainHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite' }));
+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });
+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres' }));
+
+ const path = writeCronJson(join(tmp, '.claude'), [
+ { schedule: '*/5 * * * *', kind: 'agentTurn', skill: 'sync' },
+ ]);
+ rewriteCronManifest(path, DEFAULT_OPTS);
+
+ const after = JSON.parse(readFileSync(path, 'utf-8'));
+ expect(after.jobs[0].cmd).toContain('--follow');
+ });
+});
+
describe('findAgentsMdFiles + findCronManifests scoping', () => {
test('finds AGENTS.md in $HOME/.claude and $HOME/.openclaw scopes', () => {
mkdirSync(join(tmp, '.claude'), { recursive: true });
diff --git a/test/migrations-v0_13_0.test.ts b/test/migrations-v0_13_0.test.ts
index 8e213fe5d2..04778f0e76 100644
--- a/test/migrations-v0_13_0.test.ts
+++ b/test/migrations-v0_13_0.test.ts
@@ -61,8 +61,9 @@ describe('v0.13.0 — Frontmatter relationship indexing migration', () => {
// Backfill extract goes through the stderr-capturing wrapper (still bare
// `gbrain` so the canonical shim on PATH wins).
expect(src).toContain("runGbrainSubprocess('gbrain extract links --source db --include-frontmatter'");
- // Stats readback still shells out (reads stdout); bare gbrain.
- expect(src).toContain("execSync('gbrain call get_stats'");
+ // Stats readback still shells out (reads stdout), through the running
+ // CLI rather than PATH (#5184).
+ expect(src).toContain("execSync(gbrainChildCommand('gbrain call get_stats')");
});
test('phase commands never reference `bun` or `.ts` paths (Bug 1 regression)', () => {
diff --git a/test/migrations-v0_22_4.test.ts b/test/migrations-v0_22_4.test.ts
index ccdf048097..a62076b704 100644
--- a/test/migrations-v0_22_4.test.ts
+++ b/test/migrations-v0_22_4.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, test } from 'bun:test';
import { v0_22_4 } from '../src/commands/migrations/v0_22_4.ts';
import { migrations, getMigration } from '../src/commands/migrations/index.ts';
+import { join } from 'path';
+import { withEnv } from './helpers/with-env.ts';
describe('v0.22.4 migration (B11)', () => {
test('exports a Migration with the right version', () => {
@@ -57,6 +59,15 @@ describe('v0.22.4 migration (B11)', () => {
expect(__testing.pendingHostWorkPath()).toMatch(/pending-host-work\.jsonl$/);
});
+ test('output paths resolve under GBRAIN_HOME, not $HOME/.gbrain (#5549)', async () => {
+ const { __testing } = await import('../src/commands/migrations/v0_22_4.ts');
+ await withEnv({ HOME: '/tmp/gbrain-5549-home', GBRAIN_HOME: '/tmp/gbrain-5549-gbrain-home' }, () => {
+ const migrationsDir = join('/tmp/gbrain-5549-gbrain-home', '.gbrain', 'migrations');
+ expect(__testing.auditReportPath()).toBe(join(migrationsDir, 'v0.22.4-audit.json'));
+ expect(__testing.pendingHostWorkPath()).toBe(join(migrationsDir, 'pending-host-work.jsonl'));
+ });
+ });
+
test('dotted migration filename references — emit-todo entries point at v0.22.4.md', async () => {
// The runtime convention is dotted (v0.22.4.md), not underscored.
// Source-grep guards the contract without spinning up a real audit.
@@ -71,9 +82,15 @@ describe('v0.22.4 migration (B11)', () => {
const fs = await import('fs');
const path = await import('path');
const os = await import('os');
+ // HOME and GBRAIN_HOME point at different dirs so the write must follow
+ // GBRAIN_HOME, never $HOME/.gbrain (#5549). Bun's os.homedir() ignores
+ // runtime HOME changes, so HOME alone does not isolate the test.
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-migration-test-'));
+ const gbrainHome = fs.mkdtempSync(path.join(os.tmpdir(), 'gbrain-migration-gbrain-home-'));
const origHome = process.env.HOME;
+ const origGbrainHome = process.env.GBRAIN_HOME;
process.env.HOME = tmpHome;
+ process.env.GBRAIN_HOME = gbrainHome;
try {
const fakeReport = {
ok: false,
@@ -120,7 +137,10 @@ describe('v0.22.4 migration (B11)', () => {
fakeReport,
);
expect(r.status).toBe('complete');
- const jsonl = fs.readFileSync(__testing.pendingHostWorkPath(), 'utf8');
+ const expectedPath = path.join(gbrainHome, '.gbrain', 'migrations', 'pending-host-work.jsonl');
+ expect(fs.existsSync(expectedPath)).toBe(true);
+ expect(fs.existsSync(path.join(tmpHome, '.gbrain'))).toBe(false);
+ const jsonl = fs.readFileSync(expectedPath, 'utf8');
const lines = jsonl.split('\n').filter(Boolean);
// Two sources had issues; clean-source should NOT produce an entry.
expect(lines.length).toBe(2);
@@ -142,8 +162,12 @@ describe('v0.22.4 migration (B11)', () => {
expect(e.command).toContain('--fix');
}
} finally {
- process.env.HOME = origHome;
+ if (origHome === undefined) delete process.env.HOME;
+ else process.env.HOME = origHome;
+ if (origGbrainHome === undefined) delete process.env.GBRAIN_HOME;
+ else process.env.GBRAIN_HOME = origGbrainHome;
fs.rmSync(tmpHome, { recursive: true, force: true });
+ fs.rmSync(gbrainHome, { recursive: true, force: true });
}
});
});
diff --git a/test/minions-legacy-coalesce.test.ts b/test/minions-legacy-coalesce.test.ts
new file mode 100644
index 0000000000..d4abfca63b
--- /dev/null
+++ b/test/minions-legacy-coalesce.test.ts
@@ -0,0 +1,141 @@
+/**
+ * #5157 / #5114: one coalesce rule on every coalesce path of
+ * `MinionQueue.add` (PGLite; Postgres runs the same matrix in
+ * `test/e2e/minions-legacy-coalesce-postgres.test.ts`).
+ *
+ * Only SQL NULL authority (rows from before the v0.50 cutover) gets the
+ * legacy rule; JSONB null, malformed and future authority keep the
+ * cross-authority denial.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { MinionWorker } from '../src/core/minions/worker.ts';
+import { APPLICATION_AUTHORITY, assertNoUnreviewedJobs, coalesceDecision, prepareRemoteJob } from '../src/core/minions/submission-authority.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { ALL_STATUSES, LEGACY_DOCS, PATHS, expectedOutcome, racingEngine, runCoalesceMatrix } from './helpers/legacy-coalesce-matrix.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const sandbox = mkdtempSync(join(tmpdir(), 'gbrain-legacy-coalesce-'));
+const root = join(sandbox, 'repo');
+const brainHome = join(sandbox, 'home');
+let engine: PGLiteEngine;
+
+function isolated<T>(fn: () => T | Promise<T>): Promise<T> {
+ return withEnv({ GBRAIN_HOME: brainHome, DATABASE_URL: undefined }, fn);
+}
+function ctx(): OperationContext {
+ return {
+ engine, config: {} as OperationContext['config'], dryRun: false, remote: true, sourceId: 'default',
+ logger: { info() {}, warn() {}, error() {} },
+ auth: { token: 'test-only', clientId: 'client-a', principal: { kind: 'oauth_client', id: 'client-a' }, scopes: ['admin'], sourceId: 'default' },
+ };
+}
+const remote = () => prepareRemoteJob(ctx(), 'lint', {});
+
+beforeAll(async () => isolated(async () => {
+ mkdirSync(root); mkdirSync(brainHome);
+ execFileSync('git', ['init', '-q', root]);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}), 60_000);
+afterAll(async () => { await engine?.disconnect(); rmSync(sandbox, { recursive: true, force: true }); }, 60_000);
+beforeEach(async () => isolated(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ await engine.executeRaw('DELETE FROM oauth_clients');
+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb, archived = false, local_path = $1 WHERE id = 'default'", [root]);
+ await engine.executeRaw("INSERT INTO oauth_clients (client_id, client_secret_hash, client_name, scope, source_id) VALUES ('client-a', 'test-only', 'example-client', 'admin', 'default')");
+}));
+
+describe('coalesceDecision (raw rows)', () => {
+ const remoteAuthority = { version: 1, kind: 'remote_generic', principal: { kind: 'oauth_client', id: 'client-a' } } as never;
+ test('SQL NULL gets the legacy rule; JSONB null, malformed and future authority keep the denial', () => {
+ for (const status of ALL_STATUSES) {
+ for (const [caller, authority] of [['application', APPLICATION_AUTHORITY], ['remote', remoteAuthority]] as const) {
+ const legacy = { id: 7, name: 'synthesize', status, submission_authority: null, legacy_authority_is_null: true };
+ const expected = expectedOutcome('sql_null', status, caller);
+ if (expected === 'deny-legacy') {
+ let docs: string | undefined;
+ try { coalesceDecision(legacy, authority); } catch (error) { docs = (error as { docs?: string }).docs; }
+ expect(docs, `${status}/${caller}`).toBe(LEGACY_DOCS);
+ } else {
+ expect(coalesceDecision(legacy, authority), `${status}/${caller}`).toBe(expected as 'coalesce' | 'release');
+ }
+ for (const raw of [null, { version: 1 }, { version: 2, kind: 'application' }]) {
+ // A missing marker is never legacy: JSONB null decodes to JS null too.
+ for (const marker of [false, undefined]) {
+ expect(() => coalesceDecision({ id: 7, name: 'synthesize', status, submission_authority: raw, legacy_authority_is_null: marker }, authority))
+ .toThrow('coalescing across');
+ }
+ }
+ }
+ }
+ });
+});
+
+describe('legacy coalesce matrix on every queue path (PGLite)', () => {
+ test('variant x path x status x caller', () => isolated(async () => {
+ const cells = await runCoalesceMatrix(engine, remote);
+ const expectedCells = 4 * Object.values(PATHS).reduce((n, p) => n + p.statuses.length * p.callers.length, 0);
+ expect(cells).toBe(expectedCells);
+ }), 180_000);
+
+ test('the existing cross-authority denial still holds for remote callers over an application row', () => isolated(async () => {
+ const queue = new MinionQueue(engine);
+ const accepted = await remote();
+ await queue.add('lint', accepted.data, { idempotency_key: 'same-key' });
+ const trusted = { submissionAuthority: accepted.authority };
+ await expect(queue.add('lint', accepted.data, { idempotency_key: 'same-key' }, trusted)).rejects.toThrow('coalescing across');
+ await expect(new MinionQueue(racingEngine(engine)).add('lint', accepted.data, { idempotency_key: 'same-key' }, trusted)).rejects.toThrow('coalescing across');
+ }));
+
+ test('resubmission over a dead legacy key inserts a fresh job that a worker runs', () => isolated(async () => {
+ const queue = new MinionQueue(engine);
+ const old = await queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:example' });
+ await engine.executeRaw("UPDATE minion_jobs SET status = 'dead', submission_authority = NULL WHERE id = $1", [old.id]);
+ const fresh = await queue.add('legacy-fixture', { n: 1 }, { idempotency_key: 'dream:synth-v2:example' });
+ expect(fresh.id).not.toBe(old.id);
+ await assertNoUnreviewedJobs(engine);
+ let ran = 0;
+ const worker = new MinionWorker(engine, { pollInterval: 10, healthCheckInterval: 0, stalledInterval: 60000 });
+ worker.register('legacy-fixture', async () => { ran++; return { ok: true }; });
+ const running = worker.start();
+ for (let i = 0; i < 200 && (await queue.getJob(fresh.id))?.status !== 'completed'; i++) await new Promise(r => setTimeout(r, 25));
+ worker.stop();
+ await running;
+ expect(ran).toBe(1);
+ expect((await queue.getJob(fresh.id))?.status).toBe('completed');
+ }), 30_000);
+
+ test('a release that lost its CAS (the row was reviewed in between) coalesces through the race path', () => isolated(async () => {
+ const old = await new MinionQueue(engine).add('legacy-fixture', { n: 2 }, { idempotency_key: 'cas-key' });
+ await engine.executeRaw("UPDATE minion_jobs SET status = 'cancelled', submission_authority = NULL WHERE id = $1", [old.id]);
+ // Between the fast-path read and the release, an operator authorizes the row.
+ const reviewing = new Proxy(engine, {
+ get(target, prop) {
+ if (prop !== 'transaction') { const v = Reflect.get(target, prop); return typeof v === 'function' ? v.bind(target) : v; }
+ return <T>(fn: (tx: PGLiteEngine) => Promise<T>) => target.transaction(tx => fn(new Proxy(tx, {
+ get(t, p) {
+ if (p !== 'executeRaw') { const v = Reflect.get(t, p); return typeof v === 'function' ? v.bind(t) : v; }
+ return async (sql: string, params?: unknown[]) => {
+ if (sql.includes('SET idempotency_key = NULL')) {
+ await t.executeRaw("UPDATE minion_jobs SET status = 'completed', submission_authority = $2::jsonb WHERE id = $1", [old.id, APPLICATION_AUTHORITY]);
+ }
+ return t.executeRaw(sql, params);
+ };
+ },
+ }) as PGLiteEngine));
+ },
+ });
+ const result = await new MinionQueue(reviewing as PGLiteEngine).add('legacy-fixture', { n: 2 }, { idempotency_key: 'cas-key' });
+ expect(result.id).toBe(old.id);
+ expect(result.coalesced).toBe(true);
+ const [{ count }] = await engine.executeRaw<{ count: string }>('SELECT count(*)::text AS count FROM minion_jobs');
+ expect(count).toBe('1');
+ }));
+});
diff --git a/test/minions-legacy-journey.test.ts b/test/minions-legacy-journey.test.ts
new file mode 100644
index 0000000000..ff5454c3f5
--- /dev/null
+++ b/test/minions-legacy-journey.test.ts
@@ -0,0 +1,30 @@
+/**
+ * #5157 restored-operation journey on PGLite (DX-O15(a), DX-O3(f)(g)); the
+ * Postgres run is `test/e2e/minions-legacy-journey-postgres.test.ts`. Both
+ * drive `test/helpers/legacy-journey.ts`.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runLegacyJourney, runUnsupportedRowRecovery } from './helpers/legacy-journey.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+afterAll(async () => { await engine?.disconnect(); }, 60_000);
+
+describe('legacy job recovery journey (PGLite)', () => {
+ test('/ingest 409 -> printed commands verbatim -> 202, worker runs, search finds the memory', async () => {
+ const { commands } = await runLegacyJourney(engine);
+ expect(commands).toHaveLength(6);
+ }, 120_000);
+
+ test('an unsupported non-NULL row needs its own printed cancel before a worker starts', async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ const commands = await runUnsupportedRowRecovery(engine);
+ expect(commands).toHaveLength(3);
+ }, 120_000);
+});
diff --git a/test/models-newer-hint.serial.test.ts b/test/models-newer-hint.serial.test.ts
index 1b18f97645..07d0387fb2 100644
--- a/test/models-newer-hint.serial.test.ts
+++ b/test/models-newer-hint.serial.test.ts
@@ -98,7 +98,7 @@ describe('gbrain models — newer-available hint', () => {
const think = report.per_task.find((r) => r.key === 'models.think')!;
expect(think.resolved).toBe('anthropic:claude-opus-4-7');
expect(think.newer_available).toBeUndefined();
- expect(report.tiers.deep.newer_available?.model).toBe('claude-opus-5');
+ expect(report.tiers.deep.newer_available?.model).toBe('claude-opus-5-5');
});
});
diff --git a/test/ops-search-types.test.ts b/test/ops-search-types.test.ts
index 2b538e2fd3..51ee3cba0d 100644
--- a/test/ops-search-types.test.ts
+++ b/test/ops-search-types.test.ts
@@ -89,6 +89,43 @@ describe('search op — types param (#3985)', () => {
searchOp.handler(ctxOf(), { query: 'zebra telescope', types: ' , ' }),
).rejects.toThrow(/no usable page-type/i);
});
+
+ // #5390: a structurally empty array carries no user intent (OpenAI-family
+ // MCP clients emit `types: []` whenever the model over-fills an optional
+ // parameter with a type-zero value, which happens routinely). The CLI typo
+ // guard above is preserved — only a list that had entries which all blanked
+ // out keeps throwing.
+ test('empty array is treated as no filter (#5390)', async () => {
+ const out = await searchOp.handler(ctxOf(), { query: 'zebra telescope', types: [] });
+ expect(slugsOf(out)).toEqual([
+ 'companies/acme-example',
+ 'notes/telescope-note',
+ 'people/alice-example',
+ ]);
+ });
+
+ test('non-empty array of blanks still rejects as invalid_params (#5390)', async () => {
+ await expect(
+ searchOp.handler(ctxOf(), { query: 'zebra telescope', types: [''] }),
+ ).rejects.toThrow(/no usable page-type/i);
+ });
+
+ test('empty and whitespace-only strings are treated as no filter (#5390)', async () => {
+ for (const types of ['', ' ']) {
+ const out = await searchOp.handler(ctxOf(), { query: 'zebra telescope', types });
+ expect(slugsOf(out)).toEqual([
+ 'companies/acme-example',
+ 'notes/telescope-note',
+ 'people/alice-example',
+ ]);
+ }
+ });
+
+ test('a comma-only string still rejects as invalid_params (#5390)', async () => {
+ await expect(
+ searchOp.handler(ctxOf(), { query: 'zebra telescope', types: ',,' }),
+ ).rejects.toThrow(/no usable page-type/i);
+ });
});
describe('query op — types param (#3985)', () => {
@@ -115,4 +152,16 @@ describe('query op — types param (#3985)', () => {
queryOp.handler(ctxOf(), { query: 'zebra telescope', types: { person: true } }),
).rejects.toThrow(/types.*must be an array/i);
});
+
+ test('types: [], "" and " " run unfiltered; [\'\'] still rejects (#5390)', async () => {
+ await withEnv({ OPENAI_API_KEY: undefined }, async () => {
+ for (const types of [[], '', ' ']) {
+ const out = await queryOp.handler(ctxOf(), { query: 'zebra telescope', expand: false, types });
+ expect(slugsOf(out)).toEqual(['companies/acme-example', 'notes/telescope-note', 'people/alice-example']);
+ }
+ await expect(
+ queryOp.handler(ctxOf(), { query: 'zebra telescope', expand: false, types: [''] }),
+ ).rejects.toThrow(/no usable page-type/i);
+ });
+ });
});
diff --git a/test/opus-5-5-pricing.test.ts b/test/opus-5-5-pricing.test.ts
new file mode 100644
index 0000000000..8a2c890150
--- /dev/null
+++ b/test/opus-5-5-pricing.test.ts
@@ -0,0 +1,48 @@
+/**
+ * #5359 / #5494: Claude Opus 5.5 (`claude-opus-5-5`) was missing from the
+ * recipes and the price table, so `--max-cost` runs on it hard-failed with
+ * no_pricing before the first call. Rates are Anthropic's published Opus 5.5
+ * list: $4 in / $20 out, cache reads 0.05x ($0.20), 5-minute writes 1.25x.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdtempSync, rmSync } from 'fs';
+import { join } from 'path';
+import { tmpdir } from 'os';
+
+import { BudgetTracker } from '../src/core/budget/budget-tracker.ts';
+import { CANONICAL_PRICING } from '../src/core/model-pricing.ts';
+import { anthropic } from '../src/core/ai/recipes/anthropic.ts';
+import { claudeCli } from '../src/core/ai/recipes/claude-cli.ts';
+
+describe('#5359 / #5494 Claude Opus 5.5', () => {
+ test('priced at the published rates, with the 0.05x cache-read rate', () => {
+ expect(CANONICAL_PRICING['anthropic:claude-opus-5-5']).toEqual({ input: 4, output: 20, cache_read: 0.2, cache_write: 5 });
+ });
+
+ test('listed by the anthropic and claude-cli recipes', () => {
+ expect(anthropic.touchpoints.chat?.models).toContain('claude-opus-5-5');
+ expect(anthropic.touchpoints.chat?.model_context_tokens?.['claude-opus-5-5']).toBe(1_000_000);
+ expect(claudeCli.touchpoints.chat?.models).toContain('claude-opus-5-5');
+ expect(claudeCli.touchpoints.expansion?.models).toContain('claude-opus-5-5');
+ });
+
+ test('a --max-cost reservation is estimated instead of refused with no_pricing', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-opus55-'));
+ try {
+ const tracker = new BudgetTracker({ label: 'opus55-test', maxCostUsd: 1, auditPath: join(dir, 'audit.jsonl') });
+ // 100k in + 10k out = $0.40 + $0.20 = $0.60, inside the $1 cap.
+ expect(() => tracker.reserve({ modelId: 'anthropic:claude-opus-5-5', kind: 'chat', estimatedInputTokens: 100_000, maxOutputTokens: 10_000, label: 'x' })).not.toThrow();
+ // A second identical reservation would reach $1.20 and is refused on cost.
+ let reason: string | undefined;
+ try {
+ tracker.reserve({ modelId: 'anthropic:claude-opus-5-5', kind: 'chat', estimatedInputTokens: 100_000, maxOutputTokens: 10_000, label: 'y' });
+ } catch (e) {
+ reason = (e as { reason?: string }).reason;
+ }
+ expect(reason).toBe('cost');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/page-summary-length.serial.test.ts b/test/page-summary-length.serial.test.ts
index c04bcc097a..661c2d1d2a 100644
--- a/test/page-summary-length.serial.test.ts
+++ b/test/page-summary-length.serial.test.ts
@@ -120,3 +120,19 @@ describe('resolveSynopsisMaxTokens config resolver (#3883)', () => {
expect(await resolveSynopsisMaxTokens(throwing)).toBeUndefined(); // fail-open
});
});
+
+describe('surrogate-safe document truncation (#5316)', () => {
+ test('an astral char straddling the cap produces no unpaired surrogate in the prompt', async () => {
+ const { SYNOPSIS_DOC_MAX_CHARS } = await import('../src/core/page-summary.ts');
+ const captured: ChatOpts[] = [];
+ stubChat({ stopReason: 'end' }, captured);
+ const documentText =
+ 'a'.repeat(SYNOPSIS_DOC_MAX_CHARS - 1) + '𝑇' + 'b'.repeat(100);
+ const result = await generatePerChunkSynopsis({ ...baseArgs, documentText });
+ expect(result.kind).toBe('success');
+ const prompt = captured[0].messages[0].content as string;
+ expect(prompt.isWellFormed()).toBe(true);
+ expect(() => JSON.parse(JSON.stringify(prompt))).not.toThrow();
+ expect(prompt).toContain('chars truncated for synopsis budget');
+ });
+});
diff --git a/test/persistence-effects.test.ts b/test/persistence-effects.test.ts
index fd060cbc42..22f708a855 100644
--- a/test/persistence-effects.test.ts
+++ b/test/persistence-effects.test.ts
@@ -216,6 +216,35 @@ test('a parked withdrawal mirror target retries through physical publication wit
for (const file of [f.file, laterFile]) expect(parseFactsFence(readFileSync(file, 'utf8')).facts.filter(fact => fact.active)).toHaveLength(0);
});
+test('a divergent RESOLVER.md page and a locally edited page no longer block the withdrawal request\'s git and embedding effects (#5396)', async () => {
+ const f = await fixture(body());
+ await engine.putPage('resolver', page(body()), { sourceId: f.sourceId });
+ await engine.executeRaw("UPDATE pages SET source_path='RESOLVER.md' WHERE source_id=$1 AND slug='resolver'", [f.sourceId]);
+ const resolver = (await engine.readPageSnapshot('resolver', { sourceId: f.sourceId }))!;
+ const resolverFile = join(f.root, 'RESOLVER.md');
+ const durable = `${serializePageToMarkdown(resolver.page, resolver.tags)}\n<!-- BEGIN gbrain-brain-durability (managed; do not edit between markers) -->\nCommit every page.\n<!-- END gbrain-brain-durability -->\n`;
+ writeFileSync(resolverFile, durable);
+ await engine.putPage('notes/drifted', page(body()), { sourceId: f.sourceId });
+ const drifted = (await engine.readPageSnapshot('notes/drifted', { sourceId: f.sourceId }))!;
+ const driftedFile = join(f.root, 'notes/drifted.md'); mkdirSync(dirname(driftedFile), { recursive: true });
+ const localEdit = `${serializePageToMarkdown(drifted.page, drifted.tags)}\nA local edit nobody imported.\n`;
+ writeFileSync(driftedFile, localEdit);
+ const row = await withdraw(f, { subjectless: true });
+ for (let pass = 0; pass < 4; pass++) {
+ await onlyEffects(row.id);
+ await runPersistenceEffects(engine, config, { hostId, limit: 10 });
+ }
+ const effects = await engine.executeRaw<{ kind: string; state: string; attempts: number; data: Record<string, unknown> }>(
+ 'SELECT kind,state,attempts,data FROM persistence_effects WHERE request_id=$1::uuid ORDER BY kind', [row.id]);
+ expect(effects.map(effect => [effect.kind, effect.state])).toEqual([['embedding', 'queued'], ['git', 'committed'], ['withdrawal-mirror', 'committed']]);
+ expect(effects.find(effect => effect.kind === 'embedding')!.attempts).toBeGreaterThan(0);
+ expect(effects.find(effect => effect.kind === 'withdrawal-mirror')!.data.skipped).toEqual([
+ { slug: 'notes/drifted', reason: 'file_database_drift' }, { slug: 'resolver', reason: 'metafile' }]);
+ expect(readFileSync(resolverFile, 'utf8')).toBe(durable);
+ expect(readFileSync(driftedFile, 'utf8')).toBe(localEdit);
+ expect(parseFactsFence(readFileSync(f.file, 'utf8')).facts.filter(fact => fact.active)).toHaveLength(0);
+});
+
test('configured recovery capacity refuses file mutation without undoing withdrawal', async () => {
const f = await fixture(body()); const original = readFileSync(f.file, 'utf8'); const row = await withdraw(f); await onlyEffects(row.id);
await engine.setConfig('persistence.limits.worktree_recovery_bytes', '1');
diff --git a/test/persistence-large-manifest.test.ts b/test/persistence-large-manifest.test.ts
new file mode 100644
index 0000000000..a7935e465e
--- /dev/null
+++ b/test/persistence-large-manifest.test.ts
@@ -0,0 +1,174 @@
+/**
+ * #5790: stored worktree manifests carry a digest and a file count instead of
+ * the per-file map, so brains past ~10k files can be added, claimed, rebound,
+ * archived, removed, cloned, recloned and transferred.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { cpSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
+import { basename, join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { isPhysicalRootMetadata } from '../src/core/persistence/physical-root.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { claimWorktree, getWorktreeBinding, worktreeManifest } from '../src/core/persistence/ownership.ts';
+import { runManagedSourceLifecycle } from '../src/core/persistence/source-lifecycle.ts';
+import { runManagedSourceClone } from '../src/core/persistence/topology-clone.ts';
+import { topologyPrincipal } from '../src/core/persistence/topology-locks.ts';
+import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+import { largeBareRepository, writeLargeWorktree } from './helpers/large-worktree.ts';
+
+const FILES = 12_000;
+const REMOTE = 'https://example.invalid/large-brain.git';
+
+for (const backend of testBackends()) describe(`large worktree manifests (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }
+ }, 120_000);
+ afterAll(async () => { if (!engine) return; await disposePersistenceConsumer(engine); if (close) await close(); else await engine.disconnect(); });
+
+ async function fixture(run: (home: string) => Promise<void>) {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-large-manifest-'));
+ try {
+ await withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await resetPgliteState(engine as PGLiteEngine);
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try { await run(home); } finally { await disposePersistenceConsumer(engine); }
+ });
+ } finally { rmSync(home, { recursive: true, force: true }); }
+ }
+ async function storedManifest(sourceId: string) {
+ const [row] = await engine.executeRaw<{ manifest: Record<string, unknown> | string | null }>(`SELECT w.manifest FROM persistence_worktrees w
+ JOIN persistence_source_bindings b ON b.worktree_id=w.id WHERE b.source_id=$1`, [sourceId]);
+ return typeof row?.manifest === 'string' ? JSON.parse(row.manifest) : row?.manifest ?? null;
+ }
+ async function expectCompact(sourceId: string, root: string, count = FILES) {
+ const manifest = await storedManifest(sourceId);
+ expect(manifest).toMatchObject({ digest: worktreeManifest(root).digest, file_count: count });
+ expect(manifest.files).toBeUndefined();
+ expect(Buffer.byteLength(JSON.stringify(manifest))).toBeLessThan(4096);
+ return manifest;
+ }
+ const insertSource = (id: string, path: string) => engine.transaction(async tx => {
+ await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
+ await tx.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [id, path]);
+ });
+ const copyWorktree = (from: string, to: string) => cpSync(from, to, { recursive: true, filter: path => !isPhysicalRootMetadata(basename(path)) && basename(path) !== '.git' });
+
+ test('a 12k-file source can be added, claimed, rebound, archived, restored and removed', () => fixture(async home => {
+ const root = join(home, 'added');
+ writeLargeWorktree(root, FILES);
+ expect(await runManagedSourceLifecycle(engine, { operation: 'add', sourceId: 'large-added', path: root })).toMatchObject({ state: 'committed' });
+ await expectCompact('large-added', root);
+
+ const claimed = join(home, 'claimed');
+ writeLargeWorktree(claimed, FILES);
+ await insertSource('large-claimed', claimed);
+ expect((await claimWorktree(engine, 'large-claimed', claimed)).local_path).toBe(claimed);
+ await expectCompact('large-claimed', claimed);
+
+ const candidate = join(home, 'candidate');
+ copyWorktree(root, candidate);
+ const deleted = join(candidate, 'notes', 'batch-000', 'example-note-000007.md');
+ rmSync(deleted);
+ await expect(runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'large-added', path: candidate })).rejects.toMatchObject({ code: 'writer_manifest_mismatch' });
+ cpSync(join(root, 'notes', 'batch-000', 'example-note-000007.md'), deleted);
+ expect(await runManagedSourceLifecycle(engine, { operation: 'rebind', sourceId: 'large-added', path: candidate })).toMatchObject({ state: 'committed' });
+ expect((await getWorktreeBinding(engine, 'large-added'))!.local_path).toBe(candidate);
+ await expectCompact('large-added', candidate);
+
+ expect(await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'large-added' })).toMatchObject({ state: 'committed' });
+ expect(await runManagedSourceLifecycle(engine, { operation: 'restore', sourceId: 'large-added' })).toMatchObject({ state: 'committed' });
+ expect(await runManagedSourceLifecycle(engine, { operation: 'remove', sourceId: 'large-added', confirmDestructive: true })).toMatchObject({ state: 'committed', storage_retained: true });
+ expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1', ['large-added'])).toHaveLength(0);
+ }), 240_000);
+
+ test('a 12k-file repository clones and reclones from a local bare repository', () => fixture(async home => {
+ const bare = largeBareRepository(home, FILES);
+ const target = join(home, 'cloned');
+ const clone = async (_url: string, stage: string) => { execFileSync('git', ['clone', '--quiet', bare, stage], { stdio: 'ignore' }); };
+ const principal = await topologyPrincipal(engine);
+ const add = { operation: 'add' as const, sourceId: 'large-clone', path: target, remoteUrl: REMOTE, requestId: randomUUID() };
+ expect(await runManagedSourceClone(engine, add, principal, add.requestId, { ...add, requestId: undefined, dryRun: undefined }, { clone }))
+ .toMatchObject({ state: 'committed', cloned: true });
+ await expectCompact('large-clone', target);
+ const reclone = { operation: 'reclone' as const, sourceId: 'large-clone', requestId: randomUUID() };
+ expect(await runManagedSourceClone(engine, reclone, principal, reclone.requestId, { ...reclone, requestId: undefined, dryRun: undefined }, { clone }))
+ .toMatchObject({ state: 'committed', cloned: true });
+ await expectCompact('large-clone', target);
+ expect(readdirSync(home).some(name => name.includes('gbrain-old') || name.startsWith('.gbrain-clone'))).toBe(false);
+ }), 240_000);
+
+ test('a legacy manifest with a per-file map past 1 MiB is accepted by reclone recovery and compacted', () => fixture(async home => {
+ const bare = largeBareRepository(home, 20);
+ const target = join(home, 'cloned');
+ const clone = async (_url: string, stage: string) => { execFileSync('git', ['clone', '--quiet', bare, stage], { stdio: 'ignore' }); };
+ const principal = await topologyPrincipal(engine);
+ const add = { operation: 'add' as const, sourceId: 'legacy-clone', path: target, remoteUrl: REMOTE, requestId: randomUUID() };
+ await runManagedSourceClone(engine, add, principal, add.requestId, { ...add, requestId: undefined, dryRun: undefined }, { clone });
+ await runManagedSourceLifecycle(engine, { operation: 'archive', sourceId: 'legacy-clone' });
+ const current = await storedManifest('legacy-clone');
+ const files = Object.fromEntries(Array.from({ length: FILES }, (_, i) => [`notes/legacy/example-note-${String(i).padStart(6, '0')}.md`, 'f'.repeat(64)]));
+ const legacy = { digest: current.digest, files, canonical_stamp: current.canonical_stamp };
+ expect(Buffer.byteLength(JSON.stringify(legacy))).toBeGreaterThan(1_048_576);
+ const binding = (await getWorktreeBinding(engine, 'legacy-clone'))!;
+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify(legacy)]);
+ rmSync(target, { recursive: true, force: true });
+ const reclone = { operation: 'reclone' as const, sourceId: 'legacy-clone', requestId: randomUUID() };
+ expect(await runManagedSourceClone(engine, reclone, principal, reclone.requestId, { ...reclone, requestId: undefined, dryRun: undefined }, { clone }))
+ .toMatchObject({ state: 'committed', cloned: true });
+ await expectCompact('legacy-clone', target, 20);
+ }), 240_000);
+
+ test('writer transfer prepare and accept, including self-transfer, commit at 12k files', () => fixture(async home => {
+ const root = join(home, 'owner');
+ writeLargeWorktree(root, FILES);
+ await insertSource('large-transfer', root);
+ await claimWorktree(engine, 'large-transfer', root);
+ const administer = async (operation: 'writer_transfer_prepare' | 'writer_transfer_accept', params: Record<string, unknown>) =>
+ runPersistenceAdministration(engine, operation, { ...params, ...await reviewedWriterIntent(engine, operation) }) as Promise<any>;
+
+ const self = await administer('writer_transfer_prepare', { source_id: 'large-transfer', self_transfer: true });
+ expect(self.manifest).toEqual({ digest: worktreeManifest(root).digest, file_count: FILES });
+ const draining = await storedManifest('large-transfer');
+ expect(draining.files).toBeUndefined();
+ expect(draining).toMatchObject({ digest: self.manifest.digest, file_count: FILES, self_transfer: expect.any(Object) });
+ expect(await administer('writer_transfer_accept', { source_id: 'large-transfer', path: root, expected_epoch: self.owner_epoch, manifest: self.manifest.digest, self_transfer: true }))
+ .toMatchObject({ transferred: true });
+
+ const successor = join(home, 'successor');
+ copyWorktree(root, successor);
+ const prepared = await administer('writer_transfer_prepare', { source_id: 'large-transfer' });
+ expect(prepared.manifest).toEqual({ digest: self.manifest.digest, file_count: FILES });
+ expect(await administer('writer_transfer_accept', { source_id: 'large-transfer', path: successor, expected_epoch: prepared.owner_epoch, manifest: prepared.manifest.digest }))
+ .toMatchObject({ transferred: true, binding: { local_path: successor, state: 'active' } });
+ expect((await getWorktreeBinding(engine, 'large-transfer'))!.owner_epoch).toBe('3');
+ }), 240_000);
+
+ test('an administrative preview taken before a manifest rewrite refuses afterwards', () => fixture(async home => {
+ const root = join(home, 'owner');
+ mkdirSync(root);
+ writeLargeWorktree(root, 20);
+ await insertSource('rewritten', root);
+ await claimWorktree(engine, 'rewritten', root);
+ const binding = (await getWorktreeBinding(engine, 'rewritten'))!;
+ const { digest } = worktreeManifest(root);
+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify({ digest, files: { 'example.md': 'f'.repeat(64) } })]);
+ const preview = await reviewedWriterIntent(engine, 'writer_transfer_prepare');
+ await engine.executeRaw('UPDATE persistence_worktrees SET manifest=$2::text::jsonb WHERE id=$1::uuid', [binding.worktree_id, JSON.stringify({ digest, file_count: 20 })]);
+ await expect(runPersistenceAdministration(engine, 'writer_transfer_prepare', { source_id: 'rewritten', ...preview })).rejects.toMatchObject({ code: 'writer_admin_state_changed' });
+ expect((await getWorktreeBinding(engine, 'rewritten'))!.state).toBe('active');
+ }), 120_000);
+});
diff --git a/test/persistence-local-client.test.ts b/test/persistence-local-client.test.ts
index 156bdb3bef..d413f53a5d 100644
--- a/test/persistence-local-client.test.ts
+++ b/test/persistence-local-client.test.ts
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, test } from 'bun:test';
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { persistenceConfigForBrain, readPersistenceCliRegistration, maybeDelegateLocalOperation } from '../src/core/persistence/local-client.ts';
+import { persistenceConfigForBrain, readPersistenceCliRegistration, maybeDelegateLocalOperation, residentPersistenceConfig } from '../src/core/persistence/local-client.ts';
import { resolveSourceId } from '../src/core/source-resolver.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -22,6 +22,18 @@ describe('engine-free local persistence routing', () => {
expect(() => persistenceConfigForBrain(host, 'example-brain', [{ ...mounts[0], enabled: false }])).toThrow('not an enabled mount');
});
+ test('a resident owner takes the datastore of the brain its engine opened (#5237)', async () => {
+ const dir = temp(), project = join(dir, 'project'), mounts = join(dir, 'mounts.json');
+ mkdirSync(project);
+ writeFileSync(join(project, '.gbrain-mount'), 'example-brain\n'); chmodSync(join(project, '.gbrain-mount'), 0o644);
+ writeFileSync(mounts, JSON.stringify({ version: 1, mounts: [{ id: 'example-brain', engine: 'pglite', path: join(dir, 'clone'), database_path: '/mount/db' }] }), { mode: 0o600 });
+ const host = { engine: 'postgres' as const, database_url: 'postgresql://example.invalid/host', embedding_model: 'example-model' };
+ await withEnv({ GBRAIN_MOUNTS_PATH: mounts, GBRAIN_BRAIN_ID: undefined }, () => {
+ expect(residentPersistenceConfig(host, dir)).toBe(host);
+ expect(residentPersistenceConfig(host, project)).toEqual({ ...host, engine: 'pglite', database_path: '/mount/db', database_url: undefined });
+ });
+ });
+
test('missing registration never allocates a replacement principal', async () => {
const dir = temp();
await withEnv({ GBRAIN_HOME: dir }, () => {
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index 0850aa7717..e8e1b8016e 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -81,6 +81,54 @@ test('imports files without rewriting bytes and checkpoints only committed page
}
}),120_000);
+test('a pinned import that trails the current page and its working-tree bytes is skipped, not a conflict', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const current = '---\ntitle: Example note\n---\nThe current observation, already in the database.\n';
+ const pinned = '---\ntitle: Example note\n---\nAn older observation that Git still carries.\n';
+ const f = await fixture(engine, { 'notes/example.md': current });
+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true })).status).toBe('first_sync');
+ const path = join(f.root, 'notes/example.md');
+ // The state between a coordinated page write and its queued Git effect: the newest commit
+ // holds other bytes than the page, and the working tree already carries the page's own bytes.
+ writeFileSync(path, pinned); const head = commit(f.root, 'commit that trails the page'); writeFileSync(path, current);
+ const result = await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ expect(result.status).not.toBe('blocked_by_failures'); expect(result.managedWrite).toBeUndefined(); expect(result.toCommit).toBe(head);
+ expect((await engine.getPage('notes/example', { sourceId: f.id }))?.compiled_truth).toContain('current observation');
+ expect(readFileSync(path, 'utf8')).toBe(current);
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(head);
+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);
+ // Working-tree bytes that are neither the pinned commit nor the page are still protected.
+ const foreign = '---\ntitle: Example note\n---\nA local edit that nothing imported.\n';
+ writeFileSync(path, pinned.replace('older', 'still older')); commit(f.root, 'another trailing commit'); writeFileSync(path, foreign);
+ const blocked = await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ expect(blocked).toMatchObject({ status: 'blocked_by_failures', managedWrite: { write_error: 'source_changed', reason: 'pinned_git_worktree_conflict' } });
+ expect(readFileSync(path, 'utf8')).toBe(foreign);
+ expect((await engine.getPage('notes/example', { sourceId: f.id }))?.compiled_truth).toContain('current observation');
+ rmSync(syncFailuresPath(), { force: true });
+ }
+}),120_000);
+
+test('after a trailing-commit skip, the commit that carries the page bytes imports as a no-op', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const current = '---\ntitle: Trailing note\n---\nThe page body the coordinator already published.\n';
+ const pinned = '---\ntitle: Trailing note\n---\nThe body an earlier commit still carries.\n';
+ const f = await fixture(engine, { 'notes/trailing.md': current });
+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true })).status).toBe('first_sync');
+ const path = join(f.root, 'notes/trailing.md');
+ writeFileSync(path, pinned); commit(f.root, 'commit that trails the page'); writeFileSync(path, current);
+ const before = await engine.readPageSnapshot('notes/trailing', { sourceId: f.id });
+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true })).status).not.toBe('blocked_by_failures');
+ const carried = commit(f.root, 'the queued Git effect lands');
+ const result = await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ expect(result.status).not.toBe('blocked_by_failures'); expect(result.managedWrite).toBeUndefined();
+ expect((await engine.executeRaw<{ last_commit: string }>('SELECT last_commit FROM sources WHERE id=$1', [f.id]))[0].last_commit).toBe(carried);
+ const after = await engine.readPageSnapshot('notes/trailing', { sourceId: f.id });
+ expect(after?.revision).toBe(before?.revision);
+ expect(after?.page.compiled_truth).toContain('already published');
+ expect(loadSyncFailures().filter(row => row.source_id === f.id)).toHaveLength(0);
+ }
+}),120_000);
+
test('interrupted cursor resumes its pinned target before a newer HEAD and never advances early', async () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
const f = await fixture(engine, {'a.md':'First stable observation about engineering.\n','b.md':'Original second observation about engineering.\n'});
diff --git a/test/persistence-manifest-progress.test.ts b/test/persistence-manifest-progress.test.ts
new file mode 100644
index 0000000000..37b16e94f2
--- /dev/null
+++ b/test/persistence-manifest-progress.test.ts
@@ -0,0 +1,64 @@
+/** #5790 / DX-O10: manifest hashing progress and digest compatibility. */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { join, relative, sep } from 'node:path';
+import { tmpdir } from 'node:os';
+import { PassThrough } from 'node:stream';
+import { compactStoredManifest, humanManifestProgress, MANIFEST_PROGRESS_MIN_FILES, worktreeManifest } from '../src/core/persistence/ownership.ts';
+import { digest, sha256 } from '../src/core/persistence/digest.ts';
+import { DEFAULT_CLI_OPTIONS, _resetCliOptionsForTest, setCliOptions } from '../src/core/cli-options.ts';
+import { writeLargeWorktree } from './helpers/large-worktree.ts';
+
+function sink() {
+ const stream = new PassThrough();
+ const chunks: string[] = [];
+ stream.on('data', chunk => chunks.push(chunk.toString('utf8')));
+ return { stream, read: () => chunks.join('') };
+}
+
+function withWorktree<T>(count: number, run: (root: string) => T): T {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-manifest-progress-'));
+ try { writeLargeWorktree(root, count); return run(root); } finally { rmSync(root, { recursive: true, force: true }); }
+}
+
+describe('worktree manifest hashing', () => {
+ afterEach(() => _resetCliOptionsForTest());
+
+ test('reports files hashed of total on stderr above 5,000 files', () => withWorktree(MANIFEST_PROGRESS_MIN_FILES + 1, root => {
+ const { stream, read } = sink();
+ const manifest = worktreeManifest(root, { progress: { mode: 'human', stream, minIntervalMs: 0, minItems: 1 } });
+ expect(manifest.file_count).toBe(MANIFEST_PROGRESS_MIN_FILES + 1);
+ expect(read()).toContain('sources.manifest_hash');
+ expect(read()).toContain(`/${MANIFEST_PROGRESS_MIN_FILES + 1}`);
+ }));
+
+ test('stays silent at or below 5,000 files and without a progress request', () => withWorktree(MANIFEST_PROGRESS_MIN_FILES, root => {
+ const { stream, read } = sink();
+ worktreeManifest(root, { progress: { mode: 'human', stream, minIntervalMs: 0, minItems: 1 } });
+ expect(read()).toBe('');
+ }));
+
+ test('progress is offered in human mode only', () => {
+ expect(humanManifestProgress()).toMatchObject({ mode: 'auto' });
+ setCliOptions({ ...DEFAULT_CLI_OPTIONS, progressJson: true });
+ expect(humanManifestProgress()).toBeUndefined();
+ setCliOptions({ ...DEFAULT_CLI_OPTIONS, quiet: true });
+ expect(humanManifestProgress()).toBeUndefined();
+ });
+
+ test('the digest is unchanged from the per-file map older binaries stored', () => withWorktree(25, root => {
+ const files: Record<string, string> = {};
+ const visit = (dir: string) => { for (const name of readdirSync(dir).sort()) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) visit(path); else files[relative(root, path).split(sep).join('/')] = sha256(readFileSync(path));
+ } };
+ visit(root);
+ expect(worktreeManifest(root)).toEqual({ digest: digest(files), file_count: 25 });
+ }));
+
+ test('a legacy stored manifest drops only its per-file map', () => {
+ const legacy = { digest: 'd'.repeat(64), files: { 'a.md': 'f'.repeat(64), 'b.md': 'e'.repeat(64) }, canonical_stamp: 'stamp', self_transfer: { hostId: 'h' } };
+ expect(compactStoredManifest(legacy)).toEqual({ digest: 'd'.repeat(64), file_count: 2, canonical_stamp: 'stamp', self_transfer: { hostId: 'h' } });
+ expect(compactStoredManifest({ digest: 'd'.repeat(64), file_count: 7 })).toEqual({ digest: 'd'.repeat(64), file_count: 7 });
+ });
+});
diff --git a/test/persistence-source-lifecycle.test.ts b/test/persistence-source-lifecycle.test.ts
index 80539be240..f66580628f 100644
--- a/test/persistence-source-lifecycle.test.ts
+++ b/test/persistence-source-lifecycle.test.ts
@@ -265,17 +265,17 @@ test('new clone metadata is counted alongside staging before canonical installat
const result=await runManagedSourceClone(engine,input,await topologyPrincipal(engine),input.requestId,{...input,requestId:undefined,dryRun:undefined},{
clone:async(_url,stage,budget)=>{
// Directory stat.size varies by filesystem. Fill the measured remaining
- // space so raw staging fits and only its new manifest exceeds capacity.
- for(let i=0;i<128;i++)writeFileSync(join(stage,`${String(i).padStart(4,'0')}-${'x'.repeat(175)}.md`),'');
+ // space so raw staging fits and only the prepared recovery record, which
+ // gains the manifest, stage identity and clone digest, exceeds capacity.
const payload=join(stage,'payload.md');writeFileSync(payload,'');
- const remaining=budget-await topologyDirectoryBytes(stage)-8192;
+ const remaining=budget-await topologyDirectoryBytes(stage)-64;
writeFileSync(payload,'x'.repeat(Math.max(0,remaining)));
cloneBudget=budget;stagedBytes=await topologyDirectoryBytes(stage);
manifestBytes=Buffer.byteLength(JSON.stringify(worktreeManifest(stage)));
},
});
- expect(stagedBytes).toBe(cloneBudget-8192);
- expect(manifestBytes).toBeGreaterThan(8192);expect(manifestBytes).toBeLessThan(1_048_576);
+ expect(stagedBytes).toBe(cloneBudget-64);
+ expect(manifestBytes).toBeGreaterThan(64);expect(manifestBytes).toBeLessThan(1024);
expect(result).toMatchObject({state:'failed',write_error:'request_too_large'});
expect(await engine.executeRaw('SELECT id FROM sources WHERE id=$1',[input.sourceId])).toHaveLength(0);
expect((await engine.executeRaw<{recovery_bytes:string}>("SELECT recovery_bytes::text FROM persistence_counters WHERE key='brain'"))[0].recovery_bytes).toBe('0');
diff --git a/test/preview-approval.test.ts b/test/preview-approval.test.ts
new file mode 100644
index 0000000000..27c54f3691
--- /dev/null
+++ b/test/preview-approval.test.ts
@@ -0,0 +1,143 @@
+/**
+ * Preview-approval helper contract (fix wave 5, ENG-O1 / ENG-O14), on PGLite
+ * and, with a safe DATABASE_URL, Postgres (test/e2e/preview-approval-postgres.test.ts).
+ *
+ * One contract across the four preview-bound commands: the saved set round-
+ * trips whole under its hash, sets of different commands never satisfy each
+ * other, a missing, foreign or expired set refuses with `preview_changed`
+ * (never a partial set), a purge-eligible set is never trusted, and
+ * `previewHash` is byte-identical to the `authorizeLegacyJobs --ids` digest.
+ */
+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 { OperationError } from '../src/core/ops/contract.ts';
+import { purgeStaleCheckpoints } from '../src/core/op-checkpoint.ts';
+import { authorityDigest } from '../src/core/minions/submission-authority.ts';
+import { APPROVAL_MAX_AGE_DAYS, PREVIEW_APPROVAL_OP, clearApprovedSet, loadApprovedSet, previewChangedError, previewHash, saveApprovedSet,
+ type PreviewApprovalCommand } from '../src/core/persistence/preview-approval.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const COMMANDS: Array<{ command: PreviewApprovalCommand; preview: string }> = [
+ { command: 'authorize-legacy', preview: 'gbrain jobs authorize-legacy --select "status=waiting"' },
+ { command: 'jobs-cancel', preview: 'gbrain jobs cancel --select "status=waiting|delayed"' },
+ { command: 'stale-atoms', preview: 'gbrain repair stale-atoms --source default' },
+ { command: 'extractor-facts', preview: 'gbrain repair extractor-facts --include-ambiguous' },
+];
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a preview_changed refusal');
+}
+
+describe('previewHash', () => {
+ // The shape authorizeLegacyJobs --ids hashes: raw rows with Dates, bigints, JSONB, nulls and unsorted keys.
+ const legacySnapshot = {
+ preview_version: 1, authority_version: 1, version: '0.60.26.0',
+ jobs: [{ id: 7, name: 'sync', status: 'waiting', data: { sourceId: 'default', z: [1, null, { b: 2, a: 1 }] }, submission_authority: null,
+ created_at: new Date('2026-09-01T00:00:00.000Z'), claim_generation: 3n, legacy_authority_is_null: true, absent: undefined }],
+ dependencies: [], sources: [{ id: 'default', local_path: null, config: {}, archived: false, created_at: new Date('2026-01-01T00:00:00.000Z') }],
+ };
+
+ test('is byte-identical to the authorize-legacy --ids digest (authorityDigest) and pinned', () => {
+ expect(previewHash(legacySnapshot)).toBe(authorityDigest(legacySnapshot));
+ expect(previewHash(legacySnapshot)).toBe('8a78b9ac1ca4ea11a4a0dadeab4e2733f318d8c0730766f8f62e88ff47c74351');
+ expect(previewHash(['stale-atoms', { b: 1, a: 2 }])).toBe(authorityDigest(['stale-atoms', { a: 2, b: 1 }]));
+ });
+
+ test('changes when any listed item or option changes', () => {
+ const base = previewHash({ command: 'stale-atoms', items: [{ id: 1, revision: 'r1' }], options: { limit: 10 } });
+ expect(previewHash({ command: 'stale-atoms', items: [{ id: 1, revision: 'r2' }], options: { limit: 10 } })).not.toBe(base);
+ expect(previewHash({ command: 'stale-atoms', items: [{ id: 1, revision: 'r1' }], options: { limit: 11 } })).not.toBe(base);
+ expect(base).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ test('preview_changed carries the DX-O2 message, the filled preview command and the anchor', () => {
+ const error = previewChangedError('abc123', 'gbrain repair stale-atoms');
+ expect(error.toJSON()).toMatchObject({ error: 'preview_changed',
+ message: 'The preview changed since abc123; re-run gbrain repair stale-atoms and use the new hash.',
+ suggestion: 'Re-run the preview: gbrain repair stale-atoms', docs: 'docs/guides/repair.md#preview-changed' });
+ });
+});
+
+for (const kind of testBackends()) {
+ describe(`approved sets in op_checkpoints (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); close = () => engine.disconnect(); }
+ }, 120_000);
+ afterAll(async () => { await close?.(); });
+ beforeEach(async () => { await engine.executeRaw('DELETE FROM op_checkpoints WHERE op=$1', [PREVIEW_APPROVAL_OP]); });
+
+ const age = (command: PreviewApprovalCommand, hash: string, days: number) => engine.executeRaw(
+ `UPDATE op_checkpoints SET updated_at=now()-($3 || ' days')::interval WHERE op=$1 AND fingerprint=$2`, [PREVIEW_APPROVAL_OP, `${command}:${hash}`, String(days)]);
+
+ test('every command round-trips its whole set under its hash, and never satisfies another command', async () => {
+ for (const { command, preview } of COMMANDS) {
+ const items = Array.from({ length: 500 }, (_, i) => ({ id: i, request_id: `00000000-0000-4000-a000-${String(i).padStart(12, '0')}`, note: `it's "${command}"` }));
+ const hash = previewHash({ command, items });
+ await saveApprovedSet(engine, { command, hash }, items);
+ const loaded = await loadApprovedSet<typeof items[number]>(engine, { command, hash, previewCommand: preview });
+ expect(loaded).toMatchObject({ command, hash });
+ expect(loaded.items).toEqual(items);
+ expect(Number.isNaN(Date.parse(loaded.approved_at))).toBe(false);
+ for (const other of COMMANDS.filter(c => c.command !== command)) {
+ const error = await refusal(() => loadApprovedSet(engine, { command: other.command, hash, previewCommand: other.preview }));
+ expect(error.code).toBe('preview_changed');
+ expect(error.message).toContain(other.preview);
+ }
+ }
+ });
+
+ test('an unknown hash refuses with preview_changed naming the hash and the filled preview command', async () => {
+ const error = await refusal(() => loadApprovedSet(engine, { command: 'extractor-facts', hash: 'f'.repeat(64), previewCommand: COMMANDS[3]!.preview }));
+ expect(error.toJSON()).toMatchObject({ error: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed',
+ message: `The preview changed since ${'f'.repeat(64)}; re-run ${COMMANDS[3]!.preview} and use the new hash.` });
+ });
+
+ test('a set older than the purge window refuses whole; a younger one loads; a re-preview restarts its age', async () => {
+ const items = [{ id: 1 }, { id: 2 }];
+ const hash = previewHash(['stale-atoms', items]);
+ const key = { command: 'stale-atoms' as const, hash, previewCommand: COMMANDS[2]!.preview };
+ await saveApprovedSet(engine, key, items);
+ await age('stale-atoms', hash, APPROVAL_MAX_AGE_DAYS - 1);
+ expect((await loadApprovedSet(engine, key)).items).toEqual(items);
+ await age('stale-atoms', hash, APPROVAL_MAX_AGE_DAYS + 1);
+ expect((await refusal(() => loadApprovedSet(engine, key))).code).toBe('preview_changed');
+ await saveApprovedSet(engine, key, items);
+ expect((await loadApprovedSet(engine, key)).items).toEqual(items);
+ });
+
+ test('the purge window matches purgeStaleCheckpoints: an expired set is purged, a fresh one survives', async () => {
+ const fresh = previewHash(['jobs-cancel', 'fresh']);
+ const stale = previewHash(['jobs-cancel', 'stale']);
+ await saveApprovedSet(engine, { command: 'jobs-cancel', hash: fresh }, [{ id: 1 }]);
+ await saveApprovedSet(engine, { command: 'jobs-cancel', hash: stale }, [{ id: 2 }]);
+ await age('jobs-cancel', stale, APPROVAL_MAX_AGE_DAYS + 1);
+ await purgeStaleCheckpoints(engine);
+ const rows = await engine.executeRaw<{ fingerprint: string }>('SELECT fingerprint FROM op_checkpoints WHERE op=$1', [PREVIEW_APPROVAL_OP]);
+ expect(rows.map(row => row.fingerprint)).toEqual([`jobs-cancel:${fresh}`]);
+ expect((await loadApprovedSet(engine, { command: 'jobs-cancel', hash: fresh, previewCommand: COMMANDS[1]!.preview })).items).toEqual([{ id: 1 }]);
+ });
+
+ test('a malformed saved row refuses instead of returning a partial set', async () => {
+ const hash = previewHash(['authorize-legacy', 'malformed']);
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES($1,$2,$3::text::jsonb)`,
+ [PREVIEW_APPROVAL_OP, `authorize-legacy:${hash}`, JSON.stringify([{ command: 'authorize-legacy', hash }])]);
+ expect((await refusal(() => loadApprovedSet(engine, { command: 'authorize-legacy', hash, previewCommand: COMMANDS[0]!.preview }))).code).toBe('preview_changed');
+ });
+
+ test('clearApprovedSet removes only that set', async () => {
+ const a = previewHash(['extractor-facts', 'a']);
+ const b = previewHash(['extractor-facts', 'b']);
+ await saveApprovedSet(engine, { command: 'extractor-facts', hash: a }, [1]);
+ await saveApprovedSet(engine, { command: 'extractor-facts', hash: b }, [2]);
+ await clearApprovedSet(engine, { command: 'extractor-facts', hash: a });
+ expect((await refusal(() => loadApprovedSet(engine, { command: 'extractor-facts', hash: a, previewCommand: 'p' }))).code).toBe('preview_changed');
+ expect((await loadApprovedSet(engine, { command: 'extractor-facts', hash: b, previewCommand: 'p' })).items).toEqual([2]);
+ });
+ });
+}
diff --git a/test/projection-drain-autopilot-names.test.ts b/test/projection-drain-autopilot-names.test.ts
new file mode 100644
index 0000000000..a64bc3b147
--- /dev/null
+++ b/test/projection-drain-autopilot-names.test.ts
@@ -0,0 +1,56 @@
+/**
+ * #5401 x #5195: the projection drain's stop/drain/restart steps name the
+ * autopilot job that runs THIS brain, not the shared default job, so following
+ * them never stops another brain's autopilot and leaves this owner running.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'fs';
+import { spawnSync } from 'child_process';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+const REPO = resolve(import.meta.dir, '..');
+
+/** Bun fixes os.homedir() at process start, so each case runs in a child with the HOME under test. */
+function stepsIn(env: Record<string, string>, mint: boolean): { steps: string; suffix: string | null } {
+ const script = `import { ensureAutopilotInstallId, resolveAutopilotJob } from ${JSON.stringify(join(REPO, 'src/core/autopilot-paths.ts'))};\n`
+ + `import { residentDrainSteps } from ${JSON.stringify(join(REPO, 'src/commands/projections.ts'))};\n`
+ + `if (${mint}) ensureAutopilotInstallId();\n`
+ + `process.stdout.write(JSON.stringify({ steps: residentDrainSteps(4242), suffix: resolveAutopilotJob().suffix }));\n`;
+ const childEnv: Record<string, string> = {};
+ for (const [k, v] of Object.entries({ ...process.env, ...env })) if (v !== undefined) childEnv[k] = v;
+ delete childEnv.GBRAIN_AUTOPILOT_LABEL;
+ const r = spawnSync(process.execPath, ['-e', script], { env: childEnv, encoding: 'utf-8' });
+ if (r.status !== 0) throw new Error(`child failed: ${r.stderr}`);
+ return JSON.parse(r.stdout);
+}
+
+describe('projection drain steps name this brain\'s autopilot job', () => {
+ test('a non-default GBRAIN_HOME brain gets its own suffixed launchd label and systemd unit', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-drain-names-')));
+ try {
+ mkdirSync(join(root, 'home'), { recursive: true });
+ mkdirSync(join(root, 'brain-b'), { recursive: true });
+ const { steps, suffix } = stepsIn({ HOME: join(root, 'home'), GBRAIN_HOME: join(root, 'brain-b') }, true);
+ expect(suffix).toMatch(/^[0-9a-f]{8}$/);
+ expect(steps).toContain(`systemctl --user stop gbrain-autopilot-${suffix}.service`);
+ expect(steps).toContain(`launchctl bootout gui/$(id -u)/com.gbrain.autopilot.${suffix}`);
+ expect(steps).not.toContain('systemctl --user stop gbrain-autopilot.service');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('the default brain keeps the shared names', () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'gbrain-drain-names-')));
+ try {
+ mkdirSync(join(root, 'home'), { recursive: true });
+ const { steps } = stepsIn({ HOME: join(root, 'home'), GBRAIN_HOME: '' }, false);
+ expect(steps).toContain('systemctl --user stop gbrain-autopilot.service');
+ expect(steps).toContain('launchctl bootout gui/$(id -u)/com.gbrain.autopilot ');
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/test/projection-drain.test.ts b/test/projection-drain.test.ts
new file mode 100644
index 0000000000..d8f8bfa4a7
--- /dev/null
+++ b/test/projection-drain.test.ts
@@ -0,0 +1,248 @@
+/**
+ * #5401: the projection drain command and the budgeted resident drain. Clock
+ * and per-page cost are injected; no assertion depends on wall-clock time.
+ * PGLite here; test/e2e/projection-drain-postgres.test.ts runs the same file on
+ * PostgreSQL, where the concurrent owner schedules also run.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { rebuildPendingPageProjections, projectionBacklog } from '../src/core/page-state/projections.ts';
+import { runResidentProjectionInvocation } from '../src/core/persistence/consumer.ts';
+import { claimNextWrite, hasClaimableWrite } from '../src/core/persistence/journal.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { drainProjections } from '../src/commands/projections.ts';
+import { checkProjectionReadiness } from '../src/commands/doctor/checks/projection-readiness.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requestFixture } from './helpers/persistence-request-fixture.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+let sourceSeq = 0;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ }
+ if (backends.includes('postgres')) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!); engines.push(pg.engine); closePostgres = pg.close; }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();
+ await closePostgres?.();
+});
+
+/** Each test drains its own source: earlier tests' rows are gone or out of scope. */
+async function clearQueue(engine: BrainEngine) {
+ await engine.executeRaw('DELETE FROM page_projection_jobs');
+ await engine.executeRaw("DELETE FROM persistence_requests WHERE state IN ('queued','running')");
+}
+
+async function backlog(engine: BrainEngine, pages: number): Promise<string> {
+ await clearQueue(engine);
+ const sourceId = `drain-${++sourceSeq}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ for (let i = 0; i < pages; i++) {
+ await engine.putPage(`notes/n-${String(i).padStart(4, '0')}`, { type: 'note', title: `Note ${i}`, compiled_truth: `Example note ${i} about a sample topic.` }, { sourceId });
+ }
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=NULL WHERE source_id=$1', [sourceId]);
+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id=$1
+ ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision,reason=EXCLUDED.reason,updated_at=now()`, [sourceId]);
+ return sourceId;
+}
+
+/** A clock that advances by the injected per-page cost (half per transaction: lock, then install). */
+function costed(engine: BrainEngine, costMs: number) {
+ const clock = { t: 0, now: () => clock.t };
+ const transaction = engine.transaction.bind(engine);
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>) => { clock.t += costMs / 2; return transaction(run); };
+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ return { engine: proxy, clock };
+}
+
+const pending = async (engine: BrainEngine) => (await projectionBacklog(engine)).pending;
+
+test('a budgeted rebuild starts no page after the deadline, and the resident invocation uses the 250 ms budget', async () => {
+ for (const engine of engines) {
+ await backlog(engine, 40);
+ const direct = costed(engine, 40);
+ expect(await rebuildPendingPageProjections(direct.engine, 100, { deadlineMs: 250, now: direct.clock.now })).toEqual({ rebuilt: 7, superseded: 0 });
+ expect(direct.clock.t - 40).toBeLessThan(250);
+ const resident = costed(engine, 40);
+ expect(await runResidentProjectionInvocation(resident.engine, localHostId(), [], resident.clock.now)).toEqual({ rebuilt: 7, superseded: 0 });
+ expect(await pending(engine)).toBe(26);
+ }
+}, 120_000);
+
+test('a claimable write drops the resident invocation to two pages; a blocked or excluded write does not', async () => {
+ for (const engine of engines) {
+ await backlog(engine, 30);
+ const f = await requestFixture(engine);
+ const head = await f.admit('head');
+ const invoke = (excluded: string[]) => { const timed = costed(engine, 20); return runResidentProjectionInvocation(timed.engine, localHostId(), excluded, timed.clock.now); };
+ expect(await hasClaimableWrite(engine, localHostId())).toBe(true);
+ expect((await invoke([])).rebuilt).toBe(2);
+ const root = `db:${head.source_incarnation}`;
+ expect(await hasClaimableWrite(engine, localHostId(), [root])).toBe(false);
+ expect((await invoke([root])).rebuilt).toBe(13);
+ expect((await claimNextWrite(engine, localHostId()))?.id).toBe(head.id);
+ await f.admit('behind-running-head');
+ expect(await hasClaimableWrite(engine, localHostId())).toBe(false);
+ expect((await invoke([])).rebuilt).toBe(13);
+ expect(await pending(engine)).toBe(2);
+ }
+}, 120_000);
+
+test('a 1,000-page backlog drains in the invocation count the injected per-page cost predicts', async () => {
+ for (const engine of engines) {
+ await backlog(engine, 1000);
+ const { engine: timed, clock } = costed(engine, 10);
+ let invocations = 0;
+ for (;;) {
+ const startedAt = clock.t;
+ const result = await runResidentProjectionInvocation(timed, localHostId(), [], clock.now);
+ if (result.rebuilt + result.superseded === 0) break;
+ invocations++;
+ expect(result.rebuilt).toBe(25);
+ expect(clock.t - 10 - startedAt).toBeLessThan(250);
+ }
+ expect(invocations).toBe(40);
+ expect(await pending(engine)).toBe(0);
+ }
+}, 300_000);
+
+test('a drain run tries a failing page once, keeps rebuilding the rest, and reports it with its reason', async () => {
+ for (const engine of engines) {
+ const sourceId = await backlog(engine, 3);
+ await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId });
+ const result = await drainProjections(engine);
+ expect(result).toMatchObject({ rebuilt: 3, superseded: 0, remaining: 1, limited: false });
+ expect(result.failed).toHaveLength(1);
+ expect(result.failed[0]).toMatchObject({ source_id: sourceId, slug: 'broken-code' });
+ expect(result.failed[0].reason).toContain('recorded source path');
+ expect(await engine.executeRaw("SELECT reason FROM page_projection_jobs WHERE slug='broken-code'")).toEqual([{ reason: 'rebuild_failed' }]);
+ }
+}, 120_000);
+
+test('the resident selector waits 30 seconds before retrying a failed page; the drain command does not', async () => {
+ for (const engine of engines) {
+ const sourceId = await backlog(engine, 0);
+ await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId });
+ await engine.executeRaw("UPDATE page_projection_jobs SET reason='rebuild_failed',updated_at=now()-interval '10 seconds'");
+ const stamp = async () => (await engine.executeRaw<{ at: string }>('SELECT updated_at::text AS at FROM page_projection_jobs'))[0].at;
+ const cooling = await stamp();
+ expect(await runResidentProjectionInvocation(engine, localHostId(), [])).toEqual({ rebuilt: 0, superseded: 0 });
+ expect(await stamp()).toBe(cooling);
+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at=now()-interval '1 minute'");
+ const due = await stamp();
+ await runResidentProjectionInvocation(engine, localHostId(), []);
+ expect(await stamp()).not.toBe(due);
+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at=now()-interval '10 seconds'");
+ expect((await drainProjections(engine)).failed.map(failure => failure.slug)).toEqual(['broken-code']);
+ }
+}, 120_000);
+
+test('the run-start bound keeps microseconds: a row queued at the bound is tried, one queued 100 microseconds after it is not', async () => {
+ for (const engine of engines) {
+ await backlog(engine, 1);
+ await engine.executeRaw("UPDATE page_projection_jobs SET updated_at='2026-01-01 00:00:00.000400+00'");
+ expect(await rebuildPendingPageProjections(engine, 100, { notAfter: '2026-01-01 00:00:00.000300+00' })).toEqual({ rebuilt: 0, superseded: 0 });
+ expect(await rebuildPendingPageProjections(engine, 100, { notAfter: '2026-01-01 00:00:00.000400+00' })).toEqual({ rebuilt: 1, superseded: 0 });
+ }
+}, 120_000);
+
+test('a preparation error is one page failure, not a batch abort', async () => {
+ for (const engine of engines) {
+ await backlog(engine, 4);
+ const transaction = engine.transaction.bind(engine);
+ let calls = 0;
+ const broken = new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return <T>(run: (tx: BrainEngine) => Promise<T>) => {
+ if (calls++ === 0) return Promise.reject(new Error('simulated preparation failure'));
+ return transaction(run);
+ };
+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ const failures: Array<{ slug: string; reason: string }> = [];
+ expect(await rebuildPendingPageProjections(broken, 100, { onFailure: failure => failures.push(failure) })).toEqual({ rebuilt: 3, superseded: 0 });
+ expect(failures).toEqual([expect.objectContaining({ slug: 'notes/n-0000', reason: 'simulated preparation failure' })]);
+ expect(await engine.executeRaw('SELECT slug,reason FROM page_projection_jobs')).toEqual([{ slug: 'notes/n-0000', reason: 'rebuild_failed' }]);
+ }
+}, 120_000);
+
+test('--limit caps the pages tried and the result records that the run stopped early', async () => {
+ for (const engine of engines) {
+ await backlog(engine, 12);
+ expect(await drainProjections(engine, { limit: 5 })).toEqual({ rebuilt: 5, superseded: 0, failed: [], remaining: 7, limited: true });
+ expect(await drainProjections(engine)).toEqual({ rebuilt: 7, superseded: 0, failed: [], remaining: 0, limited: false });
+ }
+}, 120_000);
+
+test('doctor names the drain command when no PGLite resident holds the brain, and the resident when one does', async () => {
+ for (const engine of engines) {
+ const sourceId = await backlog(engine, 1);
+ const local = await checkProjectionReadiness(engine, { sourceId });
+ expect(local.status).toBe('warn');
+ expect(local.message).toContain('Run `gbrain projections drain`');
+ expect(local.message).not.toContain('Restart the upgraded resident');
+ const resident = await checkProjectionReadiness(engine, { sourceId }, { resident: true });
+ expect(resident.message).toContain('resident gbrain process that holds this PGLite brain is rebuilding');
+ expect(resident.message).not.toContain('Run `gbrain projections drain`');
+ await drainProjections(engine);
+ expect((await checkProjectionReadiness(engine, { sourceId })).status).toBe('ok');
+ }
+}, 120_000);
+
+/** Pauses the first page of `engine` until `release` resolves, at `point`. */
+function paused(engine: BrainEngine, point: 'before_lock' | 'after_lock') {
+ const reached = Promise.withResolvers<void>();
+ const release = Promise.withResolvers<void>();
+ const transaction = engine.transaction.bind(engine);
+ let first = true;
+ const proxy = new Proxy(engine, { get(target, key) {
+ if (key === 'transaction') return async <T>(run: (tx: BrainEngine) => Promise<T>) => {
+ if (!first) return transaction(run);
+ first = false;
+ if (point === 'before_lock') { reached.resolve(); await release.promise; return transaction(run); }
+ return transaction(tx => run(new Proxy(tx, { get(inner, prop) {
+ if (prop === 'lockPageKeys') return async (keys: unknown) => { await (inner as any).lockPageKeys(keys); reached.resolve(); await release.promise; };
+ const value = Reflect.get(inner, prop, inner); return typeof value === 'function' ? value.bind(inner) : value;
+ } })));
+ };
+ const value = Reflect.get(target, key, target); return typeof value === 'function' ? value.bind(target) : value;
+ } });
+ return { engine: proxy, reached: reached.promise, release: () => release.resolve() };
+}
+
+test('on Postgres the drain runs beside a resident owner and each page is rebuilt once in either order', async () => {
+ for (const engine of engines.filter(candidate => candidate.kind === 'postgres')) {
+ await backlog(engine, 3);
+ const cli = paused(engine, 'before_lock');
+ const drain = drainProjections(cli.engine);
+ await cli.reached;
+ expect(await runResidentProjectionInvocation(engine, localHostId(), [])).toEqual({ rebuilt: 3, superseded: 0 });
+ cli.release();
+ expect(await drain).toEqual({ rebuilt: 0, superseded: 3, failed: [], remaining: 0, limited: false });
+
+ const sourceId = await backlog(engine, 1);
+ const holder = paused(engine, 'after_lock');
+ const first = drainProjections(holder.engine);
+ await holder.reached;
+ const resident = runResidentProjectionInvocation(engine, localHostId(), []);
+ for (let attempt = 0; attempt < 200; attempt++) {
+ const [waiting] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pg_locks WHERE NOT granted');
+ if (waiting.n > 0) break;
+ await Bun.sleep(25);
+ }
+ holder.release();
+ const [cliRun, residentRun] = await Promise.all([first, resident]);
+ expect(cliRun.failed).toEqual([]);
+ expect({ rebuilt: cliRun.rebuilt + residentRun.rebuilt, superseded: cliRun.superseded + residentRun.superseded }).toEqual({ rebuilt: 1, superseded: 1 });
+ const [page] = await engine.executeRaw<{ sealed: boolean }>("SELECT text_projection_revision=knowledge_revision AS sealed FROM pages WHERE slug='notes/n-0000' AND source_id=$1", [sourceId]);
+ expect(page.sealed).toBe(true);
+ }
+}, 120_000);
diff --git a/test/projection-resident-doctor.test.ts b/test/projection-resident-doctor.test.ts
new file mode 100644
index 0000000000..abe93dbffb
--- /dev/null
+++ b/test/projection-resident-doctor.test.ts
@@ -0,0 +1,100 @@
+/**
+ * #5401 E-T1: while a PGLite resident holds the datastore, doctor cannot open
+ * the engine; the resident answers a read-only projection_status IPC op with
+ * counts only, and doctor's filesystem-lane entry reports the backlog from it.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { projectionBacklog } from '../src/core/page-state/projections.ts';
+import {
+ persistenceSocketPathForConfig, requestPersistenceProjectionStatus, startPersistenceIpcServer, type PersistenceIpcProvider,
+} from '../src/core/persistence/ipc.ts';
+import { projectionResidentEntry } from '../src/commands/doctor/checks/projection-readiness.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-projection-resident-'));
+const config = { engine: 'pglite' as const, database_path: join(home, 'brain.pglite') };
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect(config); await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('resident-example','resident-example')");
+ for (const slug of ['notes/a', 'notes/b', 'notes/c']) {
+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Example ${slug}.` }, { sourceId: 'resident-example' });
+ }
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='resident-example'");
+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id='resident-example'
+ ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision`);
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+}, 120_000);
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const provider = (status?: PersistenceIpcProvider['projectionStatus']): PersistenceIpcProvider => ({
+ brainId: randomUUID(), dispatch: async () => { throw new Error('not used'); }, ...(status ? { projectionStatus: status } : {}),
+});
+const doctorContext = (overrides: Partial<DoctorContext> = {}) => ({ engine: null, fastMode: false, ...overrides }) as DoctorContext;
+const runEntry = (ctx: DoctorContext) => withEnv({ GBRAIN_HOME: home, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined },
+ async () => await projectionResidentEntry.run(ctx) as Check[]);
+
+test('the resident answers projection_status with counts only; an owner without it refuses', async () => {
+ const socket = persistenceSocketPathForConfig(config)!;
+ const server = (await startPersistenceIpcServer(socket, provider(() => projectionBacklog(engine))))!;
+ try {
+ const status = await requestPersistenceProjectionStatus(socket);
+ expect(status).toMatchObject({ pending: 3, failed: 0 });
+ expect(Object.keys(status).sort()).toEqual(['failed', 'oldest_age_seconds', 'pending']);
+ expect(status.oldest_age_seconds).toBeGreaterThanOrEqual(0);
+ } finally { server.close(); }
+ const old = (await startPersistenceIpcServer(socket, provider()))!;
+ try {
+ await expect(requestPersistenceProjectionStatus(socket)).rejects.toMatchObject({ code: 'unavailable' });
+ } finally { old.close(); }
+});
+
+test('stalled projection_status requests count toward the listener bound and cannot pile up', async () => {
+ const socket = persistenceSocketPathForConfig(config)!;
+ const stalled = Promise.withResolvers<void>();
+ let calls = 0;
+ const server = (await startPersistenceIpcServer(socket, provider(async () => { calls++; await stalled.promise; return { pending: 0, failed: 0, oldest_age_seconds: null }; })))!;
+ try {
+ const abandoned = await Promise.allSettled(Array.from({ length: 8 }, () => requestPersistenceProjectionStatus(socket, 200)));
+ expect(abandoned.every(result => result.status === 'rejected')).toBe(true);
+ expect(calls).toBe(8);
+ await expect(requestPersistenceProjectionStatus(socket)).rejects.toMatchObject({ code: 'queue_capacity' });
+ expect(calls).toBe(8);
+ stalled.resolve();
+ await new Promise(resolve => setTimeout(resolve, 50));
+ expect(await requestPersistenceProjectionStatus(socket)).toEqual({ pending: 0, failed: 0, oldest_age_seconds: null });
+ } finally { stalled.resolve(); server.close(); }
+});
+
+test('doctor reports the resident backlog, its pid and the stop-drain-restart path while the resident holds the brain', async () => {
+ const socket = persistenceSocketPathForConfig(config)!;
+ const server = (await startPersistenceIpcServer(socket, provider(() => projectionBacklog(engine))))!;
+ let draining: Check[];
+ try { draining = await runEntry(doctorContext()); } finally { server.close(); }
+ expect(draining).toHaveLength(1);
+ expect(draining[0]).toMatchObject({ name: 'text_projection_readiness', status: 'warn',
+ details: { readiness: 'projection_pending', ready: false, pending: 3, failed: 0, owner_pid: process.pid } });
+ expect(draining[0].message).toContain(`(pid ${process.pid}) holds this PGLite brain and is draining 3 queued text projections`);
+ expect(draining[0].message).toContain('systemctl --user stop gbrain-serve.service && { gbrain projections drain; systemctl --user start gbrain-serve.service; }');
+ expect(draining[0].message).toContain(`kill ${process.pid}`);
+
+ const silent = await runEntry(doctorContext());
+ expect(silent[0]).toMatchObject({ name: 'text_projection_readiness', status: 'warn', details: { readiness: 'unknown' } });
+ expect(silent[0].message).toContain('may predate the faster projection drain');
+
+ expect(await runEntry(doctorContext({ engine: engine as never }))).toEqual([]);
+ expect(await runEntry(doctorContext({ fastMode: true }))).toEqual([]);
+}, 60_000);
diff --git a/test/projections-drain-cli.serial.test.ts b/test/projections-drain-cli.serial.test.ts
new file mode 100644
index 0000000000..1b2763a201
--- /dev/null
+++ b/test/projections-drain-cli.serial.test.ts
@@ -0,0 +1,115 @@
+/**
+ * #5401 / DX-O5: `gbrain projections drain` through the real CLI entrypoint.
+ * Exit 0 when nothing tried failed, 1 when a page failed, 2 when it did not run
+ * (bad usage, or `projection_owner_resident` because a resident holds the
+ * PGLite brain — refused before any engine opens, including for a mounted
+ * PGLite brain on a host configured for Postgres).
+ */
+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 { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const root = mkdtempSync(join(tmpdir(), 'gbrain-projections-cli-'));
+const healthyHome = join(root, 'healthy');
+const failingHome = join(root, 'failing');
+const mountedHome = join(root, 'mounted');
+
+function writeConfig(home: string, config: Record<string, unknown>) {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(config));
+}
+
+async function seedBrain(home: string, broken: boolean) {
+ const database_path = join(home, '.gbrain', 'brain.pglite');
+ writeConfig(home, { engine: 'pglite', database_path });
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path });
+ try {
+ await engine.initSchema();
+ await engine.executeRaw("INSERT INTO sources(id,name) VALUES('cli-example','cli-example')");
+ for (const slug of ['notes/a', 'notes/b']) await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: `Example ${slug}.` }, { sourceId: 'cli-example' });
+ await engine.executeRaw("UPDATE pages SET text_projection_revision=NULL WHERE source_id='cli-example'");
+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation,slug,revision,reason)
+ SELECT s.incarnation,p.slug,p.knowledge_revision,'test_backlog' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.source_id='cli-example'
+ ON CONFLICT(source_incarnation,slug) DO UPDATE SET revision=EXCLUDED.revision`);
+ if (broken) await engine.putPage('broken-code', { type: 'code', page_kind: 'code', title: 'Missing origin', compiled_truth: 'export const example = 1;' }, { sourceId: 'cli-example' });
+ } finally { await engine.disconnect(); }
+}
+
+beforeAll(async () => {
+ await seedBrain(healthyHome, false);
+ await seedBrain(failingHome, true);
+ writeConfig(mountedHome, { engine: 'postgres', database_url: 'postgresql://[email protected]:1/unreachable' });
+ writeFileSync(join(mountedHome, '.gbrain', 'mounts.json'), JSON.stringify({ version: 1, mounts: [
+ { id: 'team-a', path: join(mountedHome, 'team-a'), engine: 'pglite', database_path: join(mountedHome, 'team-a.pglite'), enabled: true },
+ ] }));
+}, 240_000);
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+describe('gbrain projections drain', () => {
+ test('help lists the command; bad usage exits 2 without running', async () => {
+ expect((await runCli(['--help'], { home: healthyHome })).stdout).toContain('projections drain [--limit n]');
+ const help = await runCli(['projections', '--help'], { home: healthyHome });
+ expect(help.exitCode).toBe(0);
+ expect(help.stdout).toContain('Exit codes: 0 nothing tried failed; 1 some pages failed; 2 did not run');
+ const unknown = await runCli(['projections', 'rebuild'], { home: healthyHome });
+ expect(unknown.exitCode).toBe(2);
+ expect(unknown.stderr).toContain('Error [invalid_params]');
+ const limit = await runCli(['projections', 'drain', '--limit', '0', '--json'], { home: healthyHome });
+ expect(limit.exitCode).toBe(2);
+ expect(JSON.parse(limit.stdout)).toMatchObject({ error: 'invalid_params', suggestion: expect.stringContaining('gbrain projections drain --limit 1000') });
+ }, 120_000);
+
+ test('exit 0 drains the backlog and says it is empty', async () => {
+ const human = await runCli(['projections', 'drain'], { home: healthyHome });
+ expect(human.exitCode).toBe(0);
+ expect(human.stdout).toContain('projections drain: 2 rebuilt, 0 superseded, 0 failed, 0 remaining. The projection backlog is empty.');
+ const again = await runCli(['projections', 'drain', '--json'], { home: healthyHome });
+ expect(again.exitCode).toBe(0);
+ expect(JSON.parse(again.stdout)).toEqual({ rebuilt: 0, superseded: 0, failed: [], remaining: 0 });
+ }, 120_000);
+
+ test('exit 1 reports each failed page with its source, slug, reason and next action', async () => {
+ const json = await runCli(['projections', 'drain', '--json'], { home: failingHome });
+ expect(json.exitCode).toBe(1);
+ const payload = JSON.parse(json.stdout);
+ expect(payload).toMatchObject({ rebuilt: 2, superseded: 0, remaining: 1 });
+ expect(payload.failed).toEqual([{ source_id: 'cli-example', slug: 'broken-code', reason: expect.stringContaining('recorded source path') }]);
+ const human = await runCli(['projections', 'drain'], { home: failingHome });
+ expect(human.exitCode).toBe(1);
+ expect(human.stderr).toContain('failed: cli-example/broken-code: Code projection requires a recorded source path');
+ expect(human.stderr).toContain('next: restore frontmatter.file or source_path on broken-code');
+ expect(human.stdout).toContain('0 rebuilt, 0 superseded, 1 failed, 1 remaining. Failed pages stay queued');
+ expect(human.stdout).not.toContain('backlog is empty');
+ }, 120_000);
+
+ test('exit 2 projection_owner_resident while a resident holds the PGLite brain, before any engine opens', async () => {
+ const lock = await acquireLock(join(healthyHome, '.gbrain', 'brain.pglite'));
+ try {
+ const human = await runCli(['projections', 'drain'], { home: healthyHome, timeoutMs: 30_000 });
+ expect(human.exitCode).toBe(2);
+ expect(human.stderr).toContain('Error [projection_owner_resident]');
+ expect(human.stderr).toContain(`(pid ${process.pid}), so the drain did not run.`);
+ expect(human.stderr).toContain('watch the pending count with `gbrain doctor` (text_projection_readiness)');
+ expect(human.stderr).toContain('systemctl --user stop gbrain-serve.service && { gbrain projections drain; systemctl --user start gbrain-serve.service; }');
+ const json = await runCli(['projections', 'drain', '--json'], { home: healthyHome, timeoutMs: 30_000 });
+ expect(json.exitCode).toBe(2);
+ expect(JSON.parse(json.stdout)).toMatchObject({ error: 'projection_owner_resident', docs: 'docs/guides/repair.md#projection-owner-resident' });
+ } finally { await releaseLock(lock); }
+ }, 120_000);
+
+ test('a mounted PGLite brain on a Postgres-configured host is refused for its own resident', async () => {
+ const lock = await acquireLock(join(mountedHome, 'team-a.pglite'));
+ try {
+ const refused = await runCli(['projections', 'drain', '--brain', 'team-a'], { home: mountedHome, timeoutMs: 30_000 });
+ expect(refused.exitCode).toBe(2);
+ expect(refused.stderr).toContain(`The PGLite brain at ${join(mountedHome, 'team-a.pglite')} is held by`);
+ expect(refused.stderr).toContain('`gbrain doctor --brain team-a`');
+ expect(refused.stderr).toContain('systemctl --user stop gbrain-serve.service && { gbrain projections drain --brain team-a; systemctl --user start gbrain-serve.service; }');
+ } finally { await releaseLock(lock); }
+ }, 120_000);
+});
diff --git a/test/recall-explicit-default-source.test.ts b/test/recall-explicit-default-source.test.ts
new file mode 100644
index 0000000000..c2565ff0c1
--- /dev/null
+++ b/test/recall-explicit-default-source.test.ts
@@ -0,0 +1,170 @@
+/**
+ * #5535 — an explicit `--source default` must select the `default` source.
+ *
+ * parseFlags defaults flags.source to the literal 'default', so the VALUE
+ * alone cannot distinguish "user asked for the default source" from "user
+ * passed no source flag". recall's resolver mapped the literal away
+ * (`flagValue !== 'default' ? flagValue : null`) and the thin-client wire
+ * call omitted `source_id` when it equalled 'default' — so an explicit
+ * `--source default` fell through to GBRAIN_SOURCE / sources.default /
+ * the server's own default, and facts in `default` became unreachable
+ * ("No matching facts." that reads as missing data).
+ *
+ * Two halves, both against the REAL CLI (helpers/cli-spawn.ts):
+ * - local engine: the per-source `--since-last-run` cursor file names the
+ * source that was actually queried (~/.gbrain/recall-cursors/<id>.json).
+ * - thin client: a fixture MCP server records the forwarded tool call.
+ */
+
+import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+
+const ENV = {
+ GBRAIN_NO_BANNER: '1',
+ GBRAIN_MODEL_DISCOVERY: 'off',
+ GBRAIN_SKIP_STARTUP_HOOKS: '1',
+ ANTHROPIC_API_KEY: undefined,
+ OPENAI_API_KEY: undefined,
+ VOYAGE_API_KEY: undefined,
+} as const;
+
+function cursorDir(home: string): string {
+ return join(home, '.gbrain', 'recall-cursors');
+}
+
+describe('#5535 explicit --source default (local engine)', () => {
+ let home: string;
+
+ beforeAll(async () => {
+ // A throwaway PGLite brain created in-process (config-set-unknown-flag's
+ // pattern) — `gbrain init` would also run the shared-skills/managed
+ // marker writes, which this test does not exercise.
+ home = mkdtempSync(join(tmpdir(), 'gbrain-recall-5535-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const dbPath = join(home, '.gbrain', 'brain.pglite');
+ writeFileSync(
+ join(home, '.gbrain', 'config.json'),
+ JSON.stringify({ engine: 'pglite', database_path: dbPath, embedding_dimensions: 1536 }) + '\n',
+ );
+ const engine = new PGLiteEngine();
+ await engine.connect({ engine: 'pglite', database_path: dbPath });
+ await engine.initSchema();
+ await engine.disconnect();
+ // A second REGISTERED source the env tier can resolve to.
+ mkdirSync(join(home, 'otherrepo'), { recursive: true });
+ const add = await runCli(['sources', 'add', 'other', '--path', join(home, 'otherrepo'), '--force'], {
+ home, cwd: home, timeoutMs: 60_000, env: ENV,
+ });
+ expect(add.exitCode).toBe(0);
+ }, 240_000);
+
+ afterAll(() => {
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ test('the explicit flag beats GBRAIN_SOURCE; omitting it keeps the env tier', async () => {
+ // 1. Unscoped: GBRAIN_SOURCE still wins (unchanged pre-fix behavior).
+ const unscoped = await runCli(['recall', 'topics/example', '--since-last-run'], {
+ home, cwd: home, timeoutMs: 60_000, env: { ...ENV, GBRAIN_SOURCE: 'other' },
+ });
+ expect(unscoped.exitCode).toBe(0);
+ expect(existsSync(join(cursorDir(home), 'other.json'))).toBe(true);
+ rmSync(cursorDir(home), { recursive: true, force: true });
+
+ // 2. Explicit --source default: the literal id wins over the env tier.
+ // Pre-fix this queried `other` (cursor other.json) — the #5535 bug.
+ const explicit = await runCli(['recall', 'topics/example', '--since-last-run', '--source', 'default'], {
+ home, cwd: home, timeoutMs: 60_000, env: { ...ENV, GBRAIN_SOURCE: 'other' },
+ });
+ expect(explicit.exitCode).toBe(0);
+ expect(explicit.stderr).not.toContain('source not registered');
+ expect(existsSync(join(cursorDir(home), 'default.json'))).toBe(true);
+ expect(existsSync(join(cursorDir(home), 'other.json'))).toBe(false);
+ rmSync(cursorDir(home), { recursive: true, force: true });
+
+ // 3. Explicit --source-id default (the sibling spelling) behaves the same.
+ const byId = await runCli(['recall', 'topics/example', '--since-last-run', '--source-id', 'default'], {
+ home, cwd: home, timeoutMs: 60_000, env: { ...ENV, GBRAIN_SOURCE: 'other' },
+ });
+ expect(byId.exitCode).toBe(0);
+ expect(existsSync(join(cursorDir(home), 'default.json'))).toBe(true);
+ }, 180_000);
+});
+
+describe('#5535 explicit --source default (thin client wire call)', () => {
+ test('an explicit default is forwarded as source_id; the env fallback still applies when omitted', async () => {
+ const calls: Array<{ name?: string; arguments?: Record<string, unknown> }> = [];
+ const response = {
+ facts: [], results: [], total: 0, pending_consolidation_count: 0,
+ };
+ const server = Bun.serve({
+ hostname: '127.0.0.1', port: 0, async fetch(request): Promise<Response> {
+ const path = new URL(request.url).pathname;
+ const base = `http://127.0.0.1:${server.port}`;
+ if (path === '/.well-known/oauth-authorization-server') {
+ return Response.json({ issuer: base, token_endpoint: `${base}/token` });
+ }
+ if (path === '/token') {
+ return Response.json({ access_token: 'fixture', token_type: 'bearer', expires_in: 3600, scope: 'read' });
+ }
+ if (path !== '/mcp' || request.method !== 'POST') return new Response(null, { status: 405 });
+ const body = await request.json() as { id?: number; method: string; params?: { name?: string; arguments?: Record<string, unknown> } };
+ if (body.id === undefined) return new Response(null, { status: 202 });
+ if (body.method === 'initialize') {
+ return Response.json({ jsonrpc: '2.0', id: body.id, result: {
+ protocolVersion: '2025-03-26', capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' },
+ } });
+ }
+ if (body.method !== 'tools/call') return new Response(null, { status: 400 });
+ calls.push({ name: body.params?.name, arguments: body.params?.arguments });
+ return Response.json({ jsonrpc: '2.0', id: body.id,
+ result: { content: [{ type: 'text', text: JSON.stringify(response) }] } });
+ },
+ });
+
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-recall-5535-thin-'));
+ const brain = join(home, '.gbrain');
+ mkdirSync(brain);
+ // pglite-shaped thin client (the recall-budget-policy-thin-cli pattern):
+ // a valid local database_path satisfies connectEngine, while remote_mcp
+ // keeps isThinClient() true so the recall path forwards over the wire.
+ // A postgres-shaped config without database_url dies in connectEngine
+ // before the thin-client branch — plain recall (no --budget-policy) has
+ // no engine bypass.
+ const databasePath = join(brain, 'brain.pglite');
+ writeFileSync(join(brain, 'config.json'), JSON.stringify({
+ engine: 'pglite',
+ database_path: databasePath,
+ remote_mcp: {
+ issuer_url: `http://127.0.0.1:${server.port}`, mcp_url: `http://127.0.0.1:${server.port}/mcp`,
+ oauth_client_id: 'fixture', oauth_client_secret: 'fixture',
+ },
+ }));
+ try {
+ // Explicit --source default: the wire call MUST carry source_id
+ // 'default' even though GBRAIN_SOURCE names another source. Pre-fix
+ // the literal was mapped away and the server applied its own default.
+ const explicit = await runCli(['recall', 'topics/example', '--source', 'default'], {
+ home, cwd: home, timeoutMs: 60_000,
+ env: { ...ENV, GBRAIN_SOURCE: 'other', GBRAIN_BRAIN_ID: 'host' },
+ });
+ expect(explicit.exitCode).toBe(0);
+ expect(calls.at(-1)).toMatchObject({ name: 'recall', arguments: { source_id: 'default' } });
+
+ // Omitted flag: the env tier still decides (unchanged behavior).
+ const unscoped = await runCli(['recall', 'topics/example'], {
+ home, cwd: home, timeoutMs: 60_000,
+ env: { ...ENV, GBRAIN_SOURCE: 'other', GBRAIN_BRAIN_ID: 'host' },
+ });
+ expect(unscoped.exitCode).toBe(0);
+ expect(calls.at(-1)).toMatchObject({ name: 'recall', arguments: { source_id: 'other' } });
+ } finally {
+ await server.stop(true);
+ rmSync(home, { recursive: true, force: true });
+ }
+ }, 120_000);
+});
diff --git a/test/reconcile-policy-digest-cycle-stamps.test.ts b/test/reconcile-policy-digest-cycle-stamps.test.ts
new file mode 100644
index 0000000000..735ce8950a
--- /dev/null
+++ b/test/reconcile-policy-digest-cycle-stamps.test.ts
@@ -0,0 +1,45 @@
+/**
+ * Wave-3 connector follow-up #1 (small version): `reconcilePolicyDigest`
+ * hashed the raw `sources.config`, which every successful source cycle
+ * stamps with `last_source_cycle_at` / `last_full_cycle_at`. An autopilot
+ * cycle between `gbrain sources reconcile` preview and apply therefore made
+ * the preview stale ("Reconciliation preview is stale: policy_digest"). The
+ * stamps are excluded now; real policy changes still move the digest.
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { reconcilePolicyDigest } from '../src/core/persistence/reconcile-state.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('notes', 'Notes', '{"federated": true}'::jsonb) ON CONFLICT (id) DO NOTHING`);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+}, 60_000);
+
+describe('reconcilePolicyDigest ignores cycle stamps', () => {
+ test('a cycle stamp leaves the digest unchanged', async () => {
+ const before = await reconcilePolicyDigest(engine, 'notes');
+ await engine.updateSourceConfig('notes', { last_source_cycle_at: '2026-10-01T10:00:00.000Z', last_full_cycle_at: '2026-10-01T10:00:00.000Z' });
+ expect(await reconcilePolicyDigest(engine, 'notes')).toBe(before);
+ await engine.updateSourceConfig('notes', { last_source_cycle_at: '2026-10-01T11:00:00.000Z', last_full_cycle_at: '2026-10-01T11:00:00.000Z' });
+ expect(await reconcilePolicyDigest(engine, 'notes')).toBe(before);
+ });
+
+ test('a policy change still changes the digest', async () => {
+ const before = await reconcilePolicyDigest(engine, 'notes');
+ await engine.updateSourceConfig('notes', { federated: false });
+ expect(await reconcilePolicyDigest(engine, 'notes')).not.toBe(before);
+ const afterConfig = await reconcilePolicyDigest(engine, 'notes');
+ await engine.executeRaw(`UPDATE sources SET trust_frontmatter_overrides = NOT COALESCE(trust_frontmatter_overrides, false) WHERE id = 'notes'`);
+ expect(await reconcilePolicyDigest(engine, 'notes')).not.toBe(afterConfig);
+ });
+});
diff --git a/test/reflex-private-visibility.test.ts b/test/reflex-private-visibility.test.ts
new file mode 100644
index 0000000000..29e0798c7f
--- /dev/null
+++ b/test/reflex-private-visibility.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Ambient recall must not widen what remote search returns (gbrain-evals
+ * N8-1 / N8-2). volunteer_context resolved a `visibility: private` page by
+ * title, alias or surname and returned its title and body synopsis to a
+ * remote caller, and the per-turn hook block (assembleTurnContext, turn
+ * mode) injected the same page. Remote callers on every transport, the
+ * turn block and the reflex resolver's default now hide private and
+ * derived-private pages; the trusted local caller still sees them.
+ * PGLite always; Postgres when a safe DATABASE_URL is set and in the E2E
+ * lane through test/e2e/reflex-private-visibility-postgres.test.ts.
+ *
+ * Synthetic data only.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { assembleTurnContext } from '../src/core/context/turn-context.ts';
+import { resolveEntitiesToPointers } from '../src/core/context/retrieval-reflex.ts';
+import { extractCandidatesFromWindow } from '../src/core/context/entity-salience.ts';
+import { __resetPrivateVisibilityCacheForTests } from '../src/core/search/private-visibility.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+
+for (const kind of testBackends()) {
+describe(`reflex private visibility (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+ const config = { engine: kind } as any;
+
+ const put = (slug: string, content: string) =>
+ dispatchToolCall(engine, 'put_page', { slug, content }, { remote: false, sourceId: 'default', config });
+
+ const page = (title: string, type: string, visibility: string | null, aliases: string[], body: string) =>
+ `---\ntype: ${type}\ntitle: ${JSON.stringify(title)}\n${visibility ? `visibility: ${visibility}\n` : ''}aliases: ${JSON.stringify(aliases)}\n---\n\n${body}\n`;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ const pglite = new PGLiteEngine();
+ await pglite.connect({});
+ await pglite.initSchema();
+ engine = pglite;
+ close = () => pglite.disconnect();
+ }
+ __resetPrivateVisibilityCacheForTests();
+ await put('people/zora-quillfeather', page('Zora Quillfeather', 'person', 'private', ['Zee'], 'Zora Quillfeather is a confidential contact, code PRIVMARK1.'));
+ await put('atoms/velmora-claim', page('Velmora Claim', 'atom', null, [], 'Velmora Claim derived ATOMMARK1 statement.'));
+ await put('companies/harbor-logistics', page('Harbor Logistics', 'company', 'world', ['Harbor'], 'Harbor Logistics is a shipping partner WORLDMARK1.'));
+ }, 120_000);
+
+ afterAll(async () => {
+ await close?.();
+ });
+
+ const HIDDEN = ['people/zora-quillfeather', 'PRIVMARK1', 'Zora Quillfeather', 'atoms/velmora-claim', 'ATOMMARK1'];
+
+ const WINDOWS = [
+ 'user: Lunch with Zora Quillfeather and Harbor Logistics went well.',
+ 'user: Zee called about Harbor Logistics again.',
+ 'user: Did Quillfeather reply? Harbor Logistics is waiting.',
+ 'user: The Velmora Claim came up while reviewing Harbor Logistics.',
+ ];
+
+ const remoteCallers = {
+ stdio: { remote: true, transport: 'stdio' as const, sourceId: 'default', takesHoldersAllowList: ['world'], config },
+ http: {
+ remote: true,
+ transport: 'http' as const,
+ sourceId: 'default',
+ takesHoldersAllowList: ['world'],
+ config,
+ auth: { token: 't', clientId: 'c', scopes: ['read'], allowedSources: ['default'] } as any,
+ },
+ };
+
+ async function volunteer(window: string, opts: Record<string, unknown>) {
+ const r = await dispatchToolCall(engine, 'volunteer_context', { window, min_confidence: 0.5 }, opts as any);
+ expect(r.isError).toBeFalsy();
+ return r.content[0].text;
+ }
+
+ describe(`volunteer_context hides private pages from remote callers`, () => {
+ for (const [name, opts] of Object.entries(remoteCallers)) {
+ for (const window of WINDOWS) {
+ test(`${name}: ${window}`, async () => {
+ const text = await volunteer(window, opts);
+ for (const marker of HIDDEN) expect(text).not.toContain(marker);
+ expect(text).toContain('companies/harbor-logistics');
+ });
+ }
+
+ test(`${name}: remote search agrees (no private hit)`, async () => {
+ const r = await dispatchToolCall(engine, 'search', { query: 'Zora Quillfeather' }, opts as any);
+ expect(r.content[0].text).not.toContain('PRIVMARK1');
+ });
+ }
+
+ test('local trusted caller still sees the private page', async () => {
+ const text = await volunteer(WINDOWS[0], { remote: false, sourceId: 'default', config });
+ expect(text).toContain('people/zora-quillfeather');
+ expect(text).toContain('companies/harbor-logistics');
+ });
+ });
+
+ describe(`turn-context block never injects private pages`, () => {
+ for (const window of WINDOWS) {
+ test(window, async () => {
+ const r = await assembleTurnContext(engine, {
+ sourceId: 'default',
+ window: [{ role: 'user', text: window.replace(/^user: /, '') }],
+ });
+ for (const marker of HIDDEN) expect(r.text).not.toContain(marker);
+ expect(r.text).toContain('companies/harbor-logistics');
+ });
+ }
+ });
+
+ describe(`resolveEntitiesToPointers is world-only unless a caller widens it`, () => {
+ const candidates = () =>
+ extractCandidatesFromWindow([{ role: 'user', text: 'Zora Quillfeather met Harbor Logistics.' }]);
+
+ test('default excludes private pages (the ambient reflex and IPC resolve posture)', async () => {
+ const block = await resolveEntitiesToPointers(engine, 'default', candidates());
+ expect(block?.pointers.map((p) => p.slug)).toEqual(['companies/harbor-logistics']);
+ });
+
+ test('excludePrivate: false (trusted local) keeps the private page', async () => {
+ const block = await resolveEntitiesToPointers(engine, 'default', candidates(), { excludePrivate: false });
+ expect(block?.pointers.map((p) => p.slug).sort()).toEqual(['companies/harbor-logistics', 'people/zora-quillfeather']);
+ });
+ });
+});
+}
diff --git a/test/repair-explicit-only.test.ts b/test/repair-explicit-only.test.ts
new file mode 100644
index 0000000000..8856d80715
--- /dev/null
+++ b/test/repair-explicit-only.test.ts
@@ -0,0 +1,159 @@
+/**
+ * Explicit-only repair kinds (fix wave 5, ENG-O1(a) / DX-O4 / ENG-O13):
+ * `stale-atoms` and `extractor-facts` are registered with `explicit_only`.
+ * They run only when named; `gbrain repair --all`, the no-kind preview, the
+ * remediation plan and the post-upgrade banner list them with their preview
+ * command instead, and the runner refuses one that reaches it unnamed, so a
+ * supplied remediation step cannot run it.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError, type OperationContext } from '../src/core/ops/contract.ts';
+import { resolveRepairScope, runRepair, type RepairKind } from '../src/core/repair/core.ts';
+import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, repairRunner, repairSpec } from '../src/core/repair/registry.ts';
+import { staleAtomsRepair } from '../src/core/repair/stale-atoms.ts';
+import { planRepairSteps, runRepairSteps, type RepairPlanStep } from '../src/core/remediation/repairs.ts';
+import { computeRemediationPlan } from '../src/core/remediation/index.ts';
+import { classifyWaveFindings, renderRemediationPlanLines } from '../src/commands/doctor/remediate.ts';
+import { bannerFindingLine } from '../src/commands/doctor/upgrade-banner.ts';
+import type { WaveCheckSpec, WaveFinding } from '../src/commands/doctor/wave-checks.ts';
+import { REPAIR_HELP, parseRepairArgs, runRepairCommand } from '../src/commands/repair.ts';
+import { _resetCliExitVerdictForTests, currentExitCode } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const EXPLICIT: RepairKind[] = ['stale-atoms', 'extractor-facts'];
+let engine: PGLiteEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-explicit-'));
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+});
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+async function captured(args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, args)); } finally { console.log = original; }
+ return lines.join('\n');
+}
+
+/** A wave check whose findings an explicit-only kind clears (the lanes add the real check ids). */
+function withExplicitCheck<T>(run: (spec: WaveCheckSpec) => T): T {
+ const checks = repairSpec('stale-atoms').checks;
+ checks.push('fixture_stale_atoms');
+ const spec: WaveCheckSpec = { id: 'fixture_stale_atoms', resolution: 'repair', registration: 'wave', impact: 'fixture', count: d => Number(d.count ?? 0),
+ run: async () => ({ name: 'fixture_stale_atoms', status: 'warn', message: 'stale atoms' }) };
+ try { return run(spec); } finally { checks.pop(); }
+}
+
+describe('registry', () => {
+ test('stale-atoms and extractor-facts are registered explicit-only and excluded from the --all set', () => {
+ expect(EXPLICIT_REPAIR_REGISTRY.map(spec => spec.kind)).toEqual(EXPLICIT);
+ for (const kind of EXPLICIT) expect(REPAIR_REGISTRY.map(spec => spec.kind)).toContain(kind);
+ expect(AUTO_REPAIR_REGISTRY.some(spec => spec.explicit_only)).toBe(false);
+ expect(AUTO_REPAIR_REGISTRY.length + EXPLICIT_REPAIR_REGISTRY.length).toBe(REPAIR_REGISTRY.length);
+ });
+});
+
+describe('execution-time enforcement', () => {
+ test('runRepair refuses an explicit-only handler that was not named, then previews it when named', async () => {
+ const scope = await resolveRepairScope(engine);
+ const ctx = { engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: true, remote: false } as unknown as OperationContext;
+ const unnamed = await refusal(() => runRepair(ctx, staleAtomsRepair, scope, { apply: false }));
+ expect(unnamed.toJSON()).toMatchObject({ error: 'explicit_kind_required', suggestion: 'Preview it on the brain host: gbrain repair stale-atoms',
+ docs: 'docs/guides/repair.md#explicit-only-repair-kinds' });
+ const named = await runRepair(ctx, staleAtomsRepair, scope, { apply: false, explicit: true });
+ expect(named).toMatchObject({ kind: 'stale-atoms', mode: 'dry_run', affected: 0 });
+ });
+
+ test('the shared runner refuses an unnamed explicit-only kind', async () => {
+ const runner = await repairRunner(engine, { apply: true, logger: { info() {}, warn() {}, error() {} } });
+ const scope = await resolveRepairScope(engine);
+ expect((await refusal(() => runner.run('extractor-facts', scope))).code).toBe('explicit_kind_required');
+ });
+
+ test('a supplied remediation step naming an explicit-only kind refuses the whole run before any step starts', async () => {
+ const step = (kind: RepairPlanStep['kind'], n: number): RepairPlanStep => ({ step: n, id: `repair:${kind}`, kind, affected: 1, command: `gbrain repair ${kind} --apply`,
+ requires_user_agreement: true, protected: true, paid: false, embeds: 'none', est_usd_cost: 0, lifetime_ids: 0, checks: [], rationale: 'supplied' });
+ const started: string[] = [];
+ for (const kind of EXPLICIT) {
+ const error = await refusal(() => withEnv({ GBRAIN_HOME: home }, () => runRepairSteps(engine, [step('connector-checkpoints', 1), step(kind, 2)],
+ { remote: false, remainingUsd: () => undefined, onStep: s => { started.push(s.kind); } })));
+ expect(error.code).toBe('explicit_kind_required');
+ expect(error.message).toContain(kind);
+ }
+ expect(started).toEqual([]);
+ });
+});
+
+describe('surfaces that list instead of run', () => {
+ test('gbrain repair --all and the no-kind preview never run explicit kinds and list their preview commands', async () => {
+ for (const args of [['--all', '--json'], ['--json']]) {
+ const out = JSON.parse(await captured(args)) as { results: Array<{ kind: string }>; explicit_kinds: Array<{ kind: string; code: string; preview_command: string }> };
+ expect(out.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));
+ expect(out.explicit_kinds).toEqual(EXPLICIT.map(kind => ({ kind, code: 'explicit_kind_required', preview_command: `gbrain repair ${kind}`,
+ docs: 'docs/guides/repair.md#explicit-only-repair-kinds' })));
+ }
+ expect(await captured(['--all'])).toContain('Explicit-only kinds (not run without their name; preview each): gbrain repair stale-atoms; gbrain repair extractor-facts');
+ });
+
+ test('gbrain repair --all --apply exits 0 when explicit kinds are the only ones left', async () => {
+ _resetCliExitVerdictForTests();
+ const out = JSON.parse(await captured(['--all', '--apply', '--json'])) as { results: Array<{ kind: string; stopped?: unknown }> };
+ expect(out.results.some(r => EXPLICIT.includes(r.kind as RepairKind))).toBe(false);
+ expect(out.results.every(r => !r.stopped)).toBe(true);
+ expect(currentExitCode()).toBe(0);
+ });
+
+ test('naming an explicit kind runs it (here: the extractor-facts preview) instead of explicit_kind_required', async () => {
+ const out = JSON.parse(await captured(['extractor-facts', '--json'])) as { results: Array<{ kind: string; mode: string; affected: number }>; explicit_kinds?: unknown };
+ expect(out.results).toMatchObject([{ kind: 'extractor-facts', mode: 'dry_run', affected: 0 }]);
+ expect(out.explicit_kinds).toBeUndefined();
+ });
+
+ test('help marks explicit kinds with their preview and keeps them out of the --all list; --expect is accepted only for them', () => {
+ expect(REPAIR_HELP).toContain('[explicit-only; preview: gbrain repair stale-atoms]');
+ const allLine = REPAIR_HELP.split('\n').find(line => line.trimStart().startsWith('--all'))!;
+ for (const kind of EXPLICIT) expect(allLine).not.toContain(kind);
+ expect(parseRepairArgs(['stale-atoms', '--apply', '--expect', 'abc'])).toMatchObject({ kind: 'stale-atoms', apply: true, expect: 'abc' });
+ expect(parseRepairArgs(['extractor-facts', '--include-ambiguous'])).toMatchObject({ includeAmbiguous: true });
+ for (const args of [['timeline', '--expect', 'abc'], ['--all', '--expect', 'abc'], ['visibility', '--include-ambiguous']]) {
+ expect(() => parseRepairArgs(args)).toThrow(/applies only to an explicit-only kind/);
+ }
+ });
+
+ test('the remediation plan never plans explicit kinds and lists each with its preview command', async () => {
+ expect((await planRepairSteps(engine)).some(step => EXPLICIT.includes(step.kind))).toBe(false);
+ const plan = await withEnv({ GBRAIN_HOME: home }, () => computeRemediationPlan(engine, { repairs: {} }));
+ expect(plan.repair_steps!.some(step => EXPLICIT.includes(step.kind))).toBe(false);
+ expect(plan.explicit_repairs!.map(n => [n.kind, n.code, n.preview_command])).toEqual(EXPLICIT.map(kind => [kind, 'explicit_kind_required', `gbrain repair ${kind}`]));
+ const text = renderRemediationPlanLines(plan, 90).join('\n');
+ expect(text).toContain('Explicit-only repairs');
+ expect(text).toContain(' stale-atoms: gbrain repair stale-atoms');
+ expect(text).not.toContain('gbrain repair stale-atoms --apply');
+ });
+
+ test('the banner and the remediation classification report explicit_kind_required with the preview, never an apply', () => withExplicitCheck(spec => {
+ const finding: WaveFinding = { spec, check: { name: spec.id, status: 'warn', message: 'stale atoms', details: { count: 3 } }, state: 'finding' };
+ const line = bannerFindingLine(finding);
+ expect(line).toBe('[AGENT] fixture_stale_atoms: 3 (explicit_kind_required; preview with: gbrain repair stale-atoms)');
+ expect(line).not.toContain('--apply');
+ expect(classifyWaveFindings([finding], [finding], {})).toEqual([{ check_id: spec.id, message: 'stale atoms', class: 'explicit_kind_required',
+ repair_kind: 'stale-atoms', command: 'gbrain repair stale-atoms' }]);
+ }));
+});
diff --git a/test/repair-extractor-facts.test.ts b/test/repair-extractor-facts.test.ts
new file mode 100644
index 0000000000..a5b4df526e
--- /dev/null
+++ b/test/repair-extractor-facts.test.ts
@@ -0,0 +1,466 @@
+/**
+ * `gbrain repair extractor-facts` (#5731, CEO-A9, ENG-O8, DX-O4, DX-T1), on
+ * PGLite and, with a safe DATABASE_URL, Postgres
+ * (test/e2e/repair-extractor-facts-postgres.test.ts).
+ *
+ * Protects: facts the pre-fix canonical projection expired come back only
+ * with receipt evidence (a committed write of the page completed in the same
+ * transaction, by a consumer older than v0.60.11.0); compacted receipts still
+ * count; separate-transaction, post-fix, fence-history and unmanaged rows are
+ * ambiguous and need --include-ambiguous with that preview's hash;
+ * superseded, withdrawn and duplicated rows are never restored; the apply
+ * restores exactly the previewed set, rechecks each fact, and a resumed apply
+ * restores no new candidate.
+ * Seams: the pre-fix projection's expiry is reproduced by its SQL effect (a
+ * real committed page write, then `expired_at` and the receipt's completion
+ * set in one transaction); the crash replaces the handler's apply for one run.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { OperationContext } from '../src/core/ops/contract.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { VERSION } from '../src/version.ts';
+import { operations } from '../src/core/operations.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { extractorFactsRepair, EXTRACTOR_FACTS_INTENT } from '../src/core/repair/extractor-facts.ts';
+import { extractorFactsCheck } from '../src/commands/doctor/checks/extractor-facts.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { compactWriteReceipts } from '../src/core/persistence/journal.ts';
+import { declarePersistenceProtocol } from '../src/core/persistence/protocol.ts';
+import { runExtractConversationFactsCore } from '../src/commands/extract-conversation-facts.ts';
+import { writeSingleFact } from '../src/core/facts/write-single.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const EXTRACTOR = 'cli:extract-conversation-facts:sess';
+const ENTITY = 'people/alice-example';
+
+interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;
+ warnings?: string[]; listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number>;
+ outcome_items?: Array<{ item: string; outcome: string; reason?: string }> }> }
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+/** `home` only outside a managed brain, whose helper already set GBRAIN_HOME (the owner's host identity). */
+async function repair(engine: BrainEngine, home: string | null, args: string[]): Promise<RepairJson> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ const run = () => runRepairCommand(engine, ['extractor-facts', ...args, '--json']);
+ try { await (home ? withEnv({ GBRAIN_HOME: home }, run) : run()); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+}
+const hashOf = (json: RepairJson) => json.results[0].apply_command.match(/--expect ([0-9a-f]+)/)![1];
+
+/** A conversation page with extractor facts at row numbers 1..n, as `extract-conversation-facts` leaves it. */
+async function conversation(engine: BrainEngine, slug: string, facts: string[], root?: string, sourceId = 'default'): Promise<number[]> {
+ const page = await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'Alice: I will send the deck on Friday.\nBob: Thanks.' }, { sourceId });
+ if (root) {
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${slug}.md`, page.id]);
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId }))!;
+ mkdirSync(dirname(join(root, `${slug}.md`)), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ }
+ const ids: number[] = [];
+ for (const [i, fact] of facts.entries()) {
+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, source_session,
+ row_num, source_markdown_slug) VALUES ($1, $2, $3, 'commitment', 'private', $4, 'sess', $5, $6) RETURNING id`, [sourceId, ENTITY, fact, EXTRACTOR, i + 1, slug]);
+ ids.push(Number(row.id));
+ }
+ return ids;
+}
+
+async function factState(engine: BrainEngine, ids: number[]) {
+ return engine.executeRaw<{ id: number; active: boolean; row_num: number | null }>(
+ 'SELECT id::int AS id, expired_at IS NULL AS active, row_num FROM facts WHERE id=ANY($1::bigint[]) ORDER BY id', [ids]);
+}
+const activeIds = async (engine: BrainEngine, ids: number[]) => (await factState(engine, ids)).filter(row => row.active).map(row => row.id);
+
+describe('extractor-facts is CLI-only (ENG-O13)', () => {
+ test('no operation exposes it over MCP', () => {
+ expect(operations.map(op => op.name).filter(name => /repair|extractor/.test(name))).toEqual([]);
+ });
+});
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? requirePostgresTestDatabase() : undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-extractor-facts-'));
+ afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+ /** A real managed write of the page, then the pre-fix projection's effect on its extractor facts. */
+ async function prefixExpire(engine: BrainEngine, ctx: OperationContext, slug: string,
+ opts: { transaction?: 'same' | 'separate'; consumer?: string | null; ids?: number[] } = {}): Promise<string> {
+ const receipt = await submitPageMutation(ctx, { operation: 'add_timeline_entry',
+ params: { request_id: randomUUID(), slug, date: '2026-03-01', summary: `note ${randomUUID().slice(0, 8)}`, source: 'operator' } }) as { request_id: string };
+ const [row] = await engine.executeRaw<{ id: string }>('SELECT id::text AS id FROM persistence_requests WHERE request_id=$1::uuid', [receipt.request_id]);
+ const expire = (tx: BrainEngine) => tx.executeRaw(`UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id='default'
+ AND source_markdown_slug=$1 AND source LIKE 'cli:extract-conversation-facts%' AND expired_at IS NULL ${opts.ids ? 'AND id=ANY($2::bigint[])' : ''}`,
+ opts.ids ? [slug, opts.ids] : [slug]);
+ const complete = async (tx: BrainEngine) => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw('UPDATE persistence_requests SET completed_at=now(), consumer_version=$2 WHERE id=$1::uuid', [row.id, opts.consumer === undefined ? null : opts.consumer]);
+ };
+ if ((opts.transaction ?? 'same') === 'same') {
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => { await complete(tx); await expire(tx); }));
+ } else {
+ await engine.transaction(tx => complete(tx));
+ // PGLite's now() has millisecond resolution: a later transaction is at least one tick later.
+ await new Promise(resolve => setTimeout(resolve, 5));
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => expire(tx)));
+ }
+ return row.id;
+ }
+
+ describe(`gbrain repair extractor-facts, managed (${backend})`, () => {
+ test('the fix holds: a managed write to a conversation page leaves its extractor facts active', async () => {
+ let ids: number[] = [];
+ await managedBrain(async ({ engine, ctx }) => {
+ await submitPageMutation(ctx, { operation: 'add_timeline_entry',
+ params: { request_id: randomUUID(), slug: 'conversations/fixed', date: '2026-03-01', summary: 'after the fix', source: 'operator' } });
+ expect(await activeIds(engine, ids)).toEqual(ids);
+ expect((await repair(engine, null, [])).results[0].residuals).toEqual({ evidenced: 0, ambiguous: 0, excluded: 0 });
+ }, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/fixed', ['Alice sends the deck'], root); } });
+ }, 120_000);
+
+ test('retained, compacted and ambiguous histories: preview, hash-bound apply, recall, then --include-ambiguous', async () => {
+ const seeded: Record<string, number[]> = {};
+ await managedBrain(async ({ engine, ctx }) => {
+ const [retainedA, retainedB, superseded, withdrawn, duplicated] = seeded.retained;
+ // An active copy of one claim and a withdrawal of another, then one pre-fix publication expires the page.
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], async () => {
+ await tx.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ('default', $1, 'Alice sends the deck on Friday', 'commitment', 'private', $2, 9, 'conversations/retained')`, [ENTITY, EXTRACTOR]);
+ await tx.executeRaw("INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'private', '*', gbrain_fact_fingerprint('Alice withdrew this claim'))");
+ }));
+ await prefixExpire(engine, ctx, 'conversations/retained', { ids: [retainedA, retainedB, superseded, withdrawn, duplicated] });
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>
+ tx.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [retainedA, superseded])));
+ const compacted = await prefixExpire(engine, ctx, 'conversations/compacted');
+ // Older than the 30-day receipt retention, so compaction drops its intent but keeps its completion.
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ await tx.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id=$1::uuid", [compacted]);
+ await tx.executeRaw("UPDATE persistence_requests SET completed_at=completed_at-interval '40 days' WHERE id=$1::uuid", [compacted]);
+ });
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>
+ tx.executeRaw("UPDATE facts SET expired_at=expired_at-interval '40 days' WHERE source_markdown_slug='conversations/compacted'")));
+ expect(await compactWriteReceipts(engine, 30)).toBeGreaterThanOrEqual(1);
+ expect((await engine.executeRaw<{ compacted: boolean }>('SELECT compacted FROM persistence_requests WHERE id=$1::uuid', [compacted]))[0].compacted).toBe(true);
+ await prefixExpire(engine, ctx, 'conversations/separate', { transaction: 'separate' });
+ await prefixExpire(engine, ctx, 'conversations/post-fix', { consumer: VERSION });
+ await prefixExpire(engine, ctx, 'conversations/fenced');
+
+ const preview = await repair(engine, null, []);
+ const classes = Object.fromEntries(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.class]));
+ expect(classes).toEqual({
+ [retainedA]: 'evidenced', [retainedB]: 'evidenced', [superseded]: 'excluded:superseded', [withdrawn]: 'excluded:withdrawn',
+ [duplicated]: 'excluded:active_duplicate', [seeded.compacted[0]]: 'evidenced',
+ [seeded.separate[0]]: 'ambiguous', [seeded['post-fix'][0]]: 'ambiguous', [seeded.fenced[0]]: 'ambiguous',
+ });
+ const details = Object.fromEntries(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.detail]));
+ expect(details[seeded.separate[0]]).toContain('no committed write of the page completed at the exact expiry instant');
+ expect(details[seeded['post-fix'][0]]).toContain('fixed consumer');
+ expect(details[seeded.fenced[0]]).toContain('fence facts');
+ expect(details[retainedA]).toContain('unstamped');
+ expect(preview.results[0].residuals).toEqual({ evidenced: 3, ambiguous: 3, excluded: 3 });
+ expect(preview.results[0].affected).toBe(2);
+ const hash = hashOf(preview);
+ expect(preview.results[0].apply_command).toBe(`gbrain repair extractor-facts --apply --expect ${hash}`);
+ const everything = Object.values(seeded).flat();
+ const activeBefore = await activeIds(engine, everything);
+
+ const unbound = await refusal(() => repair(engine, null, ['--apply']));
+ expect(unbound.toJSON()).toMatchObject({ error: 'invalid_params', docs: 'docs/guides/repair.md#explicit-only-repair-kinds',
+ suggestion: 'Preview first: gbrain repair extractor-facts — then run the apply command it prints: gbrain repair extractor-facts --apply --expect <preview-hash>' });
+ const stale = await refusal(() => repair(engine, null, ['--apply', '--expect', 'f'.repeat(64)]));
+ expect(stale.toJSON()).toMatchObject({ error: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed',
+ message: `The preview changed since ${'f'.repeat(64)}; re-run gbrain repair extractor-facts and use the new hash.` });
+ expect(await activeIds(engine, everything)).toEqual(activeBefore);
+
+ const applied = await repair(engine, null, ['--apply', '--expect', hash]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, skipped: 0, outcomes: { restored: 2 } });
+ const restored = [retainedA, retainedB, seeded.compacted[0]];
+ expect(await activeIds(engine, everything)).toEqual([...activeBefore, ...restored].sort((a, b) => a - b));
+ // Per-history counts (CEO-A9 completion criteria): restored, ambiguous (left for --include-ambiguous), excluded, unresolved.
+ const activeNow = new Set(await activeIds(engine, everything));
+ const report = Object.fromEntries(Object.entries(seeded).map(([history, ids]) => {
+ const mine = ids.filter(id => classes[id] !== undefined);
+ const restoredHere = mine.filter(id => activeNow.has(id)).length;
+ return [history, { restored: restoredHere, ambiguous: mine.filter(id => classes[id] === 'ambiguous').length,
+ excluded: mine.filter(id => classes[id].startsWith('excluded')).length,
+ unresolved: mine.filter(id => classes[id] === 'evidenced' && !activeNow.has(id)).length }];
+ }));
+ expect(report).toEqual({
+ retained: { restored: 2, ambiguous: 0, excluded: 3, unresolved: 0 },
+ compacted: { restored: 1, ambiguous: 0, excluded: 0, unresolved: 0 },
+ separate: { restored: 0, ambiguous: 1, excluded: 0, unresolved: 0 },
+ 'post-fix': { restored: 0, ambiguous: 1, excluded: 0, unresolved: 0 },
+ fenced: { restored: 0, ambiguous: 1, excluded: 0, unresolved: 0 },
+ });
+ const rows = await factState(engine, [retainedA, retainedB]);
+ expect(rows.map(row => row.row_num)).toEqual([10, 11]);
+ const requests = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE intent->>'kind'=$1 AND state='committed'", [EXTRACTOR_FACTS_INTENT]);
+ expect(requests[0].n).toBe(2);
+ const recall = operations.find(op => op.name === 'recall')!;
+ const recalled = await recall.handler({ ...ctx, remote: false }, { entity: ENTITY }) as { facts: Array<{ fact_id: string }> };
+ for (const id of restored) expect(recalled.facts.map(fact => Number(fact.fact_id))).toContain(id);
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair-approval' AND fingerprint=$1", [`extractor-facts:${hash}`])).toEqual([]);
+
+ const wide = await repair(engine, null, ['--include-ambiguous']);
+ expect(wide.results[0].residuals).toEqual({ evidenced: 0, ambiguous: 3, excluded: 3 });
+ const wideHash = hashOf(wide);
+ expect(wide.results[0].apply_command).toBe(`gbrain repair extractor-facts --include-ambiguous --apply --expect ${wideHash}`);
+ expect((await refusal(() => repair(engine, null, ['--apply', '--expect', wideHash]))).code).toBe('preview_changed');
+ const wideApplied = await repair(engine, null, ['--include-ambiguous', '--apply', '--expect', wideHash]);
+ expect(wideApplied.results[0].outcomes).toEqual({ restored: 3 });
+ expect(await activeIds(engine, [superseded, withdrawn])).toEqual([]);
+ const after = await repair(engine, null, []);
+ expect(after.results[0].residuals).toEqual({ evidenced: 0, ambiguous: 0, excluded: 3 });
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ seeded.retained = await conversation(engine, 'conversations/retained', ['Alice sends the deck', 'Alice books the venue',
+ 'Alice hires a designer', 'Alice withdrew this claim', 'Alice sends the deck on Friday'], root);
+ seeded.compacted = await conversation(engine, 'conversations/compacted', ['Alice reviews the budget'], root);
+ seeded.separate = await conversation(engine, 'conversations/separate', ['Alice calls the bank'], root);
+ seeded['post-fix'] = await conversation(engine, 'conversations/post-fix', ['Alice drafts the memo'], root);
+ seeded.fenced = await conversation(engine, 'conversations/fenced', ['Alice signs the lease'], root);
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug, expired_at)
+ VALUES ('default', 'conversations/fenced', 'A fence row on this page', 'fact', 'private', 'fence', 7, 'conversations/fenced', now())`);
+ } });
+ }, 180_000);
+
+ test('a fact edited between preview and apply reports changed_since_preview and stays expired; the rest restore', async () => {
+ let ids: number[] = [];
+ await managedBrain(async ({ engine, ctx }) => {
+ await prefixExpire(engine, ctx, 'conversations/edited');
+ const preview = await repair(engine, null, []);
+ expect(preview.results[0].residuals).toEqual({ evidenced: 2, ambiguous: 0, excluded: 0 });
+ await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () =>
+ tx.executeRaw("UPDATE facts SET fact='Alice sends the revised deck' WHERE id=$1", [ids[1]])));
+ const applied = await repair(engine, null, ['--apply', '--expect', hashOf(preview)]);
+ expect(applied.results[0]).toMatchObject({ applied: 1, outcomes: { partially_restored: 1 } });
+ expect(applied.results[0].outcome_items![0].reason).toBe(`1 of 2 restored; changed since the preview: ${ids[1]}`);
+ expect(await activeIds(engine, ids)).toEqual([ids[0]]);
+ }, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/edited', ['Alice sends the deck', 'Alice books the venue'], root); } });
+ }, 120_000);
+
+ test('within a duplicate group the evidenced row is restored, not an older ambiguous one (Codex review)', async () => {
+ let ids: number[] = [];
+ await managedBrain(async ({ engine, ctx }) => {
+ await prefixExpire(engine, ctx, 'conversations/dupes', { transaction: 'separate' });
+ const [{ id: later }] = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ('default', $1, 'Alice sends the deck', 'commitment', 'private', $2, 5, 'conversations/dupes') RETURNING id::int AS id`, [ENTITY, EXTRACTOR])));
+ await prefixExpire(engine, ctx, 'conversations/dupes', { ids: [Number(later)] });
+ const preview = await repair(engine, null, []);
+ expect(preview.results[0].listing!.map(entry => [Number(entry.item.split('#')[1]), entry.class])).toEqual([
+ [ids[0], 'excluded:duplicate_candidate'], [Number(later), 'evidenced']]);
+ const applied = await repair(engine, null, ['--apply', '--expect', hashOf(preview)]);
+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });
+ expect(await activeIds(engine, [ids[0], Number(later)])).toEqual([Number(later)]);
+ }, { databaseUrl, setup: async ({ engine, root }) => { ids = await conversation(engine, 'conversations/dupes', ['Alice sends the deck'], root); } });
+ }, 120_000);
+
+ test('crash after a publication, before the cursor: the resumed apply replays its receipt and restores no new candidate (ENG-O8)', async () => {
+ const seeded: Record<string, number[]> = {};
+ await managedBrain(async ({ engine, ctx }) => {
+ await prefixExpire(engine, ctx, 'conversations/a', { ids: [seeded.a[0]] });
+ await prefixExpire(engine, ctx, 'conversations/b');
+ const preview = await repair(engine, null, []);
+ const hash = hashOf(preview);
+ expect(preview.results[0].affected).toBe(2);
+ const original = extractorFactsRepair.apply;
+ extractorFactsRepair.apply = async (...args) => { await original(...args); throw new Error('simulated crash after publication'); };
+ try { await expect(repair(engine, null, ['--apply', '--expect', hash])).rejects.toThrow('simulated crash after publication'); }
+ finally { extractorFactsRepair.apply = original; }
+ expect(await activeIds(engine, [...seeded.a, ...seeded.b])).toEqual(seeded.a);
+ // A new defect-evidenced candidate appears on the half-applied page after the preview.
+ await prefixExpire(engine, ctx, 'conversations/a', { ids: [seeded.a[1]] });
+ const resumed = await repair(engine, null, ['--apply', '--expect', hash]);
+ expect(resumed.results[0]).toMatchObject({ affected: 1, applied: 1, residuals: { already_restored_pages: 1 }, outcomes: { restored: 1 } });
+ expect(await activeIds(engine, [...seeded.a, ...seeded.b])).toEqual([seeded.a[0], ...seeded.b]);
+ const requests = await engine.executeRaw<{ slug: string; n: number }>(`SELECT slug, count(*)::int AS n FROM persistence_requests
+ WHERE intent->>'kind'=$1 AND state='committed' GROUP BY slug ORDER BY slug`, [EXTRACTOR_FACTS_INTENT]);
+ expect(requests).toEqual([{ slug: 'conversations/a', n: 1 }, { slug: 'conversations/b', n: 1 }]);
+ expect((await refusal(() => repair(engine, null, ['--apply', '--expect', hash]))).code).toBe('preview_changed');
+ expect((await repair(engine, null, [])).results[0].residuals).toEqual({ evidenced: 1, ambiguous: 0, excluded: 0 });
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ seeded.a = await conversation(engine, 'conversations/a', ['Alice sends the deck', 'Alice books the venue'], root);
+ seeded.b = await conversation(engine, 'conversations/b', ['Bob reviews the budget'], root);
+ } });
+ }, 120_000);
+
+ test('the preview warns, naming the host, when a consumer older than this release published after the cutoff', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const request = await prefixExpire(engine, ctx, 'conversations/mixed');
+ // The host upgraded after the pre-fix write: writer-version observation starts here.
+ await new Promise(resolve => setTimeout(resolve, 5));
+ await engine.executeRaw('UPDATE persistence_brain SET writer_version_cutoff=now() WHERE singleton=1');
+ const quiet = await repair(engine, null, []);
+ expect(quiet.results[0].warnings ?? []).toEqual([]);
+ const host = randomUUID();
+ await engine.transaction(async tx => {
+ await declarePersistenceProtocol(tx);
+ // A host still running v0.60.10.0 publishes after the upgrade cutoff.
+ await tx.executeRaw(`UPDATE persistence_requests SET consumer_version='0.60.10.0', consumer_host_id=$2::uuid, published_at=now()
+ WHERE id=$1::uuid`, [request, host]);
+ });
+ const warned = await repair(engine, null, []);
+ expect(warned.results[0].warnings).toEqual([expect.stringContaining(`host ${host} still published writes with a consumer older than this release (0.60.10.0`)]);
+ }, { databaseUrl, setup: async ({ engine, root }) => { await conversation(engine, 'conversations/mixed', ['Alice sends the deck'], root); } });
+ }, 120_000);
+
+ test('recovery journey: doctor, preview, apply, doctor, running the printed commands verbatim (DX-O15d)', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ await prefixExpire(engine, ctx, 'conversations/journey');
+ const before = await extractorFactsCheck(engine);
+ expect(before).toMatchObject({ name: 'extractor_facts_expired', status: 'warn', details: { evidenced: 3, ambiguous: 0 } });
+ const printed = before.message.match(/gbrain repair extractor-facts(?= )/)![0];
+ const preview = await repair(engine, null, printed.split(' ').slice(3));
+ const applied = await repair(engine, null, preview.results[0].apply_command.split(' ').slice(3));
+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });
+ expect(await extractorFactsCheck(engine)).toMatchObject({ status: 'ok', details: { evidenced: 0, ambiguous: 0 } });
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ await conversation(engine, 'conversations/journey', ['Alice sends the deck', 'Alice books the venue', 'Alice hires a designer'], root);
+ } });
+ }, 120_000);
+ });
+
+ describe(`cross-lane journey (ENG-O14): #5731 restore with managed writeSingleFact and a re-extraction (${backend})`, () => {
+ const CHAT = `---\ntitle: Synthetic chat\ntype: conversation\n---\n${[
+ '**Alice Example** (2024-03-15 9:00 AM): I will send the signed contract by Friday.',
+ '**Bob Demo** (2024-03-15 9:01 AM): Great, thanks.',
+ ].join('\n')}\n`;
+ const CLAIM = 'Alice Example will send the signed contract by Friday.';
+ const extractor = async () => [{ fact: CLAIM, kind: 'commitment' as const, entity_slug: ENTITY,
+ confidence: 1, notability: 'high' as const, source: 'test', visibility: 'private' as const }];
+
+ test('extract, pre-fix expiry, doctor, preview, apply, recall, remember, re-extract, doctor', async () => {
+ await managedBrain(async ({ engine, ctx }) => {
+ const slug = 'conversations/synthetic-chat';
+ const extracted = await runExtractConversationFactsCore(engine, { sourceId: 'default', overrideDisabled: true, extractor, types: ['conversation'] });
+ expect(extracted.facts_inserted).toBe(1);
+ const rows = () => engine.executeRaw<{ id: number; fact: string; active: boolean; row_num: number | null }>(
+ "SELECT id::int AS id, fact, expired_at IS NULL AS active, row_num FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY id", [slug]);
+ const original = await rows();
+ expect(original.map(row => [row.fact, row.active])).toEqual([[CLAIM, true], ['EXTRACTION_COMPLETE', true]]);
+ await prefixExpire(engine, ctx, slug);
+ expect((await rows()).every(row => !row.active && row.row_num === null)).toBe(true);
+
+ expect((await extractorFactsCheck(engine)).details).toMatchObject({ evidenced: 2, ambiguous: 0 });
+ const preview = await repair(engine, null, []);
+ const applied = await repair(engine, null, preview.results[0].apply_command.split(' ').slice(3));
+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });
+ const restored = await rows();
+ expect(restored.map(row => [row.id, row.active])).toEqual(original.map(row => [row.id, true]));
+ const recalled = await operations.find(op => op.name === 'recall')!.handler(ctx, { entity: ENTITY }) as { facts: Array<{ fact_id: string }> };
+ expect(recalled.facts.map(fact => Number(fact.fact_id))).toContain(original[0].id);
+
+ // writeSingleFact dedups against the restored fact for the same entity and keeps an absent entity's claim apart.
+ const same = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: ENTITY, kind: 'commitment' });
+ expect(same).toMatchObject({ status: 'duplicate', id: original[0].id, entity_slug: ENTITY });
+ const other = await writeSingleFact(engine, 'default', { fact: CLAIM, provenance: 'fixture', entity: 'Carol Absent', kind: 'commitment' });
+ expect(other).toMatchObject({ status: 'inserted', entity_slug: 'carol-absent' });
+
+ // A forced re-extraction replaces the restored batch, active, with nothing expired left behind on the page.
+ const rerun = await runExtractConversationFactsCore(engine, { sourceId: 'default', overrideDisabled: true, extractor, types: ['conversation'], force: true });
+ expect([rerun.facts_inserted, rerun.orphan_facts_cleaned]).toEqual([1, 2]);
+ expect((await rows()).map(row => [row.fact, row.active])).toEqual([[CLAIM, true], ['EXTRACTION_COMPLETE', true]]);
+ expect((await extractorFactsCheck(engine)).status).toBe('ok');
+ expect((await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE entity_slug='carol-absent' AND expired_at IS NULL"))[0].n).toBe(1);
+ }, { databaseUrl, setup: async ({ engine, root }) => {
+ await engine.setConfig('conversation_parser.llm_fallback_enabled', 'false');
+ const person = await engine.putPage(ENTITY, { type: 'person', title: 'Alice Example', compiled_truth: '# Alice Example' }, { sourceId: 'default' });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', [`${ENTITY}.md`, person.id]);
+ const personSnapshot = (await engine.readPageSnapshot(ENTITY, { sourceId: 'default' }))!;
+ mkdirSync(join(root, 'people'), { recursive: true });
+ writeFileSync(join(root, `${ENTITY}.md`), serializePageToMarkdown(personSnapshot.page, personSnapshot.tags));
+ const page = await engine.putPage('conversations/synthetic-chat', { type: 'conversation', title: 'Synthetic chat',
+ compiled_truth: CHAT.split('---\n')[2].trim() }, { sourceId: 'default' });
+ await engine.executeRaw('UPDATE pages SET source_path=$1 WHERE id=$2', ['conversations/synthetic-chat.md', page.id]);
+ const snapshot = (await engine.readPageSnapshot('conversations/synthetic-chat', { sourceId: 'default' }))!;
+ mkdirSync(join(root, 'conversations'), { recursive: true });
+ writeFileSync(join(root, 'conversations/synthetic-chat.md'), serializePageToMarkdown(snapshot.page, snapshot.tags));
+ } });
+ }, 180_000);
+ });
+
+ describe(`gbrain repair extractor-facts, unmanaged (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(databaseUrl!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }, 120_000);
+ afterAll(async () => { if (close) await close(); else await engine.disconnect(); });
+
+ test('every candidate is ambiguous; only --include-ambiguous with its own hash restores them', async () => {
+ const sourceId = `ef-u-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const ids = await conversation(engine, 'conversations/unmanaged', ['Alice sends the deck', 'Alice books the venue'], undefined, sourceId);
+ const superseded = (await conversation(engine, 'conversations/unmanaged-2', ['Alice hires a designer'], undefined, sourceId))[0];
+ // The same claim about another entity on the same page is a distinct fact, not a duplicate (Codex review).
+ const [{ id: bobs }] = await engine.executeRaw<{ id: number }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source, row_num, source_markdown_slug)
+ VALUES ($1, 'people/bob-example', 'Alice sends the deck', 'commitment', 'private', $2, 3, 'conversations/unmanaged') RETURNING id::int AS id`, [sourceId, EXTRACTOR]);
+ ids.push(Number(bobs));
+ await engine.executeRaw("UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id=$1", [sourceId]);
+ await engine.executeRaw('UPDATE facts SET superseded_by=$1 WHERE id=$2', [ids[0], superseded]);
+ const preview = await repair(engine, home, ['--source', sourceId]);
+ expect(preview.results[0].residuals).toEqual({ evidenced: 0, ambiguous: 3, excluded: 1 });
+ expect(preview.results[0].affected).toBe(0);
+ expect(preview.results[0].listing!.map(entry => entry.detail)).toContain('unmanaged brain: no write receipt can prove the expiry');
+ expect((await refusal(() => repair(engine, home, ['--source', sourceId, '--apply', '--expect', hashOf(preview)]))).code).toBe('preview_changed');
+ const wide = await repair(engine, home, ['--source', sourceId, '--include-ambiguous']);
+ expect(wide.results[0].affected).toBe(1);
+ // The hash is bound to the preview's source scope: applying it brain-wide refuses (Codex review).
+ expect((await refusal(() => repair(engine, home, ['--include-ambiguous', '--apply', '--expect', hashOf(wide)]))).code).toBe('preview_changed');
+ const applied = await repair(engine, home, ['--source', sourceId, '--include-ambiguous', '--apply', '--expect', hashOf(wide)]);
+ expect(applied.results[0].outcomes).toEqual({ restored: 1 });
+ expect(await factState(engine, [...ids, superseded])).toEqual([
+ { id: ids[0], active: true, row_num: 1 }, { id: ids[1], active: true, row_num: 2 }, { id: superseded, active: false, row_num: null },
+ { id: ids[2], active: true, row_num: 3 }]);
+ expect((await repair(engine, home, ['--source', sourceId])).results[0].residuals).toEqual({ evidenced: 0, ambiguous: 0, excluded: 1 });
+ }, 60_000);
+
+ test('a --limit run always advances: a partially restored page is not retried by the next run (Codex review)', async () => {
+ const sourceId = `ef-l-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const first = await conversation(engine, 'conversations/limit-a', ['Alice sends the deck', 'Alice books the venue'], undefined, sourceId);
+ const second = await conversation(engine, 'conversations/limit-b', ['Bob reviews the budget'], undefined, sourceId);
+ await engine.executeRaw('UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id=$1', [sourceId]);
+ const wide = await repair(engine, home, ['--source', sourceId, '--include-ambiguous']);
+ await engine.executeRaw("UPDATE facts SET fact='Alice sends the revised deck' WHERE id=$1", [first[1]]);
+ const apply = ['--source', sourceId, '--include-ambiguous', '--apply', '--expect', hashOf(wide), '--limit', '1'];
+ expect((await repair(engine, home, apply)).results[0].outcomes).toEqual({ partially_restored: 1 });
+ const next = await repair(engine, home, apply);
+ expect(next.results[0]).toMatchObject({ affected: 1, outcomes: { restored: 1 } });
+ expect(await activeIds(engine, [...first, ...second])).toEqual([first[0], second[0]]);
+ expect((await refusal(() => repair(engine, home, apply))).code).toBe('preview_changed');
+ }, 60_000);
+
+ test('a page deleted and recreated at the same slug since the preview restores nothing (Codex review)', async () => {
+ const sourceId = `ef-r-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const ids = await conversation(engine, 'conversations/recreated', ['Alice sends the deck'], undefined, sourceId);
+ await engine.executeRaw('UPDATE facts SET expired_at=now(), row_num=NULL WHERE source_id=$1', [sourceId]);
+ const wide = await repair(engine, home, ['--source', sourceId, '--include-ambiguous']);
+ await engine.deletePage('conversations/recreated', { sourceId });
+ await engine.putPage('conversations/recreated', { type: 'note', title: 'Another page', compiled_truth: 'Unrelated.' }, { sourceId });
+ const applied = await repair(engine, home, ['--source', sourceId, '--include-ambiguous', '--apply', '--expect', hashOf(wide)]);
+ expect(applied.results[0].outcomes).toEqual({ changed_since_preview: 1 });
+ expect(await activeIds(engine, ids)).toEqual([]);
+ }, 60_000);
+ });
+}
diff --git a/test/repair-flags.test.ts b/test/repair-flags.test.ts
index 8f5e22be0c..96039e3504 100644
--- a/test/repair-flags.test.ts
+++ b/test/repair-flags.test.ts
@@ -12,6 +12,7 @@ import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { OperationError } from '../src/core/ops/contract.ts';
import { REPAIR_KINDS } from '../src/core/repair/core.ts';
import { REPAIR_HELP, runRepairCommand } from '../src/commands/repair.ts';
+import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';
import { withEnv } from './helpers/with-env.ts';
let engine: PGLiteEngine;
@@ -76,7 +77,7 @@ describe('gbrain repair flags', () => {
const out = await captured(['--all', '--json']);
const parsed = JSON.parse(out) as { mode: string; results: Array<{ kind: string; cost: Record<string, unknown>; paid: boolean }>; paid_kinds: string[] };
expect(parsed.mode).toBe('dry_run');
- expect(parsed.results.map(r => r.kind)).toEqual([...REPAIR_KINDS]);
+ expect(parsed.results.map(r => r.kind)).toEqual(AUTO_REPAIR_REGISTRY.map(spec => spec.kind));
for (const result of parsed.results) {
expect(result.cost).toHaveProperty('lifetime_ids');
expect(result.cost).toHaveProperty('embedding_usd');
diff --git a/test/repair-stale-atoms.test.ts b/test/repair-stale-atoms.test.ts
new file mode 100644
index 0000000000..dff4af5c43
--- /dev/null
+++ b/test/repair-stale-atoms.test.ts
@@ -0,0 +1,302 @@
+/**
+ * `gbrain repair stale-atoms` (#5770, CEO-A7, ENG-O7, DX-O4), on PGLite and,
+ * with a safe DATABASE_URL, Postgres (test/e2e/repair-stale-atoms-postgres.test.ts).
+ *
+ * Unmanaged and managed brains: the preview lists both classes and changes
+ * nothing; the apply needs the preview hash and retires exactly the previewed
+ * set; an atom that changed since the preview is kept as changed_since_preview;
+ * imported and file-bound atoms survive; on a managed brain a deleted page's
+ * atoms come back when the page is restored and extracted again.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import type { ChatResult } from '../src/core/ai/gateway.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { runRepairCommand } from '../src/commands/repair.ts';
+import { runPhaseExtractAtoms, discoverExtractablePages } from '../src/core/cycle/extract-atoms.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { serializePageToMarkdown } from '../src/core/markdown.ts';
+import { operations } from '../src/core/operations.ts';
+import { computeAtomProvenanceDriftCheck } from '../src/commands/doctor.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+interface RepairJson { results: Array<{ affected: number; residuals: Record<string, number>; apply_command: string; applied: number; skipped: number;
+ listing?: Array<{ item: string; class: string; detail?: string }>; outcomes?: Record<string, number>; outcome_items?: Array<{ item: string; outcome: string }> }> }
+
+async function refusal(run: () => Promise<unknown>): Promise<OperationError> {
+ try { await run(); } catch (error) { if (error instanceof OperationError) return error; throw error; }
+ throw new Error('expected a refusal');
+}
+
+test('stale-atoms is CLI-only: no operation exposes it over MCP (ENG-O13)', () => {
+ expect(operations.map(op => op.name).filter(name => /stale|repair/.test(name))).toEqual([]);
+});
+
+for (const kind of testBackends()) {
+ describe(`gbrain repair stale-atoms (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-stale-atoms-'));
+ beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ }, 120_000);
+ afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ if (close) await close(); else await engine.disconnect();
+ resetGateway();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ const repair = async (args: string[]): Promise<RepairJson> => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await withEnv({ GBRAIN_HOME: home }, () => runRepairCommand(engine, ['stale-atoms', ...args, '--json'])); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+ };
+ const hashOf = (json: RepairJson) => json.results[0].apply_command.match(/--expect ([0-9a-f]+)/)![1];
+ const atom = async (sourceId: string, slug: string) => (await engine.executeRaw<{ deleted: boolean; frontmatter: Record<string, unknown> }>(
+ 'SELECT deleted_at IS NOT NULL AS deleted, frontmatter FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0];
+ const putAtom = (sourceId: string, slug: string, frontmatter: Record<string, unknown>) =>
+ engine.putPage(slug, { type: 'atom', title: slug, compiled_truth: `Claim ${slug}.`, frontmatter: { type: 'atom', ...frontmatter } }, { sourceId });
+
+ async function unmanagedFixture() {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = `stale-u-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const edited = await engine.putPage('notes/edited', { type: 'note', title: 'Edited', compiled_truth: 'The current text of the edited page.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/edited-old', { source_slug: 'notes/edited', source_hash: 'aaaaaaaaaaaaaaaa' });
+ await putAtom(sourceId, 'atoms/2026-01-01/edited-current', { source_slug: 'notes/edited', source_hash: edited.content_hash!.slice(0, 16) });
+ await engine.putPage('notes/unextracted', { type: 'note', title: 'Unextracted', compiled_truth: 'Edited but not extracted again.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/unextracted-old', { source_slug: 'notes/unextracted', source_hash: 'bbbbbbbbbbbbbbbb' });
+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'A page the user deleted.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/gone', { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc' });
+ await putAtom(sourceId, 'atoms/2026-01-01/imported', { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc', imported_from: 'brain-export' });
+ await putAtom(sourceId, 'atoms/2026-01-01/file-bound', { source_path: '/transcripts/meeting.txt', source_hash: 'dddddddddddddddd' });
+ await engine.softDeletePage('notes/gone', { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/orphan', { source_slug: 'notes/never-existed', source_hash: 'eeeeeeeeeeeeeeee' });
+ return sourceId;
+ }
+
+ test('unmanaged: the preview lists both classes and changes nothing; the apply needs its hash and retires exactly them', async () => {
+ const sourceId = await unmanagedFixture();
+ const preview = await repair(['--source', sourceId]);
+ expect(preview.results[0].listing).toEqual([
+ { item: `${sourceId}:atoms/2026-01-01/gone`, class: 'origin_gone', detail: 'source page notes/gone is gone' },
+ { item: `${sourceId}:atoms/2026-01-01/orphan`, class: 'origin_gone', detail: 'source page notes/never-existed is gone' },
+ { item: `${sourceId}:atoms/2026-01-01/edited-old`, class: 'origin_changed', detail: expect.stringContaining('source page notes/edited now at') },
+ ]);
+ expect(preview.results[0].residuals).toEqual({ origin_gone: 2, origin_changed: 1 });
+ const hash = hashOf(preview);
+ expect(preview.results[0].apply_command).toBe(`gbrain repair stale-atoms --source ${sourceId} --apply --expect ${hash}`);
+ for (const slug of ['gone', 'orphan', 'edited-old']) expect((await atom(sourceId, `atoms/2026-01-01/${slug}`)).deleted).toBe(false);
+
+ const unbound = await refusal(() => repair(['--source', sourceId, '--apply']));
+ expect(unbound.toJSON()).toMatchObject({ error: 'invalid_params', docs: 'docs/guides/repair.md#explicit-only-repair-kinds',
+ suggestion: `Preview first: gbrain repair stale-atoms --source ${sourceId} — then run the apply command it prints: gbrain repair stale-atoms --source ${sourceId} --apply --expect <preview-hash>` });
+ const stale = await refusal(() => repair(['--source', sourceId, '--apply', '--expect', 'f'.repeat(64)]));
+ expect(stale.toJSON()).toMatchObject({ error: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed',
+ message: `The preview changed since ${'f'.repeat(64)}; re-run gbrain repair stale-atoms --source ${sourceId} and use the new hash.` });
+
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hash]);
+ expect(applied.results[0]).toMatchObject({ applied: 3, skipped: 0, outcomes: { retired: 3 } });
+ for (const slug of ['gone', 'orphan', 'edited-old']) {
+ const row = await atom(sourceId, `atoms/2026-01-01/${slug}`);
+ expect(row.deleted).toBe(true);
+ expect(row.frontmatter.retired_by).toBe('stale-atoms');
+ }
+ for (const slug of ['edited-current', 'unextracted-old', 'imported', 'file-bound']) expect((await atom(sourceId, `atoms/2026-01-01/${slug}`)).deleted).toBe(false);
+ expect(await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='repair-approval' AND fingerprint=$1", [`stale-atoms:${hash}`])).toEqual([]);
+ expect((await repair(['--source', sourceId])).results[0].affected).toBe(0);
+ }, 60_000);
+
+ test('unmanaged: an atom edited between preview and apply reports changed_since_preview and is kept', async () => {
+ const sourceId = await unmanagedFixture();
+ const hash = hashOf(await repair(['--source', sourceId]));
+ await putAtom(sourceId, 'atoms/2026-01-01/orphan', { source_slug: 'notes/never-existed', source_hash: 'eeeeeeeeeeeeeeee', note: 'edited after the preview' });
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hash]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, skipped: 1, outcomes: { retired: 2, changed_since_preview: 1 } });
+ expect(applied.results[0].outcome_items).toContainEqual(expect.objectContaining({ item: `${sourceId}:atoms/2026-01-01/orphan`, outcome: 'changed_since_preview' }));
+ expect((await atom(sourceId, 'atoms/2026-01-01/orphan')).deleted).toBe(false);
+ }, 60_000);
+
+ test('recovery journey: doctor, preview, apply, doctor, running the printed commands verbatim (DX-O15c)', async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = `stale-j-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'A page the user deleted.' }, { sourceId });
+ for (let i = 0; i < 30; i++) await putAtom(sourceId, `atoms/2026-01-01/gone-${i}`, { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc' });
+ await engine.softDeletePage('notes/gone', { sourceId });
+ const before = await computeAtomProvenanceDriftCheck(engine);
+ expect(before.status).toBe('warn');
+ const printed = before.message.match(/gbrain repair stale-atoms/)![0];
+ const preview = await withEnv({ GBRAIN_HOME: home }, async () => {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runRepairCommand(engine, [...printed.split(' ').slice(2), '--source', sourceId, '--json']); } finally { console.log = original; }
+ return JSON.parse(lines.join('\n')) as RepairJson;
+ });
+ expect(preview.results[0].residuals).toEqual({ origin_gone: 30, origin_changed: 0 });
+ const applied = await repair(preview.results[0].apply_command.split(' ').slice(3));
+ expect(applied.results[0].outcomes).toEqual({ retired: 30 });
+ const after = await computeAtomProvenanceDriftCheck(engine);
+ expect(Number((before.details as Record<string, number>).source_gone) - Number((after.details as Record<string, number>).source_gone)).toBe(30);
+ }, 60_000);
+
+ test('an approved set applies only under the source selection it was previewed with', async () => {
+ const sourceId = await unmanagedFixture();
+ const hash = hashOf(await repair(['--source', sourceId]));
+ const refused = await refusal(() => repair(['--apply', '--expect', hash]));
+ expect(refused.toJSON()).toMatchObject({ error: 'preview_changed', docs: 'docs/guides/repair.md#preview-changed' });
+ expect((await atom(sourceId, 'atoms/2026-01-01/gone')).deleted).toBe(false);
+ }, 60_000);
+
+ test('a new preview never resumes the cursor an interrupted apply of an older preview left', async () => {
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const sourceId = `stale-r-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const edited = await engine.putPage('notes/edited', { type: 'note', title: 'Edited', compiled_truth: 'The current text.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/current', { source_slug: 'notes/edited', source_hash: edited.content_hash!.slice(0, 16) });
+ await putAtom(sourceId, 'atoms/2026-01-01/old-1', { source_slug: 'notes/edited', source_hash: 'aaaaaaaaaaaaaaaa' });
+ await putAtom(sourceId, 'atoms/2026-01-01/old-2', { source_slug: 'notes/edited', source_hash: 'aaaaaaaaaaaaaaaa' });
+ const first = hashOf(await repair(['--source', sourceId]));
+ expect((await repair(['--source', sourceId, '--apply', '--expect', first, '--limit', '1'])).results[0].outcomes).toEqual({ retired: 1 });
+ await engine.putPage('notes/gone', { type: 'note', title: 'Gone', compiled_truth: 'Deleted later.' }, { sourceId });
+ await putAtom(sourceId, 'atoms/2026-01-01/gone', { source_slug: 'notes/gone', source_hash: 'cccccccccccccccc' });
+ await engine.softDeletePage('notes/gone', { sourceId });
+ const second = await repair(['--source', sourceId]);
+ expect(second.results[0].listing!.map(entry => entry.class)).toEqual(['origin_gone', 'origin_changed']);
+ expect((await repair(['--source', sourceId, '--apply', '--expect', hashOf(second)])).results[0].outcomes).toEqual({ retired: 2 });
+ expect((await atom(sourceId, 'atoms/2026-01-01/gone')).deleted).toBe(true);
+ }, 60_000);
+
+ async function managedFixture(sourceId: string) {
+ const root = join(home, sourceId);
+ const slug = 'notes/example';
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ const writeSource = async (body: string) => {
+ const written = await engine.putPage(slug, { type: 'source', title: 'Example', compiled_truth: body }, { sourceId });
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ writeFileSync(join(root, `${slug}.md`), serializePageToMarkdown(written, []));
+ return written;
+ };
+ let page = await writeSource('A careful project record at revision one. '.repeat(40));
+ await withEnv({ GBRAIN_HOME: home }, async () => { await registerLocalWriter(engine, 'cli'); await claimWorktree(engine, sourceId, root); });
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const titles = ['Patience compounds', 'Hire slowly'];
+ let calls = 0;
+ const chat = async (): Promise<ChatResult> => {
+ calls++;
+ return { text: JSON.stringify(titles.map(title => ({ title, atom_type: 'insight', body: `Body for ${title}.` }))),
+ blocks: [], stopReason: 'end', usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ const unmanaged = async <T>(fn: () => Promise<T>): Promise<T> => {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1'); }
+ };
+ return {
+ root, slug, unmanaged, calls: () => calls,
+ extract: () => withEnv({ GBRAIN_HOME: home }, () => runPhaseExtractAtoms(engine, { sourceId, _transcripts: [],
+ _pages: [{ slug, content: page.compiled_truth, contentHash: page.content_hash! }], _chat: chat })),
+ edit: async (body: string) => { page = await unmanaged(() => writeSource(body)); return page; },
+ atoms: () => engine.executeRaw<{ slug: string; deleted: boolean; frontmatter: Record<string, unknown> }>(
+ "SELECT slug, deleted_at IS NOT NULL AS deleted, frontmatter FROM pages WHERE source_id=$1 AND type='atom' ORDER BY slug", [sourceId]),
+ };
+ }
+
+ test('managed: delete the page, repair, restore the page, and extraction re-creates its atoms', async () => {
+ const sourceId = `stale-m-${randomUUID().slice(0, 8)}`;
+ const f = await managedFixture(sourceId);
+ try {
+ expect((await f.extract()).status).toBe('ok');
+ const before = await f.atoms();
+ expect(before.map(row => row.deleted)).toEqual([false, false]);
+ await f.unmanaged(() => engine.softDeletePage(f.slug, { sourceId }));
+ const preview = await repair(['--source', sourceId]);
+ expect(preview.results[0].listing!.map(entry => entry.class)).toEqual(['origin_gone', 'origin_gone']);
+ expect((await f.atoms()).map(row => row.deleted)).toEqual([false, false]);
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hashOf(preview)]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, outcomes: { retired: 2 } });
+ for (const row of await f.atoms()) {
+ expect(row).toMatchObject({ deleted: true, frontmatter: { retired_by: 'stale-atoms' } });
+ expect(existsSync(join(f.root, `${row.slug}.md`))).toBe(false);
+ }
+ await f.unmanaged(() => engine.restorePage(f.slug, { sourceId }));
+ expect((await discoverExtractablePages(engine, sourceId)).map(item => item.slug)).toEqual([f.slug]);
+ expect((await f.extract()).status).toBe('ok');
+ expect(f.calls()).toBe(2);
+ const after = await f.atoms();
+ expect(after.map(row => row.slug)).toEqual(before.map(row => row.slug));
+ for (const row of after) {
+ expect(row.deleted).toBe(false);
+ expect(row.frontmatter).not.toHaveProperty('retired_by');
+ expect(existsSync(join(f.root, `${row.slug}.md`))).toBe(true);
+ }
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 60_000);
+
+ test('managed: an atom whose file holds an uncoordinated edit reports file_conflict, and a fresh apply retires it once the file is fixed', async () => {
+ const sourceId = `stale-f-${randomUUID().slice(0, 8)}`;
+ const f = await managedFixture(sourceId);
+ try {
+ expect((await f.extract()).status).toBe('ok');
+ await f.unmanaged(() => engine.softDeletePage(f.slug, { sourceId }));
+ const [first] = await f.atoms();
+ writeFileSync(join(f.root, `${first.slug}.md`), 'Uncoordinated operator content.');
+ const preview = await repair(['--source', sourceId]);
+ const blocked = await repair(['--source', sourceId, '--apply', '--expect', hashOf(preview)]);
+ expect(blocked.results[0].outcomes).toEqual({ file_conflict: 1, retired: 1 });
+ expect((await atom(sourceId, first.slug)).deleted).toBe(false);
+ rmSync(join(f.root, `${first.slug}.md`));
+ const again = await repair(['--source', sourceId]);
+ expect(again.results[0].listing!.map(entry => entry.item)).toEqual([`${sourceId}:${first.slug}`]);
+ expect((await repair(['--source', sourceId, '--apply', '--expect', hashOf(again)])).results[0].outcomes).toEqual({ retired: 1 });
+ expect((await atom(sourceId, first.slug))).toMatchObject({ deleted: true, frontmatter: { retired_by: 'stale-atoms' } });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 60_000);
+
+ test('managed: atoms of an edited page are stale only once its current text completed an extraction', async () => {
+ const sourceId = `stale-c-${randomUUID().slice(0, 8)}`;
+ const f = await managedFixture(sourceId);
+ try {
+ expect((await f.extract()).status).toBe('ok');
+ const edited = await f.edit('A careful project record at revision two. '.repeat(40));
+ expect((await repair(['--source', sourceId])).results[0].affected).toBe(0);
+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ await engine.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-atoms',$1,$2::text::jsonb)`,
+ [`pre-fix-${sourceId}`, JSON.stringify([{ sourceId, incarnation, requestId: randomUUID(), kind: 'page', locator: f.slug, pageId: edited.id, contentHash: edited.content_hash }])]);
+ const preview = await repair(['--source', sourceId]);
+ expect(preview.results[0].listing!.map(entry => entry.class)).toEqual(['origin_changed', 'origin_changed']);
+ const applied = await repair(['--source', sourceId, '--apply', '--expect', hashOf(preview)]);
+ expect(applied.results[0]).toMatchObject({ applied: 2, outcomes: { retired: 2 } });
+ expect((await f.atoms()).every(row => row.deleted && row.frontmatter.retired_by === 'stale-atoms')).toBe(true);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ }, 60_000);
+ });
+}
diff --git a/test/safe-chunk-reseal.test.ts b/test/safe-chunk-reseal.test.ts
index e709e6d373..224b2a39a7 100644
--- a/test/safe-chunk-reseal.test.ts
+++ b/test/safe-chunk-reseal.test.ts
@@ -206,10 +206,15 @@ for (const kind of backends) {
} });
await engine.executeRaw('UPDATE pages SET chunker_version=1 WHERE source_id=$1', [sourceId]);
const scope = await resolveRepairScope(engine, sourceId);
- const { safeChunksRepair, safeChunkUpgradeAdvisory } = await import('../src/core/repair/safe-chunks.ts');
- const advisory = await safeChunkUpgradeAdvisory(engine, true);
- expect(advisory).toContain('3 page(s) are below the safe-chunk index version');
- expect(advisory).toContain('gbrain repair safe-chunks --apply');
+ const safeChunksModule = await import('../src/core/repair/safe-chunks.ts');
+ const { safeChunksRepair } = safeChunksModule;
+ // Retired (wave 5): the pending count lives only in the doctor check.
+ expect('safeChunkUpgradeAdvisory' in safeChunksModule).toBe(false);
+ const { safeIndexPendingCheck } = await import('../src/commands/doctor/checks/safe-index.ts');
+ const pending = await safeIndexPendingCheck(engine);
+ expect(pending).toMatchObject({ status: 'warn', details: { pages_pending: 3, repair: 'safe-chunks' } });
+ expect(pending.message).toContain('3 page(s) are below the safe-chunk index version');
+ expect(pending.message).toContain('gbrain repair safe-chunks --apply');
const preview = await runRepair(ctx, safeChunksRepair, scope, { apply: false, sourceFlag: sourceId });
expect(preview).toMatchObject({ kind: 'safe-chunks', mode: 'dry_run', affected: 3,
cost: { lifetime_ids: 0, receipt_bytes: 0, embedding_pages: 3 }, apply_command: `gbrain repair safe-chunks --source ${sourceId} --apply` });
@@ -225,7 +230,7 @@ for (const kind of backends) {
expect(versions.every(r => Number(r.v) >= SAFE_FENCE_CHUNKER_VERSION)).toBe(true);
const again = await runRepair(ctx, safeChunksRepair, scope, { apply: true, sourceFlag: sourceId });
expect(again).toMatchObject({ affected: 0, applied: 0, complete: true });
- expect(await safeChunkUpgradeAdvisory(engine, true)).toBeNull();
+ expect(await safeIndexPendingCheck(engine)).toMatchObject({ status: 'ok', details: { pages_pending: 0 } });
// A provider failure after the re-seal keeps the re-seal and names the recovery command.
await submitPageMutation(ctx, { operation: 'put_page', params: { slug: 'notes/c', content: md('Legacy body of notes/c.'), request_id: randomUUID() } });
diff --git a/test/schema-engine-isolation.serial.test.ts b/test/schema-engine-isolation.serial.test.ts
index 6025124301..26d9f323c9 100644
--- a/test/schema-engine-isolation.serial.test.ts
+++ b/test/schema-engine-isolation.serial.test.ts
@@ -144,7 +144,15 @@ for (const failedKey of ['schema_pack', 'schema_pack.source.default']) {
}));
}
-test('explicit empty type sets deny hybrid and expert reads before any engine or cache access', async () => {
+test('explicit empty type sets pass through as no-filter (regression #5390)', async () => {
+ // #5390: a structurally empty `types` array (`[]`) carries no user
+ // intent — it is what OpenAI-family MCP clients emit when the model
+ // over-fills every optional parameter. The contract is now: treat it
+ // as absent (no filter applied) rather than throwing `no usable page-type
+ // strings`. The engine then runs the unfiltered search; with the proxy
+ // below, that access trips the `Empty filters must not access the engine`
+ // guard at the engine boundary, which is what proves the no-filter path
+ // reaches the engine (i.e. the filter was dropped, not rejected).
const access = new Proxy({} as PGLiteEngine, { get() { throw new Error('Empty filters must not access the engine'); } });
for (const type of [undefined, 'company']) {
expect(await expandEngineTypeFilters(access, { type, types: [] })).toEqual({ type: undefined, types: [] });
@@ -154,7 +162,10 @@ test('explicit empty type sets deny hybrid and expert reads before any engine or
expect(await findExperts(access, { topic: 'quasar', types: [] })).toEqual([]);
expect(await expandEngineTypeFilters(access, {})).toEqual({});
for (const name of ['search', 'query']) {
- await expect(operations.find(op => op.name === name)!.handler(ctx(access), { query: 'quasar', types: [] })).rejects.toThrow('no usable page-type strings');
+ // The MCP handler no longer throws on `types: []`; it drops the filter
+ // and runs unfiltered. The proxy proves the engine was reached, not
+ // short-circuited — that is the desired post-#5390 contract.
+ await expect(operations.find(op => op.name === name)!.handler(ctx(access), { query: 'quasar', types: [] })).rejects.toThrow('Empty filters must not access the engine');
}
});
diff --git a/test/search/crag-query-op.test.ts b/test/search/crag-query-op.test.ts
index effc69b78c..edae87957c 100644
--- a/test/search/crag-query-op.test.ts
+++ b/test/search/crag-query-op.test.ts
@@ -93,6 +93,28 @@ describe('query op — CRAG gate (#1663)', () => {
expect(crag.escalate_to_think).toBe(true);
}, 30000);
+ test('#5390: types: [] escalates exactly like an omitted filter (the re-run reuses the normalized types)', async () => {
+ await engine.setConfig('search.crag_escalation', 'true');
+ let keywordCalls = 0;
+ const counted = new Proxy(engine, {
+ get(target, key) {
+ const value = Reflect.get(target, key, target);
+ if (key === 'searchKeyword') return (...args: unknown[]) => { keywordCalls++; return (value as (...a: unknown[]) => unknown).apply(target, args); };
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+ const calls: number[] = [];
+ for (const types of [undefined, []]) {
+ keywordCalls = 0;
+ const { ctx, meta } = ctxWithMeta();
+ await operationsByName.query.handler({ ...ctx, engine: counted } as OperationContext,
+ { query: 'zxqv nonexistent quux', expand: false, ...(types ? { types } : {}) });
+ expect(cragOf(meta).escalated).toBe(true);
+ calls.push(keywordCalls);
+ }
+ expect(calls[1]).toBe(calls[0]);
+ }, 30000);
+
test('remote and unset-trust escalation cannot adopt a matching private page', async () => {
await engine.setConfig('search.crag_escalation', 'true');
await engine.putPage('notes/private-crag', {
diff --git a/test/serve-http-ingest-legacy.test.ts b/test/serve-http-ingest-legacy.test.ts
new file mode 100644
index 0000000000..62a7674193
--- /dev/null
+++ b/test/serve-http-ingest-legacy.test.ts
@@ -0,0 +1,110 @@
+/**
+ * #5157 / #5114: `POST /ingest` over a job row left with SQL NULL authority
+ * by an upgrade across v0.50 (PGLite, real Express route via mountWebhooks).
+ *
+ * /ingest submits with application authority, so a completed legacy key
+ * coalesces and returns 202; a live legacy row returns 409 with the
+ * `{error, message, hint, docs_url}` body; other submission errors stay 500.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import express from 'express';
+import type { Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { mountWebhooks } from '../src/commands/serve-http-webhooks.ts';
+import type { ServeHttpContext } from '../src/commands/serve-http.ts';
+import { MinionQueue } from '../src/core/minions/queue.ts';
+import { computeContentHash } from '../src/core/ingestion/types.ts';
+
+const CLIENT = 'ingest-legacy-client';
+let engine: PGLiteEngine;
+let server: Server;
+let base: string;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ const app = express();
+ const pass: express.RequestHandler = (_req, _res, next) => next();
+ mountWebhooks(app, {
+ engine,
+ resourceVerifier: {
+ verifyAccessToken: async (token: string) => ({ token, clientId: CLIENT, clientName: 'example-client', scopes: ['read', 'write'], sourceId: 'default', expiresAt: Math.floor(Date.now() / 1000) + 3600 }),
+ },
+ resourceMetadataUrl: 'http://127.0.0.1/.well-known/oauth-protected-resource',
+ ingestRateLimiter: pass,
+ githubWebhookLimiter: pass,
+ broadcastEvent: () => {},
+ } as unknown as ServeHttpContext);
+ server = await new Promise<Server>(resolve => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}, 60_000);
+afterAll(async () => {
+ await new Promise<void>(resolve => server?.close(() => resolve()));
+ await engine?.disconnect();
+}, 60_000);
+beforeEach(async () => { await engine.executeRaw('DELETE FROM minion_jobs'); });
+
+function post(content: string) {
+ return fetch(`${base}/ingest`, { method: 'POST', headers: { authorization: 'Bearer test-only', 'content-type': 'text/markdown' }, body: content });
+}
+const keyFor = (content: string) => `ingest:webhook:${CLIENT}:default:${computeContentHash(content)}`;
+
+/** A job holding the capture's exact key, rewritten to a pre-cutover row. */
+async function legacyRow(content: string, status: string, authority: string | null = null): Promise<number> {
+ const job = await new MinionQueue(engine).add('ingest_capture', { legacy: true }, { idempotency_key: keyFor(content) });
+ await engine.executeRaw('UPDATE minion_jobs SET status = $2, submission_authority = $3::text::jsonb WHERE id = $1', [job.id, status, authority]);
+ return job.id;
+}
+
+describe('POST /ingest over legacy job authority', () => {
+ test('a waiting legacy row with the same key returns 409 with the recovery hint, never 500', async () => {
+ const content = '# Waiting legacy\n\nbody';
+ const id = await legacyRow(content, 'waiting');
+ const res = await post(content);
+ expect(res.status).toBe(409);
+ const body = await res.json() as Record<string, string>;
+ expect(Object.keys(body).sort()).toEqual(['docs_url', 'error', 'hint', 'message']);
+ expect(body.error).toBe('permission_denied');
+ expect(body.message).toContain(`job ${id} (ingest_capture, waiting)`);
+ expect(body.hint).toContain('gbrain jobs authorize-legacy --select "status=waiting|delayed|waiting-children|paused"');
+ expect(body.hint).toContain('--expect <hash> --yes');
+ expect(body.docs_url).toBe('docs/guides/repair.md#legacy-job-authority');
+ });
+
+ test('a full waiting cap whose newest row is legacy returns 409', async () => {
+ const queue = new MinionQueue(engine);
+ for (let i = 0; i < 50; i++) await queue.add('ingest_capture', { n: i, sourceId: 'default' });
+ await engine.executeRaw('UPDATE minion_jobs SET submission_authority = NULL');
+ const res = await post('# Cap\n\nfresh content');
+ expect(res.status).toBe(409);
+ expect((await res.json() as Record<string, string>).docs_url).toBe('docs/guides/repair.md#legacy-job-authority');
+ });
+
+ test('a completed legacy row with the same key coalesces with 202 (application authority)', async () => {
+ const content = '# Completed legacy\n\nbody';
+ const id = await legacyRow(content, 'completed');
+ const res = await post(content);
+ expect(res.status).toBe(202);
+ expect((await res.json() as Record<string, unknown>).job_id).toBe(id);
+ });
+
+ test('a cancelled legacy key is released and the capture queues a fresh job', async () => {
+ const content = '# Cancelled legacy\n\nbody';
+ const id = await legacyRow(content, 'cancelled');
+ const res = await post(content);
+ expect(res.status).toBe(202);
+ expect((await res.json() as Record<string, unknown>).job_id).not.toBe(id);
+ });
+
+ test('a non-legacy submission error still returns 500 queue_submission_failed', async () => {
+ const content = '# JSONB null\n\nbody';
+ await legacyRow(content, 'waiting', 'null');
+ const res = await post(content);
+ expect(res.status).toBe(500);
+ const body = await res.json() as Record<string, string>;
+ expect(body.error).toBe('queue_submission_failed');
+ expect(body.message).toContain('coalescing across');
+ });
+});
diff --git a/test/serve-http-log-epipe.test.ts b/test/serve-http-log-epipe.test.ts
new file mode 100644
index 0000000000..03ecd99a8f
--- /dev/null
+++ b/test/serve-http-log-epipe.test.ts
@@ -0,0 +1,76 @@
+/**
+ * #5079: `serve --http` exited when its stdout/stderr pipe closed (a
+ * hand-written systemd unit or a log pipeline that restarts), because the
+ * CLI-wide broken-pipe handling (SIGPIPE under Bun, EPIPE stream errors)
+ * stops the process. For `serve --http` those streams only carry logs, so it
+ * now drops the write and keeps serving; stdio `serve` and every other
+ * command still exit, since there a broken stdout means the reader left.
+ *
+ * The broken pipe is real: a child installs the handlers through the same
+ * entrypoint cli.ts uses, keeps logging on a timer, and the parent destroys
+ * the child's stdout/stderr pipes.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { spawn } from 'child_process';
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+import { isHttpServeInvocation } from '../src/core/serve-invocation.ts';
+
+const ENTRY = resolve(import.meta.dir, '..', 'src', 'core', 'serve-invocation.ts');
+
+async function logThroughClosedPipe(argv: string[]): Promise<{ exit: number | string | null; ticksAfterClose: number }> {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-5079-'));
+ try {
+ const marker = join(dir, 'ticks.log');
+ const script = join(dir, 'child.ts');
+ writeFileSync(script, `
+const { installCleanupSignalHandlers } = await import(${JSON.stringify(ENTRY)});
+const { appendFileSync } = await import('fs');
+installCleanupSignalHandlers(${JSON.stringify(argv)});
+let n = 0;
+setInterval(() => {
+ n++;
+ console.log('request log ' + n);
+ console.error('request err ' + n);
+ appendFileSync(${JSON.stringify(marker)}, n + '\\n');
+}, 50);
+`);
+ const child = spawn(process.execPath, [script], { stdio: ['ignore', 'pipe', 'pipe'] });
+ let exit: number | string | null = 'alive';
+ child.on('exit', (code, signal) => { exit = code ?? signal; });
+ const ticks = () => (existsSync(marker) ? readFileSync(marker, 'utf-8').trim().split('\n').length : 0);
+ for (let i = 0; i < 100 && ticks() < 5; i++) await new Promise(r => setTimeout(r, 50));
+ child.stdout!.destroy();
+ child.stderr!.destroy();
+ const atClose = ticks();
+ await new Promise(r => setTimeout(r, 1500));
+ const after = ticks() - atClose;
+ child.kill('SIGKILL');
+ return { exit, ticksAfterClose: after };
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe('#5079 serve --http survives a closed log pipe', () => {
+ test('serve --http keeps running and logging', async () => {
+ const r = await logThroughClosedPipe(['serve', '--http', '--port', '3131']);
+ expect(r.exit).toBe('alive');
+ expect(r.ticksAfterClose).toBeGreaterThan(5);
+ }, 30_000);
+
+ test('stdio serve and other commands still exit on a broken pipe', async () => {
+ for (const argv of [['serve'], ['sync']]) expect((await logThroughClosedPipe(argv)).exit).not.toBe('alive');
+ }, 30_000);
+
+ test('only `serve --http` gets the setting', () => {
+ expect(isHttpServeInvocation(['serve', '--http', '--port', '3131'])).toBe(true);
+ expect(isHttpServeInvocation(['--timeout', '30s', 'serve', '--http'])).toBe(true);
+ expect(isHttpServeInvocation(['serve'])).toBe(false);
+ expect(isHttpServeInvocation(['sync', '--http'])).toBe(false);
+ expect(isHttpServeInvocation([])).toBe(false);
+ });
+});
diff --git a/test/serve-mounted-owner.serial.test.ts b/test/serve-mounted-owner.serial.test.ts
new file mode 100644
index 0000000000..367bd76b00
--- /dev/null
+++ b/test/serve-mounted-owner.serial.test.ts
@@ -0,0 +1,125 @@
+/**
+ * #5237: a resident `gbrain serve` started in a `.gbrain-mount` project opens the
+ * mounted brain, so its persistence owner socket must follow that brain. A CLI
+ * write from the same project then reaches the owner and commits instead of
+ * failing `owner_unavailable`; a serve on the host brain is unchanged.
+ *
+ * Serial: real `gbrain serve` and CLI subprocesses on PGLite under a sandboxed
+ * HOME/GBRAIN_HOME; every serve child is stopped in afterEach.
+ */
+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createEngine } from '../src/core/engine-factory.ts';
+import { resolveSocketPath } from '../src/core/context/resolve-ipc.ts';
+import { persistenceSocketPathForConfig } from '../src/core/persistence/ipc.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+const CLI = join(REPO_ROOT, 'src', 'cli.ts');
+const MOUNT = 'example-mount';
+
+let root: string, home: string, hostDb: string, mountDb: string, project: string, neutral: string;
+let serve: ReturnType<typeof Bun.spawn> | null = null;
+let serveStderr = '';
+
+function env(): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) out[key] = value;
+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']) delete out[key];
+ return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_MOUNTS_PATH: join(home, '.gbrain', 'mounts.json'),
+ GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300' };
+}
+
+async function initBrain(path: string) {
+ const config = { engine: 'pglite' as const, database_path: path };
+ const engine = await createEngine(config);
+ await engine.connect(config);
+ await engine.initSchema();
+ await engine.disconnect();
+}
+
+async function pageExists(path: string, slug: string): Promise<boolean> {
+ const config = { engine: 'pglite' as const, database_path: path };
+ const engine = await createEngine(config);
+ await engine.connect(config);
+ try { return (await engine.executeRaw('SELECT slug FROM pages WHERE slug=$1', [slug])).length === 1; }
+ finally { await engine.disconnect(); }
+}
+
+async function startServe(cwd: string, readyDb: string) {
+ serveStderr = '';
+ serve = Bun.spawn(['bun', 'run', CLI, 'serve'], { cwd, env: env(), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ void (async () => {
+ const reader = (serve!.stderr as ReadableStream<Uint8Array>).getReader();
+ const decoder = new TextDecoder();
+ try { while (true) { const { value, done } = await reader.read(); if (done) break; serveStderr += decoder.decode(value, { stream: true }); } } catch { /* child gone */ }
+ })();
+ // The persistence listener binds before the resolve listener in the same helper.
+ const socket = resolveSocketPath(readyDb);
+ const deadline = Date.now() + 120_000;
+ while (!existsSync(socket)) {
+ if (serve.exitCode !== null) throw new Error(`serve exited early (${serve.exitCode})\n${serveStderr}`);
+ if (Date.now() > deadline) throw new Error(`serve never bound ${socket}\n${serveStderr}`);
+ await Bun.sleep(150);
+ }
+}
+
+async function stopServe() {
+ if (!serve) return;
+ if (serve.exitCode === null) { serve.kill('SIGTERM'); await Promise.race([serve.exited, Bun.sleep(15_000)]); }
+ if (serve.exitCode === null) { serve.kill('SIGKILL'); await serve.exited; }
+ serve = null;
+}
+
+async function cli(args: string[], cwd: string) {
+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd, env: env(), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ return { stdout, stderr, exitCode };
+}
+
+beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gb-5237-'));
+ home = join(root, 'h');
+ hostDb = join(root, 'hdb');
+ mountDb = join(root, 'mdb');
+ project = join(root, 'p');
+ neutral = join(root, 'n');
+ for (const dir of [join(home, '.gbrain'), project, neutral, join(root, 'mount-clone')]) mkdirSync(dir, { recursive: true });
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: hostDb }));
+ writeFileSync(join(home, '.gbrain', 'mounts.json'), JSON.stringify({ version: 1, mounts: [
+ { id: MOUNT, path: join(root, 'mount-clone'), engine: 'pglite', database_path: mountDb, enabled: true },
+ ] }), { mode: 0o600 });
+ const dotfile = join(project, '.gbrain-mount');
+ writeFileSync(dotfile, `${MOUNT}\n`);
+ chmodSync(dotfile, 0o644);
+ await initBrain(hostDb);
+ await initBrain(mountDb);
+}, 240_000);
+
+afterEach(stopServe, 30_000);
+afterAll(() => { rmSync(root, { recursive: true, force: true }); });
+
+describe('resident serve owner on a mounted brain (#5237)', () => {
+ test('a CLI write from a .gbrain-mount project commits through the mounted serve owner', async () => {
+ await startServe(project, hostDb);
+ expect(existsSync(persistenceSocketPathForConfig({ engine: 'pglite', database_path: mountDb })!)).toBe(true);
+ const put = await cli(['put', 'notes/mounted-example', '--content', '# Mounted example\n\nWritten through the resident owner.'], project);
+ expect(put.stderr).not.toContain('owner_unavailable');
+ expect(put.exitCode).toBe(0);
+ await stopServe();
+ expect(await pageExists(mountDb, 'notes/mounted-example')).toBe(true);
+ expect(await pageExists(hostDb, 'notes/mounted-example')).toBe(false);
+ }, 240_000);
+
+ test('a serve on the host brain still owns the host socket and commits host writes', async () => {
+ await startServe(neutral, hostDb);
+ expect(existsSync(persistenceSocketPathForConfig({ engine: 'pglite', database_path: hostDb })!)).toBe(true);
+ expect(existsSync(persistenceSocketPathForConfig({ engine: 'pglite', database_path: mountDb })!)).toBe(false);
+ const put = await cli(['put', 'notes/host-example', '--content', '# Host example\n\nWritten through the host owner.'], neutral);
+ expect(put.exitCode).toBe(0);
+ await stopServe();
+ expect(await pageExists(hostDb, 'notes/host-example')).toBe(true);
+ expect(await pageExists(mountDb, 'notes/host-example')).toBe(false);
+ }, 240_000);
+});
diff --git a/test/serve-stdio-bound-explicit-read.test.ts b/test/serve-stdio-bound-explicit-read.test.ts
new file mode 100644
index 0000000000..7fb7425549
--- /dev/null
+++ b/test/serve-stdio-bound-explicit-read.test.ts
@@ -0,0 +1,107 @@
+/**
+ * #5081 over the real stdio transport: `gbrain serve` started with
+ * GBRAIN_SOURCE=work (the harness `.mcp.json` shape from the report) may name
+ * a federated source in an explicit `source_id` read, gets only that source's
+ * rows back, is refused a source that is not federated with the
+ * bound-connection hint, and keeps unqualified reads on the bound source.
+ *
+ * PGLite, hermetic temp HOME; the MCP SDK spawns `gbrain serve` and performs
+ * the same initialize handshake Claude Code does. The in-process matrix over
+ * every affected read lives in test/explicit-read-admission-5081.test.ts.
+ *
+ * Lane: unit. Run: `bun test test/serve-stdio-bound-explicit-read.test.ts`.
+ */
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { spawnSync } from 'child_process';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { cliDiagnostic } from './helpers/fixture-diagnostics.ts';
+
+const MARKER = 'halcyon-bound-read-5081';
+
+function execFixture(args: string[], env: Record<string, string>): void {
+ const result = spawnSync('bun', ['--no-env-file', ...args], { cwd: process.cwd(), env, encoding: 'utf8' });
+ if (result.status !== 0) throw new Error(cliDiagnostic(args[2] ?? 'stdio fixture', {
+ exitCode: result.status ?? -1, stdout: result.stdout ?? '', stderr: result.stderr ?? '',
+ }));
+}
+
+function textOf(result: unknown): string {
+ const content = (result as { content?: Array<{ text?: string }> })?.content;
+ return Array.isArray(content) ? content.map((c) => c?.text ?? '').join('\n') : '';
+}
+
+function sourcesOf(text: string): string[] {
+ const rows = JSON.parse(text) as Array<{ source_id?: string }>;
+ return [...new Set(rows.map((row) => row.source_id ?? ''))].sort();
+}
+
+describe('#5081 — GBRAIN_SOURCE-bound stdio serve, explicit source_id reads', () => {
+ let home: string;
+ let client: Client | null = null;
+ let transport: StdioClientTransport | null = null;
+
+ beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-stdio-5081-'));
+ const env = keylessBrainEnv(process.env, home, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,
+ });
+ delete env.GBRAIN_SOURCE;
+ execFixture(['run', 'src/cli.ts', 'init', '--pglite', '--no-embedding', '--non-interactive'], env);
+ for (const [id, flag] of [['work', null], ['notes', '--federated'], ['private', null]] as const) {
+ const dir = join(home, id);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, `${id}-page.md`),
+ `---\ntitle: ${MARKER} in ${id}\n---\n\n# ${MARKER}\n\nThis ${MARKER} page lives in the ${id} source.\n`);
+ execFixture(['run', 'src/cli.ts', 'sources', 'add', id, '--path', dir, ...(flag ? [flag] : []), '--force'], env);
+ execFixture(['run', 'src/cli.ts', 'import', dir, '--no-embed', '--source-id', id], env);
+ }
+
+ transport = new StdioClientTransport({
+ command: 'bun',
+ args: ['--no-env-file', 'run', 'src/cli.ts', 'serve'],
+ cwd: process.cwd(),
+ env: { ...env, GBRAIN_SOURCE: 'work' },
+ });
+ client = new Client({ name: 'gbrain-stdio-5081', version: '1.0.0' }, { capabilities: {} });
+ await client.connect(transport);
+ }, 120_000);
+
+ afterAll(async () => {
+ if (client) { try { await client.close(); } catch { /* best-effort */ } }
+ if (transport) { try { await transport.close(); } catch { /* best-effort */ } }
+ if (home) { try { rmSync(home, { recursive: true, force: true }); } catch { /* best-effort */ } }
+ });
+
+ test('search, query and get_page name a federated source and return only its rows', async () => {
+ const search = await client!.callTool({ name: 'search', arguments: { query: MARKER, source_id: 'notes', limit: 10 } });
+ expect(search.isError).toBeFalsy();
+ expect(sourcesOf(textOf(search))).toEqual(['notes']);
+
+ const query = await client!.callTool({ name: 'query', arguments: { query: MARKER, source_id: 'notes', expand: false, limit: 10 } });
+ expect(query.isError).toBeFalsy();
+ expect(sourcesOf(textOf(query))).toEqual(['notes']);
+
+ const page = await client!.callTool({ name: 'get_page', arguments: { slug: 'notes-page', source_id: 'notes' } });
+ expect(page.isError).toBeFalsy();
+ expect(JSON.parse(textOf(page)).source_id).toBe('notes');
+ }, 60_000);
+
+ test('a source that is not federated is refused with the bound-connection hint', async () => {
+ const res = await client!.callTool({ name: 'search', arguments: { query: MARKER, source_id: 'private' } });
+ expect(res.isError).toBe(true);
+ const body = JSON.parse(textOf(res));
+ expect(body.error).toBe('permission_denied');
+ expect(body.suggestion).toStartWith('This connection is bound to source work (GBRAIN_SOURCE). private ');
+ expect(body.suggestion).toContain('`gbrain sources federate private` on the brain host, or start this connection without GBRAIN_SOURCE.');
+ }, 60_000);
+
+ test('unqualified reads stay on the bound source', async () => {
+ const res = await client!.callTool({ name: 'search', arguments: { query: MARKER, limit: 10 } });
+ expect(sourcesOf(textOf(res))).toEqual(['work']);
+ }, 60_000);
+});
diff --git a/test/shared-skills-writer-boundary.serial.test.ts b/test/shared-skills-writer-boundary.serial.test.ts
index cd563676cb..8eb0aedaed 100644
--- a/test/shared-skills-writer-boundary.serial.test.ts
+++ b/test/shared-skills-writer-boundary.serial.test.ts
@@ -19,6 +19,7 @@ import { importFromContent } from '../src/core/import-file.ts';
import { activateSharedSkillPersistence } from '../src/core/persistence/skill-activation.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { disposePersistenceConsumer, writeResponse } from '../src/core/persistence/service.ts';
+import { rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';
import { adoptSharedSkillpack } from '../src/core/shared-skills/publication.ts';
import { setSharedSkillPolicy } from '../src/core/shared-skills/policy.ts';
import { assertKnowledgePublicationAllowed } from '../src/core/shared-skills/knowledge-guard.ts';
@@ -140,6 +141,9 @@ test('unresolvable stored file aliases fail closed with a metadata diagnostic in
const [page] = await f.engine.executeRaw<{ source_uri: string }>(
'SELECT source_uri FROM pages WHERE source_id=$1 AND slug=$2', ['default', row.slug]);
expect(page.source_uri).toBe('file:///notes/%2F.md');
+ // The running resident drains queued projections in the background (#5401);
+ // finish that first so the snapshot below compares canonical state only.
+ while ((await rebuildPendingPageProjections(f.engine, 100)).rebuilt > 0) { /* drain */ }
const snapshot = await f.engine.readPageSnapshot(row.slug, { sourceId: 'default' });
await expect(submitPageMutation(f.ctx, { operation: 'put_page', params: {
slug: row.slug, content: note, request_id: randomUUID(), expected_revision: snapshot!.revision,
diff --git a/test/sources-mirror-read-only.test.ts b/test/sources-mirror-read-only.test.ts
new file mode 100644
index 0000000000..ae016331d4
--- /dev/null
+++ b/test/sources-mirror-read-only.test.ts
@@ -0,0 +1,201 @@
+/**
+ * #5409: a per-source read-only mirror (`sources.config.mirror_read_only`),
+ * on PGLite and, with a safe DATABASE_URL, Postgres
+ * (test/e2e/sources-mirror-read-only-postgres.test.ts).
+ *
+ * Protects: with the flag on, managed sync imports a file whose canonical form
+ * differs (no frontmatter) database-only and leaves the checkout's bytes and
+ * `git status` clean, so the next upstream commit fast-forwards and syncs; a
+ * page write into the source is stored database-only and says so
+ * (`storage: "database_only"`). With the flag off (the default) both paths
+ * keep writing the canonical file. `sources mirror-readonly|mirror-writable`
+ * set and clear the flag and `sources list --json` reports it.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { acquireWorktree, claimWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { claimNextWrite } from '../src/core/persistence/journal.ts';
+import { localHostId } from '../src/core/persistence/identity.ts';
+import { preparePageMutation } from '../src/core/persistence/page-prepare.ts';
+import { publishMutation } from '../src/core/persistence/coordinator.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
+import { submitForgetMutation } from '../src/core/persistence/memory-mutations.ts';
+import { runSources } from '../src/commands/sources.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
+function commit(root: string, message = 'upstream'): string {
+ git(root, 'add', '.'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', message);
+ return git(root, 'rev-parse', 'HEAD');
+}
+
+for (const backend of testBackends()) {
+ describe(`read-only mirror sources (${backend})`, () => {
+ let engine: BrainEngine;
+ let close: (() => Promise<void>) | undefined;
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-mirror-read-only-'));
+ beforeAll(async () => {
+ if (backend === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else { const pglite = new PGLiteEngine(); await pglite.connect({}); await pglite.initSchema(); engine = pglite; }
+ }, 120_000);
+ afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: home }, () => disposePersistenceConsumer(engine));
+ if (close) await close(); else await engine.disconnect();
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ const TODOS = '# Todos\n\n- ship the mirror flag\n';
+
+ /** A managed Git source whose TODOS.md has no frontmatter, so its canonical form differs from its bytes. */
+ async function mirror(readOnly: boolean) {
+ const id = `mirror-${randomUUID().slice(0, 8)}`;
+ const root = join(home, id); mkdirSync(root); git(root, 'init', '-q');
+ writeFileSync(join(root, 'TODOS.md'), TODOS);
+ commit(root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [id, root]);
+ await claimWorktree(engine, id, root);
+ if (readOnly) await cli(['mirror-readonly', id]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ return { id, root };
+ }
+ async function cli(args: string[]): Promise<string> {
+ const lines: string[] = [];
+ const original = console.log;
+ console.log = (...parts: unknown[]) => { lines.push(parts.map(String).join(' ')); };
+ try { await runSources(engine, args); } finally { console.log = original; }
+ return lines.join('\n');
+ }
+ const ctx = (sourceId: string) => ({ engine, sourceId, remote: false as const, dryRun: false,
+ config: { engine: engine.kind, embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} } });
+
+ test('sources mirror-readonly / mirror-writable set the flag and sources list --json reports it', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const id = `mirror-cli-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES($1,$1,'{\"federated\":true}')", [id]);
+ const listed = async () => (JSON.parse(await cli(['list', '--json'])) as { sources: Array<{ id: string; mirror_read_only: boolean; federated: boolean }> })
+ .sources.find(source => source.id === id)!;
+ expect(await listed()).toMatchObject({ mirror_read_only: false, federated: true });
+ expect(await cli(['mirror-readonly', id])).toContain(`Source "${id}" is now a read-only mirror`);
+ expect(await listed()).toMatchObject({ mirror_read_only: true, federated: true });
+ expect(await cli(['mirror-writable', id])).toContain(`Source "${id}" is writable again`);
+ expect(await listed()).toMatchObject({ mirror_read_only: false, federated: true });
+ }), 60_000);
+
+ /** First sync, a database-only tag, then an upstream edit: the canonical form now differs from the file's bytes (an overlay). */
+ async function overlaySync(m: { id: string; root: string }) {
+ expect(await performManagedSync(engine, { sourceId: m.id, noPull: true })).toMatchObject({ status: 'first_sync', filesImported: 1 });
+ await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.addTag('todos', 'kept-in-brain', { sourceId: m.id })));
+ writeFileSync(join(m.root, 'TODOS.md'), `${TODOS}- keep the mirror pullable\n`);
+ commit(m.root, 'upstream edit');
+ expect(await performManagedSync(engine, { sourceId: m.id, noPull: true })).toMatchObject({ filesImported: 1 });
+ }
+ const tracked = (root: string) => git(root, 'status', '--porcelain', '--untracked-files=no');
+
+ test('read-only: an overlay imports database-only, the checkout stays clean, and the next upstream commit syncs', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(true);
+ await overlaySync(m);
+ expect(readFileSync(join(m.root, 'TODOS.md'), 'utf8')).toBe(`${TODOS}- keep the mirror pullable\n`);
+ expect(tracked(m.root)).toBe('');
+ const page = (await engine.readPageSnapshot('todos', { sourceId: m.id }))!;
+ expect(page.page.compiled_truth).toContain('keep the mirror pullable');
+ expect(page.tags).toContain('kept-in-brain');
+ const [receipt] = await engine.executeRaw<{ outcome: Record<string, unknown> }>(
+ "SELECT outcome FROM persistence_requests WHERE source_id=$1 AND slug='todos' AND state='committed' ORDER BY sequence DESC LIMIT 1", [m.id]);
+ expect(receipt.outcome).toMatchObject({ storage: 'database_only', write_through: { written: false, skipped: 'mirror_read_only' } });
+ writeFileSync(join(m.root, 'TODOS.md'), `${TODOS}- keep the mirror pullable\n- and again\n`);
+ commit(m.root, 'second upstream edit');
+ expect(await performManagedSync(engine, { sourceId: m.id, noPull: true })).toMatchObject({ filesImported: 1 });
+ expect(tracked(m.root)).toBe('');
+ expect((await engine.getPage('todos', { sourceId: m.id }))?.compiled_truth).toContain('and again');
+ }), 120_000);
+
+ test('writable (default): the overlay is written back into the checkout', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(false);
+ await overlaySync(m);
+ expect(readFileSync(join(m.root, 'TODOS.md'), 'utf8')).toContain('kept-in-brain');
+ expect(tracked(m.root)).toBe('M TODOS.md');
+ }), 120_000);
+
+ test('a page write into a read-only mirror is stored database-only and says so; a writable source gets its file', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const readOnly of [true, false]) {
+ const m = await mirror(readOnly);
+ const receipt = await submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'notes/agent-note', request_id: randomUUID(),
+ content: '---\ntitle: Agent note\ntype: note\n---\nWritten by an agent.\n' } }) as Record<string, unknown>;
+ expect((await engine.getPage('notes/agent-note', { sourceId: m.id }))?.compiled_truth).toContain('Written by an agent.');
+ if (readOnly) {
+ expect(receipt).toMatchObject({ storage: 'database_only', write_through: { written: false, skipped: 'mirror_read_only' } });
+ expect(existsSync(join(m.root, 'notes/agent-note.md'))).toBe(false);
+ expect(tracked(m.root)).toBe('');
+ } else {
+ expect(receipt).not.toHaveProperty('storage');
+ expect(receipt.write_through).toMatchObject({ written: true });
+ expect(existsSync(join(m.root, 'notes/agent-note.md'))).toBe(true);
+ }
+ }
+ }), 120_000);
+
+ test('a file target prepared before the source became a read-only mirror is refused at publication (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(false);
+ const binding = (await getWorktreeBinding(engine, m.id))!;
+ const lock = (await acquireWorktree(binding, 5000))!;
+ try {
+ await expect(submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'notes/racing', request_id: randomUUID(),
+ content: '---\ntitle: Racing\ntype: note\n---\nPrepared before the flag.\n' } })).rejects.toMatchObject({ code: 'write_pending' });
+ await disposePersistenceConsumer(engine);
+ } finally { await lock.release(); }
+ const row = (await claimNextWrite(engine, localHostId()))!;
+ expect(row.slug).toBe('notes/racing');
+ const prepared = await preparePageMutation(engine, row, { engine: engine.kind, embedding_disabled: true });
+ expect(prepared.file).toBeDefined();
+ const outcome = await publishMutation(engine, row, prepared, localHostId(), { boundary: async name => {
+ if (name === 'prepared') await cli(['mirror-readonly', m.id]);
+ } });
+ expect(outcome).toMatchObject({ state: 'conflict', error_code: 'source_changed' });
+ expect(existsSync(join(m.root, 'notes/racing.md'))).toBe(false);
+ expect(await engine.getPage('notes/racing', { sourceId: m.id })).toBeNull();
+ }), 120_000);
+
+ test('a page created while read-only stays database-only after mirror-writable and can still be edited (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(true);
+ const put = (body: string, extra: Record<string, unknown> = {}) => submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'notes/brain-only',
+ request_id: randomUUID(), content: `---\ntitle: Brain only\ntype: note\n---\n${body}\n`, ...extra } }) as Promise<Record<string, unknown>>;
+ await put('Created while the source was a read-only mirror.');
+ await cli(['mirror-writable', m.id]);
+ const prior = (await engine.readPageSnapshot('notes/brain-only', { sourceId: m.id }))!;
+ const edited = await put('Edited after mirror-writable.', { expected_revision: prior.revision });
+ expect(edited).toMatchObject({ storage: 'database_only', write_through: { written: false, skipped: 'mirror_read_only' } });
+ expect((await engine.getPage('notes/brain-only', { sourceId: m.id }))?.compiled_truth).toContain('Edited after mirror-writable.');
+ expect(existsSync(join(m.root, 'notes/brain-only.md'))).toBe(false);
+ }), 120_000);
+
+ test('a fact withdrawal in a read-only mirror settles its Git effect as skipped, never failed (Codex review)', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ const m = await mirror(true);
+ await submitPageMutation(ctx(m.id), { operation: 'put_page', params: { slug: 'people/alice-example', request_id: randomUUID(),
+ content: '---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n' } });
+ const [{ id }] = await engine.transaction(tx => withCoordinatedWrite(tx, [m.id], () => tx.executeRaw<{ id: number }>(
+ `INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, source) VALUES ($1, 'people/alice-example', 'Alice prefers mornings', 'preference', 'private', 'test')
+ RETURNING id::int AS id`, [m.id])));
+ const forgot = await submitForgetMutation(ctx(m.id), 'forget', { id: Number(id), request_id: randomUUID() }) as { request_id: string };
+ let effects: Array<{ kind: string; state: string; outcome: Record<string, unknown> | null }> = [];
+ for (let i = 0; i < 100; i++) {
+ effects = await engine.executeRaw(`SELECT e.kind, e.state, e.outcome FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id
+ WHERE r.request_id=$1::uuid AND e.kind='git'`, [forgot.request_id]);
+ if (effects.length && effects.every(e => e.state !== 'queued' && e.state !== 'running')) break;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ expect(effects).toEqual([expect.objectContaining({ kind: 'git', state: 'committed', outcome: expect.objectContaining({ git: 'skipped', reason: 'mirror_read_only' }) })]);
+ expect(tracked(m.root)).toBe('');
+ }), 120_000);
+ });
+}
diff --git a/test/think-save-source.test.ts b/test/think-save-source.test.ts
new file mode 100644
index 0000000000..09b977270f
--- /dev/null
+++ b/test/think-save-source.test.ts
@@ -0,0 +1,92 @@
+/**
+ * #5426: `think --save` wrote every synthesis to source `default` and bound
+ * its citations by bare slug, so on a multi-source brain the synthesis landed
+ * in the wrong source and its evidence could point at a same-slug page in
+ * another source. persistSynthesis now takes the think's scope from all three
+ * callers (CLI think, the think op, auto-think).
+ */
+
+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
+import { readFileSync } from 'fs';
+import { resolve } from 'path';
+
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { persistSynthesis, type ThinkResult } from '../src/core/think/index.ts';
+
+let engine: PGLiteEngine;
+let defaultAliceId: number;
+let alphaAliceId: number;
+
+function synthesis(question: string): ThinkResult {
+ return {
+ question,
+ answer: 'Alice leads Acme [people/alice-example#1].',
+ gaps: [],
+ citations: [{ page_slug: 'people/alice-example', row_num: 1, citation_index: 1 }],
+ modelUsed: 'stub',
+ pagesGathered: 1,
+ takesGathered: 1,
+ warnings: [],
+ synthesisOk: true,
+ } as unknown as ThinkResult;
+}
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw(`INSERT INTO sources (id, name) VALUES ('alpha', 'Alpha'), ('beta', 'Beta') ON CONFLICT (id) DO NOTHING`);
+ defaultAliceId = (await engine.putPage('people/alice-example', { title: 'Alice', type: 'person', compiled_truth: 'Default Alice.' })).id;
+ alphaAliceId = (await engine.putPage('people/alice-example', { title: 'Alice', type: 'person', compiled_truth: 'Alpha Alice.' }, { sourceId: 'alpha' })).id;
+ expect(alphaAliceId).not.toBe(defaultAliceId);
+ await engine.addTakesBatch([
+ { page_id: defaultAliceId, row_num: 1, claim: 'Default claim', kind: 'fact', holder: 'world', weight: 1 },
+ { page_id: alphaAliceId, row_num: 1, claim: 'Alpha claim', kind: 'fact', holder: 'world', weight: 1 },
+ ]);
+}, 60_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+}, 60_000);
+
+async function evidenceFor(slug: string, sourceId: string): Promise<number[]> {
+ const rows = await engine.executeRaw<{ take_page_id: number }>(
+ `SELECT e.take_page_id FROM synthesis_evidence e JOIN pages p ON p.id = e.synthesis_page_id WHERE p.slug = $1 AND p.source_id = $2`,
+ [slug, sourceId],
+ );
+ return rows.map(r => Number(r.take_page_id));
+}
+
+describe('#5426 think --save persists into the think source', () => {
+ test('the synthesis lands in the requested source and cites that source\'s page', async () => {
+ const saved = await persistSynthesis(engine, synthesis('alpha question'), { sourceId: 'alpha' });
+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages WHERE slug = $1`, [saved.slug]);
+ expect(rows.map(r => r.source_id)).toEqual(['alpha']);
+ expect(await evidenceFor(saved.slug, 'alpha')).toEqual([alphaAliceId]);
+ });
+
+ test('a citation outside the gathered sources is not bound to a same-slug page elsewhere', async () => {
+ const saved = await persistSynthesis(engine, synthesis('beta question'), { sourceId: 'beta' });
+ expect(saved.warnings).toContain('CITATION_PAGE_NOT_IN_BRAIN: people/alice-example#1');
+ expect(await evidenceFor(saved.slug, 'beta')).toEqual([]);
+ });
+
+ test('a federated think binds to a gathered source, preferring its own', async () => {
+ const saved = await persistSynthesis(engine, synthesis('federated question'), { sourceId: 'beta', allowedSources: ['beta', 'alpha'] });
+ expect(await evidenceFor(saved.slug, 'beta')).toEqual([alphaAliceId]);
+ });
+
+ test('an unscoped think keeps the default source', async () => {
+ const saved = await persistSynthesis(engine, synthesis('unscoped question'));
+ const rows = await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM pages WHERE slug = $1`, [saved.slug]);
+ expect(rows.map(r => r.source_id)).toEqual(['default']);
+ });
+
+ test('all three callers pass their scope', () => {
+ // test-reads-source-ok[structural]: the three callers need a live LLM synthesis to observe end to end; persistSynthesis itself is tested above.
+ const read = (p: string) => readFileSync(resolve(import.meta.dir, '..', p), 'utf-8');
+ expect(read('src/commands/think.ts')).toContain('persistSynthesis(engine, result, { sourceId, allowedSources })');
+ expect(read('src/core/ops/takes.ts')).toMatch(/persistSynthesis\(ctx\.engine, result, \{[\s\S]*?sourceId: ctx\.sourceId === ALL_SOURCES \? undefined : ctx\.sourceId/);
+ expect(read('src/core/cycle/auto-think.ts')).toContain('persistSynthesis(engine, result, opts.sourceId ? { sourceId: opts.sourceId } : {})');
+ });
+});
diff --git a/test/transcript-offset-timestamps.test.ts b/test/transcript-offset-timestamps.test.ts
new file mode 100644
index 0000000000..15d99862bc
--- /dev/null
+++ b/test/transcript-offset-timestamps.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Offset-stamped source timestamps must round-trip exactly (gbrain-evals
+ * N12-2). An adapter that copied '2026-08-10T22:30:00.000-07:00' verbatim
+ * met a renderer that paired the local DATE (sliced from the string) with
+ * the UTC HOUR, so the anchor read "2026-08-10 5:30 AM" and re-parsed one
+ * day early. Adapters now normalize offset timestamps to UTC, and the
+ * renderer takes date and hour from the same UTC instant.
+ *
+ * Synthetic data only.
+ */
+import { describe, test, expect, afterAll } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { claudeExportAdapter } from '../src/core/transcripts/claude-export.ts';
+import { claudeCodeAdapter } from '../src/core/transcripts/claude-code.ts';
+import { mapCodexLine } from '../src/core/transcripts/codex.ts';
+import { mapOpenclawLine } from '../src/core/transcripts/openclaw.ts';
+import { redactSession, renderSessionParts } from '../src/core/transcripts/render.ts';
+import { parseConversation } from '../src/core/conversation-parser/parse.ts';
+import type { ParsedSession } from '../src/core/transcripts/types.ts';
+
+const OFFSET = '2026-08-10T22:30:00.000-07:00';
+const INSTANT = '2026-08-11T05:30:00.000Z';
+
+const dir = mkdtempSync(join(tmpdir(), 'n12-2-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+async function first(gen: AsyncGenerator<ParsedSession, unknown>): Promise<ParsedSession> {
+ const r = await gen.next();
+ if (r.done) throw new Error('no session');
+ return r.value;
+}
+
+function roundTrip(session: ParsedSession) {
+ const part = renderSessionParts(redactSession(session, { patterns: [] }), { sourcePath: 'x' }).parts[0];
+ const parsed = parseConversation(part.body, { noFallback: true, noPolish: true, page: { frontmatter: part.frontmatter } } as any);
+ return { part, parsed };
+}
+
+describe('render round-trips offset timestamps exactly', () => {
+ test('anchor carries the UTC date with the UTC hour; frontmatter date and slug use the UTC day', () => {
+ const session: ParsedSession = {
+ meta: { harness: 'claude-export', sessionId: 'c1', title: 'evening chat', startedAt: OFFSET },
+ messages: [{ role: 'user', timestamp: OFFSET, text: 'hello' }],
+ };
+ const { part, parsed } = roundTrip(session);
+ expect(part.body.split('\n')[0]).toBe('**User** (2026-08-11 5:30 AM): hello');
+ expect(part.frontmatter.date).toBe('2026-08-11');
+ expect(part.slug).toContain('/2026-08-11-');
+ expect(Date.parse(parsed.messages[0].timestamp)).toBe(Date.parse(INSTANT));
+ });
+});
+
+describe('adapters normalize offset timestamps to UTC', () => {
+ test('claude-export (the N12-2 repro)', async () => {
+ const p = join(dir, 'conversations.json');
+ writeFileSync(p, JSON.stringify([{ uuid: 'c1', name: 'evening chat', created_at: OFFSET,
+ chat_messages: [{ uuid: 'm1', sender: 'human', created_at: OFFSET, text: 'hello' }] }]));
+ const s = await first(claudeExportAdapter.parse(p));
+ expect(s.messages[0].timestamp).toBe(INSTANT);
+ expect(s.meta.startedAt).toBe(INSTANT);
+ expect(Date.parse(roundTrip(s).parsed.messages[0].timestamp)).toBe(Date.parse(INSTANT));
+ });
+
+ test('claude-code', async () => {
+ const p = join(dir, 'session.jsonl');
+ writeFileSync(p, JSON.stringify({ type: 'user', sessionId: 's1', uuid: 'u1', timestamp: OFFSET, message: { role: 'user', content: 'hello' } }) + '\n');
+ const s = await first(claudeCodeAdapter.parse(p));
+ expect(s.messages[0].timestamp).toBe(INSTANT);
+ expect(s.meta.startedAt).toBe(INSTANT);
+ });
+
+ test('codex', () => {
+ const session = mapCodexLine({ type: 'session_meta', timestamp: OFFSET, payload: { id: 's1', timestamp: OFFSET } });
+ expect(session.kind === 'session' && session.startedAt).toBe(INSTANT);
+ const user = mapCodexLine({ type: 'event_msg', timestamp: OFFSET, payload: { type: 'user_message', message: 'hello' } });
+ expect(user.kind === 'user' && user.message.timestamp).toBe(INSTANT);
+ });
+
+ test('openclaw', () => {
+ const session = mapOpenclawLine({ type: 'session', id: 's1', timestamp: OFFSET });
+ expect(session.kind === 'session' && session.startedAt).toBe(INSTANT);
+ const msg = mapOpenclawLine({ type: 'message', timestamp: OFFSET, message: { role: 'user', content: 'hello', timestamp: OFFSET } });
+ expect(msg.kind === 'message' && msg.message.timestamp).toBe(INSTANT);
+ });
+
+ test('UTC timestamps pass through byte-identical (no churn for existing imports)', () => {
+ const z = '2026-08-01T10:00:00Z';
+ const user = mapCodexLine({ type: 'event_msg', timestamp: z, payload: { type: 'user_message', message: 'hello' } });
+ expect(user.kind === 'user' && user.message.timestamp).toBe(z);
+ });
+});
diff --git a/test/upgrade-exact-tag-pin.serial.test.ts b/test/upgrade-exact-tag-pin.serial.test.ts
new file mode 100644
index 0000000000..a7fd3b4265
--- /dev/null
+++ b/test/upgrade-exact-tag-pin.serial.test.ts
@@ -0,0 +1,90 @@
+/**
+ * #5311: bare `gbrain upgrade` reported success on an exact-tag Bun Git
+ * install. `bun update` keeps a pinned tag (exit 0, nothing changes) and the
+ * #4366 mismatch check only runs when a caller passes a target version, so the
+ * user saw "Upgrade complete" while still on the old version.
+ *
+ * SERIAL + subprocess: detectInstallMethod keys on argv[1] living under
+ * node_modules and the `bun update` / `gbrain --version` calls must hit PATH
+ * shims, which Bun snapshots at process start.
+ */
+
+import { describe, test, expect } from 'bun:test';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { join, resolve } from 'path';
+import { tmpdir } from 'os';
+
+import { bunGlobalExactTagPin } from '../src/commands/upgrade.ts';
+import { VERSION } from '../src/version.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+
+async function runBareUpgrade(spec: string, observedVersion: string): Promise<{ home: string; exitCode: number; stdout: string; stderr: string }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-5311-'));
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ // `bun update` succeeds without changing anything (the pinned-tag no-op);
+ // `gbrain --version` keeps reporting the observed version.
+ writeFileSync(join(bin, 'bun'), `#!/bin/sh\necho "$*" >> '${join(home, 'bun-calls.log')}'\nexit 0\n`);
+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${observedVersion}"\n`);
+ chmodSync(join(bin, 'bun'), 0o755);
+ chmodSync(join(bin, 'gbrain'), 0o755);
+ const globalRoot = join(home, '.bun', 'install', 'global');
+ const pkgDir = join(globalRoot, 'node_modules', 'gbrain');
+ mkdirSync(pkgDir, { recursive: true });
+ writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: spec } }));
+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));
+ const driver = join(pkgDir, 'driver.ts');
+ writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(['--swap-only']);\n`);
+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };
+ delete env.BUN_INSTALL;
+ const proc = Bun.spawn([process.execPath, 'run', driver], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]);
+ return { home, exitCode: await proc.exited, stdout, stderr };
+}
+
+describe('#5311 bare upgrade on an exact-tag pin', () => {
+ test('bunGlobalExactTagPin recognizes tag pins only', () => {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-5311-pin-'));
+ try {
+ const pin = (spec: string | null) => {
+ writeFileSync(join(root, 'package.json'), JSON.stringify({ dependencies: spec === null ? {} : { gbrain: spec } }));
+ return bunGlobalExactTagPin(root);
+ };
+ expect(pin('github:garrytan/gbrain#v0.51.6.0')).toBe('github:garrytan/gbrain#v0.51.6.0');
+ expect(pin('github:garrytan/gbrain#0.51.6')).toBe('github:garrytan/gbrain#0.51.6');
+ expect(pin('github:garrytan/gbrain')).toBeNull();
+ expect(pin('github:garrytan/gbrain#master')).toBeNull();
+ expect(pin(null)).toBeNull();
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
+ test('an unchanged version on a pinned tag exits non-zero with the reinstall command', async () => {
+ const r = await runBareUpgrade(`github:garrytan/gbrain#v${VERSION}`, VERSION);
+ try {
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain('Upgrade did not take effect');
+ expect(r.stderr).toContain(`pinned to github:garrytan/gbrain#v${VERSION}`);
+ expect(r.stderr).toContain('bun add -g github:garrytan/gbrain');
+ expect(readFileSync(join(r.home, 'bun-calls.log'), 'utf-8')).toContain('update gbrain');
+ // No false "just upgraded" breadcrumb for an upgrade that never happened.
+ expect(existsSync(join(r.home, '.gbrain', 'just-upgraded-from'))).toBe(false);
+ const errors = readFileSync(join(r.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf-8').trim().split('\n').map(l => JSON.parse(l));
+ expect(errors.some(e => e.phase === 'verify-pin' && e.hint.startsWith('bun add -g github:garrytan/gbrain'))).toBe(true);
+ } finally {
+ rmSync(r.home, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ test('an unpinned install that is already current still succeeds', async () => {
+ const r = await runBareUpgrade('github:garrytan/gbrain', VERSION);
+ try {
+ expect(r.exitCode).toBe(0);
+ expect(r.stderr).not.toContain('Upgrade did not take effect');
+ } finally {
+ rmSync(r.home, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
diff --git a/test/voice-gate-judge-tier.test.ts b/test/voice-gate-judge-tier.test.ts
new file mode 100644
index 0000000000..57e04acd7b
--- /dev/null
+++ b/test/voice-gate-judge-tier.test.ts
@@ -0,0 +1,35 @@
+/**
+ * #5165 (duplicates #5303, #5357): the voice-gate judge hardcoded the
+ * Anthropic utility default, so installs without Anthropic credit failed every
+ * gate. It now resolves the utility tier through the key-aware resolver.
+ */
+
+import { describe, test, expect, afterEach } from 'bun:test';
+
+import { defaultJudge } from '../src/core/calibration/voice-gate.ts';
+import { configureGateway, resetGateway, __setChatTransportForTests, type ChatOpts } from '../src/core/ai/gateway.ts';
+import { resolveTierDefault, TIER_DEFAULTS } from '../src/core/model-config.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+afterEach(() => {
+ resetGateway();
+ __setChatTransportForTests(null);
+});
+
+describe('#5165 voice-gate judge model', () => {
+ test('an OpenAI-only install judges with the OpenAI utility model', async () => {
+ await withEnv({ OPENAI_API_KEY: 'sk-fake', ANTHROPIC_API_KEY: undefined }, async () => {
+ configureGateway({ env: { OPENAI_API_KEY: 'sk-fake' } });
+ let model: string | undefined;
+ __setChatTransportForTests(async (opts: ChatOpts) => {
+ model = opts.model;
+ return { text: '{"verdict":"conversational","reason":"ok"}', blocks: [], stopReason: 'end', usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: opts.model ?? '', providerId: 'openai' } as never;
+ });
+ const verdict = await defaultJudge({ candidate: 'hey, quick note', mode: 'nudge' as never, rubric: 'be casual' });
+ expect(verdict.verdict).toBe('conversational');
+ const expected = resolveTierDefault('utility', { OPENAI_API_KEY: 'sk-fake' });
+ expect(expected).not.toBe(TIER_DEFAULTS.utility);
+ expect(model).toBe(expected);
+ });
+ });
+});