Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Fix attach retries, dropped webhook events, cut-off stdio replies and other small CLI defects (GST-2779) (#9415)

Garry Tanc5ed4f991c3a
diff --git a/.gitignore b/.gitignore
index 0dca68dbbc..5681d07dd0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,7 +14,6 @@ bin/
# file in cwd; glob catches all of them.
*.bun-build
.gstack/*
-!.gstack/redact-allowlist
!.gstack/pregate.json
!.gstack/ship-policy.json
!.gstack/ubicloud.json
diff --git a/.gstack/redact-allowlist b/.gstack-redact-allowlist
similarity index 100%
rename from .gstack/redact-allowlist
rename to .gstack-redact-allowlist
diff --git a/behavior-changes.d/setup_codex_backups_gst2779.md b/behavior-changes.d/setup_codex_backups_gst2779.md
new file mode 100644
index 0000000000..3b12717216
--- /dev/null
+++ b/behavior-changes.d/setup_codex_backups_gst2779.md
@@ -0,0 +1 @@
+gbrain setup codex and gbrain setup codex --remove now copy each config.toml or hooks.json they change to a .bak.<timestamp> file beside it before writing, and print the backup path. Nothing else about the setup changes; delete the backups once you no longer need them.
diff --git a/changelog.d/capy-gbra-541-wave-a.md b/changelog.d/capy-gbra-541-wave-a.md
new file mode 100644
index 0000000000..f8f35387f2
--- /dev/null
+++ b/changelog.d/capy-gbra-541-wave-a.md
@@ -0,0 +1,21 @@
+**A batch of small fixes: folder attach retries, dropped webhook events, cut-off stdio replies, and clearer help and doctor text.**
+
+### Fixed
+- Retrying a managed folder attach with the same `--request-id` replays the first attempt's default-search choice instead of failing with `idempotency_conflict`.
+- Two different GitHub events on one item within 30 seconds are both processed; a redelivery of the same event is still deduplicated.
+- Local `serve` and the thin-client bridge deliver a large stdio reply in full when stdin closes right after it.
+- Atoms stamped by `repair visibility` can be adopted by a later generation again, without widening their visibility (#9386).
+- A migration that keeps failing gets the `migrations_pending` notice with the `apply-migrations --force-retry <version>` step.
+- Doctor's `derived_visibility` check counts only active sources, so it no longer suggests a repair that finds nothing.
+- `repair purged-page-facts`: a preview that approves nothing prints an apply command that reports nothing to do.
+- A DNS failure on a Supabase pooler URL points at this machine's DNS and network instead of a paused project (#8531).
+- `sources status --json` prints each held file's fix with the `--brain` pin, so it runs as written (#9319).
+- A hosted install asking setup for the skill resolver is told the command that works without a local brain (#9245).
+
+### Changed
+- `gbrain setup codex` and `--remove` keep a `.bak.<timestamp>` copy of each `config.toml` or `hooks.json` they change and print its path.
+- `gbrain setup codex` prices the search-mode cost matrix with OpenAI models.
+- `embed --help` names the `--stale --facts --source <id>` form for facts saved with `remember`; `upgrade --help` no longer mentions a postinstall step; doctor's consent wording says gbrain makes no provider request on its own.
+- The enrich skill says to leave out empty sections instead of writing `[No data yet]` (#7061).
+
+<!-- behavior-change: setup_codex_backups_gst2779 -->
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 1b5c502bf4..6ec181d5e4 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -1024,7 +1024,7 @@ names — reasons may be added, never renamed or removed). All 16:
| `ssl_required` | the server demands SSL — `?sslmode=require` rewrite (rewrite tier) |
| `pool_exhausted` | 53300 / session-slot exhaustion — [pool sizing](#pool-sizing) guidance: `export GBRAIN_POOL_SIZE=6` per long-running process, fewer processes |
| `conn_refused` | ECONNREFUSED — docker-start arm for gbrain's own container; pooler rewrite for Supabase direct URLs |
-| `dns_failed` | ENOTFOUND/EAI_AGAIN — one bounded retry; persistent + Supabase suggests a paused project |
+| `dns_failed` | ENOTFOUND/EAI_AGAIN — one bounded retry; persistent on a Supabase direct host suggests a paused project, while on a Supabase pooler URL it points at this machine's DNS and network (the shared pooler host resolves whatever a project's state) |
| `network_unreachable` | ENETUNREACH/ETIMEDOUT — often an IPv6-only direct host; session-pooler rewrite |
| `conn_dropped` | 08xxx / reset mid-connection — transient, bounded reconnect |
| `server_starting` | "the database system is starting up" — retry shortly |
diff --git a/docs/GBRAIN_RECOMMENDED_SCHEMA.md b/docs/GBRAIN_RECOMMENDED_SCHEMA.md
index 81d73ab57c..17f6781e82 100644
--- a/docs/GBRAIN_RECOMMENDED_SCHEMA.md
+++ b/docs/GBRAIN_RECOMMENDED_SCHEMA.md
@@ -306,7 +306,7 @@ whole `Meeting: Agreed on the Q2 plan` text is the summary, because `Note: …`
and `TODO: …` are ordinary prose. gbrain's own writers (`add_timeline_entry`,
the extractors) keep writing the em dash.
-All sections are optional — include what you have, leave empty sections as `[No data yet]` rather than omitting them. **The structure itself is a prompt for future enrichment.** When a section says `[No data yet]`, the agent knows what to look for next time it encounters this person.
+All sections are optional — include what you have and omit a section until there is something to put under it (`gbrain lint` flags an empty section, `[No data yet]` included). **The template itself is a prompt for future enrichment.** A section the page lacks tells the agent what to look for next time it encounters this person.
The principle: facts are table stakes. Context is the value.
@@ -631,7 +631,7 @@ Each cron job is essentially: "wake up, read a skill, do the work, post results
**Weekly:**
- **Brain lint** — run the full maintenance pass: contradictions, stale pages, orphans, missing cross-references, MECE filing violations. Post a report.
-- **Enrichment sweep** — find brain pages that haven't been enriched in 90+ days, or pages with many `[No data yet]` sections. Queue them for re-enrichment.
+- **Enrichment sweep** — find brain pages that haven't been enriched in 90+ days, or pages missing many of their type's template sections. Queue them for re-enrichment.
- **Contact sync** — pull recent additions from your contacts, cross-reference with brain. Create pages for significant new contacts.
### How crons feed the brain
@@ -943,7 +943,7 @@ RAG re-derives knowledge from scratch on every query. The brain pre-computes syn
- **Cross-references are pre-built.** You don't need the LLM to discover that Person A works at Company B and was in Meeting C — that's already linked.
- **Contradictions are pre-flagged.** When new data conflicts with old data, the agent resolves or flags it during ingest, not at query time.
- **The compilation is persistent.** Each source ingested makes the brain richer. Nothing is thrown away or re-derived.
-- **The structure itself is a prompt.** Empty sections ("What They Believe: [No data yet]") tell the agent what to look for next.
+- **The template itself is a prompt.** A template section the page lacks ("What They Believe") tells the agent what to look for next.
## Page Lifecycle
diff --git a/docs/architecture/key-files/agent-bootstrap-more.md b/docs/architecture/key-files/agent-bootstrap-more.md
new file mode 100644
index 0000000000..d8b548ffdd
--- /dev/null
+++ b/docs/architecture/key-files/agent-bootstrap-more.md
@@ -0,0 +1,5 @@
+# Agent bootstrap cluster (the paste-in desktop-agent install) (more)
+
+[Subsystem index](../KEY_FILES.md) · [Previous entries](agent-bootstrap.md).
+
+- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; `recognizedOnly` when every non-blank line parsed and was a session header, so hook.ts ends a Codex session opened and closed with no prompt as `ok`/`empty_session` (no status alert, no corpus file) while any unknown or torn record with zero turns stays `parser_drift`; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.
diff --git a/docs/architecture/key-files/agent-bootstrap.md b/docs/architecture/key-files/agent-bootstrap.md
index 1d4853a780..28fb22d63e 100644
--- a/docs/architecture/key-files/agent-bootstrap.md
+++ b/docs/architecture/key-files/agent-bootstrap.md
@@ -19,7 +19,7 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/bootstrap/hooks.ts` + `host-specs.ts` — host wiring. `host-specs.ts` is the ONE module owning host-format assumptions (dated spec targets with verifiedAt + doc references: claude-code hooks/settings shapes incl. the 10,000-char hook-output cap and the five hook events; codex mcp-add argv, the streamable-HTTP `url` + `http_headers = { Authorization = "Bearer <t>" }` config shape (loads on codex-cli 0.147.x and 0.149.x; inline `bearer_token` is rejected at config load by >=0.149), `codexConfigPath()` honoring CODEX_HOME, `claudeUserSettingsPath()` honoring CLAUDE_CONFIG_DIR/$HOME explicitly — Bun's homedir() ignores a remapped HOME, which would point sandboxed writers at the operator's real settings; the shared resolution lives in the private `claudeConfigBase()` (CLAUDE_CONFIG_DIR-else-$HOME-else-homedir(), the directory playing the role of `~/.claude` — NOT for `claudeUserMcpConfigPath`, whose default lives at the HOME level as `~/.claude.json`), which also feeds `claudeUserSkillsDir()`/`claudeProjectSkillsDir()` (native SKILL.md discovery, the harness-bridge install targets; user scope attested, project scope provisional-from-docs) — and the opencode shapes: `opencodeConfigDir`/`opencodeGlobalConfigPath` (XDG-only resolution; the `.jsonc` name preferred for parity with `opencode mcp add`; OPENCODE_CONFIG/_CONFIG_DIR/_CONFIG_CONTENT deliberately NOT honored — observed INERT in opencode 1.18.18, honoring them would write registrations into a file opencode never reads), `opencodeProjectConfigPath`, `opencodeGlobalSiblingPath` (the OTHER member of the global filename pair — writers reconcile `mcp.<name>` across it because opencode merges both), and `OPENCODE_HAS_HOOKS=false` — 'gbrain does not wire opencode's plugin/event system yet', not 'opencode has no hooks'). The settings writers are path+marker parameterized: `writeClaudeHooksAt`/`removeClaudeHooksAt` take an explicit settings file and a marker VALUE (workspace installs stamp `bootstrap-v1` in `.claude/settings.local.json`; harness installs stamp `bootstrap-harness-v1` in user-scope settings or a --project dir — the two coexist and each removal strips only its own; `refuseOnForeignGbrainMarker` blocks same-file double-wiring), fail-closed on broken JSON (a settings file that doesn't parse THROWS with the path — a writer must never relocate or overwrite a config it can't read), mode-preserving realpath-resolved atomic writes (dotfile symlinks survive), and fixed-or-timestamped backups. `addPermissionsAllowEntry`/`removePermissionsAllowEntry` manage the harness lane's `mcp__<name>` headless pre-approval with set semantics and NO marker (ownership rides the harness receipt; foreign entries always survive); the add path fails CLOSED when an existing `permissions` key or `permissions.allow` carries a shape it doesn't understand (host security policy is never rewritten on a guess), while removal leaves shapes it can't read untouched and reports nothing-to-remove. `registerClaudeMcp`/`registerCodexMcp` build argv only (Claude Code takes `--scope`, project default; Codex has no scope flag — `codex mcp add` is always user-global; `-e`/`--env GBRAIN_SOURCE` so MCP writes land in the workspace source, and the serve argv from `stdioServeArgv` in `src/core/mcp-registration.ts`: `--surface starter` by default so a pre-existing `mcp_surface: verbs` config row can't narrow the registration, or the `surface` the caller passes — `bootstrap hooks --surface`, or an existing entry's form carried over on replacement, `null` meaning a bare `serve`). `bootstrap hooks` never narrows: a matching registration is kept, `verifyMcpTargetsWorkspace` returns the existing entry's surface (`registeredSurface`) and the mismatch re-add keeps it, and the opencode writer keeps the existing command's form unless `--surface` is given. The opencode workspace lane execs NOTHING — registration is the direct `opencode-json.ts` write with an INVERTED scope default (user-global; opencode spawns project-config servers with no trust prompt, so `MCP_SCOPE=project` is an explicit opt-in that writes the committed-candidate `opencode.json` with a PATH-resolved command and prints the sharing warning), verification is config parse-back + a best-effort `opencode mcp list --pure` probe — the probe spawns via a held Bun.spawn handle from a fresh EMPTY temp-dir cwd (never the invoking cwd: opencode merges a project opencode.json from cwd and spawns its servers with no trust prompt), is SKIPPED entirely for project scope (printed note; parse-back is authoritative) and on plugin-bearing configs (`mcp list` is a code-execution surface), and on timeout actually kills the child (SIGTERM → SIGKILL, bounded pipe drain, code 124 into the could-not-confirm branch; `probeSpawn` is the injectable seam). User-scope writes also reconcile the SIBLING global filename first (ours → removed with a note; foreign → refuse naming both files) so a merge-shadow registration can never survive. `detectHarness` probes `OPENCODE`/`OPENCODE_PID` (set in opencode's bash-tool children, observed 1.18.18). `ClaudeHookEnv.GBRAIN_SEAT` (#4618) renders `GBRAIN_SEAT=<label>` into local-carrier hook commands (never the committed carrier); `writeClaudeHooksAt` keeps the seat a prior install of the same marker rendered when the caller passes none, and `''` clears it. `parseSeatFlags` validates `--seat <label>` / `--no-seat` for `bootstrap hooks` and `bootstrap harness` and returns a `note` where a seat cannot be rendered (codex, opencode, the cloud committed carrier). Pinned by `test/bootstrap-seat.serial.test.ts`. Harness-lane hook ownership does not rest on the marker alone: Claude Code can drop unknown keys when it rewrites settings.json, so `parseClaudeHookCommand` (the inverse of `buildClaudeHookCommand`: shellQuote-aware word split, env keys limited to the four the builder writes, each at most once, an absolute launcher, nothing after `hook <sub>`, and a re-render that must equal the input) feeds `classifyHarnessHook(entry, event, identity)` → `marked` / `command` (unmarked, exactly the harness hook for THAT event, launcher/source/seat inside a `HarnessHookIdentity`, no GBRAIN_HOME) / `unowned` (harness-looking under a wired event but edited or another install's; never deleted) / null. `harnessHookIdentity(receipt, target, current)` merges the running install with the receipt's recorded `launcher`/`seat` and source binding (seats constrain only when recorded). `writeClaudeHooksAt({identity})` replaces owned unmarked entries like marked ones (one entry per event on re-run, seat carried from marked then owned entries) and notes `harness_hook_unowned` lookalikes; `removeClaudeHooksAt(path, marker, {identity, dryRun})` returns `unmarked` (event + why, never command text) and `unowned` events; `scanHarnessHookCarrier` is the read-only per-event census (doctor, `--status`, the cross-HOME guard with identity `'any'`); `groupsCarryGbrainHook` feeds `hook_carrier_overlap`. The workspace lane (bootstrap-v1) keys on the marker alone. Pinned by `test/bootstrap-harness-hook-ownership.test.ts`. `hookEntryHash` (sha256 over `type`, `command`, `timeout`; the marker excluded, so a dropped marker keeps the hash) backs the opt-in `ownedEntryHashes` option on both writers: with it a marker match alone never replaces or removes an entry, edited marked entries come back in `preserved`, and unmarked entries with an owned hash are still ours (`gbrain setup`); without it every existing caller keeps marker-keyed ownership.
- `src/core/bootstrap/harness-hooks.ts` — the receipt-aware glue for harness hook entries without their marker: `removeHarnessHooksTarget` (one hooks target: owned marked + unmarked entries removed and listed by event; a surviving lookalike prints the `harness_hook_unowned` notice block with `next: tell_user_to_run` and throws so the target stays failed and `--remove` exits 1), `previewHarnessRemoval` (`--remove --dry-run`: every target's would-be action, nothing written, receipt untouched), `harnessHooksPresent` (the cross-HOME `--project` guard: marked, unmarked or edited-by-shape `unowned` entries, any install; W4.8) and `harnessHookCarrierStatus` (`--status` text line + `hook_carriers` JSON).
- `src/core/setup/capabilities.ts` + `src/core/setup/claude-code.ts` — `gbrain setup`'s data and Claude Code writer. `capabilities.ts` is the versioned harness × transport table (`SETUP_CAPABILITY_TABLE_VERSION`; per row `setup`, `pull`, `push`, `read_events`, `capture_events`, `docs`); push is `native-pending` or `unsupported` on every row until an observed injected event proves it. `claude-code.ts` owns entries by exact hash through the connection receipt `.gbrain-connection-claude-code-<name>[-project-<hash>].json` beside `~/.claude.json` (`connection: 'local-stdio'`, `entry_hash`/`pending_entry_hash`, `hooks.{owned,pending,edited}`, `consent`, `gbrain_home`; a receipt with `client_id` is a hosted one and is never adopted). The MCP entry (`{type:'stdio', command, args, env}`, user scope `mcpServers` or project scope `projects[<dir>].mcpServers`) is written directly; hooks go through `writeClaudeHooksAt`/`removeClaudeHooksAt` with marker `GBRAIN_SETUP_MARKER_VALUE` and `ownedEntryHashes`. `applyClaudeSetup` (under the config-dir bootstrap lock) writes the receipt `prepared` first, then the brain (`beforeMcp`), the MCP entry, the hooks and `installed`, each step recording its hash so a resume never duplicates; an unchanged install writes nothing. An owned event whose recorded hash vanished while a marked entry remains is `edited`: preserved, reported, and skipped by later runs. `removeClaudeSetup` deletes only hash-matched entries (adopted entries stay), keeps a `removed` receipt when an edited entry survives, and otherwise deletes the receipt. The codex row (table version 2) is `supported` with `push: 'native-verified'` and a `push_evidence` string (codex-cli 0.162.1, observed UserPromptSubmit injection into fresh native sessions, 3/3, with a `--no-hooks` control); `entryHash` is `ownedEntryFingerprint` from adopted-connections.ts.
-- `src/core/setup/codex.ts` — `gbrain setup codex`'s writer. Owns three kinds of entry, each by `ownedEntryFingerprint` (sha256 over canonical JSON of the exact parsed entry) recorded per entry in `$CODEX_HOME/.gbrain-connection-codex-<name>.json` (`setup_receipt_version: 2`: the claude-code receipt fields plus `hooks_path`, `gbrain_home_env` and `trust.{owned,pending,edited}` keyed by event as `{key, hash}`; a `client_id` receipt is hosted and never adopted): the stdio `[mcp_servers.<name>]` table (`command`, `args`, inline `env`), one hooks.json group per wanted event (`codexSetupHookGroup`), and one `[hooks.state."<hooks.json>:<event>:<index>:0"]` trust table per group. `applyCodexSetup` (under the CODEX_HOME bootstrap lock) writes in a crash-recoverable order: receipt `prepared` (the consent record and pending fingerprints) → brain (`beforeMcp`) → MCP table → hooks.json groups (inert until trusted) → stale owned trust tables removed, wanted ones appended (activation last) → `installed`; each step records its fingerprints so a resume never duplicates. Compare-and-swap everywhere: a group whose recorded hash vanished while a this-install setup-lane group remains is `edited` (preserved, reported, never trusted by setup); a trust table at setup's key with a different value is preserved (`conflict`/`edited`); an identical pre-existing MCP table is `mcp_adopted` and kept on removal. `removeCodexSetup` runs trust → hooks → MCP → receipt and keeps a `removed` receipt when an edited entry survives. `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks|trust` is the crash seam. Pinned by the codex blocks of `test/setup.test.ts`.
+- `src/core/setup/codex.ts` — `gbrain setup codex`'s writer. Owns three kinds of entry, each by `ownedEntryFingerprint` (sha256 over canonical JSON of the exact parsed entry) recorded per entry in `$CODEX_HOME/.gbrain-connection-codex-<name>.json` (`setup_receipt_version: 2`: the claude-code receipt fields plus `hooks_path`, `gbrain_home_env` and `trust.{owned,pending,edited}` keyed by event as `{key, hash}`; a `client_id` receipt is hosted and never adopted): the stdio `[mcp_servers.<name>]` table (`command`, `args`, inline `env`), one hooks.json group per wanted event (`codexSetupHookGroup`), and one `[hooks.state."<hooks.json>:<event>:<index>:0"]` trust table per group. `applyCodexSetup` (under the CODEX_HOME bootstrap lock) writes in a crash-recoverable order: receipt `prepared` (the consent record and pending fingerprints) → brain (`beforeMcp`) → MCP table → hooks.json groups (inert until trusted) → stale owned trust tables removed, wanted ones appended (activation last) → `installed`; each step records its fingerprints so a resume never duplicates. Compare-and-swap everywhere: a group whose recorded hash vanished while a this-install setup-lane group remains is `edited` (preserved, reported, never trusted by setup); a trust table at setup's key with a different value is preserved (`conflict`/`edited`); an identical pre-existing MCP table is `mcp_adopted` and kept on removal. `removeCodexSetup` runs trust → hooks → MCP → receipt and keeps a `removed` receipt when an edited entry survives. Both keep `<file>.bak.<timestamp>` of each existing config.toml or hooks.json they changed (also on a failed run) and name it in a note. `GBRAIN_SETUP_ABORT_AFTER=receipt|mcp|hooks|trust` is the crash seam. Pinned by the codex blocks of `test/setup.test.ts`.
- `src/core/setup/local-receipts.ts` — read-only view of this install's live local-stdio setup receipts (`.gbrain-connection-*.json` beside `~/.claude.json` and in `CODEX_HOME`; kept only when `connection: 'local-stdio'`, a numeric `setup_receipt_version`, `gbrain_home === configDir()` and status `prepared`/`installed`). Engine-free, imports no harness writer. `providerDeclineRecord()` (a recorded `providers: declined`, opt-outs win) gates OpenAI model discovery and doctor's provider probe; `claudeCodeSpawnsServe(cwd)` (an installed claude-code receipt, user scope or a project receipt for exactly `cwd`) tells the SessionStart hook that Claude Code is starting a stdio serve.
- `src/core/bootstrap/plugin-lanes.ts` — plugin-lane detection (`*PluginProvidesName`, `*AnyRegistrationExists`, re-exported by harness.ts; variants count as `gbrain`) plus `enabledPluginLanes(name)`, read by `plugin_lane_collision`/`harness_wiring`. Config, not health. `pluginHookYields`: yield to no-hooks consent, another lane (Codex: trusted, enabled), a higher `GBRAIN_PLUGIN`.
- `src/core/bootstrap/codex-hooks.ts` — the codex `hooks.json` writer (SessionEnd capture lane), built entirely on the dated `CODEX_HOOKS_SPEC_TARGET` (verified 2026-08-25 against pinned codex-cli 0.147.0, live + tag-source evidence; re-run the observation gate on codex version bumps). The three load-bearing facts: hooks.json is TOP-LEVEL deny-unknown-fields (ownership rides the legal `description` slot + a command-substring token, never a `_gbrain` key); user-layer hooks are TRUST-GATED and fail SILENTLY (the writer lands BOTH the hooks.json entry AND its `[hooks.state."<path>:session_end:<g>:<h>"].trusted_hash` config.toml entry — sha256 of the recursively-key-sorted compact canonical JSON of the normalized handler identity — inside a gbrain-managed marker block, backing config.toml up to `.hooks.bak` so it never clobbers the MCP writer's `.bak` rollback anchor); SessionEnd handlers are hard-killed at 3s (the command captures stdin to a mktemp file and detaches a nohup grandchild running the real `gbrain hook session-end --harness codex` — live-verified end-to-end). Deliberately NO `GBRAIN_SOURCE` in the command: hooks.json is user-global, so a baked source would stamp every codex session on the machine; session-end resolves everything from the payload. a fresh install APPENDS our group last while a re-run REPLACES it IN PLACE (a single well-formed install never shifts a foreign group's trust index; dropping DUPLICATE gbrain groups can shift foreign groups sitting after them — the writer prints a note naming the re-trust); the whole command is wrapped in a top-level `sh -c '…' <bin>` so a non-POSIX $SHELL (fish/csh) never parses the POSIX script; the foreign-trust-entry guard is a tolerant [hooks.state…] header match (not byte-exact); a golden known-answer hash vector pins the canonical recipe; removal also deletes the gbrain description when byte-identical to ours and NOTES the inherent index shift for foreign groups that sat after ours; unparseable hooks.json is never touched, on write or removal; the residual stale-trust-index case (user reorders their own groups) degrades to silent non-execution, which doctor's `codex_hooks_never_fired` rung names. Pinned by `test/codex-hooks-writer.test.ts`. `codexHookTrustHash(eventName, command, timeout)` is the generalized recipe (re-read against openai/codex rust-v0.162.1 `hook_hash` + `version_for_toml`; a known-answer vector from trust entries a live codex-cli 0.162.1 executed pins it in `test/setup.test.ts`). The setup lane (`CODEX_SETUP_EVENTS` SessionStart/UserPromptSubmit 15s, SessionEnd 3s) is hash-owned: `codexSetupHookGroup` renders `env GBRAIN_HOOK_LANE=setup [GBRAIN_HOME=…] [GBRAIN_SOURCE=…] <bin> hook <sub> --harness codex` (SessionEnd prefixes the detached capture command), `codexHookCensus` fingerprints every group and tags its lane, `writeCodexSetupHooks` replaces owned groups in place / appends / drops only owned groups (notes any index shift), and the token-owned bootstrap writer's `isOurGroup` skips groups carrying `GBRAIN_HOOK_LANE=setup`, so bootstrap never claims or strips setup's groups.
@@ -35,6 +35,5 @@ User-facing contract: `docs/guides/bootstrap.md`. Runbook the paste block fetche
- `src/core/transcripts/claude-code-jsonl.ts` — the Claude Code transcript parser as a dated spec-target (tool_use/tool_result/thinking/image/sidechain/summary/compact-boundary shapes; placeholders for non-text content). `recognizedOnly`: whole file read, every line parsed, no conversation message, some session scaffolding (session-end: `empty_session`). Both the hook-tail and full-session parsers skip root `isSidechain`, `isMeta`, or `isCompactSummary` exactly `true`; nested markers and truthy non-booleans do not exclude a turn. User text with a non-empty string root `origin.kind` other than `'human'` is excluded; missing, empty, or unstructured origins stay compatible, without guessing from message text. Assistant text and non-text placeholders remain eligible, while skipped metadata entries also contribute no collected tool calls. `test/claude-code-jsonl-origin.test.ts` uses synthetic fixtures, not new live-harness validation. `genuineUserTurnIndexes` separately records accepted user-role turns containing real text blocks (harness tags and paste blocks removed first), because Claude stores tool-result-only entries with `role:'user'`; archival consumers keep every placeholder while prompt-only consumers select by structure. Also extracts `injectedContextBlocks` — the `hook_additional_context` attachment lines a gbrain hook previously injected (verified live against claude CLI 2.1.224), plus a SessionStart `hook_success` attachment's `content` from the gbrain envelope on (session-start stdout, #7026; marker-filtered, so a foreign hook's blocks are excluded and another tool's output can't suppress volunteering — a same-user mislabeling guard, not an authenticity check), the user-prompt hook's cross-turn dedupe input; `confineTranscriptPath` (contained under `~/.claude/projects`, `.jsonl`, lstat-rejects symlinks, byte cap; under WSL, a Windows drive-literal `transcript_path` — Claude Code on the Windows host invoking hooks via `wsl.exe` — is translated through `src/core/wsl-paths.ts` and then held to the SAME confinement, rooted Windows-side, so translation never widens what a hook may read). Fixtures: `test/fixtures/conversation-formats/claude-code.jsonl` (synthetic, privacy-guarded) + `test/fixtures/hook-transcript.jsonl` (real captured hook round-trip). `parseTranscript` additionally returns `toolCalls`, but collection is OPT-IN (`collectToolCalls: true`; the bare parse — every per-prompt lane — collects nothing, so tool INPUTS are never retained for users who never opted in): the tool name + input args for every `tool_use` block, oldest → newest, each joined to its `tool_result` outcome by `tool_use_id` and then stripped of that id so no transcript-internal identifier reaches a consumer; every STRING in a collected input is bounded to `TOOL_CALL_VALUE_MAX_CHARS` (32k) with an explicit `…[N chars omitted]` marker (`capToolCallInput`, shared with the codex lane — one receipt-size ceiling for every harness). It is a parallel extraction, never a change to the placeholder-only archival rendering, which is load-bearing for the token-budget-constrained ambient-recall path; existing callers that ignore the field see no behavior change.
- `src/core/transcripts/pasted-content.ts` — #5812, the ONE Claude Code paste detector (`<pasted_content id="…">…</pasted_content id="…">`, tag shape from a real 2.1.287 transcript; depends on that harness format). `stripPastedContent` removes closed blocks and an unclosed tail only when the opening tag has the exact harness shape, scanning with `indexOf` (no lazy regex); `stripPastedContentFromCorpus` strips inside each `[user]` block of the `toCorpusText` rendering, never across the flattened corpus, so an unclosed paste ends with its turn. Consumers: the writeback gate (banked text), `isGenuineUserText` in the parser (classification only; turn, corpus, segment and ingest text keep the paste), and `corpusTextForExtraction` (`corpus-segments.ts`: a `.wb-` file is one turn, other corpus files per block) used by the sweep, the checkpoint harvest and dream `extract_atoms`. `synthesize` keeps pastes. Tests: `test/transcripts-pasted-content.test.ts`, `test/facts/writeback-gate.test.ts`, `test/extract-atoms-pasted-content.test.ts`.
- `src/core/transcripts/grok.ts` — the Grok Build (grok CLI) transcript adapter: one session directory (`~/.grok/sessions/<url-encoded-cwd>/<uuid>/chat_history.jsonl`) = one session; `GROK_HOME` relocates the root. Turn selection is STRUCTURAL (`mapGrokLine`, exported so the dated `SPEC_TARGET` mapping is pinned): user turns are `type:'user'` text blocks WITHOUT `synthetic_reason` (injected system_reminder/task_completed rows are `typed`, i.e. intentionally text-free, as are tool_result-only user arrays); assistant turns need non-empty string `content` (tool-only rows — `content` ''/null WITH `tool_calls` — are `typed`); system/reasoning/tool_result/backend_tool_call rows are `typed`; unknown row types `skip`. A recognised HUMAN-turn row whose content this parser cannot decode (user `content` missing / non-string / non-array / an array holding non-block entries; assistant non-string `content` with no `tool_calls`) is `malformed` and counted as SKIPPED, never typed, so a file made only of such rows is never `expectedEmpty` — the ingest drift signal fires (`bytesRead > 0`, sessions 0, `cleanScan=false`, watermark frozen) and `zeroSessionsReason` names the malformed row count, instead of an upstream schema change silently advancing the watermark past whole conversations. `chat_history.jsonl` carries NO per-message timestamps: session times come from the sibling `summary.json` (`created_at`/`last_active_at`; a malformed summary is ignored, an unparseable date is never fabricated) and, because grok writes `summary.json` at session END, an in-progress session or partial rsync falls back to the log file's own mtime — a real filesystem time — with `raw.timestamp_source` stamped `'summary.json'` vs `'file_mtime'` so consumers can tell them apart (without the fallback the render refusal would freeze the `--since-last` watermark for the whole grok root). Every message carries the session bounds (last message = `last_active_at`, the rest = start). Session id: summary → UUID dir name → `stableIdFromPath` (a sha256 prefix of the log path, never the bare `chat_history` basename, which would collapse every such session onto one page). Sidecars (updates.jsonl, events.jsonl, rewind_points.jsonl, summary.json, prompt_history.jsonl) are not sessions — discover.ts's grok-sidecar filter is scoped to PROVEN grok trees and the head sniff rejects claude-family keys (grok detection runs after claude-code; an oversized system head still detects through the truncated-line sniff); a percent-encoded cwd segment that fails to decode yields `cwd` undefined with the session id intact.
-- `src/core/transcripts/capture-spec.ts` + `codex-hook-lane.ts` — the per-harness session-end capture seam. `capture-spec.ts`: the satisfies-anchored `CAPTURE_SPECS` record ({confine, parse, discover?}) for the STDIN-DRIVEN lanes (claude-code, codex); `captureSpecFor()` resolves unknown/undefined/opencode to the claude spec (golden-pinned by `test/codex-hook-lane.test.ts`); openclaw is deliberately NOT a member (its lane is in-process, trusted-plane — see context-engine.ts). `codex-hook-lane.ts`: `confineCodexTranscriptPath` (the same S3#8 ladder as the claude root, pinned at BOTH `codexSessionsDir()` AND `codexArchivedSessionsDir()` — codex MOVES a rollout into the flat `archived_sessions` store on archive, so fencing only the live store refused a still-valid path; both CODEX_HOME-resolved since the spawner IS codex; an explicitly pinned test-seam `root` stays single-root; ENOENT/ENOTDIR on the path is `missing_path` — the rung hook.ts gates its discovery fallback on — while `unreadable` is reserved for EACCES/IO faults, so the codex session-end heartbeat reason for a nonexistent `transcript_path` after a failed discovery is `transcript_missing_path`, not `transcript_unreadable`; no WSL branch v1), `parseCodexHookTranscript` (ParsedTranscript shape over the adapter's exported `mapCodexLine`; same OPT-IN `collectToolCalls` contract as `parseTranscript`, and the same `capToolCallInput` bound on observed args; head+tail over budget so session_meta identity survives; `recognizedOnly` when every non-blank line parsed and was a session header, so hook.ts ends a Codex session opened and closed with no prompt as `ok`/`empty_session` (no status alert, no corpus file) while any unknown or torn record with zero turns stays `parser_drift`; tool calls from the OBSERVED args keys — `custom_tool_call.input` fixture-verified, `function_call.arguments` source-verified at rust-v0.147.0; tolerant JSON-string parse; NO `result` join — 0.147.0 persists no success flag on `*_output` rows; `compacted` rows become boundary positions), and `discoverNewestCodexRollout` (bounded newest-first walk over the dated live store, then a flat pass over the archived store under the SAME 4096 dirent cap — skipped once the cap trips; id-in-filename match, and an id-matched archived hit keeps `transcript_discovered` (never relabelled `_newest`, which hook.ts reads as a guess and bars from the relay); symlink-reject — the fallback for `transcript_path: null` or a moved rollout, and the seam for SIGKILL'd sessions, which never fire SessionEnd). Engine-free by construction; never imports discover.ts. Pinned by `test/codex-hook-lane.test.ts` + `test/codex-hook-lane-archived.test.ts` + the runHook-driven matrix in `test/memorable-relay.serial.test.ts`.
-[Continue this subsystem](agent-bootstrap-continued.md).
+[Continue this subsystem](agent-bootstrap-continued.md) · [More entries](agent-bootstrap-more.md).
diff --git a/docs/guides/repair.md b/docs/guides/repair.md
index 715af2d5fc..f3de1c8b2b 100644
--- a/docs/guides/repair.md
+++ b/docs/guides/repair.md
@@ -5174,7 +5174,9 @@ the harness configuration, or a `gbrain connect --install` receipt), and no
because sessions would then read an empty brain while useful memory stays on
the hosted one. Manage that connection with `gbrain connect <mcp-url>
--harness <claude-code|codex> --install`; `gbrain doctor --only harness_wiring` shows
-which brain the registration reaches.
+which brain the registration reaches. The skill resolver needs no local brain:
+set it up there with `gbrain setup <claude-code|codex> --skills-index-only
+--skill-loading resolve`.
### Turn hook not loaded
diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.md
index bc49de25cf..8922e6ce2b 100644
--- a/docs/protocol/MCP_META_CHANNELS.md
+++ b/docs/protocol/MCP_META_CHANNELS.md
@@ -130,8 +130,8 @@ source. Over HTTP that is the token's or client's write source (the first id
of its source grant), or `default` with no grant. Over stdio it is the source
the server resolved (`GBRAIN_SOURCE`, `.gbrain-source`, then `default`). With
a `_meta.session_id`, the block holds that session's facts. Without one, or
-when the session has none, it holds the source's facts from the last 24 hours,
-unless the host set `context.hot_memory.session_only`. A remote caller only
+when the session has none, it holds the source's facts from the last 24 hours
+(`context.hot_memory.session_only` does not narrow this key). A remote caller only
ever gets facts with `visibility: world`, and never a fact from a source its
grant can't read.
diff --git a/llms-full.txt b/llms-full.txt
index 43f368c73d..febd8e7707 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5822,7 +5822,7 @@ names — reasons may be added, never renamed or removed). All 16:
| `ssl_required` | the server demands SSL — `?sslmode=require` rewrite (rewrite tier) |
| `pool_exhausted` | 53300 / session-slot exhaustion — [pool sizing](#pool-sizing) guidance: `export GBRAIN_POOL_SIZE=6` per long-running process, fewer processes |
| `conn_refused` | ECONNREFUSED — docker-start arm for gbrain's own container; pooler rewrite for Supabase direct URLs |
-| `dns_failed` | ENOTFOUND/EAI_AGAIN — one bounded retry; persistent + Supabase suggests a paused project |
+| `dns_failed` | ENOTFOUND/EAI_AGAIN — one bounded retry; persistent on a Supabase direct host suggests a paused project, while on a Supabase pooler URL it points at this machine's DNS and network (the shared pooler host resolves whatever a project's state) |
| `network_unreachable` | ENETUNREACH/ETIMEDOUT — often an IPv6-only direct host; session-pooler rewrite |
| `conn_dropped` | 08xxx / reset mid-connection — transient, bounded reconnect |
| `server_starting` | "the database system is starting up" — retry shortly |
diff --git a/plugin-variants/gbrain-coding/skills/enrich/SKILL.md b/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
index 35a0912ac6..40b9b32b14 100644
--- a/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
+++ b/plugin-variants/gbrain-coding/skills/enrich/SKILL.md
@@ -181,7 +181,7 @@ the raw data shows exactly what the API returned.
placeholder.
4. Fill compiled truth with citations
5. Add first timeline entry
-6. Leave empty sections as `[No data yet]` (don't fill with boilerplate)
+6. Omit sections with nothing to put under them (`gbrain lint` flags empty ones)
7. In a batch, create the pages other pages will link to first. A link to a
page that doesn't exist yet is recorded as a wanted page and becomes an
edge once that page is written (`gbrain wanted` lists them).
diff --git a/plugin/skills/enrich/SKILL.md b/plugin/skills/enrich/SKILL.md
index 35a0912ac6..40b9b32b14 100644
--- a/plugin/skills/enrich/SKILL.md
+++ b/plugin/skills/enrich/SKILL.md
@@ -181,7 +181,7 @@ the raw data shows exactly what the API returned.
placeholder.
4. Fill compiled truth with citations
5. Add first timeline entry
-6. Leave empty sections as `[No data yet]` (don't fill with boilerplate)
+6. Omit sections with nothing to put under them (`gbrain lint` flags empty ones)
7. In a batch, create the pages other pages will link to first. A link to a
page that doesn't exist yet is recorded as a wanted page and becomes an
edge once that page is written (`gbrain wanted` lists them).
diff --git a/scripts/check-install-ref.ts b/scripts/check-install-ref.ts
index 27e8e62e1b..a1466c36ec 100644
--- a/scripts/check-install-ref.ts
+++ b/scripts/check-install-ref.ts
@@ -7,7 +7,8 @@
* not a channel ref, and is left alone) must name INSTALL_REF; `#master` is never an install ref;
* - raw fetches of the install artifacts (BOOTSTRAP_FOR_AGENTS.md, scripts/setup-in-agent.sh) must use INSTALL_REF;
* - the setup helper's `gbrain_install_ref=` must equal INSTALL_REF;
- * - TypeScript sources never spell the ref: they import INSTALL_PIN / INSTALL_RAW_BASE.
+ * - TypeScript sources never spell the ref: they import INSTALL_PIN / INSTALL_RAW_BASE. behavior-changes.d rows
+ * count as TypeScript, because the release folds their text into src/core/behavior-change-notice.ts.
*
* `--write` rewrites the text surfaces to INSTALL_REF (the flip after a stable promotion); TypeScript violations are
* listed, never rewritten. Exit 1 on drift.
@@ -26,13 +27,14 @@ const EXACT_PIN = /^v|^[0-9]|^[0-9a-f]{7,40}$/;
const OWNER = 'src/core/install-ref.ts';
const skipped = (file: string) => file === 'CHANGELOG.md' || file.startsWith('test/') || file === OWNER;
+const foldedIntoTs = (file: string) => file.endsWith('.ts') || (/^behavior-changes\.d\/[^/]+\.md$/.test(file) && file !== 'behavior-changes.d/README.md');
/** Drift in one file's text; `ref` is the sanctioned install ref. */
export function driftIn(file: string, text: string, ref: string = INSTALL_REF): InstallRefDrift[] {
if (skipped(file)) return [];
const out: InstallRefDrift[] = [];
const at = (index: number) => text.slice(0, index).split('\n').length;
- const ts = file.endsWith('.ts');
+ const ts = foldedIntoTs(file);
for (const m of text.matchAll(PIN)) {
if (EXACT_PIN.test(m[1]!)) continue;
if (ts) out.push({ file, line: at(m.index!), found: m[0], why: `TypeScript names install refs through INSTALL_PIN (${OWNER})` });
@@ -51,7 +53,7 @@ export function driftIn(file: string, text: string, ref: string = INSTALL_REF):
/** The text surface rewritten to `ref` (TypeScript is left for a human). */
export function rewriteText(file: string, text: string, ref: string = INSTALL_REF): string {
- if (skipped(file) || file.endsWith('.ts')) return text;
+ if (skipped(file) || foldedIntoTs(file)) return text;
return text
.replace(PIN, (all, r: string) => (EXACT_PIN.test(r) ? all : `github:garrytan/gbrain#${ref}`))
.replace(ARTIFACT, (all, r: string, path: string) => (/^[0-9a-f]{40}$/.test(r) ? all : `raw.githubusercontent.com/garrytan/gbrain/${ref}/${path}`))
diff --git a/scripts/promote-stable.ts b/scripts/promote-stable.ts
index b88c842df1..cb18affc6e 100644
--- a/scripts/promote-stable.ts
+++ b/scripts/promote-stable.ts
@@ -547,13 +547,20 @@ export function rolledUpNotes(changelog: string, previous: string | null, versio
/** The version of the release GitHub calls Latest now, or null when there is none or it cannot be read. */
export async function latestReleaseVersion(deps: Pick<PromoteDeps, 'repo' | 'ghApi'>): Promise<string | null> {
+ return readLatestReleaseVersion(deps).catch(() => null);
+}
+
+/** The current Latest release's version; null when there is none (404). Any other failed read throws. */
+async function readLatestReleaseVersion(deps: Pick<PromoteDeps, 'repo' | 'ghApi'>): Promise<string | null> {
+ let release: { tag_name?: string };
try {
- const tag = ((await deps.ghApi(`repos/${deps.repo}/releases/latest`)) as { tag_name?: string }).tag_name ?? '';
- const v = tag.replace(/^v/, '');
- return VERSION_RE.test(v) ? v : null;
- } catch {
- return null;
+ release = (await deps.ghApi(`repos/${deps.repo}/releases/latest`)) as { tag_name?: string };
+ } catch (error) {
+ if (/HTTP 404/.test((error as Error).message)) return null;
+ throw error;
}
+ const v = (release.tag_name ?? '').replace(/^v/, '');
+ return VERSION_RE.test(v) ? v : null;
}
/**
@@ -563,8 +570,15 @@ export async function latestReleaseVersion(deps: Pick<PromoteDeps, 'repo' | 'ghA
* then stays put until stable passes it. A rollback moves it back on purpose.
*/
export async function markLatest(deps: PromoteDeps, releaseId: number, version: string, notes: string | null, rollback = false): Promise<void> {
- const latest = await latestReleaseVersion(deps);
- if (!rollback && latest && compareVersions(latest, version) > 0) {
+ let latest: string | null = null;
+ if (!rollback) {
+ try {
+ latest = await readLatestReleaseVersion(deps);
+ } catch (error) {
+ throw new Refusal(`stable now points at v${version}, but GitHub's current Latest release could not be read (${(error as Error).message.split('\n')[0]}), so Latest was left alone; run \`bun scripts/release-channel.ts backfill --apply\` from a checkout to set it (${DOCS}).`);
+ }
+ }
+ if (latest && compareVersions(latest, version) > 0) {
deps.log(`[promote-stable] GitHub's Latest stays v${latest}, which is newer than v${version}; it moves to the stable release once stable passes it.`);
return;
}
diff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.sh
index 124fc67a0a..363927f019 100755
--- a/scripts/run-verify-parallel.sh
+++ b/scripts/run-verify-parallel.sh
@@ -299,7 +299,7 @@ if [ -n "${GBRAIN_VERIFY_LOG_DIR:-}" ]; then
LOG_DIR="$GBRAIN_VERIFY_LOG_DIR"
mkdir -p "$LOG_DIR" || { echo "ERROR: cannot create $LOG_DIR" >&2; exit 2; }
else
- LOG_DIR="$(mktemp -d /tmp/gbrain-verify-XXXXXX)"
+ LOG_DIR="$(mktemp -d "${TMPDIR:-/tmp}/gbrain-verify-XXXXXX")"
KEEP_LOGS=0
trap '[ "$KEEP_LOGS" = "1" ] || rm -rf "$LOG_DIR"' EXIT
fi
diff --git a/scripts/stress/iteration-weights.json b/scripts/stress/iteration-weights.json
index 799c5e7b16..2adfa2352f 100644
--- a/scripts/stress/iteration-weights.json
+++ b/scripts/stress/iteration-weights.json
@@ -42,7 +42,7 @@
"test/claim-fifo-foreground-waiting.test.ts": 4900,
"test/claim-lease-holder-only-6712.test.ts": 4500,
"test/claude-cli-output-cap.test.ts": 10800,
- "test/cli-cold-start-registries.test.ts": 12500,
+ "test/cli-cold-start-registries.test.ts": 7400,
"test/cli-page-writes.test.ts": 159200,
"test/cli-socket.test.ts": 2600,
"test/code-file-path-6712.test.ts": 100,
@@ -66,9 +66,11 @@
"test/derived-link-reconciliation.test.ts": 5700,
"test/destructive-guard.test.ts": 7150,
"test/direct-pool-profile.test.ts": 9300,
+ "test/doctor-advice-matches-repair-preview.test.ts": 1100,
"test/doctor-content-golden.test.ts": 16600,
"test/doctor-day-zero.test.ts": 9250,
"test/doctor-early-stop-golden.serial.test.ts": 700,
+ "test/doctor-entry-deadline-6803.test.ts": 10700,
"test/doctor-frontmatter-holds.test.ts": 12200,
"test/doctor-harness-smoke.test.ts": 12350,
"test/doctor-hot-checks-golden.test.ts": 36550,
@@ -215,10 +217,12 @@
"test/forecast-journal.test.ts": 26300,
"test/frontmatter-alias-bomb.test.ts": 100,
"test/frontmatter-reserved-keys-6454.test.ts": 6300,
+ "test/generation-identity-visibility-9386.test.ts": 1200,
"test/get-chunks-paging.test.ts": 5000,
"test/git-canonical-conversion-g8a.test.ts": 210700,
"test/git-canonical-conversion-progress.test.ts": 143250,
"test/git-commit-push-managed-unpublished.test.ts": 1350,
+ "test/git-gap-census.test.ts": 6300,
"test/git-literal-pathspec-hooks-7759.test.ts": 1600,
"test/google-connector-facts-fence-7292.test.ts": 13200,
"test/grade-takes-window.test.ts": 2500,
@@ -441,6 +445,7 @@
"test/migrate.test.ts": 10400,
"test/migration-persistence-request-id-index.test.ts": 7400,
"test/migration-persistence-request-slug-index.test.ts": 7900,
+ "test/migrations-notice.test.ts": 400,
"test/normalized-file-hash.test.ts": 200,
"test/on-commit-embedding.serial.test.ts": 7700,
"test/oneshot-consumer-direct-route.test.ts": 4200,
@@ -673,6 +678,7 @@
"test/schema-missing-tables.test.ts": 3800,
"test/scripts/check-item-allowlist-catches.test.ts": 800,
"test/scripts/nightly-issue.test.ts": 200,
+ "test/scripts/run-verify-parallel.test.ts": 27000,
"test/scripts/test-stress-postgres.test.ts": 11400,
"test/search-read-keyword-bound.test.ts": 3700,
"test/search/page-rank-cut.test.ts": 8500,
@@ -685,8 +691,9 @@
"test/serve-status-mode.serial.test.ts": 68700,
"test/serve-sync-handoff.serial.test.ts": 4100,
"test/setup-brain-first.test.ts": 62000,
+ "test/setup-brain-layout.test.ts": 131300,
"test/setup-serves-several.test.ts": 134100,
- "test/setup.test.ts": 432400,
+ "test/setup.test.ts": 507300,
"test/shared-content-freshness.test.ts": 6900,
"test/shared-skills-catalog.test.ts": 17200,
"test/shared-skills-retention-capacity.test.ts": 3800,
diff --git a/scripts/structural-suites.tsv b/scripts/structural-suites.tsv
index 56ad6ca96c..6976fd3a25 100644
--- a/scripts/structural-suites.tsv
+++ b/scripts/structural-suites.tsv
@@ -366,7 +366,7 @@ test/scripts/release-restamp.test.ts release:restamp end to end 16 readFileSync
test/scripts/release-restamp.test.ts release:unstamp and merge: direct 7 readFileSync
test/scripts/require-executed-tests.test.ts require-executed-tests 9 readFileSync
test/scripts/run-verify-parallel.test.ts guard registration ⇒ execution coverage 1 readFileSync
-test/scripts/run-verify-parallel.test.ts run-verify-parallel.sh — no-timeout-binary fallback rc capture (regression) 7 readFileSync
+test/scripts/run-verify-parallel.test.ts run-verify-parallel.sh — no-timeout-binary fallback rc capture (regression) 8 readFileSync
test/scripts/serial-files.test.ts scripts/serial-files.tsv (serial lane manifest) 5 readFileSync
test/scripts/stable-daily.test.ts stable-daily.yml 2 readFileSync
test/scripts/stress-gate.test.ts docs anchors 1 readFileSync
diff --git a/skills/enrich/SKILL.md b/skills/enrich/SKILL.md
index 9884701fdf..42ba09d425 100644
--- a/skills/enrich/SKILL.md
+++ b/skills/enrich/SKILL.md
@@ -180,7 +180,7 @@ the raw data shows exactly what the API returned.
placeholder.
4. Fill compiled truth with citations
5. Add first timeline entry
-6. Leave empty sections as `[No data yet]` (don't fill with boilerplate)
+6. Omit sections with nothing to put under them (`gbrain lint` flags empty ones)
7. In a batch, create the pages other pages will link to first. A link to a
page that doesn't exist yet is recorded as a wanted page and becomes an
edge once that page is written (`gbrain wanted` lists them).
diff --git a/skills/skills.lock.history.json b/skills/skills.lock.history.json
index ee212c744b..3b330d701a 100644
--- a/skills/skills.lock.history.json
+++ b/skills/skills.lock.history.json
@@ -481,6 +481,7 @@
"d0000eec8154ba48488eed07e8f1a6a0ccb66d0b39e41f29d279a875c1673227"
],
"enrich/SKILL.md": [
+ "635ae97e4623525a0ce164bef2067a092dea7074088ac190c3b1ed3624c06be6",
"7f281eb60dc5f1fe2225c5d6fca1c3e2a0312418b8fb7df9fd7a192be00c614c",
"9988168348f6c3391d3aeec6621f9c99c8d75d1e1bfdd6c44d48e4c1067ab775",
"a876b1f89ab0b492bcf3ebbe3447f682ecbcf4f83d213d3ca854c3922f2b3fb5",
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index f014379dd0..c452c67a32 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -81,7 +81,7 @@
"draft-in-voice/routing-eval.jsonl": "590fc16277ed7c3338776e7fac6daf1270b91058941f8101079bb295d2d8f787",
"eiirp/SKILL.md": "507249ce40746c0f3d5ae2a374164797798c6ebbc6209b312e3404a2f4902e6c",
"eiirp/routing-eval.jsonl": "d0000eec8154ba48488eed07e8f1a6a0ccb66d0b39e41f29d279a875c1673227",
- "enrich/SKILL.md": "cbe6068373f4cd5006a6171a1795c3e619cfc82009ec4b3d86174b8ee2bcee2e",
+ "enrich/SKILL.md": "635ae97e4623525a0ce164bef2067a092dea7074088ac190c3b1ed3624c06be6",
"fact-check/SKILL.md": "49f0d356eee44541eddbc9cd501dc36707d417d84ca10446c0d315321f259674",
"fact-check/routing-eval.jsonl": "7519c6eada244813264b0df34ed67613e2d4404cfdf3cb209051b461749f5662",
"frontmatter-guard/SKILL.md": "0f805093fdc06c49698e215a5652d8fa319236e725711ef522caf01aab82467f",
@@ -226,7 +226,7 @@
"skillpack-check/SKILL.md": "0d2d2d201ed72e19b47d7e3743b5bbdfb5c2655d1f34d29447c601fca3908f9e",
"skillpack-harvest/SKILL.md": "0f86314b58d25b5511809f567c04aedc3fba6fe35ed642ac52d8216ae365b6eb",
"skillpack-harvest/routing-eval.jsonl": "cb4783288e95af3132b32ecb40a54cffc095f57b36240f96a25c2d2adf5e68c6",
- "skills.lock.history.json": "32d383ea0cd961b0d1cc8e8f7308e5abf23a7971833334e6cffde799d87a7e90",
+ "skills.lock.history.json": "b94d36832095a449c2ff32d676b7a1d9f620e53729f45d7f8f003f504ae4e91f",
"smoke-test/SKILL.md": "f5099e1d2ab9dc6827096249e68414f7ae357c29b39fb069a54bb7fb74f414a5",
"soul-audit/SKILL.md": "7a48e180849f7502d332878c443397f90a3756f45caa94f76bcfcc7c997469c8",
"storage-manifest/SKILL.md": "1debbefba61007a17cda1525496875d1edfde90642adf3ec031f25a71724807e",
diff --git a/src/cli/commands/embed.ts b/src/cli/commands/embed.ts
index 619e2a471c..b3814efc25 100644
--- a/src/cli/commands/embed.ts
+++ b/src/cli/commands/embed.ts
@@ -88,8 +88,9 @@ async function authorizeEmbed(engine: BrainEngine, args: string[]): Promise<{ au
/** `gbrain embed --help` (answered without a brain) and the usage error. */
const EMBED_USAGE = [
- 'Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...|--held] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--source <id>] [--yes | --max-usd N] [--json] | --stale --images | --facts',
+ 'Usage: gbrain embed [<slug>|--all|--stale|--slugs s1 s2 ...|--held] [--dry-run] [--batch-size N] [--priority recent] [--catch-up] [--include-null-signature] [--source <id>] [--yes | --max-usd N] [--json] | --stale --images | --stale --facts --source <id>',
' Embeds chunks without a vector (--stale; --catch-up keeps going until the backlog is empty) or re-embeds pages (--all, a slug, --slugs).',
+ ' --stale covers pages, not facts saved with remember: embed those with --stale --facts --source <id> (--dry-run, then --yes --max-cost-usd N).',
' A page over 1 MiB spends at most embed.max_usd_per_page (default $2) and embeds its newest chunks first. --held --dry-run lists, for every',
' source, the pages a cap or a pending approval stopped, the cost to finish and one approve command per source. --held --source <id>',
' --max-usd N (or --slugs <slug> --source <id> --max-usd N) approves them, one source at a time: N is both the run\'s cap and the extra per-page allowance it',
diff --git a/src/cli/migrations-notice.ts b/src/cli/migrations-notice.ts
index dc65f12f66..3ef2d53485 100644
--- a/src/cli/migrations-notice.ts
+++ b/src/cli/migrations-notice.ts
@@ -22,6 +22,10 @@ export async function pendingUpgradeMigrationsNotice(engine: BrainEngine, comman
const { loadCompletedMigrations } = await import('../core/preferences.ts');
if (loadCompletedMigrations().length === 0) return null;
const summary = migrationLedgerSummary(version, await declinedMigrations(engine));
+ if (summary.wedged.length > 0) {
+ const { wedgedMigrationFix } = await import('../commands/apply-migrations.ts');
+ return { ...migrationsNotice(`Upgrade migration(s) ${summary.wedged.join(', ')} failed several runs in a row and are wedged; the command ran, and apply-migrations --yes will not clear them until the cause is fixed.`), fix: wedgedMigrationFix(summary.wedged) };
+ }
const pending = [...summary.pending, ...summary.partial];
if (pending.length === 0) return null;
const notice = migrationsNotice(`${pending.length} upgrade migration(s) have not finished on this brain yet (${pending.join(', ')}); the command ran, and gbrain apply-migrations --yes --no-autopilot-install finishes the upgrade.`);
diff --git a/src/commands/apply-migrations.ts b/src/commands/apply-migrations.ts
index 19793cb5b2..6e54aa873d 100644
--- a/src/commands/apply-migrations.ts
+++ b/src/commands/apply-migrations.ts
@@ -40,7 +40,7 @@ import {
wedgedLedgerHint,
} from '../core/migration-ledger.ts';
import { clearRepoPathWedge } from './migrations/v0_11_0-install.ts';
-import { shellQuote, type Effect } from '../core/agent-output.ts';
+import { shellQuote, type Action, type Effect } from '../core/agent-output.ts';
import { writeJsonDocument } from '../core/cli-force-exit.ts';
import { consentGate } from '../core/consent-cli.ts';
import { opError, OperationError } from '../core/ops/contract.ts';
@@ -1046,13 +1046,19 @@ function failWedged(report: RunReport): number | undefined {
report.failure = opError('migrations_pending',
`Migration ${versions} is wedged (${MAX_CONSECUTIVE_PARTIALS}+ consecutive partial runs with no completion), so the run did not complete every migration.`,
`Read ${wedgedLedgerHint()} for the last failure, fix its cause, then clear it with \`${shellQuote(forceRetryArgv(wedged[0]!.version))}\` and run \`gbrain apply-migrations --yes\` again. Ask the user first.`,
- { reason: 'wedged', fix: { ask_user: true, argv: forceRetryArgv(wedged[0]!.version), consent: [], actor: 'agent', requires_exclusive: true,
- why: `Writes a 'retry' marker so the next run re-attempts v${wedged[0]!.version}; without fixing the cause the run partials again.`,
- user_message: `gbrain migration ${versions} failed ${MAX_CONSECUTIVE_PARTIALS} or more times in a row. Fix the cause recorded in ${wedgedLedgerHint()}, then clear it with ${shellQuote(forceRetryArgv(wedged[0]!.version))} and run gbrain apply-migrations --yes. Clear it now?`,
- verify: { argv: ['gbrain', COMMAND, '--list', '--json'] } } });
+ { reason: 'wedged', fix: wedgedMigrationFix(wedged.map(m => m.version)) });
return 1;
}
+/** The ask-the-user step that clears the first wedged migration; also the fix of connect's pending-migrations notice (src/cli/migrations-notice.ts). */
+export function wedgedMigrationFix(wedged: readonly string[]): Action {
+ const versions = wedged.map(v => `v${v}`).join(', ');
+ return { ask_user: true, argv: forceRetryArgv(wedged[0]!), consent: [], actor: 'agent', requires_exclusive: true,
+ why: `Writes a 'retry' marker so the next run re-attempts v${wedged[0]!}; without fixing the cause the run partials again.`,
+ user_message: `gbrain migration ${versions} failed ${MAX_CONSECUTIVE_PARTIALS} or more times in a row. Fix the cause recorded in ${wedgedLedgerHint()}, then clear it with ${shellQuote(forceRetryArgv(wedged[0]!))} and run gbrain apply-migrations --yes. Clear it now?`,
+ verify: { argv: ['gbrain', COMMAND, '--list', '--json'] } };
+}
+
/** Bug 3 — surface wedged migrations as a loud, actionable error; the run continues (applied/partial/pending are still reported and run). */
function reportWedgedMigrations(wedged: readonly Migration[], superseded: readonly Migration[], completed: readonly CompletedMigrationEntry[]): void {
for (const m of superseded) {
diff --git a/src/commands/doctor/checks/derived-visibility.ts b/src/commands/doctor/checks/derived-visibility.ts
index fafce27792..14236af882 100644
--- a/src/commands/doctor/checks/derived-visibility.ts
+++ b/src/commands/doctor/checks/derived-visibility.ts
@@ -28,7 +28,7 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
const name = 'derived_visibility';
try {
const aliasesHonored = await readHonorAliases(engine);
- const sources = sourceId ? [sourceId] : (await engine.executeRaw<{ id: string }>('SELECT id FROM sources')).map(s => s.id);
+ const sources = (await engine.executeRaw<{ id: string }>(`SELECT id FROM sources WHERE archived IS NOT TRUE${sourceId ? ' AND id=$1' : ''}`, sourceId ? [sourceId] : [])).map(s => s.id);
const facts = await worldFactsFromPrivateSources(engine, sources);
const readable = facts.filter(f => f.readable);
const factDetails = { world_facts_from_private_sources: facts.length, world_facts_remotely_readable: readable.length,
@@ -39,7 +39,7 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
try {
counts = await engine.executeRaw<{ unstamped_atoms: number; unstamped_concepts: number; looser_atoms: number; looser_concepts: number; looser_events: number; alias_pages_without_visibility: number }>(
`WITH derived AS (
- SELECT p.* FROM pages p WHERE p.deleted_at IS NULL ${sourceId ? 'AND p.source_id=$1' : ''}
+ SELECT p.* FROM pages p WHERE p.deleted_at IS NULL AND p.source_id=ANY($1::text[])
AND (p.type='atom' OR (p.type='concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)
OR (p.type='event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%')))
SELECT
@@ -55,8 +55,8 @@ export async function derivedVisibilityCheck(engine: BrainEngine, sourceId?: str
COUNT(*) FILTER (WHERE d.type='event' AND COALESCE(d.frontmatter->>'visibility','world')<>'private' AND EXISTS (SELECT 1 FROM pages o
WHERE o.source_id=d.source_id AND o.slug=d.frontmatter->'event'->>'depth' AND o.deleted_at IS NULL
AND ${derivationPrivateSql('o')}))::int AS looser_events,
- (SELECT COUNT(*)::int FROM pages ap WHERE ${aliasOnlyPagesSql('ap')} ${sourceId ? 'AND ap.source_id=$1' : ''}) AS alias_pages_without_visibility
- FROM derived d`, sourceId ? [sourceId] : [], { timeoutMs: PLAN_STATEMENT_MS });
+ (SELECT COUNT(*)::int FROM pages ap WHERE ${aliasOnlyPagesSql('ap')} AND ap.source_id=ANY($1::text[])) AS alias_pages_without_visibility
+ FROM derived d`, [sources], { timeoutMs: PLAN_STATEMENT_MS });
} catch (e) {
if ((e as { code?: string } | null)?.code !== '57014') throw e;
return { name, status: 'warn', details: { ...factDetails, derived_counts: 'unknown', count: 'lower_bound', truncated: true, repair: 'visibility' },
diff --git a/src/commands/doctor/checks/provider-consent.ts b/src/commands/doctor/checks/provider-consent.ts
index f9c241ebad..ac133413cf 100644
--- a/src/commands/doctor/checks/provider-consent.ts
+++ b/src/commands/doctor/checks/provider-consent.ts
@@ -27,8 +27,8 @@ export function providerConsentFix(record: LocalSetupRecord): Action {
argv,
consent: ['paid', 'egress'],
actor: 'user',
- why: 'Setup recorded provider use as declined, so gbrain contacts no model provider. Re-running setup with --providers records it as accepted; provider calls then follow the configured keys.',
- user_message: `gbrain is not contacting any AI provider because you declined provider use at setup. To allow it, run \`${argv.join(' ')}\`${record.scope === 'project' ? ' in that project directory' : ''}.`,
+ why: 'Setup recorded provider use as declined, so gbrain contacts no model provider on its own. Re-running setup with --providers records it as accepted; provider calls then follow the configured keys.',
+ user_message: `gbrain contacts no AI provider on its own because you declined provider use at setup; a command you run yourself with a provider key, such as gbrain embed, still uses it. To allow it, run \`${argv.join(' ')}\`${record.scope === 'project' ? ' in that project directory' : ''}.`,
verify: doctorVerify('provider_consent'),
docs: DOCS,
requires_exclusive: false,
@@ -56,7 +56,7 @@ async function runProviderConsent(_ctx: DoctorContext): Promise<Check[]> {
const env = keys.length ? ` even though ${keys.join(', ')} ${keys.length === 1 ? 'is' : 'are'} set in this environment` : '';
const fix = providerConsentFix(declined);
checks.push(infoCheck('provider_consent',
- `Provider check skipped by consent: gbrain setup recorded provider use as declined (${declined.path}), so gbrain sends no request to a model provider${env}, model discovery and the embedding probe included. The user decides; to allow provider use they run: ${fix.argv!.join(' ')}`,
+ `Provider check skipped by consent: gbrain setup recorded provider use as declined (${declined.path}), so gbrain sends no request to a model provider on its own${env}: model discovery and the embedding probe are skipped, while a command the user runs with a provider key, such as gbrain embed, still uses it. The user decides; to allow provider use they run: ${fix.argv!.join(' ')}`,
'disabled_by_choice', fix,
{ decision: 'declined', receipt: declined.path, harness: declined.harness, provider_env: keys, probed: false }));
return checks;
diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.ts
index 89921ef776..c9b4442377 100644
--- a/src/commands/init-first-run.ts
+++ b/src/commands/init-first-run.ts
@@ -23,7 +23,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { resolveGbrainBin } from '../core/gbrain-bin.ts';
import { configReadiness, embeddingEnablement, harnessWiringEntry } from '../core/readiness.ts';
import type { SearchMode } from '../core/search/mode.ts';
-import { costMatrixSentence } from '../core/search/mode-advice.ts';
+import { costMatrixSentence, OPENAI_COST_MATRIX_MODELS } from '../core/search/mode-advice.ts';
import type { McpSurface } from '../mcp/surface.ts';
export interface InitFirstRunInputs {
@@ -171,7 +171,9 @@ const WRITEBACK_IN_EFFECT = 'agents save only what you ask them to remember, unt
*/
export function setupFirstRunNotices(initNotices: readonly unknown[], harness: string, opts: { reportBack?: boolean } = {}): Notice[] {
const bundle = initNotices.find((n): n is Notice => (n as Notice | null)?.code === 'first_run_decisions');
- const decisions = (bundle?.decisions ?? []).filter(d => d.id !== 'harness_wiring');
+ const matrix = costMatrixSentence(harness === 'Codex' ? OPENAI_COST_MATRIX_MODELS : undefined);
+ const decisions = (bundle?.decisions ?? []).filter(d => d.id !== 'harness_wiring')
+ .map(d => (d.id === 'search_mode' ? { ...d, question: `Which search mode should this brain use? ${matrix}` } : d));
if (decisions.length === 0) return [];
const searchMode = decisions.find(d => d.id === 'search_mode');
const upkeep = decisions.find(d => d.id === 'upkeep');
@@ -189,7 +191,7 @@ export function setupFirstRunNotices(initNotices: readonly unknown[], harness: s
why: `Setup is complete: the brain is ready and ${harness} is wired, so memory works now. These first-run settings are in effect as listed; none blocks memory or needs a new session to answer. `
+ 'Relay them once, in the reply that reports this install, as the current settings and how to change them; do not hold the install open or end it waiting on an answer. '
+ 'When the user picks an option, run its command. Automatic saving (`writeback`) is separate from setup\'s capture decision (Stop/SessionEnd hooks); while unanswered it comes back in a later session until the user answers or mutes it.',
- user_message: `gbrain is set up and ${harness} is wired, so memory works now.${inEffect.length ? ` In effect: ${inEffect.join('; ')}.` : ''} ${reportBack}${upkeep ? ` ${upkeep.question}` : ''}${searchMode ? ` ${costMatrixSentence()}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
+ user_message: `gbrain is set up and ${harness} is wired, so memory works now.${inEffect.length ? ` In effect: ${inEffect.join('; ')}.` : ''} ${reportBack}${upkeep ? ` ${upkeep.question}` : ''}${searchMode ? ` ${matrix}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
decisions,
}];
}
diff --git a/src/commands/serve-http-webhooks.ts b/src/commands/serve-http-webhooks.ts
index 79b92623cc..b12181a49b 100644
--- a/src/commands/serve-http-webhooks.ts
+++ b/src/commands/serve-http-webhooks.ts
@@ -171,6 +171,7 @@ async function handleGitHubItemEvent(
payload: Buffer,
res: Response,
eventName: string,
+ deliveryId: string | undefined,
): Promise<void> {
const ref = extractGitHubItemRef(parsed);
if (ref === null) {
@@ -227,9 +228,19 @@ async function handleGitHubItemEvent(
// #8799: the key names the item and its intent, so a deletion never reuses an edit's refresh. The waiting cap is per
// source, so a cap hit can return another item's job: unless that job covers this event (the same item and intent, or an
// explicit source-wide sync for an edit), it is a refusal, never this event's 202. A busy source defers the job (sync handler).
+ // An event joins a refresh of its item that has not started; otherwise its delivery id keys a new one, so an event
+ // after the refresh began is never dropped and a GitHub redelivery (same delivery id) maps to its first job.
const deleted = eventName === 'issues' && parsed.action === 'deleted';
- const idempotencyKey = `webhook:item:${source.id}:${ref.repo}:${ref.number}:${deleted ? 'delete' : 'refresh'}:${Math.floor(Date.now() / 30_000)}`;
+ const idempotencyKey = `webhook:item:${source.id}:${ref.repo}:${ref.number}:${deleted ? 'delete' : 'refresh'}:${deliveryId || Math.floor(Date.now() / 30_000)}`;
try {
+ const [waiting] = await engine.executeRaw<{ id: number }>(
+ `SELECT id FROM minion_jobs WHERE name = 'sync' AND status = 'waiting' AND data->>'sourceId' = $1 AND data->'github_item'->>'repo' = $2
+ AND data->'github_item'->>'number' = $3 AND COALESCE(data->'github_item'->>'deleted', 'false') = $4 ORDER BY id LIMIT 1`,
+ [source.id, ref.repo, String(ref.number), String(deleted)]);
+ if (waiting) {
+ res.status(202).json({ job_id: Number(waiting.id), source_id: source.id, item: ref });
+ return;
+ }
const queue = new MinionQueue(engine);
const job = await queue.add(
'sync',
@@ -774,7 +785,7 @@ function mountGitHubWebhook(app: Express, ctx: ServeHttpContext): void {
// comment / review / label / assignee / milestone / check events
// refresh exactly the item that changed.
if (GH_ITEM_EVENTS.has(event)) {
- await handleGitHubItemEvent(engine, parsed, sigHeader, payload, res, event);
+ await handleGitHubItemEvent(engine, parsed, sigHeader, payload, res, event, req.header('X-GitHub-Delivery'));
return;
}
diff --git a/src/commands/serve.ts b/src/commands/serve.ts
index 25482bc430..7927b4e757 100644
--- a/src/commands/serve.ts
+++ b/src/commands/serve.ts
@@ -7,7 +7,7 @@ import type { IdleUpkeep } from '../core/maintenance/idle.ts';
export { serveFailFastRequested, writeServeFailFastEnvelope } from '../core/serve-fail-fast.ts';
import { isEngineDegraded as isEngineDegradedForServe } from '../core/degraded-marker.ts';
import { startMcpServer, stdioRpcsInFlightCount, resolveMcpStdioSourceScope } from '../mcp/server.ts';
-import { installStdioShutdownTriggers, probeWatchdogAvailable, readLiveParentPid, resolveEofDrainMs, type StdioLifecycleDeps } from '../mcp/stdio-lifecycle.ts';
+import { exitAfterStdoutDrains, installStdioShutdownTriggers, probeWatchdogAvailable, readLiveParentPid, resolveEofDrainMs, type StdioLifecycleDeps } from '../mcp/stdio-lifecycle.ts';
// The parent-liveness readers moved to the engine-free stdio lifecycle the thin-client bridge shares.
export { isPidAlive, probeWatchdogAvailable, readLiveParentPid } from '../mcp/stdio-lifecycle.ts';
import { VERB_NAMES } from '../core/verbs.ts';
@@ -598,7 +598,7 @@ function resolveBootTimeoutMs(): number {
*/
function installGraduationHandoff(engine: BrainEngine, opts: ServeOptions): ServeOptions {
if (engine.kind !== 'pglite') return opts;
- const exit = opts.exit ?? ((code?: number) => { process.exit(code); });
+ const exit = opts.exit ?? exitAfterStdoutDrains();
const log = opts.log ?? ((msg: string) => console.error(msg));
let handoffExit: number | null = null;
let shutdown: ((reason: string) => void) | null = null;
@@ -678,7 +678,7 @@ function installStdioLifecycle(
const deps: StdioLifecycleDeps = {
stdin: opts.stdin ?? process.stdin,
signals: opts.signals ?? process,
- exit: opts.exit ?? ((code?: number) => { process.exit(code); }),
+ exit: opts.exit ?? exitAfterStdoutDrains(),
log: opts.log ?? ((msg: string) => console.error(msg)),
getParentPid: opts.getParentPid ?? readLiveParentPid,
setInterval: opts.setInterval ?? ((fn, ms) => setInterval(fn, ms)),
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index d827b13d4d..d0fd4eb5d5 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -564,7 +564,7 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string
if (flags.remove) return await runRemove(flags, receiptRead.setup, paths.receiptPath, brainHome, out);
const hostedUrl = cfg?.remote_mcp?.mcp_url ?? receiptRead.hosted?.mcp_url ?? (receiptRead.hosted ? 'a hosted brain' : undefined);
- if (hostedUrl) return refuse(hostedConnection(hostedUrl, receiptRead.hosted !== null, flags.name), out);
+ if (hostedUrl) return refuse(hostedConnection(hostedUrl, receiptRead.hosted !== null, flags), out);
const prior = receiptRead.setup;
if (prior && prior.gbrain_home !== brainHome) {
return refuse(ownerConflict('other_install', `The '${flags.name}' connection belongs to the gbrain install at ${prior.gbrain_home}, not ${brainHome}.`, {
@@ -594,7 +594,7 @@ export async function runSetup(args: string[], deps: { openclaw?: { bin?: string
}
const binding = entryBinding(flags, found.mcp.stdioMember);
if (binding.member) { plan = { ...plan, stdioMember: binding.member }; found = inspectClaudeSetup(plan); }
- if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name), out);
+ if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags), out);
const pluginOwner = flags.name === 'gbrain' ? claudePluginProvidesName(claudeUserSettingsPath(), 'gbrain') : null;
if (pluginOwner && flags.stdioMember !== undefined) return refuse(pluginBindingRefusal(pluginOwner, 'claude-code', flags.stdioMember), out);
@@ -764,7 +764,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
if (flags.remove) return await runCodexRemove(flags, receiptRead.setup, paths.receiptPath, brainHome, out);
const hostedUrl = cfg?.remote_mcp?.mcp_url ?? receiptRead.hosted?.mcp_url ?? (receiptRead.hosted ? 'a hosted brain' : undefined);
- if (hostedUrl) return refuse(hostedConnection(hostedUrl, receiptRead.hosted !== null, flags.name, 'codex'), out);
+ if (hostedUrl) return refuse(hostedConnection(hostedUrl, receiptRead.hosted !== null, flags, 'codex'), out);
const prior = receiptRead.setup;
if (prior && prior.gbrain_home !== brainHome) {
return refuse(ownerConflict('other_install', `The '${flags.name}' connection belongs to the gbrain install at ${prior.gbrain_home}, not ${brainHome}.`, {
@@ -793,7 +793,7 @@ async function runCodexSetup(flags: SetupFlags, launcher: string, cfg: GBrainCon
}
const binding = entryBinding(flags, found.mcp.stdioMember);
if (binding.member) { plan = { ...plan, stdioMember: binding.member }; found = inspectCodexSetup(plan); }
- if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags.name, 'codex'), out);
+ if (found.mcp.state === 'remote') return refuse(hostedConnection(found.mcp.url ?? 'a hosted brain', true, flags, 'codex'), out);
const pluginOwner = codexPluginProvidesName(paths.configPath, flags.name);
if (pluginOwner && flags.stdioMember !== undefined) return refuse(pluginBindingRefusal(pluginOwner, 'codex', flags.stdioMember), out);
@@ -902,11 +902,12 @@ async function runCodexRemove(flags: SetupFlags, receipt: CodexSetupReceipt | nu
return finish(out, { harness: 'codex', dryRun: flags.dryRun, remove: true, steps: r.steps, states: [], verify: null, notices: [], notes: r.notes, preserved: r.preserved, instructions, skills, resolver });
}
-function hostedConnection(url: string, wired: boolean, name: string, harness: SetupHarnessId = 'claude-code'): OperationError {
+function hostedConnection(url: string, wired: boolean, flags: Pick<SetupFlags, 'name' | 'skillResolver'>, harness: SetupHarnessId = 'claude-code'): OperationError {
const label = HARNESS_LABEL[harness];
+ const resolver = flags.skillResolver === 'on' ? ` The skill resolver needs no local brain: set it up with \`gbrain setup ${harness} --skills-index-only --skill-loading resolve\`.` : '';
return opError('setup_hosted_connection',
- `This machine already reaches a hosted brain (${url})${wired ? ` and ${label}'s '${name}' entry points at it` : ''}; gbrain setup will not create a second, local brain.`,
- wired ? 'Nothing to do: the hosted connection is wired. `gbrain doctor --only harness_wiring` verifies it.' : `Connect ${label} to it with \`gbrain connect ${url} --harness ${harness} --install\`.`,
+ `This machine already reaches a hosted brain (${url})${wired ? ` and ${label}'s '${flags.name}' entry points at it` : ''}; gbrain setup will not create a second, local brain.`,
+ (wired ? 'Nothing to do: the hosted connection is wired. `gbrain doctor --only harness_wiring` verifies it.' : `Connect ${label} to it with \`gbrain connect ${url} --harness ${harness} --install\`.`) + resolver,
{ docs: 'docs/guides/repair.md#setup-hosted-connection',
fix: wired
? { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the registration reaches and smoke-tests it.' }
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 6221a521b6..b45155edb8 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -50,7 +50,7 @@ export function assessUpgradeOutcome(
export async function runUpgrade(args: string[], opts: { targetVersion?: string } = {}) {
if (args.includes('--help') || args.includes('-h')) {
- console.log('Usage: gbrain upgrade [--channel stable|alpha] [--dry-run] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\n\nDetects install method (bun, bun-link, binary) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--channel <name> stable (weekly, promoted after its gates passed on the exact release; the default) or alpha\n (every published release; latest is an alias). Precedence: --channel, GBRAIN_RELEASE_CHANNEL,\n self_upgrade.channel, stable. Persist it as self_upgrade.channel in config.\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run Print the effective channel, where it came from and what would install; change nothing.\n With --restart-only: print the restart plan instead.\n--no-autopilot-install Skip autopilot installation and service rewrites, including package postinstall.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');
+ console.log('Usage: gbrain upgrade [--channel stable|alpha] [--dry-run] [--stop-mcp] [--no-restart] [--swap-only] [--no-autopilot-install] [--no-bun-floor-check]\n gbrain upgrade --restart-only [--stop-mcp] [--dry-run] [--json]\n\nSelf-update the CLI, then restart every gbrain process on this host onto the new build.\n\nDetects install method (bun, bun-link, binary) and runs the appropriate update.\nAfter upgrading, shows what\'s new and offers to set up new features.\n\n--channel <name> stable (weekly, promoted after its gates passed on the exact release; the default) or alpha\n (every published release; latest is an alias). Precedence: --channel, GBRAIN_RELEASE_CHANNEL,\n self_upgrade.channel, stable. Persist it as self_upgrade.channel in config.\n--stop-mcp Stop MCP stdio servers agent harnesses started, instead of refusing; reconnect gbrain\n in each harness afterwards.\n--no-restart Install without restarting anything (doctor reports runtime_build_skew until\n \'gbrain upgrade --restart-only\' runs).\n--restart-only Restart serve, autopilot, the jobs supervisor and its worker (and, with --stop-mcp, MCP\n servers) onto the installed build, then verify every process reports it and the warm\n CLI socket accepts it. A process it cannot restart refuses with the exact step (exit 3).\n--dry-run Print the effective channel, where it came from and what would install; change nothing.\n With --restart-only: print the restart plan instead.\n--no-autopilot-install Skip autopilot installation and service rewrites.\n Also supported as GBRAIN_NO_AUTOPILOT_INSTALL=1.\n--no-bun-floor-check Upgrade even when the target release\'s Bun floor cannot be read or is above\n this host\'s Bun (manual upgrades only). Docs: docs/guides/upgrades-auto-update.md#bun-floor.\n--swap-only Perform ONLY the binary/source swap and skip post-upgrade\n (migrations run on the next launch). Used by the autopilot\n silent self-upgrade channel so the daemon can swap + relaunch\n without a 30-min blocking post-upgrade inside its tick.');
return;
}
diff --git a/src/core/generations/adapters/page.ts b/src/core/generations/adapters/page.ts
index 6114e39a3b..f9dc69b309 100644
--- a/src/core/generations/adapters/page.ts
+++ b/src/core/generations/adapters/page.ts
@@ -88,14 +88,21 @@ export async function importPageItem(tx: BrainEngine, sourceId: string, slug: st
await importFromContent(tx, slug, content, { noEmbed: true, ...opts, sourceId, preserveGateMarkers: true });
}
-/** Rows whose retained page version was written by the producer (`producer`: a predicate over version alias `v`) at the row's identity. */
+/**
+ * Rows whose retained page version was written by the producer (`producer`: a predicate over version alias `v`) at the row's identity.
+ * The version is compared under the row's own visibility, which `repair visibility` stamps after the fact (#9386); adoption keeps
+ * the row, so its visibility never widens.
+ */
export async function pageVersionEvidence(engine: BrainEngine, sourceId: string, rows: readonly ItemRow[], producer: string): Promise<Set<string>> {
if (!rows.length) return new Set();
- const versions = await engine.executeRaw<PageIdentityInput & { slug: string; tags: string[] | null }>(
- `SELECT p.slug, v.type, v.title, v.compiled_truth, v.timeline, v.frontmatter, v.tags
+ const versions = await engine.executeRaw<PageIdentityInput & { slug: string; tags: string[] | null; live_visibility: unknown }>(
+ `SELECT p.slug, v.type, v.title, v.compiled_truth, v.timeline, v.frontmatter, v.tags, p.frontmatter->'visibility' AS live_visibility
FROM page_versions v JOIN pages p ON p.id = v.page_id
WHERE p.source_id = $1 AND p.slug = ANY($2::text[]) AND v.compiled_truth IS NOT NULL AND v.title IS NOT NULL AND (${producer})`,
[sourceId, rows.map(row => row.key)]);
const wanted = new Map(rows.map(row => [row.key, row.identityHash]));
- return new Set(versions.filter(v => pageIdentityHash({ ...v, tags: v.tags ?? [] }) === wanted.get(v.slug)).map(v => v.slug));
+ return new Set(versions.filter(({ live_visibility, ...v }) => {
+ const { visibility: _ignored, ...frontmatter } = v.frontmatter ?? {};
+ return pageIdentityHash({ ...v, frontmatter: live_visibility == null ? frontmatter : { ...frontmatter, visibility: live_visibility }, tags: v.tags ?? [] }) === wanted.get(v.slug);
+ }).map(v => v.slug));
}
diff --git a/src/core/persistence/connector-status.ts b/src/core/persistence/connector-status.ts
index 24baf2ffb8..f76306cf8f 100644
--- a/src/core/persistence/connector-status.ts
+++ b/src/core/persistence/connector-status.ts
@@ -15,7 +15,7 @@ import { opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { CONNECTOR_STOPPED_RUNS, readManagedConnectorState, type ConnectorPurgedItem, type ConnectorRunCounts, type ConnectorRunFailure, type UpgradeRecovery } from './connector-state.ts';
import { classifySyncFault, type SyncFaultVerdict } from './sync-fault-class.ts';
-import type { Action } from '../agent-output.ts';
+import { cliRenderContext, renderAction, type Action } from '../agent-output.ts';
import { managedBrain, readAllSourceHolds } from '../connectors/item-holds-store.ts';
import type { ItemHoldRecord } from '../connectors/item-holds.ts';
import { fenceAutoRepairFor, gitHoldItem, readGitHoldListing, readSyncConversions, readSyncHoldPolicy, type GitHoldItem, type SyncConversion } from './sync-holds.ts';
@@ -188,8 +188,8 @@ export async function readGitHoldStatuses(engine: Pick<BrainEngine, 'executeRaw'
export type GitHoldListing = { mode: 'summary' } | { mode: 'all' } | { mode: 'page'; request: ListingRequest };
/** Held items per code, largest first, each with its first item as the example (its fix and docs apply to the rest). */
-function holdsByCode(items: readonly GitHoldItem[]): Array<{ code: string; count: number; example: GitHoldItem }> {
- const groups = new Map<string, { code: string; count: number; example: GitHoldItem }>();
+function holdsByCode<T extends { code: string }>(items: readonly T[]): Array<{ code: string; count: number; example: T }> {
+ const groups = new Map<string, { code: string; count: number; example: T }>();
for (const item of items) {
const group = groups.get(item.code);
if (group) group.count++;
@@ -198,9 +198,11 @@ function holdsByCode(items: readonly GitHoldItem[]): Array<{ code: string; count
return [...groups.values()].sort((a, b) => b.count - a.count || (a.code < b.code ? -1 : 1));
}
-/** A source's `git_holds` for `sources status --json`, summary first and items last, bounded by `listing`. */
+/** A source's `git_holds` for `sources status --json`, summary first and items last, bounded by `listing`; each fix rendered with the CLI routing pin (#9319). */
export function gitHoldStatusJson(sourceId: string, status: GitHoldStatus, listing: GitHoldListing) {
- const { items, ...rest } = status;
+ const ctx = cliRenderContext();
+ const { items: held, ...rest } = status;
+ const items = held.map(item => ({ ...item, fix: renderAction(item.fix, ctx) }));
const head = { ...rest, by_code: holdsByCode(items) };
if (listing.mode === 'all') return { ...head, items };
if (listing.mode === 'page') {
diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.ts
index 7a506b252e..49920c99f0 100644
--- a/src/core/persistence/source-lifecycle.ts
+++ b/src/core/persistence/source-lifecycle.ts
@@ -62,6 +62,11 @@ function retireSuperseded(row:TopologyChange):OperationError{
{fix:ownerStatusFix(row.source_id)});
}
/** A prior receipt of this request_id, replayed; a retire admission (#8984) returns null so the run resumes. */
+/** The arguments a lifecycle request id is bound to (its receipt digest). */
+export function topologyIntent(input:SourceLifecycleInput):Record<string,unknown>{
+ return {...input,requestId:undefined,dryRun:undefined,automaticClaim:undefined};
+}
+
function replayTopologyChange(row:TopologyChange|null):Record<string,unknown>|null{
if(!row||isRetireAdmission(row))return null;
if(isSupersededRetire(row))throw retireSuperseded(row);
@@ -145,7 +150,7 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceL
if(['remove','purge','archive'].includes(input.operation)&&input.sourceId==='default') throw opError('invalid_params','The default source cannot be removed or archived.',
`The default source holds the brain's primary pages and always stays registered. ${input.operation} a named source instead; the command in fix lists them.`,{fix:sourcesListFix()});
const principal=await topologyPrincipal(engine);
- const intent={...input,requestId:undefined,dryRun:undefined,automaticClaim:undefined};
+ const intent=topologyIntent(input);
const prior=await priorTopologyChange(engine,principal,requestId,intent);
const replayed=replayTopologyChange(prior);
if(replayed) return replayed;
diff --git a/src/core/pg-access-classify.ts b/src/core/pg-access-classify.ts
index ee8c6d3065..86044172a6 100644
--- a/src/core/pg-access-classify.ts
+++ b/src/core/pg-access-classify.ts
@@ -414,7 +414,7 @@ export function classifyPgAccessError(err: unknown, ctx?: PgAccessContext): PgAc
transient: row.transient,
sqlstate: looksLikeSqlstate(code),
message,
- remediation: ctx?.url && !looksLikeSupabase(ctx.url) && row.plainRemediation ? row.plainRemediation
+ remediation: ctx?.url && row.plainRemediation && (!looksLikeSupabase(ctx.url) || (row.reason === 'dns_failed' && isSupabasePoolerUrl(ctx.url))) ? row.plainRemediation
: row.remediation ?? (CODES as Record<string, { suggestion?: string }>)[code ?? '']?.suggestion ?? UNKNOWN_REMEDIATION,
fix: contextualFix(row.reason, ctx?.url) ?? row.fix,
supabase: supabaseHints(ctx?.url, row.reason),
diff --git a/src/core/repair/purged-page-facts.ts b/src/core/repair/purged-page-facts.ts
index 5617878835..b592b0c60d 100644
--- a/src/core/repair/purged-page-facts.ts
+++ b/src/core/repair/purged-page-facts.ts
@@ -15,7 +15,9 @@
* - ambiguous: no purge record (a retention purge of a soft-deleted page leaves none, and neither does a rename that
* did not carry the facts); retired only with `--include-ambiguous` and that preview's hash.
*
- * The preview lists every candidate, prints a hash over all of it and saves the approved set. The apply, bound to that
+ * The preview lists every candidate, prints a hash over all of it and saves the approved set; a preview that approves
+ * nothing (only ambiguous or excluded rows) prints the empty set's hash, so its apply answers with nothing to do instead
+ * of preview_changed (#9407). The apply, bound to that
* hash and the user's consent, expires exactly the approved rows that are still active, unchanged, of the same class
* and still without a page (expired_at set, row_num cleared, as the fixed purge does); anything else is reported
* changed_since_preview and kept. Rows are expired, never deleted. A managed brain publishes one database-only
@@ -156,13 +158,13 @@ export const purgedPageFactsRepair: RepairHandler = {
return { items, preview_hash: opts.expect, residuals: {} };
}
const facts = await classifyPurgedPageFacts(engine, scope.source_ids);
- const hash = await hashOf(facts);
const batches: Approved[] = [];
for (const fact of facts.filter(f => f.class === 'evidenced' || f.class === 'ambiguous' && includeAmbiguous)) {
const open = batches.at(-1);
if (open && open.source_id === fact.source_id && open.facts.length < BATCH_FACTS) open.facts.push(fact);
else batches.push({ source_id: fact.source_id, include_ambiguous: includeAmbiguous, scope: scope.source_ids, facts: [fact] });
}
+ const hash = await hashOf(batches.length ? facts : []);
if (batches.length) await saveApprovedSet(engine, { command: COMMAND, hash }, batches);
const count = (klass: PurgedPageFactClass) => facts.filter(f => f.class === klass).length;
const listing: RepairListing[] = facts.map(fact => ({ item: `${fact.source_id}:${fact.slug}#${fact.id}`,
diff --git a/src/core/search/mode-advice.ts b/src/core/search/mode-advice.ts
index 852e4ce599..919c154c60 100644
--- a/src/core/search/mode-advice.ts
+++ b/src/core/search/mode-advice.ts
@@ -31,6 +31,13 @@ export const COST_MATRIX_MODELS: ReadonlyArray<{ label: string; id: string }> =
{ label: 'Opus 5.5', id: 'anthropic:claude-opus-5-5' },
];
+/** The same three tiers in OpenAI's newest fully priced family, for a Codex setup. */
+export const OPENAI_COST_MATRIX_MODELS: ReadonlyArray<{ label: string; id: string }> = [
+ { label: 'GPT-5.6 Luna', id: 'openai:gpt-5.6-luna' },
+ { label: 'GPT-5.6 Terra', id: 'openai:gpt-5.6-terra' },
+ { label: 'GPT-5.6 Sol', id: 'openai:gpt-5.6-sol' },
+];
+
/** Assumed retrieved payload per query, in tokens, for each mode. */
export const COST_MATRIX_PAYLOAD_TOKENS: Readonly<Record<SearchMode, number>> = { conservative: 4_000, balanced: 10_000, tokenmax: 20_000 };
export const COST_MATRIX_QUERIES_PER_MONTH = 10_000;
@@ -77,9 +84,9 @@ export function costMatrixLines(indent = ' '): string[] {
}
/** The matrix in one sentence (init's first-run decision). */
-export function costMatrixSentence(): string {
- const labels = COST_MATRIX_MODELS.map(x => x.label).join(' / ');
- const cells = MODES.map(m => `${m} ${COST_MATRIX_MODELS.map(x => usd(monthlyPayloadCost(m, x.id))).join(' / ')}`).join(', ');
+export function costMatrixSentence(models = COST_MATRIX_MODELS): string {
+ const labels = models.map(x => x.label).join(' / ');
+ const cells = MODES.map(m => `${m} ${models.map(x => usd(monthlyPayloadCost(m, x.id))).join(' / ')}`).join(', ');
return `Estimated downstream input cost of the retrieved payload at ${COST_MATRIX_QUERIES_PER_MONTH / 1000}K queries/month (${labels}): ${cells} per month.`;
}
diff --git a/src/core/setup/codex.ts b/src/core/setup/codex.ts
index 2ce84ffff8..e352a5a4fc 100644
--- a/src/core/setup/codex.ts
+++ b/src/core/setup/codex.ts
@@ -31,7 +31,7 @@
* leaves pending fingerprints the next run treats as owned, so a resume never
* duplicates an entry, and an untrusted hook never runs.
*/
-import { existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { atomicWriteTextFile } from '../bootstrap/atomic-write.ts';
import { ownedEntryFingerprint } from '../bootstrap/adopted-connections.ts';
@@ -255,6 +255,21 @@ export interface CodexApplyResult { steps: CodexSetupStep[]; receipt: CodexSetup
* `beforeMcp` runs after the receipt is prepared (the brain init step);
* `abortAfter` is the crash-injection test seam.
*/
+/** The current text of each file setup may rewrite, read before it writes; absent files have nothing to back up. */
+function readOriginals(paths: string[]): Array<{ path: string; text: string }> {
+ return paths.filter((path) => existsSync(path)).map((path) => ({ path, text: readFileSync(path, 'utf8') }));
+}
+
+/** Keep `<file>.bak.<stamp>` of each file setup changed (the autopilot convention); one note per backup. */
+function keepBackups(originals: Array<{ path: string; text: string }>): string[] {
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ return originals.filter(({ path, text }) => !existsSync(path) || readFileSync(path, 'utf8') !== text).map(({ path, text }) => {
+ const bakPath = `${path}.bak.${stamp}`;
+ writeFileSync(bakPath, text, { mode: 0o600 });
+ return `${path} as it was before setup changed it: ${bakPath}`;
+ });
+}
+
export async function applyCodexSetup(
plan: CodexSetupPlan,
consent: SetupConsent,
@@ -263,6 +278,7 @@ export async function applyCodexSetup(
const paths = codexSetupPaths(plan.name);
mkdirSync(dirname(paths.configPath), { recursive: true, mode: 0o700 });
const lock = await acquireBootstrapLock(dirname(paths.configPath));
+ const originals = readOriginals([paths.configPath, paths.hooksPath]);
try {
// The MCP table and every hook command start gbrain through the launcher, so it goes down before anything names it (#8424, #8426).
ensureHookLauncher(hookLauncherPath(plan.brainHome));
@@ -384,7 +400,11 @@ export async function applyCodexSetup(
if (opts.abortAfter === 'trust') throw new SetupAbortInjected('trust');
receipt.status = 'installed';
save();
+ notes.push(...keepBackups(originals));
return { steps, receipt, changed: true, preserved, notes };
+ } catch (e) {
+ keepBackups(originals);
+ throw e;
} finally {
lock.release();
}
@@ -395,6 +415,7 @@ export interface CodexRemoveResult { steps: CodexSetupStep[]; preserved: CodexPr
/** Remove exactly what the receipt owns by fingerprint (trust, hooks, MCP, receipt); edited entries survive and are reported. */
export async function removeCodexSetup(receipt: CodexSetupReceipt, receiptPath: string, opts: { dryRun: boolean }): Promise<CodexRemoveResult> {
const lock = await acquireBootstrapLock(dirname(receipt.config_path));
+ const originals = readOriginals([receipt.config_path, receipt.hooks_path]);
try {
const steps: CodexSetupStep[] = [];
const preserved: CodexPreserved[] = [];
@@ -464,7 +485,11 @@ export async function removeCodexSetup(receipt: CodexSetupReceipt, receiptPath:
steps.push({ step: 'receipt', action: 'remove', detail: receiptPath });
}
}
+ notes.push(...keepBackups(originals));
return { steps, preserved, notes, receiptRemoved };
+ } catch (e) {
+ keepBackups(originals);
+ throw e;
} finally {
lock.release();
}
diff --git a/src/core/source-default-search.ts b/src/core/source-default-search.ts
index 727a0a865a..ae4a4b6b5a 100644
--- a/src/core/source-default-search.ts
+++ b/src/core/source-default-search.ts
@@ -19,9 +19,22 @@ export async function newSourceJoinsDefaultSearch(engine: BrainEngine): Promise<
}
}
+/** The choice an earlier attempt with this request id was accepted with, so an identical retry replays it instead of re-reading the row it wrote. */
+async function acceptedChoice(engine: BrainEngine, opts: AddSourceOpts): Promise<AddSourceOpts | null> {
+ if (!opts.requestId) return null;
+ const [prior] = await engine.executeRaw<{ digest: string }>('SELECT digest FROM persistence_topology_changes WHERE request_id = $1::uuid AND source_id = $2', [opts.requestId, opts.id]);
+ if (!prior) return null;
+ const { managedSourceAddInput } = await import('./persistence/managed-sources.ts');
+ const { topologyIntent } = await import('./persistence/source-lifecycle.ts');
+ const { digest } = await import('./persistence/digest.ts');
+ return [{ ...opts, federated: true }, opts].find(candidate => digest(topologyIntent(managedSourceAddInput(candidate))) === prior.digest) ?? null;
+}
+
/** Folder and Git sources only: connectors keep their own defaults (GitHub and Google federated, meetings and Slack chats out). */
export async function withDefaultSearchChoice(engine: BrainEngine, opts: AddSourceOpts): Promise<AddSourceOpts> {
if (opts.federated != null || opts.github || opts.google || opts.meetings || opts.slack || opts.addedByRemoteCaller) return opts;
+ const accepted = await acceptedChoice(engine, opts);
+ if (accepted) return accepted;
const joins = await newSourceJoinsDefaultSearch(engine);
if (opts.localPath && (await engine.executeRaw('SELECT 1 FROM sources WHERE id = $1 AND local_path IS NULL', [opts.id])).length > 0) return opts;
return joins ? { ...opts, federated: true } : opts;
diff --git a/src/mcp/remote-bridge.ts b/src/mcp/remote-bridge.ts
index 5ddf39e6e4..f28e263ff4 100644
--- a/src/mcp/remote-bridge.ts
+++ b/src/mcp/remote-bridge.ts
@@ -31,7 +31,7 @@ import { VERSION } from '../version.ts';
import { hiddenToolHint } from './hidden-tool-hint.ts';
import { installInstructionsResolver, MCP_SERVER_DESCRIPTION, resolveMcpInstructions } from './instructions.ts';
import { BRIDGE_LOG_PREFIX, bridgeCallFailure, bridgeInternalFailure, bridgeListFailure, bridgeRefusal, endpointLabel, writeBridgeTrace, type BridgeErrorContext } from './remote-bridge-errors.ts';
-import { installStdioShutdownTriggers, mcpStdioTransport, probeWatchdogAvailable, readLiveParentPid, resolveEofDrainMs, type StdioLifecycleDeps } from './stdio-lifecycle.ts';
+import { exitAfterStdoutDrains, installStdioShutdownTriggers, mcpStdioTransport, probeWatchdogAvailable, readLiveParentPid, resolveEofDrainMs, type StdioLifecycleDeps } from './stdio-lifecycle.ts';
import { clampSurface, createStdioSurfaceState, isMcpSurface, resolveStdioSurface, sessionWidenAllowed, stdioToolListing, surfaceWiderThan, SURFACE_SOURCE_LABEL, type McpSurface } from './surface.ts';
import { stripUrlSecrets } from '../core/url-redact.ts';
@@ -74,7 +74,7 @@ const isPlainObject = (v: unknown): v is Record<string, unknown> => v !== null &
/** Start the bridge on this process's stdio. Resolves once the transport is connected; the lifecycle exits the process. */
export async function startRemoteStdioBridge(cfg: GBrainConfig, opts: RemoteBridgeOptions = {}): Promise<void> {
const deps: StdioLifecycleDeps = {
- stdin: process.stdin, signals: process, exit: (code?: number) => { process.exit(code); }, log: (msg: string) => console.error(msg),
+ stdin: process.stdin, signals: process, exit: exitAfterStdoutDrains(), log: (msg: string) => console.error(msg),
getParentPid: readLiveParentPid, setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (h) => clearInterval(h as ReturnType<typeof setInterval>),
probeWatchdog: probeWatchdogAvailable, ...opts.lifecycle,
};
diff --git a/src/mcp/stdio-lifecycle.ts b/src/mcp/stdio-lifecycle.ts
index 67bcc950b7..3b7495f34f 100644
--- a/src/mcp/stdio-lifecycle.ts
+++ b/src/mcp/stdio-lifecycle.ts
@@ -60,6 +60,29 @@ export function resolveEofDrainMs(defaultMs: number = DEFAULT_EOF_DRAIN_MS): num
return Math.floor(n);
}
+/** How long an exit waits for buffered stdout; a reader that stopped reading cannot hold the process past it. */
+export const STDOUT_DRAIN_MS = 5_000;
+
+/**
+ * GST-2760: the process exit both stdio servers use. Bun's process.exit drops stdout it still buffers natively (an
+ * 8 MiB reply written just before exit arrives as 64 KiB), so the exit waits for stdout.end() to report the buffer
+ * flushed, an error (the reader is gone) or STDOUT_DRAIN_MS, whichever comes first.
+ */
+export function exitAfterStdoutDrains(exit: (code?: number) => void = (code) => { process.exit(code); }, stdout: Writable = process.stdout, boundMs = STDOUT_DRAIN_MS): (code?: number) => void {
+ return (code) => {
+ let done = false;
+ const finish = (): void => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ exit(code);
+ };
+ const timer = setTimeout(finish, boundMs);
+ stdout.once('error', finish);
+ try { stdout.end(finish); } catch { finish(); }
+ };
+}
+
export interface StdioLifecycleDeps {
stdin: NodeJS.ReadableStream & { isTTY?: boolean };
signals: Pick<NodeJS.Process, 'on'>;
diff --git a/test/cli-cold-start-registries.test.ts b/test/cli-cold-start-registries.test.ts
index 50154b6f4a..f8640ac313 100644
--- a/test/cli-cold-start-registries.test.ts
+++ b/test/cli-cold-start-registries.test.ts
@@ -95,7 +95,9 @@ describe('load-time registries under per-op loading', () => {
test('every op loaded alone misses only registrations that cannot be observed incomplete', async () => {
const registering = new Set(Object.keys(REGISTRATIONS));
const full = (await loadedModules("await import('./src/core/operations.ts');")).filter(f => registering.has(f));
- const names = Object.keys(OPERATION_LOADERS);
+ const byLoader = new Map<unknown, string>();
+ for (const [name, [load]] of Object.entries(OPERATION_LOADERS)) if (!byLoader.has(load)) byLoader.set(load, name);
+ const names = [...byLoader.values()];
const missing = new Map<string, Set<string>>();
for (let i = 0; i < names.length; i += 8) {
await Promise.all(names.slice(i, i + 8).map(async (name) => {
diff --git a/test/doctor-advice-matches-repair-preview.test.ts b/test/doctor-advice-matches-repair-preview.test.ts
new file mode 100644
index 0000000000..d381535098
--- /dev/null
+++ b/test/doctor-advice-matches-repair-preview.test.ts
@@ -0,0 +1,31 @@
+/**
+ * #8848: a doctor check must not send the operator to a repair whose preview then reports nothing to repair.
+ *
+ * 1. Protects: derived_visibility counts only what `gbrain repair visibility` previews: pages on active sources.
+ * A synthesized concept with no visibility on an archived source is neither counted nor previewed.
+ * 2. Fails when: the check counts rows the repair's scope (every active source) never reads, so the advice it
+ * prints leads to a 0-item preview.
+ * 3. No production seam: PGLite, the real check and the real repair preview.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
+import { visibilityRepair } from '../src/core/repair/visibility.ts';
+import { derivedVisibilityCheck } from '../src/commands/doctor/checks/derived-visibility.ts';
+
+let engine: PGLiteEngine;
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 60_000);
+afterAll(async () => { await engine.disconnect(); });
+
+const ctx = () => ({ engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId: 'default' }) as never;
+
+test('derived_visibility ignores an archived source, as the repair preview does', async () => {
+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('source-a', 'source-a') ON CONFLICT (id) DO NOTHING");
+ await engine.putPage('concepts/idea-a', { type: 'concept', title: 'Idea A', compiled_truth: 'An idea.', frontmatter: { synthesized_by: 'cycle' } } as never, { sourceId: 'source-a' });
+ await engine.executeRaw("UPDATE sources SET archived = true WHERE id = 'source-a'");
+ const preview = await runRepair(ctx(), visibilityRepair, await resolveRepairScope(engine), { apply: false });
+ expect(preview.affected).toBe(0);
+ const check = await derivedVisibilityCheck(engine);
+ expect(check.status, check.message).toBe('ok');
+});
diff --git a/test/doctor-provider-consent.serial.test.ts b/test/doctor-provider-consent.serial.test.ts
index 8cd1594603..0e2653e068 100644
--- a/test/doctor-provider-consent.serial.test.ts
+++ b/test/doctor-provider-consent.serial.test.ts
@@ -126,6 +126,10 @@ describe('doctor with provider keys present', () => {
expect(fix.consent).toEqual(['paid', 'egress']);
expect(fix.next).not.toBe('run');
expect((check.details as { provider_env: string[] }).provider_env).toEqual(['OPENAI_API_KEY']);
+ for (const text of [String(check.message), String((check.fix as { user_message: string }).user_message)]) {
+ expect(text).toContain('on its own');
+ expect(text).toContain('gbrain embed');
+ }
}, 180_000);
test('control: the opt-in embedding probe contacts the provider when no decision is recorded', async () => {
diff --git a/test/embed-help-facts.test.ts b/test/embed-help-facts.test.ts
new file mode 100644
index 0000000000..c43c0cce77
--- /dev/null
+++ b/test/embed-help-facts.test.ts
@@ -0,0 +1,16 @@
+/**
+ * `embed --stale` embeds page chunks, never facts saved with `remember`; the help names the fact form that does.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+
+describe('gbrain embed --help', () => {
+ test('says --stale skips saved facts and names the working --stale --facts --source form', () => {
+ const run = spawnSync('bun', [join(import.meta.dir, '..', 'src', 'cli.ts'), 'embed', '--help'], { encoding: 'utf8', timeout: 60_000 });
+ expect(run.status).toBe(0);
+ expect(run.stdout).toContain('--stale --facts --source <id>');
+ expect(run.stdout).toContain('remember');
+ expect(run.stdout).not.toMatch(/\| --facts(\s|$)/);
+ }, 90_000);
+});
diff --git a/test/eval-longmemeval-reader-mode.slow.test.ts b/test/eval-longmemeval-reader-mode.slow.test.ts
index 0774b4e657..3b19d23485 100644
--- a/test/eval-longmemeval-reader-mode.slow.test.ts
+++ b/test/eval-longmemeval-reader-mode.slow.test.ts
@@ -6,10 +6,14 @@ import type Anthropic from '@anthropic-ai/sdk';
import { runEvalLongMemEval } from '../src/commands/eval-longmemeval.ts';
import type { ThinkLLMClient } from '../src/core/think/index.ts';
import { buildQaAccuracy } from '../src/eval/longmemeval/qa-accuracy.ts';
+import { createBenchmarkBrain } from '../src/eval/longmemeval/harness.ts';
+import type { PGLiteEngine } from '../src/core/pglite-engine.ts';
let dir: string;
let dataset: string;
-beforeAll(() => {
+let engine: PGLiteEngine;
+beforeAll(async () => {
+ engine = await createBenchmarkBrain();
dir = mkdtempSync(join(tmpdir(), 'lme-reader-mode-'));
dataset = join(dir, 'dataset.jsonl');
writeFileSync(dataset, JSON.stringify({
@@ -18,7 +22,10 @@ beforeAll(() => {
haystack_sessions: [{ session_id: 's1', turns: [{ role: 'user', content: 'I like mint tea.' }] }],
}) + '\n');
});
-afterAll(() => rmSync(dir, { recursive: true, force: true }));
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(dir, { recursive: true, force: true });
+});
const base = () => [dataset, '--keyword-only', '--no-trajectory', '--no-embed-cache', '--by-type', '--model', 'anthropic:claude-sonnet-4-6'];
const rows = (path: string) => readFileSync(path, 'utf8').trim().split('\n').map(line => JSON.parse(line));
@@ -35,8 +42,8 @@ describe('reader mode CLI receipts', () => {
const notesPath = join(dir, 'notes.jsonl');
const directCalls: Anthropic.MessageCreateParamsNonStreaming[] = [];
const notesCalls: Anthropic.MessageCreateParamsNonStreaming[] = [];
- await runEvalLongMemEval([...base(), '--reader-mode', 'direct', '--output', directPath], { client: stub('end_turn', directCalls), exitOnError: false });
- await runEvalLongMemEval([...base(), '--output', notesPath], { client: stub('end_turn', notesCalls), exitOnError: false });
+ await runEvalLongMemEval([...base(), '--reader-mode', 'direct', '--output', directPath], { client: stub('end_turn', directCalls), exitOnError: false, engine });
+ await runEvalLongMemEval([...base(), '--output', notesPath], { client: stub('end_turn', notesCalls), exitOnError: false, engine });
expect(directCalls).toHaveLength(1);
expect(notesCalls).toHaveLength(1);
expect(directCalls[0].messages).toEqual(notesCalls[0].messages);
@@ -54,15 +61,15 @@ describe('reader mode CLI receipts', () => {
expect(notesSummary.run_config.reader).toMatchObject({ mode: 'notes', max_tokens: 1024, config_hash: notes.reader_config_hash });
expect(direct.retrieval_config_hash).toBe(notes.retrieval_config_hash);
- await expect(runEvalLongMemEval([...base(), '--reader-mode', 'notes', '--output', directPath, '--resume-from', directPath, '--allow-mixed-run-config'], { client: stub('end_turn', []), exitOnError: false })).rejects.toThrow('exit 1');
+ await expect(runEvalLongMemEval([...base(), '--reader-mode', 'notes', '--output', directPath, '--resume-from', directPath, '--allow-mixed-run-config'], { client: stub('end_turn', []), exitOnError: false, engine })).rejects.toThrow('exit 1');
expect(rows(directPath)[0].reader_mode).toBe('direct');
- await runEvalLongMemEval([...base(), '--reader-mode', 'direct', '--output', directPath, '--resume-from', directPath], { client: stub('end_turn', []), exitOnError: false });
+ await runEvalLongMemEval([...base(), '--reader-mode', 'direct', '--output', directPath, '--resume-from', directPath], { client: stub('end_turn', []), exitOnError: false, engine });
});
test('max_tokens records cutoff as error, keeps its denominator, and fails instead of judging partial text', async () => {
const path = join(dir, 'cutoff.jsonl');
const calls: Anthropic.MessageCreateParamsNonStreaming[] = [];
- await expect(runEvalLongMemEval([...base(), '--reader-mode', 'notes', '--reader-max-tokens', '512', '--output', path], { client: stub('max_tokens', calls), exitOnError: false })).rejects.toThrow('exit 1');
+ await expect(runEvalLongMemEval([...base(), '--reader-mode', 'notes', '--reader-max-tokens', '512', '--output', path], { client: stub('max_tokens', calls), exitOnError: false, engine })).rejects.toThrow('exit 1');
expect(calls[0].max_tokens).toBe(512);
const [row, summary] = rows(path);
expect(row).toMatchObject({ reader_mode: 'notes', reader_max_tokens: 512, reader_finish_reason: 'max_tokens', hypothesis: '', error: 'reader_max_tokens', reader_partial_output: 'mint' });
@@ -74,7 +81,7 @@ describe('reader mode CLI receipts', () => {
test('invalid reader flags fail before any provider call', async () => {
for (const flags of [['--reader-mode', 'summarize'], ['--reader-max-tokens', '0'], ['--reader-max-tokens', '1.5'], ['--reader-max-tokens', 'NaN']]) {
const calls: Anthropic.MessageCreateParamsNonStreaming[] = [];
- await expect(runEvalLongMemEval([...base(), ...flags], { client: stub('end_turn', calls), exitOnError: false })).rejects.toThrow('exit 1');
+ await expect(runEvalLongMemEval([...base(), ...flags], { client: stub('end_turn', calls), exitOnError: false, engine })).rejects.toThrow('exit 1');
expect(calls).toHaveLength(0);
}
});
@@ -86,7 +93,7 @@ describe('reader mode CLI receipts', () => {
] as const) {
const path = join(dir, `${name}.jsonl`);
const client: ThinkLLMClient = { create: async (params) => ({ model: params.model, content: [{ type: 'text', text }], stop_reason: reason }) as Anthropic.Message };
- await expect(runEvalLongMemEval([...base(), '--output', path], { client, exitOnError: false })).rejects.toThrow('exit 1');
+ await expect(runEvalLongMemEval([...base(), '--output', path], { client, exitOnError: false, engine })).rejects.toThrow('exit 1');
const [row] = rows(path);
expect(row).toMatchObject({ hypothesis: '', reader_finish_reason: reason, error });
if (text) expect(row.reader_partial_output).toBe(text);
diff --git a/test/generation-identity-visibility-9386.test.ts b/test/generation-identity-visibility-9386.test.ts
new file mode 100644
index 0000000000..fa10e5173e
--- /dev/null
+++ b/test/generation-identity-visibility-9386.test.ts
@@ -0,0 +1,59 @@
+/**
+ * #9386: `repair visibility` stamps an explicit visibility on a pre-ledger atom. The atom must still be adopted against
+ * the extractor-written page version, and adoption keeps the stamped visibility. PGLite, real repair path.
+ */
+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 { importFromContent } from '../src/core/import-file.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { resolveRepairScope, runRepair } from '../src/core/repair/core.ts';
+import { visibilityRepair } from '../src/core/repair/visibility.ts';
+import { atomGenerationAdapter, atomOwnerKey } from '../src/core/generations/adapters/atoms.ts';
+import { pageIdentityHash } from '../src/core/generations/adapters/page.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+let engine: PGLiteEngine;
+const home = mkdtempSync(join(tmpdir(), 'gbrain-9386-'));
+
+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+afterAll(async () => { await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+
+async function seed(slug: string, type: string, frontmatter: Record<string, unknown>, body: string) {
+ const result = await importFromContent(engine, slug, serializeMarkdown(frontmatter, body, '', { type: type as never, title: slug, tags: [] }),
+ { noEmbed: true, forceRechunk: true });
+ expect(['imported', 'skipped']).toContain(result.status);
+}
+
+describe('#9386 atoms stamped by repair visibility stay adoptable', () => {
+ test('a private-origin atom repaired to private matches its extractor version and stays private', async () => {
+ await seed('notes/private-origin', 'note', { visibility: 'private' }, 'A private planning record.');
+ const extractor = { source_slug: 'notes/private-origin', extracted_by: 'extract_atoms-v0.41.2.1' };
+ await seed('atoms/legacy-insight', 'atom', extractor, 'An insight distilled from the planning record.');
+ await engine.createVersion('atoms/legacy-insight', { sourceId: 'default' });
+ await withEnv({ GBRAIN_HOME: home }, async () => {
+ await runRepair({ engine, config: { engine: 'pglite', embedding_disabled: true }, logger: { info() {}, warn() {}, error() {} },
+ dryRun: false, remote: false, sourceId: 'default' } as never, visibilityRepair, await resolveRepairScope(engine), { apply: true });
+ });
+ const [row] = await engine.executeRaw<{ v: string | null }>("SELECT frontmatter->>'visibility' AS v FROM pages WHERE slug='atoms/legacy-insight'");
+ expect(row?.v).toBe('private');
+
+ const key = { kind: 'atom', sourceId: 'default', ownerKey: atomOwnerKey({ kind: 'page', slug: 'notes/private-origin' }) };
+ const items = await atomGenerationAdapter.readItems(engine, key, []);
+ const owned = [...items.values()].filter(item => item.key === 'atoms/legacy-insight');
+ expect(owned).toHaveLength(1);
+ expect([...await atomGenerationAdapter.legacyEvidence(engine, key, owned)]).toEqual(['atoms/legacy-insight']);
+ await atomGenerationAdapter.completeItems!(engine, key, ['atoms/legacy-insight'], undefined);
+ const [adopted] = await engine.executeRaw<{ v: string | null; h: string | null }>("SELECT frontmatter->>'visibility' AS v, frontmatter->>'source_hash' AS h FROM pages WHERE slug='atoms/legacy-insight'");
+ expect(adopted?.h).toBeTruthy();
+ expect(adopted?.v).toBe('private');
+ }, 120_000);
+
+ test('a content edit still changes the identity', () => {
+ const base = { type: 'atom', title: 'T', timeline: '', tags: [] as string[], frontmatter: { visibility: 'private' } };
+ expect(pageIdentityHash({ ...base, compiled_truth: 'edited' })).not.toBe(pageIdentityHash({ ...base, compiled_truth: 'body' }));
+ });
+});
diff --git a/test/gstack-redact-allowlist-9308.test.ts b/test/gstack-redact-allowlist-9308.test.ts
new file mode 100644
index 0000000000..c8f7b35150
--- /dev/null
+++ b/test/gstack-redact-allowlist-9308.test.ts
@@ -0,0 +1,11 @@
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+
+const tracked = (path: string) => spawnSync('git', ['ls-files', '--error-unmatch', path], { cwd: `${import.meta.dir}/..` }).status === 0;
+
+describe('#9308: the pre-push redaction allowlist sits where the guard reads it', () => {
+ test('it is committed at the repository root, not under .gstack/', () => {
+ expect(tracked('.gstack-redact-allowlist')).toBe(true);
+ expect(tracked('.gstack/redact-allowlist')).toBe(false);
+ });
+});
diff --git a/test/init-first-run.test.ts b/test/init-first-run.test.ts
index b01c5dd3f5..e131d81f71 100644
--- a/test/init-first-run.test.ts
+++ b/test/init-first-run.test.ts
@@ -151,6 +151,15 @@ describe('setupFirstRunNotices (gbrain setup <harness>)', () => {
expect(n.why).toContain('do not hold the install open');
});
+ test('a Codex setup prices the matrix with OpenAI models, not Claude ones', () => {
+ const [n] = setupFirstRunNotices(fromInit({ searchMode }), 'Codex');
+ const mode = n.decisions!.find(d => d.id === 'search_mode')!;
+ for (const text of [n.user_message!, mode.question]) {
+ expect(text).not.toContain('Haiku');
+ expect(text).toContain('GPT-5.6 Luna / GPT-5.6 Terra / GPT-5.6 Sol');
+ }
+ });
+
test('the search-mode matrix still reaches the user and every option keeps its command', () => {
const [n] = setupFirstRunNotices(fromInit({ searchMode }), 'Claude Code');
expect(n.user_message).toContain(costMatrixSentence());
diff --git a/test/install-ref.test.ts b/test/install-ref.test.ts
index 7372c34e27..578e70641c 100644
--- a/test/install-ref.test.ts
+++ b/test/install-ref.test.ts
@@ -47,6 +47,13 @@ describe('install ref lint', () => {
expect(driftIn('src/x.ts', 'const a = `github:garrytan/gbrain#v${v}`; const b = INSTALL_PIN;')).toEqual([]);
});
+ test('behavior-changes.d rows are held to the TypeScript rule, because the release folds their text into TypeScript', () => {
+ const row = 'Run bun install -g github:garrytan/gbrain#stable, then fetch https://raw.githubusercontent.com/garrytan/gbrain/stable/BOOTSTRAP_FOR_AGENTS.md\n';
+ expect(driftIn('behavior-changes.d/x_1.md', row, 'stable')).toHaveLength(2);
+ expect(rewriteText('behavior-changes.d/x_1.md', row, 'stable')).toBe(row);
+ expect(driftIn('behavior-changes.d/README.md', row, 'stable')).toEqual([]);
+ });
+
test('the setup helper resolves the constant, and --write flips every text surface in one pass', () => {
expect(driftIn('scripts/setup-in-agent.sh', 'gbrain_install_ref=master\n')).toHaveLength(1);
const doc = 'github:garrytan/gbrain#latest-stable\nraw.githubusercontent.com/garrytan/gbrain/latest-stable/BOOTSTRAP_FOR_AGENTS.md\ngbrain_install_ref=latest-stable\ngithub:garrytan/gbrain#v1.2.3.4\n';
diff --git a/test/migrations-notice.test.ts b/test/migrations-notice.test.ts
index 828c524fac..4b77cd1023 100644
--- a/test/migrations-notice.test.ts
+++ b/test/migrations-notice.test.ts
@@ -42,6 +42,16 @@ describe('pendingUpgradeMigrationsNotice', () => {
expect(notice?.why).toContain(latest);
});
+ test('a wedged migration gets a notice whose fix asks the user before clearing it', async () => {
+ const notice = await inHome(async () => {
+ for (const version of MIGRATION_VERSIONS) if (version !== latest) appendCompletedMigration({ version, status: 'complete' } as never);
+ for (let i = 0; i < 3; i++) appendCompletedMigration({ version: latest, status: 'partial' } as never);
+ return pendingUpgradeMigrationsNotice(engine, 'query', latest);
+ });
+ expect(notice).toMatchObject({ code: 'migrations_pending', fix: { ask_user: true, argv: ['gbrain', 'apply-migrations', '--force-retry', latest] } });
+ expect(notice!.why).toContain(latest);
+ });
+
test('no ledger yet (a fresh brain) means no notice', async () => {
expect(await inHome(() => pendingUpgradeMigrationsNotice(engine, 'query', latest))).toBeNull();
});
diff --git a/test/pg-access-classify.test.ts b/test/pg-access-classify.test.ts
index 0c680bde27..57c4c6b572 100644
--- a/test/pg-access-classify.test.ts
+++ b/test/pg-access-classify.test.ts
@@ -216,6 +216,14 @@ describe('supabase enrichment', () => {
}
});
+ it('#8531: dns_failed on a shared pooler host points at local DNS, not a paused project; a direct host keeps the paused hint', () => {
+ const pooler = classifyPgAccessError(errWithCode('ENOTFOUND'), { url: POOLER }).remediation;
+ expect(pooler).toContain("this machine's DNS/network");
+ expect(pooler).not.toContain('paused');
+ const direct = classifyPgAccessError(errWithCode('ENOTFOUND'), { url: 'postgresql://[email protected]:5432/postgres' }).remediation;
+ expect(direct).toContain('paused');
+ });
+
it('does not flag pausedSuspect on non-pause reasons or non-supabase urls', () => {
expect(classifyPgAccessError(errWithCode('ECONNREFUSED'), { url: POOLER }).supabase?.pausedSuspect).toBe(false);
expect(classifyPgAccessError(errWithCode('ENOTFOUND'), { url: 'postgresql://me:pw@localhost:5432/db' }).supabase).toBeUndefined(); /* allow-pg-url-literal */
diff --git a/test/remote-bridge-errors.test.ts b/test/remote-bridge-errors.test.ts
index 94f106bf17..8acac0ce2f 100644
--- a/test/remote-bridge-errors.test.ts
+++ b/test/remote-bridge-errors.test.ts
@@ -30,15 +30,15 @@ afterAll(() => { for (const h of homes) rmSync(h, { recursive: true, force: true
type Forward = (c: GBrainConfig, name: string, args: Record<string, unknown>, o: ForwardRemoteToolOptions & { meta?: Record<string, unknown> }) => Promise<CallToolResult>;
-async function startBridge(over: { forward?: Forward; list?: () => Promise<RemoteToolDefs>; transport?: RemoteBridgeOptions['transport']; advertise?: RemoteBridgeOptions['advertise'] } = {}) {
+async function startBridge(over: { forward?: Forward; list?: () => Promise<RemoteToolDefs>; transport?: RemoteBridgeOptions['transport']; advertise?: RemoteBridgeOptions['advertise']; eofDrainMs?: number } = {}) {
const home = mkdtempSync(join(tmpdir(), 'gbrain-bridge-unit-'));
homes.push(home);
const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
const logs: string[] = [];
const exits: number[] = [];
- const stdin = Object.assign(new EventEmitter(), { isTTY: true });
+ const stdin = Object.assign(new EventEmitter(), { isTTY: over.eofDrainMs === undefined });
await withEnv({ GBRAIN_HOME: home, GBRAIN_SURFACE: undefined }, () => startRemoteStdioBridge(cfg, {
- installFatalHandlers: false, mcpStdio: false, eofDrainMs: 0, ...(over.advertise ? { advertise: over.advertise } : {}),
+ installFatalHandlers: false, mcpStdio: false, eofDrainMs: over.eofDrainMs ?? 0, ...(over.advertise ? { advertise: over.advertise } : {}),
transport: over.transport ?? (() => serverSide),
lifecycle: { stdin: stdin as never, signals: new EventEmitter() as never, log: (m: string) => { logs.push(m); }, exit: (c?: number) => { exits.push(c ?? 0); },
getParentPid: () => 1, probeWatchdog: () => false },
@@ -47,7 +47,7 @@ async function startBridge(over: { forward?: Forward; list?: () => Promise<Remot
}));
const client = new Client({ name: 'bridge-unit', version: '1' }, { capabilities: {} });
if (!over.transport) await client.connect(clientSide);
- return { client, logs, exits, home, close: () => client.close().catch(() => {}) };
+ return { client, logs, exits, home, stdin, close: () => client.close().catch(() => {}) };
}
const body = (r: unknown) => JSON.parse(((r as CallToolResult).content[0] as { text: string }).text);
@@ -172,6 +172,21 @@ describe('unexpected faults', () => {
} finally { await b.close(); }
});
+ test('stdin EOF whose drain bound expires with a write in flight logs write_outcome_unknown and exits 1', async () => {
+ let started = false;
+ const b = await startBridge({ eofDrainMs: 50, forward: async () => { started = true; return await new Promise<CallToolResult>(() => {}); } });
+ try {
+ void b.client.callTool({ name: 'put_page', arguments: { slug: 'notes/eof-example', content: 'x' } }).catch(() => {});
+ for (let i = 0; i < 200 && !started; i++) await Bun.sleep(5);
+ b.stdin.emit('end');
+ for (let i = 0; i < 400 && !b.exits.length; i++) await Bun.sleep(5);
+ const unknown = b.logs.filter(l => l.includes('code=write_outcome_unknown'));
+ expect(unknown).toHaveLength(1);
+ expect(unknown[0]).toMatch(/tool=put_page submission_status=unknown request_id=[0-9a-f-]{36} fix="gbrain write-request -- [0-9a-f-]{36}"/);
+ expect(b.exits[0]).toBe(1);
+ } finally { await b.close(); }
+ });
+
test('a startup failure exits 1 with one secret-free stderr line', async () => {
const b = await startBridge({ transport: () => { throw new Error(`cannot open ${SECRET_URL}`); } });
expect(b.exits).toEqual([1]);
diff --git a/test/repair-purged-page-facts-8859.test.ts b/test/repair-purged-page-facts-8859.test.ts
index cdf9c8ebfa..fa02b53501 100644
--- a/test/repair-purged-page-facts-8859.test.ts
+++ b/test/repair-purged-page-facts-8859.test.ts
@@ -181,4 +181,13 @@ describe('#8859 purged-page-facts repair, unmanaged PGLite', () => {
await engine.executeRaw("UPDATE facts SET expired_at = now() WHERE expired_at IS NULL");
await edgeCases(engine);
}, 120_000);
+ test('a preview that lists only ambiguous rows prints an apply command that answers, not preview_changed (#9407)', async () => {
+ await engine.executeRaw("UPDATE facts SET expired_at = now() WHERE expired_at IS NULL");
+ const ambiguous = await fact(engine, 'An unrecorded example claim', 'notes/gone-example');
+ const preview = await repair(engine, []);
+ expect(preview.results[0]!.residuals).toMatchObject({ evidenced: 0, ambiguous: 1 });
+ const applied = await repair(engine, ['--apply', '--expect', hashOf(preview), '--yes']);
+ expect(applied.results[0]!.applied ?? 0).toBe(0);
+ expect(await active(engine, [ambiguous])).toEqual([ambiguous]);
+ }, 120_000);
});
diff --git a/test/scripts/promote-stable.test.ts b/test/scripts/promote-stable.test.ts
index ae64714ff7..5930ec0285 100644
--- a/test/scripts/promote-stable.test.ts
+++ b/test/scripts/promote-stable.test.ts
@@ -869,6 +869,14 @@ describe('GitHub Latest release', () => {
expect(back.writes).toHaveLength(1);
});
+ test('a forward promotion that cannot read the current Latest leaves it alone and says so (#9408)', async () => {
+ const h = harness();
+ const ghApi = h.deps.ghApi;
+ h.deps.ghApi = async path => { if (path.endsWith('/releases/latest')) throw new Error(`gh api ${path} failed: HTTP 502: Bad Gateway`); return ghApi(path); };
+ await refusedAsync(promote(h.deps, inputs()), /stable now points at v0\.60\.361\.0, but GitHub's current Latest release could not be read \(gh api .* HTTP 502.*\), so Latest was left alone; run `bun scripts\/release-channel\.ts backfill --apply`/);
+ expect(h.writes).toEqual([]);
+ });
+
test('a release with no id refuses before anything moves', async () => {
const h = harness({ release: { draft: false } });
await refusedAsync(promote(h.deps, inputs()), /has no id, so it cannot be marked Latest/);
diff --git a/test/scripts/run-verify-parallel.test.ts b/test/scripts/run-verify-parallel.test.ts
index 868f70d69e..00a47584ae 100644
--- a/test/scripts/run-verify-parallel.test.ts
+++ b/test/scripts/run-verify-parallel.test.ts
@@ -351,6 +351,25 @@ exit 0
}
});
+ it("#9316: creates its default temp log directory under TMPDIR", () => {
+ const { root, env } = makeFallbackHarness();
+ const { GBRAIN_VERIFY_LOG_DIR: _unused, ...defaults } = env;
+ const tmp = join(root, "tmp");
+ mkdirSync(tmp);
+ try {
+ const r = spawnSync("bash", [join(root, "scripts", "run-verify-parallel.sh")], {
+ encoding: "utf8",
+ env: { ...defaults, TMPDIR: tmp, STUB_FAIL_CHECK: "check:jsonb" },
+ });
+ expect(r.status).toBe(1);
+ const kept = /per-check logs kept in (\S+)/.exec(r.stderr)?.[1];
+ if (kept && !kept.startsWith(`${tmp}/`)) rmSync(kept, { recursive: true, force: true });
+ expect(kept?.startsWith(`${tmp}/gbrain-verify-`)).toBe(true);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
it("a self-timed SOLO check starts only after every pool check has finished, and fails like any other", () => {
const { root, env } = makeFallbackHarness();
try {
diff --git a/test/scripts/stable-daily.test.ts b/test/scripts/stable-daily.test.ts
index decfa62295..4ef785d989 100644
--- a/test/scripts/stable-daily.test.ts
+++ b/test/scripts/stable-daily.test.ts
@@ -136,6 +136,7 @@ function world(w: World) {
}
if (path.includes('/releases/tags/')) return { draft: false, id: 42 };
if (path.endsWith('/permission')) return { permission: 'none' };
+ if (path.endsWith('/releases/latest')) throw new Error(`gh api ${path} failed: HTTP 404: Not Found`);
throw new Error(`unexpected api ${path}`);
},
git,
diff --git a/test/serve-http-github-items-8799.test.ts b/test/serve-http-github-items-8799.test.ts
index 64675d61e7..e6c4fed79c 100644
--- a/test/serve-http-github-items-8799.test.ts
+++ b/test/serve-http-github-items-8799.test.ts
@@ -51,11 +51,11 @@ afterAll(async () => {
await engine?.disconnect();
}, 60_000);
-async function issueEvent(number: number, action: string, repo = REPO) {
+async function issueEvent(number: number, action: string, repo = REPO, delivery?: string) {
const payload = JSON.stringify({ action, repository: { full_name: repo }, issue: { number } });
const res = await fetch(`${base}/webhooks/github`, {
method: 'POST',
- headers: { 'content-type': 'application/json', 'x-github-event': 'issues',
+ headers: { 'content-type': 'application/json', 'x-github-event': 'issues', ...(delivery ? { 'x-github-delivery': delivery } : {}),
'x-hub-signature-256': `sha256=${createHmac('sha256', SECRET).update(payload).digest('hex')}` },
body: payload,
});
@@ -92,6 +92,20 @@ describe('#8799 GitHub item webhooks', () => {
expect(item).toMatchObject({ number: 1, deleted: true });
});
+ test('a second event after the first refresh started gets its own refresh; a redelivery of it does not', async () => {
+ const first = await issueEvent(7, 'edited', REPO, 'delivery-a');
+ expect(first.status).toBe(202);
+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed' WHERE id = $1", [first.body.job_id]);
+ const second = await issueEvent(7, 'labeled', REPO, 'delivery-b');
+ expect(second.status).toBe(202);
+ expect(second.body.job_id).not.toBe(first.body.job_id);
+ const redelivered = await issueEvent(7, 'labeled', REPO, 'delivery-b');
+ expect(redelivered.body.job_id).toBe(second.body.job_id);
+ expect((await issueEvent(7, 'assigned', REPO, 'delivery-c')).body.job_id).toBe(second.body.job_id);
+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed' WHERE id = $1", [second.body.job_id]);
+ expect((await issueEvent(7, 'edited', REPO, 'delivery-a')).body.job_id).toBe(first.body.job_id);
+ });
+
test('a full backlog refuses the event with 429 instead of answering with another item', async () => {
for (let number = 1; number <= 50; number++) expect((await issueEvent(number, 'edited', 'acme-example/other')).status).toBe(202);
const refused = await issueEvent(51, 'edited', 'acme-example/other');
diff --git a/test/setup-hosted-resolver-9245.test.ts b/test/setup-hosted-resolver-9245.test.ts
new file mode 100644
index 0000000000..377e575f36
--- /dev/null
+++ b/test/setup-hosted-resolver-9245.test.ts
@@ -0,0 +1,37 @@
+import { afterAll, describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { runCli } from './helpers/cli-spawn.ts';
+
+const CLI = resolve(import.meta.dir, '..', 'src', 'cli.ts');
+const root = mkdtempSync(join(tmpdir(), 'gbrain-setup-hosted-resolver-'));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+const home = join(root, 'home');
+const bin = join(root, 'bin', 'gbrain');
+mkdirSync(home, { recursive: true });
+mkdirSync(join(root, 'bin'));
+writeFileSync(bin, `#!/bin/sh\nexec '${process.execPath}' --no-env-file '${CLI}' "$@"\n`);
+chmodSync(bin, 0o755);
+mkdirSync(join(home, '.claude', 'skills', 'demo'), { recursive: true });
+writeFileSync(join(home, '.claude', 'skills', 'demo', 'SKILL.md'), '---\nname: demo\ndescription: a demo skill\n---\nbody\n');
+writeFileSync(join(home, '.claude.json'), JSON.stringify({ mcpServers: { gbrain: { type: 'http', url: 'https://brain.example.test/mcp', headers: { Authorization: 'Bearer x' } } } }));
+writeFileSync(join(home, '.gbrain-connection-claude-code-gbrain.json'), JSON.stringify({ client_id: 'client-a', mcp_url: 'https://brain.example.test/mcp', status: 'installed', harness: 'claude-code' }));
+
+const setup = (args: string[]) => runCli(['setup', 'claude-code', ...args, '--gbrain-bin', bin, '--json'], {
+ env: { CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, GBRAIN_SOURCE: undefined, GBRAIN_SURFACE: undefined, HOME: home, GBRAIN_HOME: home },
+});
+
+describe('#9245: a hosted install asking for the skill resolver is told the setup path that works', () => {
+ test('the refusal names --skills-index-only --skill-loading resolve, and that command runs', async () => {
+ const refused = await setup(['--skill-loading', 'resolve', '--dry-run']);
+ expect(refused.exitCode).toBe(1);
+ const doc = JSON.parse(refused.stdout);
+ expect(doc.code).toBe('setup_hosted_connection');
+ expect(JSON.stringify(doc)).toContain('gbrain setup claude-code --skills-index-only --skill-loading resolve');
+ const named = await setup(['--skills-index-only', '--skill-loading', 'resolve', '--dry-run']);
+ expect(named.exitCode).toBe(0);
+ expect(JSON.parse(named.stdout).skill_resolver.steps.map((s: { step: string }) => s.step)).toContain('catalog');
+ }, 60_000);
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 392aa65b3c..807ef54d24 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -19,9 +19,9 @@
*/
import { afterAll, describe, expect, test } from 'bun:test';
import { createServer, type Server } from 'node:net';
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
-import { join, resolve } from 'node:path';
+import { basename, join, resolve } from 'node:path';
import { runCli, type CliResult } from './helpers/cli-spawn.ts';
import { hookEntryHash, removeClaudeHooksAt, writeClaudeHooksAt } from '../src/core/bootstrap/hooks.ts';
import { GBRAIN_HOOK_MARKER_VALUE } from '../src/core/bootstrap/host-specs.ts';
@@ -584,6 +584,23 @@ describe('gbrain setup codex: install lifecycle', () => {
expect([codexToml(b), hooksJson(b), codexReceipt(b)].map((p) => readFileSync(p, 'utf8'))).toEqual(before);
});
+ test('an install that changes an existing config.toml or hooks.json keeps a timestamped .bak of each and names it', async () => {
+ const b = box();
+ mkdirSync(codexDir(b), { recursive: true });
+ const foreignToml = 'model = "o5"\n';
+ const foreignHooks = JSON.stringify({ hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'echo user-hook', timeout: 2 }] }] } }, null, 2);
+ writeFileSync(codexToml(b), foreignToml);
+ writeFileSync(hooksJson(b), foreignHooks);
+ const installed = await setup(b, ['codex', '--json']);
+ expect(installed.exitCode, installed.stderr).toBe(0);
+ for (const [file, original] of [[codexToml(b), foreignToml], [hooksJson(b), foreignHooks]] as const) {
+ const backups = readdirSync(codexDir(b)).filter((n) => n.startsWith(`${basename(file)}.bak.`));
+ expect(backups).toHaveLength(1);
+ expect(readFileSync(join(codexDir(b), backups[0]!), 'utf8')).toBe(original);
+ expect(installed.doc.notes.join('\n')).toContain(join(codexDir(b), backups[0]!));
+ }
+ });
+
test('--remove deletes exactly the owned entries; foreign config, hooks, trust entries and the brain stay byte-for-byte', async () => {
const b = box();
mkdirSync(codexDir(b), { recursive: true });
diff --git a/test/sources-attach-retry-default-search.test.ts b/test/sources-attach-retry-default-search.test.ts
new file mode 100644
index 0000000000..f477902127
--- /dev/null
+++ b/test/sources-attach-retry-default-search.test.ts
@@ -0,0 +1,33 @@
+/**
+ * An identical retry of a managed folder attach (same request id) replays the first answer.
+ *
+ * 1. Protects: attaching a folder to an existing source with no local path, then retrying the exact call with the
+ * same request id, succeeds both times; the default-search choice made for the first attempt is reused.
+ * 2. Fails when: the retry re-derives federated from the row the first attempt already wrote (it now has a local
+ * path), so the request digest changes and the retry answers idempotency_conflict.
+ * 3. No production seam: managedBrain on PGLite and the real addSource.
+ */
+import { expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { addSource } from '../src/core/sources-ops.ts';
+
+test('an identical attach retry with the same request id succeeds', async () => {
+ await managedBrain(async ({ engine }) => {
+ await addSource(engine, { id: 'att', requestId: randomUUID() });
+ await engine.executeRaw("UPDATE sources SET config = config - 'federated' WHERE id = 'att'");
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-attach-retry-'));
+ try {
+ const rid = randomUUID();
+ await addSource(engine, { id: 'att', localPath: dir, force: true, requestId: rid });
+ await addSource(engine, { id: 'att', localPath: dir, force: true, requestId: rid });
+ const [row] = await engine.executeRaw<{ local_path: string | null }>("SELECT local_path FROM sources WHERE id = 'att'");
+ expect(row?.local_path).toBe(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+}, 120_000);
diff --git a/test/sources-status-hold-fix-routing-9319.test.ts b/test/sources-status-hold-fix-routing-9319.test.ts
new file mode 100644
index 0000000000..398261cdea
--- /dev/null
+++ b/test/sources-status-hold-fix-routing-9319.test.ts
@@ -0,0 +1,22 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { gitHoldStatusJson } from '../src/core/persistence/connector-status.ts';
+import { gitHoldFix, type GitHoldItem } from '../src/core/persistence/sync-holds.ts';
+import { __resetCliRoutingForTests, installCliRouting } from '../src/core/fix-routing.ts';
+
+afterEach(() => __resetCliRoutingForTests());
+
+const hold = { source_id: 'source-a', path: 'notes/alice-example.md', code: 'concurrent_write' as const, slug: 'notes/alice-example', meta: {} };
+const item: GitHoldItem = {
+ path: hold.path, code: hold.code, message: 'held', slug: hold.slug, stale: true, held_since: '2026-01-01T00:00:00Z',
+ docs: 'docs/guides/write-refusals.md', fix: gitHoldFix(hold as Parameters<typeof gitHoldFix>[0]),
+};
+
+describe('#9319: sources status --json renders hold fixes with the routing pin', () => {
+ test('a concurrent_write fix names the brain the status call read, in items and by_code', () => {
+ installCliRouting(() => ({ brain: 'host' }));
+ const out = gitHoldStatusJson('source-a', { count: 1, items: [item], sync_argv: ['gbrain', 'sync', '--source', 'source-a', '--no-pull'] }, { mode: 'summary' });
+ const pinned = ['gbrain', 'sources', 'reconcile', 'source-a', 'notes/alice-example', '--preview', '--brain', 'host'];
+ expect(out.items[0]!.fix.argv).toEqual(pinned);
+ expect(out.by_code[0]!.example.fix.argv).toEqual(pinned);
+ });
+});
diff --git a/test/sources-status-holds-bounded-7326.test.ts b/test/sources-status-holds-bounded-7326.test.ts
index 3acf08177e..a9951c7cbd 100644
--- a/test/sources-status-holds-bounded-7326.test.ts
+++ b/test/sources-status-holds-bounded-7326.test.ts
@@ -5,7 +5,7 @@ import type { GitHoldItem } from '../src/core/persistence/sync-holds.ts';
const item = (i: number, code: string): GitHoldItem => ({
path: `notes/file-${String(i).padStart(4, '0')}.md`, code: code as GitHoldItem['code'], message: 'held: a location-only message '.repeat(20),
slug: null, stale: false, held_since: '2026-01-01T00:00:00Z', docs: 'docs/guides/write-refusals.md',
- fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', 'source-a'], why: 'Previews the repair; read-only. '.repeat(10) } as unknown as GitHoldItem['fix'],
+ fix: { argv: ['gbrain', 'repair', 'frontmatter', '--source', 'source-a'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Previews the repair; read-only. '.repeat(10) },
});
const holds = (n: number): GitHoldStatus => ({
diff --git a/test/stdio-exit-drain.test.ts b/test/stdio-exit-drain.test.ts
new file mode 100644
index 0000000000..c4a31e889a
--- /dev/null
+++ b/test/stdio-exit-drain.test.ts
@@ -0,0 +1,56 @@
+/**
+ * GST-2760: a stdio MCP process whose stdin closes while a large reply is still buffered must deliver the whole reply
+ * before it exits. Bun's process.exit drops stdout it still holds (an 8 MiB write arrives as 64 KiB). Drives the real
+ * thin-client bridge in a child process over its own stdio, with the remote calls injected.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+const dir = mkdtempSync(join(tmpdir(), 'gbrain-stdio-drain-'));
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+const BRIDGE = join(import.meta.dir, '..', 'src', 'mcp', 'remote-bridge.ts');
+const SIZE = 8 * 1024 * 1024;
+
+describe('stdio exit drains stdout', () => {
+ test('stdin EOF right after a large reply delivers all of it', async () => {
+ const script = join(dir, 'bridge-child.ts');
+ writeFileSync(script, `
+import { startRemoteStdioBridge } from ${JSON.stringify(BRIDGE)};
+const cfg = { engine: 'postgres', remote_mcp: { issuer_url: 'https://host.example', mcp_url: 'https://host.example/mcp', oauth_client_id: 'gbrain_cl_example', oauth_client_secret: 'secret-example' } };
+await startRemoteStdioBridge(cfg as never, {
+ installFatalHandlers: false, mcpStdio: false,
+ lifecycle: { getParentPid: () => 1, probeWatchdog: () => false },
+ list: (async () => ({ server: { name: 'gbrain', version: '9.0.0.0' }, tools: [{ name: 'get_page', inputSchema: { type: 'object' } }] })) as never,
+ forward: (async () => ({ content: [{ type: 'text', text: 'y'.repeat(${SIZE}) }] })) as never,
+});
+`);
+ const child = Bun.spawn([process.execPath, '--no-env-file', script], { cwd: dir, env: { PATH: process.env.PATH ?? '', HOME: dir, GBRAIN_HOME: dir, GBRAIN_SURFACE: 'full' },
+ stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'raw', version: '1' } } }) + '\n');
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n');
+ child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'get_page', arguments: { slug: 'notes/big-example' } } }) + '\n');
+ child.stdin.end();
+ const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]);
+ const reply = out.split('\n').filter(Boolean).map(line => { try { return JSON.parse(line); } catch { return null; } }).find(m => m?.id === 2);
+ expect({ code, bytes: out.length >= SIZE, err: code ? err : '' }).toEqual({ code: 0, bytes: true, err: '' });
+ expect(reply?.result?.content?.[0]?.text?.length).toBe(SIZE);
+ }, 60_000);
+
+ test('the exit waits for the flush, and a reader that never reads cannot hold it past the bound', async () => {
+ const { PassThrough } = await import('node:stream');
+ const { exitAfterStdoutDrains } = await import('../src/mcp/stdio-lifecycle.ts');
+ const exits: Array<number | undefined> = [];
+ const flushed = new PassThrough();
+ exitAfterStdoutDrains(code => exits.push(code), flushed, 5_000)(0);
+ flushed.resume();
+ for (let i = 0; i < 100 && !exits.length; i++) await Bun.sleep(5);
+ expect(exits).toEqual([0]);
+ const stuck = Object.assign(new PassThrough(), { end: () => stuck });
+ exitAfterStdoutDrains(code => exits.push(code), stuck as never, 20)(1);
+ await Bun.sleep(60);
+ expect(exits).toEqual([0, 1]);
+ });
+});
diff --git a/test/upgrade-help-postinstall.test.ts b/test/upgrade-help-postinstall.test.ts
new file mode 100644
index 0000000000..94c880cd66
--- /dev/null
+++ b/test/upgrade-help-postinstall.test.ts
@@ -0,0 +1,15 @@
+/**
+ * gbrain ships no postinstall script (#9383), so upgrade's help names none.
+ */
+import { describe, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { join } from 'node:path';
+
+describe('gbrain upgrade --help', () => {
+ test('names no package postinstall', () => {
+ const run = spawnSync('bun', [join(import.meta.dir, '..', 'src', 'cli.ts'), 'upgrade', '--help'], { encoding: 'utf8', timeout: 60_000 });
+ expect(run.status).toBe(0);
+ expect(run.stdout).toContain('--no-autopilot-install');
+ expect(run.stdout).not.toContain('postinstall');
+ }, 90_000);
+});