Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(lane-h): H1b split, H2 mid-transition row, journey transcripts; fix(serve-http): fail fast on a taken port
garrytan2461bcec8bb7
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 4d709b354d..9ba3cbed18 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1533,6 +1533,14 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-cMore: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-connect.md#troubleshooting)+### serve_port_in_use++<a id="serve_port_in_use"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| gbrain serve --http could not listen: another process already holds that host and port. | A capability this request needs is not configured or not reachable on this brain. | Stop the process on that port, or start the server with another --port and point the harnesses at it. | agent | `gbrain doctor --json` | 1 | no |+### serve_status_only<a id="serve_status_only"></a>diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex 1a72e67bc1..9769bd0f84 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -25,13 +25,16 @@ offline: `gbrain errors <code>`), [exit codes](../guides/exit-codes.md),4. Treat `[gbrain notice …]` blocks and `[AGENT]` blocks the same way. A degraded result is not proof of "no notes".<!-- END quick-contract -->-## Three transcripts+## TranscriptsThese are generated from the frozen wire goldens in`test/fixtures/agent-contract/v1/` by `bun run build:agent-protocol`; thegoldens never store `next`, so the generator recomputes it with the samedecision table gbrain uses at render time. Docs URLs on the wire are pinned to-the installed version; the transcripts show `master`.+the installed version; the transcripts show `master`. Transcripts marked+"journey" are recorded from real CLI and stdio MCP runs by the deterministic+agent journey (`test/agent-journey.serial.test.ts`); machine values (home+directory, pids, ids, times) show as fixed examples.<!-- BEGIN GENERATED agent-protocol:transcripts (bun run build:agent-protocol) -->### 1. A caller mistake over MCP: `run`@@ -215,6 +218,282 @@ user_message: I found no notes on that topic. Your brain searches keywords only````content[0]` is still the bare array `[]`; the second block is the notice. The agent does not tell the user "you have no notes on that". It relays `user_message` ("I found no notes on that topic. Your brain searches keywords only right now."). `fix.next` is `tell_user_to_run` because the fix is the user's to run (`gbrain doctor --json`) in their terminal, so the agent offers it rather than running it.++### 4. First run on a keyless brain: one decision bundle, `ask_user` (journey)++An agent installs gbrain for a user with no provider keys, from a non-interactive shell (H1a journey, recorded from the real CLI).++```bash+gbrain init --pglite --no-embedding --json+```++stdout (`--json`):++```json+{+ "status": "success",+ "engine": "pglite",+ "path": "/home/alice-example/.gbrain/brain.pglite",+ "pages": 0,+ "embedding_check": {+ "ok": true,+ "skipped": "no_embedding"+ },+ "content": {+ "version": 1,+ "brain_id": "7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11",+ "source_id": "default",+ "source_incarnation": "7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11",+ "root": "/home/alice-example/.gbrain/content/7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11/default",+ "repository_kind": "content_directory",+ "backup": "not_verified",+ "status": "ready",+ "stage": "complete",+ "pending_actions": [+ "Optional: initialize Git explicitly; configure an off-host backup separately."+ ],+ "owned_root": true,+ "fresh_root_activation": true,+ "root_identity": "(device and inode of the content root)"+ },+ "notices": [+ {+ "code": "first_run_decisions",+ "kind": "ask",+ "why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; harness_wiring: skip), or tell me what to change.",+ "decisions": [+ {+ "id": "search_mode",+ "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "options": [+ {+ "id": "conservative",+ "label": "conservative (applied)",+ "argv": [+ "gbrain",+ "config",+ "set",+ "search.mode",+ "conservative"+ ]+ },+ {+ "id": "balanced",+ "label": "balanced",+ "argv": [+ "gbrain",+ "config",+ "set",+ "search.mode",+ "balanced"+ ]+ },+ {+ "id": "tokenmax",+ "label": "tokenmax",+ "argv": [+ "gbrain",+ "config",+ "set",+ "search.mode",+ "tokenmax"+ ]+ }+ ],+ "default": "conservative",+ "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ },+ {+ "id": "harness_wiring",+ "question": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",+ "options": [+ {+ "id": "wire",+ "label": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."+ },+ {+ "id": "skip",+ "label": "Do not register gbrain with an agent harness now."+ }+ ],+ "default": "skip",+ "default_reason": "No agent harness was detected."+ }+ ],+ "contract_version": 1+ }+ ],+ "contract_version": 1+}+```++stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.++### 5. A caller mistake over stdio MCP, recorded: `run` (journey)++A harness on `gbrain serve --surface verbs` passes a string where `recall` expects a number (H1a journey, recorded from a real stdio session).++```text+recall {"query":"quokka-journey-marker","limit":"abc"}+```++gbrain returns (`isError: true`, the envelope shown parsed):++```json+{+ "error": "invalid_params",+ "code": "invalid_params",+ "message": "Parameter \"limit\" must be a number",+ "suggestion": "Pass `limit` as a number (Per-arm cap: max fact rows AND max search results. Default 50, cap 100). Example: recall {\"limit\": 10}. Next: recall {\"query\":\"quokka-journey-marker\",\"limit\":10}",+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#invalid_params",+ "protocol_version": 1,+ "fix": {+ "mcp": {+ "tool": "recall",+ "arguments": {+ "query": "quokka-journey-marker",+ "limit": 10+ }+ },+ "consent": [],+ "actor": "agent",+ "next": "run",+ "why": "The call failed validation before it ran, so nothing changed. This is the same call with your other arguments kept and `limit` set to 10.",+ "requires_exclusive": false+ },+ "docs_cmd": [+ "gbrain",+ "errors",+ "invalid_params"+ ],+ "class": "caller",+ "retryable": false,+ "contract_version": 1+}+```++One content block, `code: invalid_params`, `class: caller`. Nothing ran, so `fix.next: run`: the agent calls `recall {"query":"quokka-journey-marker","limit":10}` exactly as given (its other arguments kept, the bad one corrected) and gets the recall it wanted.++### 6. A second session on a locked brain: status-only serve, `tell_user_to_run` (journey)++A second agent session starts `gbrain serve` while another session's serve owns the PGLite brain. The handshake still completes, with one tool, `gbrain_status` (H1a journey, recorded).++```text+gbrain_status {}+```++gbrain returns these content blocks:++`content[0]`:++```json+{+ "status": "unavailable",+ "reason": "lock_held",+ "why": "This brain (/home/alice-example/.gbrain/brain.pglite) is open in another `gbrain serve` (PID 48213), usually started by another agent session, so this server cannot open it.",+ "brain_path": "/home/alice-example/.gbrain/brain.pglite",+ "config_path": "/home/alice-example/.gbrain/config.json",+ "lock_owner": {+ "pid": "48213",+ "transport": "stdio",+ "serve": true+ },+ "fix": {+ "mcp": {+ "tool": "gbrain_status",+ "arguments": {}+ },+ "consent": [],+ "actor": "user",+ "next": "tell_user_to_run",+ "why": "Close the session that owns the brain (another `gbrain serve` (PID 48213), usually started by another agent session); then call gbrain_status again and this server opens the brain in place (re-checked at most every 5 s). If your client does not refresh its tool list after recovery, restart this MCP server.",+ "user_message": "Your gbrain brain is already open in another gbrain serve (PID 48213), usually started by another agent session, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?",+ "requires_exclusive": false+ },+ "user_message": "Your gbrain brain is already open in another gbrain serve (PID 48213), usually started by another agent session, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?",+ "decisions": [+ {+ "id": "lock_recovery",+ "question": "Two agent sessions want the same brain. Close the other session, or share one HTTP server?",+ "options": [+ {+ "id": "close_owner",+ "label": "Close another gbrain serve (PID 48213), usually started by another agent session; this server recovers on the next gbrain_status call."+ },+ {+ "id": "share_http",+ "label": "Run one shared `gbrain serve --http` and connect every harness to it (writes harness config, mints tokens); the full plan is share_http_plan.",+ "argv": [+ "kill",+ "48213"+ ]+ }+ ],+ "default": "close_owner",+ "default_reason": "Nothing is installed or reconfigured; the brain comes back as soon as the other session ends."+ }+ ],+ "share_http_plan": {+ "argv": [+ "kill",+ "48213"+ ],+ "command": "kill 48213",+ "consent": [],+ "actor": "user",+ "why": "Stop another `gbrain serve` (PID 48213), usually started by another agent session first (or quit that session); the shared server needs the brain's single-writer lock.",+ "requires_exclusive": false,+ "then": {+ "argv": [+ "gbrain",+ "serve",+ "--http"+ ],+ "command": "gbrain serve --http",+ "consent": [+ "persistent_install"+ ],+ "actor": "user",+ "why": "Run ONE shared HTTP server for every agent session on this machine (keep it running, e.g. under autopilot or a terminal).",+ "requires_exclusive": true,+ "then": {+ "argv": [+ "gbrain",+ "bootstrap",+ "harness",+ "--harness",+ "all",+ "--yes"+ ],+ "command": "gbrain bootstrap harness --harness all --yes",+ "consent": [+ "persistent_install",+ "credentials"+ ],+ "actor": "user",+ "why": "Mints one bearer token per detected harness through the running HTTP server and rewrites each harness MCP entry to it (each stdio entry keeps working until its harness is rewired).",+ "user_message": "I can connect your agent apps to the shared gbrain server so every session uses memory at once. That stores an access token in each app's config and pre-approves gbrain's tools. OK?",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "harness_wiring",+ "--json"+ ]+ },+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/remote-mcp.md",+ "requires_exclusive": false+ }+ }+ },+ "checked_at": "2026-10-03T16:20:00.000Z",+ "contract_version": 1+}+```++`reason: lock_held` names the owner (`lock_owner.pid`). `fix.next` is `tell_user_to_run` because only the user can close the other session: the agent relays `user_message` and offers `close_owner` or `share_http`. Calling `gbrain_status` again after the owner exits opens the brain in place and the full tool list arrives through `tools/list_changed`.<!-- END GENERATED agent-protocol:transcripts -->## The error envelopediff --git a/llms-full.txt b/llms-full.txtindex 3810771d9f..1a21ddff84 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3088,13 +3088,16 @@ offline: `gbrain errors <code>`), [exit codes](../guides/exit-codes.md),4. Treat `[gbrain notice …]` blocks and `[AGENT]` blocks the same way. A degraded result is not proof of "no notes".<!-- END quick-contract -->-## Three transcripts+## TranscriptsThese are generated from the frozen wire goldens in`test/fixtures/agent-contract/v1/` by `bun run build:agent-protocol`; thegoldens never store `next`, so the generator recomputes it with the samedecision table gbrain uses at render time. Docs URLs on the wire are pinned to-the installed version; the transcripts show `master`.+the installed version; the transcripts show `master`. Transcripts marked+"journey" are recorded from real CLI and stdio MCP runs by the deterministic+agent journey (`test/agent-journey.serial.test.ts`); machine values (home+directory, pids, ids, times) show as fixed examples.<!-- BEGIN GENERATED agent-protocol:transcripts (bun run build:agent-protocol) -->### 1. A caller mistake over MCP: `run`@@ -3278,6 +3281,282 @@ user_message: I found no notes on that topic. Your brain searches keywords only````content[0]` is still the bare array `[]`; the second block is the notice. The agent does not tell the user "you have no notes on that". It relays `user_message` ("I found no notes on that topic. Your brain searches keywords only right now."). `fix.next` is `tell_user_to_run` because the fix is the user's to run (`gbrain doctor --json`) in their terminal, so the agent offers it rather than running it.++### 4. First run on a keyless brain: one decision bundle, `ask_user` (journey)++An agent installs gbrain for a user with no provider keys, from a non-interactive shell (H1a journey, recorded from the real CLI).++```bash+gbrain init --pglite --no-embedding --json+```++stdout (`--json`):++```json+{+ "status": "success",+ "engine": "pglite",+ "path": "/home/alice-example/.gbrain/brain.pglite",+ "pages": 0,+ "embedding_check": {+ "ok": true,+ "skipped": "no_embedding"+ },+ "content": {+ "version": 1,+ "brain_id": "7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11",+ "source_id": "default",+ "source_incarnation": "7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11",+ "root": "/home/alice-example/.gbrain/content/7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11/default",+ "repository_kind": "content_directory",+ "backup": "not_verified",+ "status": "ready",+ "stage": "complete",+ "pending_actions": [+ "Optional: initialize Git explicitly; configure an off-host backup separately."+ ],+ "owned_root": true,+ "fresh_root_activation": true,+ "root_identity": "(device and inode of the content root)"+ },+ "notices": [+ {+ "code": "first_run_decisions",+ "kind": "ask",+ "why": "The brain is ready. These settings were applied with defaults or need the user's choice; none blocks using the brain.",+ "user_message": "gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; harness_wiring: skip), or tell me what to change.",+ "decisions": [+ {+ "id": "search_mode",+ "question": "Which search mode should this brain use? Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.",+ "options": [+ {+ "id": "conservative",+ "label": "conservative (applied)",+ "argv": [+ "gbrain",+ "config",+ "set",+ "search.mode",+ "conservative"+ ]+ },+ {+ "id": "balanced",+ "label": "balanced",+ "argv": [+ "gbrain",+ "config",+ "set",+ "search.mode",+ "balanced"+ ]+ },+ {+ "id": "tokenmax",+ "label": "tokenmax",+ "argv": [+ "gbrain",+ "config",+ "set",+ "search.mode",+ "tokenmax"+ ]+ }+ ],+ "default": "conservative",+ "default_reason": "No expansion-capable API key (Anthropic/OpenAI/Google) — start with a tight result budget; semantic result caching is temporarily disabled."+ },+ {+ "id": "harness_wiring",+ "question": "Which agent app should get gbrain memory? The install guide has a one-line command for each.",+ "options": [+ {+ "id": "wire",+ "label": "Register `<absolute path to gbrain> serve --surface verbs` as a stdio MCP server in your agent host; the install section lists the exact command per harness (Claude Code, Codex, Grok Build, opencode, OpenClaw)."+ },+ {+ "id": "skip",+ "label": "Do not register gbrain with an agent harness now."+ }+ ],+ "default": "skip",+ "default_reason": "No agent harness was detected."+ }+ ],+ "contract_version": 1+ }+ ],+ "contract_version": 1+}+```++stdout is one document; the brain is ready and nothing blocks using it. The `first_run_decisions` notice is `kind: ask`, so the agent relays its `user_message` ("gbrain is installed. Reply 'defaults' to keep the recommended settings (search_mode: conservative; harness_wiring: skip), or tell me what to change.") once and stops. The decisions are `search_mode` (default `conservative`), `harness_wiring` (default `skip`); each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.++### 5. A caller mistake over stdio MCP, recorded: `run` (journey)++A harness on `gbrain serve --surface verbs` passes a string where `recall` expects a number (H1a journey, recorded from a real stdio session).++```text+recall {"query":"quokka-journey-marker","limit":"abc"}+```++gbrain returns (`isError: true`, the envelope shown parsed):++```json+{+ "error": "invalid_params",+ "code": "invalid_params",+ "message": "Parameter \"limit\" must be a number",+ "suggestion": "Pass `limit` as a number (Per-arm cap: max fact rows AND max search results. Default 50, cap 100). Example: recall {\"limit\": 10}. Next: recall {\"query\":\"quokka-journey-marker\",\"limit\":10}",+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#invalid_params",+ "protocol_version": 1,+ "fix": {+ "mcp": {+ "tool": "recall",+ "arguments": {+ "query": "quokka-journey-marker",+ "limit": 10+ }+ },+ "consent": [],+ "actor": "agent",+ "next": "run",+ "why": "The call failed validation before it ran, so nothing changed. This is the same call with your other arguments kept and `limit` set to 10.",+ "requires_exclusive": false+ },+ "docs_cmd": [+ "gbrain",+ "errors",+ "invalid_params"+ ],+ "class": "caller",+ "retryable": false,+ "contract_version": 1+}+```++One content block, `code: invalid_params`, `class: caller`. Nothing ran, so `fix.next: run`: the agent calls `recall {"query":"quokka-journey-marker","limit":10}` exactly as given (its other arguments kept, the bad one corrected) and gets the recall it wanted.++### 6. A second session on a locked brain: status-only serve, `tell_user_to_run` (journey)++A second agent session starts `gbrain serve` while another session's serve owns the PGLite brain. The handshake still completes, with one tool, `gbrain_status` (H1a journey, recorded).++```text+gbrain_status {}+```++gbrain returns these content blocks:++`content[0]`:++```json+{+ "status": "unavailable",+ "reason": "lock_held",+ "why": "This brain (/home/alice-example/.gbrain/brain.pglite) is open in another `gbrain serve` (PID 48213), usually started by another agent session, so this server cannot open it.",+ "brain_path": "/home/alice-example/.gbrain/brain.pglite",+ "config_path": "/home/alice-example/.gbrain/config.json",+ "lock_owner": {+ "pid": "48213",+ "transport": "stdio",+ "serve": true+ },+ "fix": {+ "mcp": {+ "tool": "gbrain_status",+ "arguments": {}+ },+ "consent": [],+ "actor": "user",+ "next": "tell_user_to_run",+ "why": "Close the session that owns the brain (another `gbrain serve` (PID 48213), usually started by another agent session); then call gbrain_status again and this server opens the brain in place (re-checked at most every 5 s). If your client does not refresh its tool list after recovery, restart this MCP server.",+ "user_message": "Your gbrain brain is already open in another gbrain serve (PID 48213), usually started by another agent session, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?",+ "requires_exclusive": false+ },+ "user_message": "Your gbrain brain is already open in another gbrain serve (PID 48213), usually started by another agent session, so this session can't use memory right now. Close that session and I'll reconnect, or I can set up one shared gbrain server so both sessions work at once. Which do you prefer?",+ "decisions": [+ {+ "id": "lock_recovery",+ "question": "Two agent sessions want the same brain. Close the other session, or share one HTTP server?",+ "options": [+ {+ "id": "close_owner",+ "label": "Close another gbrain serve (PID 48213), usually started by another agent session; this server recovers on the next gbrain_status call."+ },+ {+ "id": "share_http",+ "label": "Run one shared `gbrain serve --http` and connect every harness to it (writes harness config, mints tokens); the full plan is share_http_plan.",+ "argv": [+ "kill",+ "48213"+ ]+ }+ ],+ "default": "close_owner",+ "default_reason": "Nothing is installed or reconfigured; the brain comes back as soon as the other session ends."+ }+ ],+ "share_http_plan": {+ "argv": [+ "kill",+ "48213"+ ],+ "command": "kill 48213",+ "consent": [],+ "actor": "user",+ "why": "Stop another `gbrain serve` (PID 48213), usually started by another agent session first (or quit that session); the shared server needs the brain's single-writer lock.",+ "requires_exclusive": false,+ "then": {+ "argv": [+ "gbrain",+ "serve",+ "--http"+ ],+ "command": "gbrain serve --http",+ "consent": [+ "persistent_install"+ ],+ "actor": "user",+ "why": "Run ONE shared HTTP server for every agent session on this machine (keep it running, e.g. under autopilot or a terminal).",+ "requires_exclusive": true,+ "then": {+ "argv": [+ "gbrain",+ "bootstrap",+ "harness",+ "--harness",+ "all",+ "--yes"+ ],+ "command": "gbrain bootstrap harness --harness all --yes",+ "consent": [+ "persistent_install",+ "credentials"+ ],+ "actor": "user",+ "why": "Mints one bearer token per detected harness through the running HTTP server and rewrites each harness MCP entry to it (each stdio entry keeps working until its harness is rewired).",+ "user_message": "I can connect your agent apps to the shared gbrain server so every session uses memory at once. That stores an access token in each app's config and pre-approves gbrain's tools. OK?",+ "verify": {+ "argv": [+ "gbrain",+ "doctor",+ "--only",+ "harness_wiring",+ "--json"+ ]+ },+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/remote-mcp.md",+ "requires_exclusive": false+ }+ }+ },+ "checked_at": "2026-10-03T16:20:00.000Z",+ "contract_version": 1+}+```++`reason: lock_held` names the owner (`lock_owner.pid`). `fix.next` is `tell_user_to_run` because only the user can close the other session: the agent relays `user_message` and offers `close_owner` or `share_http`. Calling `gbrain_status` again after the owner exits opens the brain in place and the full tool list arrives through `tools/list_changed`.<!-- END GENERATED agent-protocol:transcripts -->## The error envelopediff --git a/scripts/build-agent-protocol.ts b/scripts/build-agent-protocol.tsindex 5aee364233..c8e1c30f65 100644--- a/scripts/build-agent-protocol.ts+++ b/scripts/build-agent-protocol.ts@@ -5,7 +5,7 @@* bun run build:agent-protocol rewrite the regions* bun run build:agent-protocol --check exit 1 when a committed region is stale*- * 1. docs/protocol/AGENT_OPERATOR_v1.md "Three transcripts": rendered from the+ * 1. docs/protocol/AGENT_OPERATOR_v1.md "Transcripts": rendered from the* frozen wire goldens in test/fixtures/agent-contract/v1/. Goldens never* store `next`; it is recomputed here with deriveNext (the same decision* table gbrain renders with) and checked against each transcript's@@ -14,7 +14,9 @@* the protocol page's quick-contract region.** Adding a transcript (Lane H journey goldens): append a TRANSCRIPTS entry- * naming its golden file, transport, expected `next` and narration.+ * naming its golden file, transport, expected `next` and narration. Journey+ * goldens (`journey/*.json`) are recorded by test/agent-journey.serial.test.ts+ * from real runs; their placeholders render as fixed example values.* Drift test: test/agent-protocol-doc.test.ts.*/import { readFileSync, writeFileSync } from 'node:fs';@@ -44,6 +46,8 @@ interface Transcript {call: string;/** Prose for what the agent does, given the rendered value. */after: (doc: Json) => string;+ /** The value checked against expectNext when it is not a fix's `next` (an `ask` notice means ask_user). */+ nextOf?: (doc: Json) => string;}function contextFor(transport: Transport): RenderContext {@@ -73,13 +77,23 @@ function hydrate(value: unknown, ctx: RenderContext, noticeNexts: string[] = [])return out;}if (typeof value !== 'string') return value;- const text = value.split('{{DOCS_BASE}}').join(DOCS_BASE);+ const text = value.split('{{DOCS_BASE}}').join(DOCS_BASE).replace(/\{\{([A-Z_]+)\}\}/g, (m, name: string) => JOURNEY_VALUES[name] ?? m);if (text.startsWith('{')) {try { return JSON.stringify(hydrate(JSON.parse(text), ctx), null, 2); } catch { /* prose */ }}return text.includes('next: {{next}}') ? text.replace('next: {{next}}', `next: ${noticeNexts.shift() ?? 'report'}`) : text;}+/**+ * Journey goldens (test/fixtures/agent-contract/v1/journey/, Lane H) are real+ * runs with machine values replaced by placeholders; transcripts show fixed+ * example values instead.+ */+const JOURNEY_VALUES: Record<string, string> = {+ HOME: '/home/alice-example', PID: '48213', UUID: '7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11', TIME: '2026-10-03T16:20:00.000Z',+ PLAN_HASH: 'ph_5f1c0e9a2b7d4c3e8a6b0d1f', DURATION_S: '0.4', ROOT_IDENTITY: '(device and inode of the content root)', DOCTOR_RUN_ID: '7f3c2a10-5b6e-4d1a-9c8b-2e4f6a8d0c11',+};+function loadGolden(name: string, transport: Transport): Json {const raw = JSON.parse(readFileSync(join(GOLDENS, name), 'utf8')) as Json;const ctx = contextFor(transport);@@ -91,7 +105,7 @@ function loadGolden(name: string, transport: Transport): Json {/** The envelope inside an MCP error result, or the document itself. */function body(doc: Json): Json {const content = doc.content as { text: string }[] | undefined;- return content ? JSON.parse(content[0].text) as Json : doc;+ return Array.isArray(content) ? JSON.parse(content[0].text) as Json : doc;}function step(fix: Json | undefined): string {@@ -150,12 +164,57 @@ export const TRANSCRIPTS: readonly Transcript[] = [+ `because the fix is the user's to run (\`${fix.command}\`) in their terminal, so the agent offers it rather than running it.`;},},+ {+ title: 'First run on a keyless brain: one decision bundle, `ask_user` (journey)',+ golden: 'journey/init-first-run.json',+ transport: 'cli',+ expectNext: 'ask_user',+ setting: 'An agent installs gbrain for a user with no provider keys, from a non-interactive shell (H1a journey, recorded from the real CLI).',+ call: 'gbrain init --pglite --no-embedding --json',+ nextOf: (doc) => (((doc.notices as Json[]).find(n => n.code === 'first_run_decisions')?.kind) === 'ask' ? 'ask_user' : ''),+ after: (doc) => {+ const bundle = (doc.notices as Json[]).find(n => n.code === 'first_run_decisions') as Json;+ const ids = (bundle.decisions as Json[]).map(d => `\`${d.id}\` (default \`${d.default}\`)`).join(', ');+ return `stdout is one document; the brain is ready and nothing blocks using it. The \`first_run_decisions\` notice is \`kind: ask\`, `+ + `so the agent relays its \`user_message\` ("${bundle.user_message}") once and stops. The decisions are ${ids}; `+ + 'each option carries the exact argv to apply it, so a reply of "defaults" needs no command at all.';+ },+ },+ {+ title: 'A caller mistake over stdio MCP, recorded: `run` (journey)',+ golden: 'journey/caller-mistake.json',+ transport: 'stdio',+ expectNext: 'run',+ setting: 'A harness on `gbrain serve --surface verbs` passes a string where `recall` expects a number (H1a journey, recorded from a real stdio session).',+ call: 'recall {"query":"quokka-journey-marker","limit":"abc"}',+ after: (doc) => {+ const env = body(doc);+ const fix = env.fix as Json;+ return `One content block, \`code: ${env.code}\`, \`class: ${env.class}\`. Nothing ran, so \`fix.next: ${fix.next}\`: the agent calls `+ + `\`${step(fix)}\` exactly as given (its other arguments kept, the bad one corrected) and gets the recall it wanted.`;+ },+ },+ {+ title: 'A second session on a locked brain: status-only serve, `tell_user_to_run` (journey)',+ golden: 'journey/status-only-lock-held.json',+ transport: 'stdio',+ expectNext: 'tell_user_to_run',+ setting: 'A second agent session starts `gbrain serve` while another session\'s serve owns the PGLite brain. The handshake still completes, with one tool, `gbrain_status` (H1a journey, recorded).',+ call: 'gbrain_status {}',+ after: (doc) => {+ const env = body(doc);+ const options = ((env.decisions as Json[])[0].options as Json[]).map(o => `\`${o.id}\``).join(' or ');+ return `\`reason: ${env.reason}\` names the owner (\`lock_owner.pid\`). \`fix.next\` is \`${(env.fix as Json).next}\` because only the user can close `+ + `the other session: the agent relays \`user_message\` and offers ${options}. Calling \`gbrain_status\` again after the owner exits `+ + 'opens the brain in place and the full tool list arrives through `tools/list_changed`.';+ },+ },];function renderTranscript(t: Transcript, i: number): string {const doc = loadGolden(t.golden, t.transport);const env = body(doc);- const fixNext = String(((env.fix as Json | undefined)?.next)+ const fixNext = t.nextOf ? t.nextOf(doc) : String(((env.fix as Json | undefined)?.next)?? ((((doc._meta as Json | undefined)?.gbrain_notices as Json[] | undefined)?.[0]?.fix as Json | undefined)?.next) ?? '');if (fixNext !== t.expectNext) {throw new Error(`transcript "${t.golden}": next is ${fixNext}, expected ${t.expectNext}. Update the narration with the contract change.`);@@ -170,9 +229,11 @@ function renderTranscript(t: Transcript, i: number): string {];if (t.transport === 'cli') {parts.push('stdout (`--json`):', '', fence('json', JSON.stringify(doc, null, 2)), '');- const human = renderConsentRefusal(doc as unknown as ConfirmationPayload, { json: false });- parts.push('Without `--json`, the same refusal prints as an `[AGENT]` block:', '', fence('text', human.stdout ?? ''), '');- } else if (doc.isError) {+ if (doc.code === 'confirmation_required') {+ const human = renderConsentRefusal(doc as unknown as ConfirmationPayload, { json: false });+ parts.push('Without `--json`, the same refusal prints as an `[AGENT]` block:', '', fence('text', human.stdout ?? ''), '');+ }+ } else if (doc.isError || !Array.isArray(doc.content)) {parts.push('gbrain returns (`isError: true`, the envelope shown parsed):', '', fence('json', JSON.stringify(env, null, 2)), '');} else {const content = doc.content as { text: string }[];diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex a4a30b2bb4..540d7307fa 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -4,7 +4,10 @@"test/agent-error-surfaces.serial.test.ts": 25,"test/agent-injection-http-view.serial.test.ts": 22,"test/agent-install-backup.serial.test.ts": 114,+ "test/agent-journey-recovery.serial.test.ts": 35,+ "test/agent-journey-tier2.serial.test.ts": 85,"test/agent-journey-upgrade.serial.test.ts": 70,+ "test/agent-journey.serial.test.ts": 50,"test/agent-recovery-consent-journeys.serial.test.ts": 23,"test/agent-register-guards.serial.test.ts": 22,"test/agent-scheduler-contract.serial.test.ts": 39,@@ -238,7 +241,7 @@"test/serve-fail-fast.serial.test.ts": 2,"test/serve-idle-sweep-source.serial.test.ts": 1,"test/serve-source-guard.serial.test.ts": 1,- "test/serve-status-mode.serial.test.ts": 25,+ "test/serve-status-mode.serial.test.ts": 32,"test/serve-sync-ipc-killswitch.serial.test.ts": 16,"test/serve-sync-runner.serial.test.ts": 11,"test/skillopt/adversarial/concurrent-runs.serial.test.ts": 5,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 0fd9966789..e446287924 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -277,7 +277,10 @@"serial:test/agent-install-backup.serial.test.ts": 81187,"serial:test/agent-install-follow-setup.serial.test.ts": 44197,"serial:test/agent-install-shared-skills.serial.test.ts": 2732,+ "serial:test/agent-journey-recovery.serial.test.ts": 35000,+ "serial:test/agent-journey-tier2.serial.test.ts": 85000,"serial:test/agent-journey-upgrade.serial.test.ts": 70000,+ "serial:test/agent-journey.serial.test.ts": 50000,"serial:test/agent-recovery-consent-journeys.serial.test.ts": 23000,"serial:test/agent-register-guards.serial.test.ts": 11667,"serial:test/agent-scheduler-contract.serial.test.ts": 25493,@@ -546,6 +549,7 @@"serial:test/self-upgrade-checkonly.serial.test.ts": 386,"serial:test/serve-idle-sweep-source.serial.test.ts": 580,"serial:test/serve-source-guard.serial.test.ts": 562,+ "serial:test/serve-status-mode.serial.test.ts": 32000,"serial:test/serve-sync-embed-drain.serial.test.ts": 13637,"serial:test/serve-sync-ipc-killswitch.serial.test.ts": 8579,"serial:test/serve-sync-runner.serial.test.ts": 4869,diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 811eb4370c..d4b9c8062b 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -847,7 +847,26 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption// ---------------------------------------------------------------------------const clientCount = await sql`SELECT count(*)::int as count FROM oauth_clients`;- const httpServer = app.listen(port, bind, () => {+ const httpServer = app.listen(port, bind);+ // H2 mid-transition: a taken port must fail the start, never print the banner and keep+ // the brain lock while serving nothing (Bun runs the listen callback with listening=false+ // and emits 'error' to no listener). Wait for one outcome before announcing the server.+ const listenError = await new Promise<Error | null>(resolve => {+ if (httpServer.listening) return resolve(null);+ httpServer.once('listening', () => resolve(null));+ httpServer.once('error', (e: Error) => resolve(e));+ });+ if (listenError) {+ try { httpServer.close(); } catch { /* never listened */ }+ const { opError } = await import('../core/ops/contract.ts');+ throw opError('serve_port_in_use', `gbrain serve --http could not listen on ${bind}:${port}: ${listenError.message}`,+ 'Nothing was started and the brain is free again. Stop the process holding the port, or pass another --port (and point the harnesses at that URL).', {+ why: 'Another process (often an earlier gbrain serve --http) already listens on that address.',+ fix: { argv: ['gbrain', 'serve', '--http', '--bind', bind, '--port', String(port + 1)], consent: ['persistent_install'], actor: 'user', requires_exclusive: true,+ why: 'Starts the shared server on the next port; every harness must then use that URL.' },+ });+ }+ {console.error(`╔══════════════════════════════════════════════════════╗║ GBrain MCP Server v${VERSION.padEnd(37)}║@@ -871,7 +890,7 @@ ${bootstrapFromEnv? '║ Admin Token: hidden (non-TTY log-leak guard) ║\n║ set $GBRAIN_ADMIN_BOOTSTRAP_TOKEN, or pass ║\n║ --print-admin-token on a trusted terminal. ║\n╚══════════════════════════════════════════════════════╝': `║ Admin Token (paste into /admin login): ║\n║ ${bootstrapToken.substring(0, 50)} ║\n║ ${bootstrapToken.substring(50).padEnd(50)} ║\n╚══════════════════════════════════════════════════════╝`}`);- });+ }// #4474: bind the resolve-IPC unix socket under --http too. This is the// exact posture `gbrain bootstrap harness` targets — without the listenerdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 3b6a5796ba..2ca409f769 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -225,6 +225,7 @@ export const CODES = {revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ serve_port_in_use: { class: 'unavailable', summary: "gbrain serve --http could not listen: another process already holds that host and port.", suggestion: 'Stop the process on that port, or start the server with another --port and point the harnesses at it.' },serve_status_only: { class: 'unavailable', summary: "gbrain serve is in status-only mode: its brain is locked by another server, missing, or its config is unreadable.", reasons: ['lock_held', 'no_brain', 'config_unreadable'], suggestion: 'Call gbrain_status for the cause, the fix and what to tell the user.' },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },diff --git a/test/agent-journey-recovery.serial.test.ts b/test/agent-journey-recovery.serial.test.tsnew file mode 100644index 0000000000..cb38c0341e--- /dev/null+++ b/test/agent-journey-recovery.serial.test.ts@@ -0,0 +1,307 @@+/**+ * Lane H1b (Tier 2), surfaces and recovery rows (split from+ * test/agent-journey-tier2.serial.test.ts to keep each serial file well under+ * the pool's per-file wall clock). Rows 5–8 of the H1b list there. Real CLI subprocesses, real `gbrain serve`+ * sessions (stdio and HTTP), keyless PGLite in temp homes, hard timeouts.+ *+ * 1. Every `--json` stdout parses: the journey's commands, the doctor family,+ * every read op the CLI exposes (mutating:false, no required params), and+ * every command a fix or plan names. (json-declared commands' success and+ * failure shapes: test/cli-contract.serial.test.ts D5.)+ * 2. Zero WARNs without an executable fix, and every runnable fix runs: each+ * doctor WARN/FAIL carries fix.argv; fixes the agent may run itself+ * (consent [], actor agent, no inputs) are executed, and each fix.verify.+ * 3. Every remediation-plan command executes (plan steps, repair steps,+ * explicit-repair previews, the combined command) through a `gbrain` on+ * PATH, the way an agent pastes them.+ * 4. One embedding-enable command on every surface: init's hint, doctor's+ * checks, `embed --all`, `whoami`, MCP whoami and gbrain://capabilities+ * (behind the lock owner's two-step plan there).+ * 5. `--surface starter`: a subset of full, instructions name only listed+ * tools, a listed tool answers, an unlisted one is a one-block error.+ * 6. Read-only grant over HTTP: only read tools listed; a write is refused+ * with insufficient_scope as one block naming the host-side fix.+ * 7. Recovery from another directory with conflicting ambient brain/source+ * (GBRAIN_BRAIN_ID, GBRAIN_SOURCE, .gbrain-mount, .gbrain-source) acts+ * on the intended brain and source.+ * 8. Each exclusive fix while a live stdio serve holds the lock: the+ * refusal is the two-step plan (stop the owner, then the same command),+ * and following it succeeds.+ *+ * Existing lane coverage this builds on: D5 test/cli-contract.serial.test.ts,+ * E1 test/doctor-status-set.test.ts, A7 test/readiness-embedding-enablement.serial.test.ts+ * (the enable argv runs), F1 test/mcp-initialize-instructions.test.ts,+ * F6 test/mcp-notice-channels.test.ts, A2 test/callable-predicate.test.ts,+ * B5 test/scope-denial-contract.test.ts, A7 test/readiness.test.ts (exclusiveFix).+ *+ * Serial: real subprocesses, PGLite locks, an HTTP port.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawn, type ChildProcess } from 'node:child_process';+import { Client } from '@modelcontextprotocol/sdk/client/index.js';+import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';+import { operations } from '../src/core/operations.ts';+import { shellQuote } from '../src/core/agent-output.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { withCoordinatedWrite } from '../src/core/persistence/context.ts';+import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';+import {+ REPO, body, call, expectOneBlockError, gb, journeyEnv, mcp, oneDocument, waitFor, type GbResult,+} from './helpers/agent-journey.ts';++const MARKER = 'wombat-tier2-marker';++function writeNotes(dir: string, n: number, prefix = 'tier2-note'): string {+ mkdirSync(dir, { recursive: true });+ for (let i = 1; i <= n; i++) writeFileSync(join(dir, `${prefix}-${i}.md`), `---\ntitle: ${prefix} ${i}\n---\n\n# ${prefix} ${i}\n\nThe ${MARKER} ${i}.\n`);+ return dir;+}++async function withBrain<T>(home: string, fn: (engine: PGLiteEngine) => Promise<T>): Promise<T> {+ const engine = new PGLiteEngine();+ await engine.connect({ engine: 'pglite', database_path: join(home, '.gbrain', 'brain.pglite') });+ try { return await fn(engine); } finally { await engine.disconnect(); }+}++async function seedTimelineFinding(home: string, slug: string): Promise<void> {+ await withBrain(home, engine => engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw(+ `INSERT INTO timeline_entries(page_id,date,source,summary,detail)+ SELECT id,'2026-07-01','legacy','A database-only event','' FROM pages WHERE source_id='default' AND slug=$1`, [slug]),+ TEST_WRITE_ATTRIBUTION)));+}++async function pagesOf(home: string): Promise<string[]> {+ return withBrain(home, async engine => (await engine.executeRaw<{ s: string }>(+ "SELECT source_id || ':' || slug AS s FROM pages WHERE deleted_at IS NULL ORDER BY 1")).map(r => r.s));+}++/** A `--json` invocation: one parseable document; a failure document names code + suggestion. */+function expectJsonContract(r: GbResult, label: string): Record<string, any> {+ const doc = oneDocument(r, label);+ if (r.exitCode !== 0 && r.exitCode !== 3) {+ expect(typeof doc.code, `${label}: failure document has code (exit ${r.exitCode})`).toBe('string');+ expect(typeof doc.suggestion, `${label}: failure document has suggestion`).toBe('string');+ }+ return doc;+}++/** A directory with a `gbrain` that runs this checkout, so plan/fix command strings run as pasted. */+function gbrainShim(root: string): string {+ const bin = join(root, 'bin');+ mkdirSync(bin, { recursive: true });+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\nexec bun --no-env-file run ${JSON.stringify(join(REPO, 'src', 'cli.ts'))} "$@"\n`);+ chmodSync(join(bin, 'gbrain'), 0o755);+ return bin;+}++async function sh(home: string, command: string, bin: string, timeoutMs = 120_000): Promise<GbResult> {+ const t0 = performance.now();+ const env = journeyEnv(home, { PATH: `${bin}:${process.env.PATH ?? ''}` });+ const proc = Bun.spawn(['sh', '-c', command], { cwd: home, env, stdin: Bun.file('/dev/null'), stdout: 'pipe', stderr: 'pipe' });+ let killed = false;+ const killer = setTimeout(() => { killed = true; try { proc.kill('SIGKILL'); } catch { /* gone */ } }, timeoutMs);+ try {+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ expect(killed, `${command} hung`).toBe(false);+ return { exitCode, stdout, stderr, ms: Math.round(performance.now() - t0), killed };+ } finally { clearTimeout(killer); }+}++interface Check { name: string; status: string; message: string; fix?: Fix; fix_unavailable_reason?: string }+interface Fix { argv?: string[]; command?: string; consent: string[]; actor: string; next: string; inputs?: unknown[]; verify?: { argv?: string[] }; then?: Fix; requires_exclusive?: boolean }++describe('H1b: --surface starter', () => {+ let home = '';+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-starter-'));+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await gb(home, ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'])).exitCode).toBe(0);+ }, 300_000);+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });++ test('a subset of full; instructions name only listed tools; listed tools answer, unlisted ones are one-block errors', async () => {+ const full = await mcp(home, ['--surface', 'full']);+ const fullTools = new Set((await full.client.listTools()).tools.map(t => t.name));+ await full.close();+ const starter = await mcp(home, ['--surface', 'starter']);+ try {+ const tools = (await starter.client.listTools()).tools.map(t => t.name);+ expect(tools.length).toBeGreaterThan(3);+ expect(tools.length).toBeLessThan(fullTools.size);+ for (const t of tools) expect(fullTools.has(t), `${t} is a full-surface tool`).toBe(true);+ const instructions = starter.client.getInstructions() ?? '';+ for (const name of fullTools) {+ if (tools.includes(name)) continue;+ expect(instructions.includes(`\`${name}\``) || new RegExp(`\\b${name}\\b \\{`).test(instructions), `instructions name unlisted ${name}`).toBe(false);+ }+ const recallTool = tools.includes('recall') ? 'recall' : 'search';+ const found = await call(starter, recallTool, { query: MARKER });+ expect(found.isError).toBeFalsy();+ expect(JSON.stringify(body(found))).toContain(MARKER);+ const hidden = [...fullTools].find(t => !tools.includes(t) && t === 'get_health') ?? [...fullTools].find(t => !tools.includes(t))!;+ const refused = expectOneBlockError(await call(starter, hidden, {}), `${hidden} on starter`);+ expect(refused.suggestion.length).toBeGreaterThan(0);+ } finally { await starter.close(); }+ }, 300_000);+});++describe('H1b: read-only grant over HTTP', () => {+ let home = '';+ let http: ChildProcess | null = null;+ const PORT = 43000 + Math.floor(Math.random() * 2000);+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-ro-'));+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await gb(home, ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'])).exitCode).toBe(0);+ }, 300_000);+ afterAll(() => {+ if (http) try { http.kill('SIGTERM'); } catch { /* gone */ }+ rmSync(home, { recursive: true, force: true });+ });++ test('only read tools are listed and callable; a write is one insufficient_scope block with the host-side fix', async () => {+ const minted = await gb(home, ['auth', 'create', 'ro-harness', '--scopes', 'read']);+ expect(minted.exitCode, minted.stderr).toBe(0);+ const token = (minted.stdout.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];+ expect(token).toBeTruthy();+ http = spawn('bun', ['--no-env-file', 'run', join(REPO, 'src', 'cli.ts'), 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],+ { cwd: home, env: journeyEnv(home), stdio: ['ignore', 'ignore', 'ignore'] });+ expect(await waitFor(async () => (await fetch(`http://127.0.0.1:${PORT}/health`).catch(() => null))?.ok === true, 60_000)).toBe(true);+ const client = new Client({ name: 'ro-harness', version: '1' }, { capabilities: {} });+ await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${PORT}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));+ try {+ const listed = (await client.listTools()).tools;+ const byName = new Map(operations.map(op => [op.name, op]));+ // A read grant lists only read-scope tools (think writes nothing over MCP; request_tools is discovery).+ const beyondRead = listed.filter(t => byName.get(t.name)?.scope !== 'read').map(t => t.name);+ expect(beyondRead, 'a read grant lists no tool needing more than read').toEqual([]);+ expect(listed.map(t => t.name)).not.toContain('remember');+ for (const t of listed) if (byName.get(t.name)?.mutating === false) expect(t.annotations?.readOnlyHint, `${t.name} readOnlyHint`).toBe(true);+ const found = await client.callTool({ name: 'search', arguments: { query: MARKER } }) as any;+ expect(found.isError).toBeFalsy();+ const refused = await client.callTool({ name: 'remember', arguments: { fact: 'x', provenance: 'ro' } }) as any;+ const env = expectOneBlockError(refused, 'remember with a read grant');+ expect(env.code).toBe('insufficient_scope');+ expect(env.fix.actor).toBe('host_admin');+ expect(env.fix.next).toBe('tell_user_to_run');+ expect(env.fix.argv.slice(0, 3)).toEqual(['gbrain', 'auth', 'rescope-token']);+ expect(JSON.stringify(env)).not.toContain(home);+ } finally { await client.close(); }+ }, 300_000);+});++describe('H1b: recovery from another directory with conflicting ambient brain/source', () => {+ let root = '';+ let host = '';+ let team = '';+ let work = '';+ const ambient = () => ({ GBRAIN_BRAIN_ID: 'teambrain', GBRAIN_SOURCE: 'other' });+ beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'gbrain-tier2-route-'));+ host = join(root, 'host'); team = join(root, 'team'); work = join(root, 'elsewhere');+ for (const d of [host, team, work]) mkdirSync(d, { recursive: true });+ expect((await gb(host, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ expect((await gb(team, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ for (const id of ['other', 'third']) {+ writeNotes(join(root, id), 1, id);+ const added = await gb(host, ['sources', 'add', id, '--path', join(root, id), '--force']);+ expect(added.exitCode, added.stderr).toBe(0);+ }+ const mounted = await gb(host, ['mounts', 'add', 'teambrain', '--path', team, '--engine', 'pglite', '--db-path', join(team, '.gbrain', 'brain.pglite')]);+ expect(mounted.exitCode, mounted.stderr).toBe(0);+ writeFileSync(join(work, '.gbrain-mount'), 'teambrain\n');+ writeFileSync(join(work, '.gbrain-source'), 'other\n');+ }, 300_000);+ afterAll(() => { rmSync(root, { recursive: true, force: true }); });++ test('the import refusal fix, the approved remediation and the plan fix act on host/default', async () => {+ const notes = writeNotes(join(root, 'notes'), 2, 'route-note');+ // The refusal is produced in the intended context: the host brain, no ambient routing.+ const refused = await gb(host, ['import', notes, '--json']);+ expect(refused.exitCode).toBe(1);+ const fix = expectJsonContract(refused, 'import --json (keyless refusal)').fix as Fix;+ expect(fix.next).toBe('run');+ expect(fix.argv).toEqual(expect.arrayContaining(['--no-embed', '--brain', 'host', '--source', 'default']));+ // The agent runs it later from another directory whose ambient settings point elsewhere.+ const ran = await gb(host, fix.argv!.slice(1), { cwd: work, env: ambient() });+ expect(ran.exitCode, ran.stderr.slice(-1500)).toBe(0);+ expect(await pagesOf(host)).toEqual(expect.arrayContaining(['default:route-note-1', 'default:route-note-2']));+ expect(await pagesOf(team)).toEqual([]);++ await seedTimelineFinding(host, 'route-note-1');+ const consent = await gb(host, ['doctor', '--remediate', '--include-repairs', '--json']);+ expect(consent.exitCode).toBe(3);+ const payload = expectJsonContract(consent, 'doctor --remediate --json (refusal)');+ expect(payload.fix.argv).toEqual(expect.arrayContaining(['--brain', 'host']));+ expect(payload.preview.argv).toEqual(expect.arrayContaining(['--brain', 'host']));+ const preview = await gb(host, payload.preview.argv.slice(1), { cwd: work, env: ambient() });+ const previewDoc = expectJsonContract(preview, 'remediation preview from elsewhere');+ expect(previewDoc.repair_steps.map((s: { kind: string }) => s.kind)).toContain('timeline');+ const approved = await gb(host, payload.fix.argv.slice(1), { cwd: work, env: ambient(), timeoutMs: 240_000 });+ expect(approved.exitCode, approved.stderr.slice(-2000)).toBe(0);+ expect(expectJsonContract(approved, 'approved remediation from elsewhere').repairs_completed).toBe(1);+ const verify = expectJsonContract(await gb(host, ['doctor', '--only', 'timeline_history', '--json']), 'verify on host');+ expect((verify.checks as Check[]).find(c => c.name === 'timeline_history')?.status).toBe('ok');+ }, 600_000);+});++describe('H1b: exclusive fixes while a live stdio serve holds the lock', () => {+ let home = '';+ beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-excl-'));+ expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);+ }, 120_000);+ afterAll(() => { rmSync(home, { recursive: true, force: true }); });++ const exclusive: Array<{ label: string; args: () => string[]; done: (r: GbResult) => void }> = [+ { label: 'import --no-embed', args: () => ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'],+ done: r => expect(oneDocument(r, 'import').imported).toBe(2) },+ { label: 'doctor --remediate (approved)', args: () => ['doctor', '--remediate', '--yes', '--target-score', '50', '--json'],+ done: r => expect(oneDocument(r, 'doctor --remediate').exit_status).toBe(0) },+ { label: 'apply-migrations', args: () => ['apply-migrations', '--yes', '--no-autopilot-install', '--json'],+ done: r => expect(oneDocument(r, 'apply-migrations').status).not.toBe('failed') },+ ];++ for (const row of exclusive) {+ test(`${row.label}: the refusal is a two-step plan naming the owner; following it succeeds`, async () => {+ const owner = await mcp(home, ['--surface', 'verbs']);+ let ownerOpen = true;+ try {+ const args = row.args();+ const r = await gb(home, args);+ expect(r.exitCode, `${row.label} under a live serve: ${r.stdout.slice(0, 800)}`).not.toBe(0);+ const env = expectJsonContract(r, `${row.label} (busy)`);+ const fix = env.fix as Fix;+ expect(fix, `${row.label}: the refusal carries a fix, not "wait"`).toBeTruthy();+ expect(fix.argv).toEqual(['kill', String(owner.pid)]);+ expect(fix.actor).toBe('user');+ expect(fix.next).toBe('tell_user_to_run');+ expect(fix.then?.argv).toEqual(['gbrain', ...args]);+ expect(fix.then?.next).toBe('run');+ // Step one: the user stops the owning session. Step two: the agent runs `then` as given.+ await owner.close();+ ownerOpen = false;+ const second = await gb(home, fix.then!.argv!.slice(1), { timeoutMs: 240_000 });+ expect(second.exitCode, `${row.label} then-step: ${second.stderr.slice(-1500)}`).toBe(0);+ row.done(second);+ } finally { if (ownerOpen) await owner.close(); }+ }, 300_000);+ }++ test('doctor under a live serve: no FAIL, the DB checks name the owner and the two-step plan', async () => {+ const owner = await mcp(home, ['--surface', 'verbs']);+ try {+ const r = await gb(home, ['doctor', '--json']);+ expect(r.exitCode).toBe(0);+ const report = expectJsonContract(r, 'doctor --json under a live serve');+ expect((report.checks as Check[]).filter(c => c.status === 'fail').map(c => c.name)).toEqual([]);+ const connection = (report.checks as Check[]).find(c => c.name === 'connection')!;+ expect(connection.fix?.argv).toEqual(['kill', String(owner.pid)]);+ expect(connection.fix?.then?.argv).toEqual(['gbrain', 'doctor', '--json']);+ expect((report.checks as Check[]).filter(c => c.status === 'warn' && !c.fix?.argv).map(c => c.name)).toEqual([]);+ } finally { await owner.close(); }+ }, 300_000);+});diff --git a/test/agent-journey-tier2.serial.test.ts b/test/agent-journey-tier2.serial.test.tsindex 2c2e5ed115..a8320e0745 100644--- a/test/agent-journey-tier2.serial.test.ts+++ b/test/agent-journey-tier2.serial.test.ts@@ -16,6 +16,7 @@* 4. One embedding-enable command on every surface: init's hint, doctor's* checks, `embed --all`, `whoami`, MCP whoami and gbrain://capabilities* (behind the lock owner's two-step plan there).+ * (rows 5–8 run in test/agent-journey-recovery.serial.test.ts)* 5. `--surface starter`: a subset of full, instructions name only listed* tools, a listed tool answers, an unlisted one is a one-block error.* 6. Read-only grant over HTTP: only read tools listed; a write is refused@@ -240,196 +241,3 @@ describe('H1b: one embedding-enable command on every surface', () => {for (const [surface, argv] of Object.entries(surfaces)) expect(argv, surface).toEqual(expected);}, 600_000);});--describe('H1b: --surface starter', () => {- let home = '';- beforeAll(async () => {- home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-starter-'));- expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);- expect((await gb(home, ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'])).exitCode).toBe(0);- }, 300_000);- afterAll(() => { rmSync(home, { recursive: true, force: true }); });-- test('a subset of full; instructions name only listed tools; listed tools answer, unlisted ones are one-block errors', async () => {- const full = await mcp(home, ['--surface', 'full']);- const fullTools = new Set((await full.client.listTools()).tools.map(t => t.name));- await full.close();- const starter = await mcp(home, ['--surface', 'starter']);- try {- const tools = (await starter.client.listTools()).tools.map(t => t.name);- expect(tools.length).toBeGreaterThan(3);- expect(tools.length).toBeLessThan(fullTools.size);- for (const t of tools) expect(fullTools.has(t), `${t} is a full-surface tool`).toBe(true);- const instructions = starter.client.getInstructions() ?? '';- for (const name of fullTools) {- if (tools.includes(name)) continue;- expect(instructions.includes(`\`${name}\``) || new RegExp(`\\b${name}\\b \\{`).test(instructions), `instructions name unlisted ${name}`).toBe(false);- }- const recallTool = tools.includes('recall') ? 'recall' : 'search';- const found = await call(starter, recallTool, { query: MARKER });- expect(found.isError).toBeFalsy();- expect(JSON.stringify(body(found))).toContain(MARKER);- const hidden = [...fullTools].find(t => !tools.includes(t) && t === 'get_health') ?? [...fullTools].find(t => !tools.includes(t))!;- const refused = expectOneBlockError(await call(starter, hidden, {}), `${hidden} on starter`);- expect(refused.suggestion.length).toBeGreaterThan(0);- } finally { await starter.close(); }- }, 300_000);-});--describe('H1b: read-only grant over HTTP', () => {- let home = '';- let http: ChildProcess | null = null;- const PORT = 43000 + Math.floor(Math.random() * 2000);- beforeAll(async () => {- home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-ro-'));- expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);- expect((await gb(home, ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'])).exitCode).toBe(0);- }, 300_000);- afterAll(() => {- if (http) try { http.kill('SIGTERM'); } catch { /* gone */ }- rmSync(home, { recursive: true, force: true });- });-- test('only read tools are listed and callable; a write is one insufficient_scope block with the host-side fix', async () => {- const minted = await gb(home, ['auth', 'create', 'ro-harness', '--scopes', 'read']);- expect(minted.exitCode, minted.stderr).toBe(0);- const token = (minted.stdout.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];- expect(token).toBeTruthy();- http = spawn('bun', ['--no-env-file', 'run', join(REPO, 'src', 'cli.ts'), 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],- { cwd: home, env: journeyEnv(home), stdio: ['ignore', 'ignore', 'ignore'] });- expect(await waitFor(async () => (await fetch(`http://127.0.0.1:${PORT}/health`).catch(() => null))?.ok === true, 60_000)).toBe(true);- const client = new Client({ name: 'ro-harness', version: '1' }, { capabilities: {} });- await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${PORT}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));- try {- const listed = (await client.listTools()).tools;- const byName = new Map(operations.map(op => [op.name, op]));- // A read grant lists only read-scope tools (think writes nothing over MCP; request_tools is discovery).- const beyondRead = listed.filter(t => byName.get(t.name)?.scope !== 'read').map(t => t.name);- expect(beyondRead, 'a read grant lists no tool needing more than read').toEqual([]);- expect(listed.map(t => t.name)).not.toContain('remember');- for (const t of listed) if (byName.get(t.name)?.mutating === false) expect(t.annotations?.readOnlyHint, `${t.name} readOnlyHint`).toBe(true);- const found = await client.callTool({ name: 'search', arguments: { query: MARKER } }) as any;- expect(found.isError).toBeFalsy();- const refused = await client.callTool({ name: 'remember', arguments: { fact: 'x', provenance: 'ro' } }) as any;- const env = expectOneBlockError(refused, 'remember with a read grant');- expect(env.code).toBe('insufficient_scope');- expect(env.fix.actor).toBe('host_admin');- expect(env.fix.next).toBe('tell_user_to_run');- expect(env.fix.argv.slice(0, 3)).toEqual(['gbrain', 'auth', 'rescope-token']);- expect(JSON.stringify(env)).not.toContain(home);- } finally { await client.close(); }- }, 300_000);-});--describe('H1b: recovery from another directory with conflicting ambient brain/source', () => {- let root = '';- let host = '';- let team = '';- let work = '';- const ambient = () => ({ GBRAIN_BRAIN_ID: 'teambrain', GBRAIN_SOURCE: 'other' });- beforeAll(async () => {- root = mkdtempSync(join(tmpdir(), 'gbrain-tier2-route-'));- host = join(root, 'host'); team = join(root, 'team'); work = join(root, 'elsewhere');- for (const d of [host, team, work]) mkdirSync(d, { recursive: true });- expect((await gb(host, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);- expect((await gb(team, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);- for (const id of ['other', 'third']) {- writeNotes(join(root, id), 1, id);- const added = await gb(host, ['sources', 'add', id, '--path', join(root, id), '--force']);- expect(added.exitCode, added.stderr).toBe(0);- }- const mounted = await gb(host, ['mounts', 'add', 'teambrain', '--path', team, '--engine', 'pglite', '--db-path', join(team, '.gbrain', 'brain.pglite')]);- expect(mounted.exitCode, mounted.stderr).toBe(0);- writeFileSync(join(work, '.gbrain-mount'), 'teambrain\n');- writeFileSync(join(work, '.gbrain-source'), 'other\n');- }, 300_000);- afterAll(() => { rmSync(root, { recursive: true, force: true }); });-- test('the import refusal fix, the approved remediation and the plan fix act on host/default', async () => {- const notes = writeNotes(join(root, 'notes'), 2, 'route-note');- // The refusal is produced in the intended context: the host brain, no ambient routing.- const refused = await gb(host, ['import', notes, '--json']);- expect(refused.exitCode).toBe(1);- const fix = expectJsonContract(refused, 'import --json (keyless refusal)').fix as Fix;- expect(fix.next).toBe('run');- expect(fix.argv).toEqual(expect.arrayContaining(['--no-embed', '--brain', 'host', '--source', 'default']));- // The agent runs it later from another directory whose ambient settings point elsewhere.- const ran = await gb(host, fix.argv!.slice(1), { cwd: work, env: ambient() });- expect(ran.exitCode, ran.stderr.slice(-1500)).toBe(0);- expect(await pagesOf(host)).toEqual(expect.arrayContaining(['default:route-note-1', 'default:route-note-2']));- expect(await pagesOf(team)).toEqual([]);-- await seedTimelineFinding(host, 'route-note-1');- const consent = await gb(host, ['doctor', '--remediate', '--include-repairs', '--json']);- expect(consent.exitCode).toBe(3);- const payload = expectJsonContract(consent, 'doctor --remediate --json (refusal)');- expect(payload.fix.argv).toEqual(expect.arrayContaining(['--brain', 'host']));- expect(payload.preview.argv).toEqual(expect.arrayContaining(['--brain', 'host']));- const preview = await gb(host, payload.preview.argv.slice(1), { cwd: work, env: ambient() });- const previewDoc = expectJsonContract(preview, 'remediation preview from elsewhere');- expect(previewDoc.repair_steps.map((s: { kind: string }) => s.kind)).toContain('timeline');- const approved = await gb(host, payload.fix.argv.slice(1), { cwd: work, env: ambient(), timeoutMs: 240_000 });- expect(approved.exitCode, approved.stderr.slice(-2000)).toBe(0);- expect(expectJsonContract(approved, 'approved remediation from elsewhere').repairs_completed).toBe(1);- const verify = expectJsonContract(await gb(host, ['doctor', '--only', 'timeline_history', '--json']), 'verify on host');- expect((verify.checks as Check[]).find(c => c.name === 'timeline_history')?.status).toBe('ok');- }, 600_000);-});--describe('H1b: exclusive fixes while a live stdio serve holds the lock', () => {- let home = '';- beforeAll(async () => {- home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-excl-'));- expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);- }, 120_000);- afterAll(() => { rmSync(home, { recursive: true, force: true }); });-- const exclusive: Array<{ label: string; args: () => string[]; done: (r: GbResult) => void }> = [- { label: 'import --no-embed', args: () => ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'],- done: r => expect(oneDocument(r, 'import').imported).toBe(2) },- { label: 'doctor --remediate (approved)', args: () => ['doctor', '--remediate', '--yes', '--target-score', '50', '--json'],- done: r => expect(oneDocument(r, 'doctor --remediate').exit_status).toBe(0) },- { label: 'apply-migrations', args: () => ['apply-migrations', '--yes', '--no-autopilot-install', '--json'],- done: r => expect(oneDocument(r, 'apply-migrations').status).not.toBe('failed') },- ];-- for (const row of exclusive) {- test(`${row.label}: the refusal is a two-step plan naming the owner; following it succeeds`, async () => {- const owner = await mcp(home, ['--surface', 'verbs']);- let ownerOpen = true;- try {- const args = row.args();- const r = await gb(home, args);- expect(r.exitCode, `${row.label} under a live serve: ${r.stdout.slice(0, 800)}`).not.toBe(0);- const env = expectJsonContract(r, `${row.label} (busy)`);- const fix = env.fix as Fix;- expect(fix, `${row.label}: the refusal carries a fix, not "wait"`).toBeTruthy();- expect(fix.argv).toEqual(['kill', String(owner.pid)]);- expect(fix.actor).toBe('user');- expect(fix.next).toBe('tell_user_to_run');- expect(fix.then?.argv).toEqual(['gbrain', ...args]);- expect(fix.then?.next).toBe('run');- // Step one: the user stops the owning session. Step two: the agent runs `then` as given.- await owner.close();- ownerOpen = false;- const second = await gb(home, fix.then!.argv!.slice(1), { timeoutMs: 240_000 });- expect(second.exitCode, `${row.label} then-step: ${second.stderr.slice(-1500)}`).toBe(0);- row.done(second);- } finally { if (ownerOpen) await owner.close(); }- }, 300_000);- }-- test('doctor under a live serve: no FAIL, the DB checks name the owner and the two-step plan', async () => {- const owner = await mcp(home, ['--surface', 'verbs']);- try {- const r = await gb(home, ['doctor', '--json']);- expect(r.exitCode).toBe(0);- const report = expectJsonContract(r, 'doctor --json under a live serve');- expect((report.checks as Check[]).filter(c => c.status === 'fail').map(c => c.name)).toEqual([]);- const connection = (report.checks as Check[]).find(c => c.name === 'connection')!;- expect(connection.fix?.argv).toEqual(['kill', String(owner.pid)]);- expect(connection.fix?.then?.argv).toEqual(['gbrain', 'doctor', '--json']);- expect((report.checks as Check[]).filter(c => c.status === 'warn' && !c.fix?.argv).map(c => c.name)).toEqual([]);- } finally { await owner.close(); }- }, 300_000);-});diff --git a/test/agent-protocol-doc.test.ts b/test/agent-protocol-doc.test.tsindex 5cb46e4b8d..9f3da8287e 100644--- a/test/agent-protocol-doc.test.ts+++ b/test/agent-protocol-doc.test.ts@@ -36,7 +36,11 @@ describe('AGENT_OPERATOR_v1.md generated regions', () => {});test('transcripts cover run, ask_user and tell_user_to_run', () => {- expect(TRANSCRIPTS.map(t => t.expectNext).sort()).toEqual(['ask_user', 'run', 'tell_user_to_run']);+ expect([...new Set(TRANSCRIPTS.map(t => t.expectNext))].sort()).toEqual(['ask_user', 'run', 'tell_user_to_run']);+ });++ test('Lane H journey transcripts come from recorded journey goldens', () => {+ expect(TRANSCRIPTS.filter(t => t.golden.startsWith('journey/')).length).toBeGreaterThanOrEqual(3);});test('generated transcripts never carry an unresolved placeholder', () => {diff --git a/test/serve-status-mode.serial.test.ts b/test/serve-status-mode.serial.test.tsindex e64e6c8f18..f05f0b9b78 100644--- a/test/serve-status-mode.serial.test.ts+++ b/test/serve-status-mode.serial.test.ts@@ -11,7 +11,9 @@* stale stdio server then names the HTTP owner and the rewiring fix, and* both HTTP sessions recall;* no brain → `gbrain init` (the fix) → recovery in place → recall.- * `--fail-fast` keeps the pre-F4 exit for supervisors.+ * `--fail-fast` keeps the pre-F4 exit for supervisors. H2 mid-transition row:+ * `serve --http` on a taken port fails fast (serve_port_in_use) instead of+ * holding the brain while serving nothing, and both stdio harnesses recover.** Serial: real subprocesses over one temp GBRAIN_HOME (PGLite lock).*/@@ -236,3 +238,67 @@ describe('status-only serve: lock contention → one shared serve --http (b)', (}}, 240_000);});++describe('status-only serve: the shared-HTTP transition fails midway (H2)', () => {+ let home: string;+ let env: Record<string, string>;+ let blocker: ReturnType<typeof import('node:http').createServer> | null = null;+ const opened: Array<{ client: Client; transport: StdioClientTransport }> = [];+ const PORT = 44000 + Math.floor(Math.random() * 2000);++ beforeAll(() => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-status-midway-'));+ env = envFor(home);+ expect(cli(['init', '--pglite', '--no-embedding', '--non-interactive'], env).status).toBe(0);+ const notes = join(home, 'notes');+ mkdirSync(notes, { recursive: true });+ writeFileSync(join(notes, 'm.md'), `---\ntitle: ${MARKER}\n---\n\n# ${MARKER}\n\nMid-transition recall proof ${MARKER}.\n`);+ expect(cli(['import', notes, '--no-embed'], env).status).toBe(0);+ }, 120_000);++ afterAll(async () => {+ for (const c of opened) { try { await c.client.close(); } catch { /* best-effort */ } }+ blocker?.close();+ rmSync(home, { recursive: true, force: true });+ });++ test('serve --http cannot listen: it fails fast without keeping the brain, and both stdio registrations keep working', async () => {+ const owner = await connect(env);+ opened.push(owner);+ const stale = await connect(env);+ opened.push(stale);+ expect(body(await stale.client.callTool({ name: 'gbrain_status', arguments: {} })).reason).toBe('lock_held');++ // Step 1 of the plan: the owner closes.+ await owner.client.close();+ opened.shift();+ // Step 2 fails: the port is taken, so the shared server cannot start.+ const http = await import('node:http');+ blocker = http.createServer((_q, r) => { r.end('not gbrain'); });+ await new Promise<void>(r => blocker!.listen(PORT, '127.0.0.1', () => r()));+ const started = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],+ { cwd: process.cwd(), env, input: '', encoding: 'utf8', timeout: 60_000 });+ expect(started.signal, 'serve --http on a taken port must exit, not hang holding the brain').toBeNull();+ expect(started.status).not.toBe(0);+ expect(started.stderr).toContain('serve_port_in_use');+ expect(started.stderr).toContain(`--port ${PORT + 1}`);++ // The stale stdio server recovers in place and recalls; the re-launched first harness handshakes+ // (status-only, naming the new owner) — no harness config was rewritten by the failed step.+ expect(await waitFor(async () => body(await stale.client.callTool({ name: 'gbrain_status', arguments: {} })).status === 'recovered', 60_000)).toBe(true);+ const found = await stale.client.callTool({ name: 'search', arguments: { query: MARKER } });+ expect(found.isError).toBeFalsy();+ expect(JSON.stringify(body(found))).toContain(MARKER);+ const relaunched = await connect(env);+ opened.push(relaunched);+ const status = body(await relaunched.client.callTool({ name: 'gbrain_status', arguments: {} }));+ expect(status.reason).toBe('lock_held');+ expect(status.lock_owner.transport).toBe('stdio');+ // Recovery (a) still ends in a recall for the re-launched harness once the other session closes.+ await stale.client.close();+ opened.splice(opened.indexOf(stale), 1);+ expect(await waitFor(async () => body(await relaunched.client.callTool({ name: 'gbrain_status', arguments: {} })).status === 'recovered', 60_000)).toBe(true);+ const again = await relaunched.client.callTool({ name: 'search', arguments: { query: MARKER } });+ expect(JSON.stringify(body(again))).toContain(MARKER);+ }, 300_000);+});