Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wakeshift PR 1: CLI, doctor check, guide, tests, regenerated artifacts

garrytan590b163f0aa3
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8fad36a767..bbee0c11b7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,21 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**gbrain can now wake an agent's conversation when a job it started finishes, through Wakeshift. It's off until the brain owner turns it on.**
+
+An agent that submits a long job no longer has to poll. With reporting back on, it calls `watch_job` with the job id and ends its turn. When the job completes, fails, dies or is cancelled, Wakeshift wakes that conversation with one line naming the job and the `get_job` call that reads the result. The wake is a pointer (the job id, kind, status and times), never page text, titles or slugs, so it can't widen what anyone reads. The owner turns it on with `gbrain wakeshift enable` on the brain host, using a key from their own Wakeshift app, and `gbrain wakeshift disable` turns it off at once. Until then nothing changes: the tools aren't listed, no rows are written and nothing is sent. This release reports back only on brains that serve their owner alone. `wait_job` and `gbrain jobs wait <id>` remain the way to wait with nothing leaving the machine. Guide: docs/guides/wakeshift.md.
+
+### Itemized changes
+
+- New MCP tools `watch_job`, `list_watches` and `unwatch`, listed only while reporting back is on and a usable key is on the host. `watch_job` runs the same owner check as `get_job`: a job the caller doesn't own reads like a missing one and nothing is sent. A watch belongs to the credential that made it, and a revoked credential's watch ends without a wake.
+- New `gbrain wakeshift enable | disable | status | test`. `enable` asks consent (it sends data off the machine and stores a credential), refuses a brain with live access members, checks the key with Wakeshift and publishes gbrain's `gbrain.job.finished` event. The key comes from `WAKESHIFT_API_KEY` or a 0600 `~/.gbrain/wakeshift.key`, and is never stored in the database or printed (status shows its fingerprint).
+- Delivery runs inside `gbrain serve` (stdio and HTTP) and the job worker every 5 seconds, and once more at the end of `gbrain jobs work`. A watch on a job that already finished wakes at once. A failed delivery is retried at most 5 times over about 40 minutes, then the watch ends and the conversation is told. Jobs are never slowed by Wakeshift.
+- New doctor check `wakeshift`: a key file other users can read, reporting back enabled without a usable key, and watches that died or were refused as `id_reused` in the last 7 days.
+- Schema migration v290 adds `wake_subscriptions` (empty unless reporting back is on). Repo-less brains get it unchanged.
+- `--log-full-params` on `gbrain serve --http` now redacts a tool call's `session_key` argument.
+
## [0.60.584.0] - 2026-11-05
**`gbrain sources refresh --abandon` no longer lets the next sync delete pages a member source already synced.**
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.md
index 3fa32c5baa..db4eb3db30 100644
--- a/docs/TOOL_CATALOG.md
+++ b/docs/TOOL_CATALOG.md
@@ -4,7 +4,7 @@
<!-- Regenerate: bun run scripts/generate-tool-catalog.ts -->
<!-- Freshness-guarded by scripts/check-tool-catalog-fresh.sh (bun run verify). -->
-Every non-localOnly operation on the MCP surface: 168 tools across 26 areas. **Starter** marks membership in the ~41-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
+Every non-localOnly operation on the MCP surface: 171 tools across 26 areas. **Starter** marks membership in the ~41-op `starter` surface (`src/mcp/surface.ts`); **Gate** names the config key that must be true before remote callers see/call the op (`gbrain config set <key> true`). What a given token actually sees is further filtered per request by scope, bound-client fence, publish gates, and the per-client surface — see `docs/operations/mcp-surface-runbook.md`. Area names are non-contractual groupings.
## admin
@@ -105,6 +105,7 @@ Every non-localOnly operation on the MCP surface: 168 tools across 26 areas. **S
| `get_job_progress` | Get structured progress for a running job. | admin | | |
| `get_job_stats` | Job queue statistics. | admin | | |
| `list_jobs` | List background jobs with optional status/queue/name filters; pass fields to project each job to the columns you need. | admin | | |
+| `list_watches` | List the jobs this connection is watching through Wakeshift (open watches, plus ones that ended in the last day) with their state: open, delivered, dead or ended. | admin | | `mcp.publish_wakeshift` |
| `pause_job` | Pause a waiting, active or delayed background job. | admin | | |
| `replay_job` | Replay a completed/failed/dead job, optionally with modified data | admin | | |
| `resume_job` | Resume a paused background job (back to waiting). | admin | | |
@@ -112,7 +113,9 @@ Every non-localOnly operation on the MCP surface: 168 tools across 26 areas. **S
| `send_job_message` | Send a sidechannel message to a running job's inbox (for jobs that read steering messages). | admin | | |
| `submit_agent` | Submit an agent job (agent scope; tools and budget bound to your client). | agent | yes | |
| `submit_job` | Submit a background job. | admin | | |
+| `unwatch` | Stop watching a job: ends this connection's open Wakeshift watches on it, so no wake comes for it. | admin | | `mcp.publish_wakeshift` |
| `wait_job` | Wait until a job is completed, failed, dead or cancelled (at most 55 s per call), then return it like get_job plus terminal. | admin | | |
+| `watch_job` | This tool notifies you: it has gbrain wake this conversation through Wakeshift when job id finishes (completed, failed, dead or cancelled), so you can stop polling. | admin | | `mcp.publish_wakeshift` |
## links
diff --git a/docs/architecture/KEY_FILES.md b/docs/architecture/KEY_FILES.md
index 5d7b127688..5bf68d9dd3 100644
--- a/docs/architecture/KEY_FILES.md
+++ b/docs/architecture/KEY_FILES.md
@@ -43,7 +43,7 @@ link it here; never raise the cap.
| [Core Cycle (continued)](key-files/core-cycle-continued.md) | synthesis postprocess |
| [Core Cycle (patterns)](key-files/core-cycle-patterns.md) | patterns, drift, synthesis |
| [Core Minions (1/2)](key-files/core-minions-1.md) | `src/core/minions/` through `src/core/minions/protected-names.ts` |
-| [Core Minions (2/2)](key-files/core-minions-2.md) | `src/core/minions/queue.ts` through `src/core/minions/worker.ts` |
+| [Core Minions (2/2)](key-files/core-minions-2.md) | `minions/queue.ts` to `worker.ts`; [Wakeshift](key-files/wakeshift.md) |
| [Core Persistence](key-files/core-persistence.md) | `src/core/persistence/` journal, coordinator, effects, managed sync |
| [Core Persistence (continued)](key-files/core-persistence-continued.md) | connectors, holds, receipts; [Git writer](key-files/core-persistence-git.md); [fence repair](key-files/core-fence-repair.md) |
| [Persistence capacity](key-files/core-persistence-capacity.md) | write caps, true-up; [history](key-files/page-history.md), [as_of](key-files/valid-time.md) |
diff --git a/docs/architecture/key-files/wakeshift.md b/docs/architecture/key-files/wakeshift.md
new file mode 100644
index 0000000000..da0e7725e5
--- /dev/null
+++ b/docs/architecture/key-files/wakeshift.md
@@ -0,0 +1,6 @@
+# Key files: Wakeshift report-back
+
+[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.
+Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
+
+- `src/core/ops/wakeshift.ts` + `src/core/wakeshift/{client,config,events,drain}.ts` + `src/commands/wakeshift.ts` + `src/commands/doctor/checks/wakeshift.ts` — report back to agent conversations through Wakeshift (docs/guides/wakeshift.md), off by default. `client.ts` is the in-repo HTTP client (no SDK): key parsing (`wst_` + 50 base58 with a CRC32; legacy formats refused), a fresh EdDSA `app+jwt` assertion per request, one `fetch` with a 10 s timeout and no retry, loopback-only http. `config.ts` holds the host-only state: `wakeshift.enabled`/`url` in the file plane, the key (WAKESHIFT_API_KEY moved out of the environment on first read, else a 0600 `~/.gbrain/wakeshift.key`), the 0600 HMAC secret and the opaque Wakeshift user (HMAC over brain and principal); `wakeshiftPublished` is publish gate `mcp.publish_wakeshift`, which `mcp/publish-gates.ts` resolves from the file plane and key presence only (never the DB plane; not in `PUBLISH_GATE_KEYS`). `watch_job` runs the get_job owner fence (exported from `ops/jobs.ts`), subscribes the conversation (`once`, 7 d), stores a `wake_subscriptions` row (migration v290), rolls the subscription back when the insert fails, and hands Wakeshift's addition to dispatch through `ctx.emitToolTail` (the result's last text block plus `_meta` keys); `ctx.mcpCaller` (client name, User-Agent, request `_meta`) is set by the stdio and both HTTP transports. `drain.ts` is pull reconciliation: `gbrain serve` and `MinionWorker.start` run a 5 s unref'd timer, `gbrain jobs work` (PGLite) a final pass; at most 20 leased rows a tick, the emit id `<event>:<target>:<finished_us>:<status>:<row>`, the principal re-checked before each emit, 5 attempts on 30 s/2 m/8 m/30 m (429 honours Retry-After, other 4xx final), dead/revoked/expired rows ended at Wakeshift once. The payload (`events.ts`) is a pointer: job id, kind, status, times, next call; never page text. The CLI (`enable` with consent, the owner-only member check, GET /app and the manifest merge; `disable`, `status`, `test`) is the only writer of the enabled flag. Tests: `test/wakeshift-client.test.ts`, `test/wakeshift.serial.test.ts` (repo-less PGLite against `test/helpers/fake-wakeshift.ts`), `test/e2e/wakeshift-postgres.test.ts`.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 6a39fdaaa7..170c839702 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -5146,6 +5146,68 @@ Reasons: `noncanonical_value`, `not_kept`.
More: [docs/guides/write-refusals.md#visibility_not_applied](../../docs/guides/write-refusals.md#visibility_not_applied)
+### wakeshift_key_invalid
+
+<a id="wakeshift_key_invalid"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| The Wakeshift key is missing, mistyped, in an older format, or in a key file other users can read, so reporting back was not turned on. | A Wakeshift key is an Ed25519 private key (wst_ followed by 50 base58 characters whose last four bytes are a checksum). gbrain reads it from WAKESHIFT_API_KEY or ~/.gbrain/wakeshift.key, which must be readable by its owner only; it never stores the key in the database or prints it. | Ask the user to create a key in their Wakeshift console and put it in ~/.gbrain/wakeshift.key (chmod 600) or WAKESHIFT_API_KEY in ~/.gbrain/.env, then run gbrain wakeshift enable again. | user | `repeat the read that failed` | 1 | no |
+
+Reasons: `format`, `checksum`, `legacy`, `file_too_open`, `missing`.
+
+More: [docs/guides/wakeshift.md#the-key](../../docs/guides/wakeshift.md#the-key)
+
+### wakeshift_needs_conversation
+
+<a id="wakeshift_needs_conversation"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| watch_job wakes an MCP conversation, and a local CLI run has none to wake. | The request itself was wrong or no longer matches the brain; nothing was changed. | Run gbrain jobs wait <id> to block until the job finishes. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/wakeshift.md](../../docs/guides/wakeshift.md)
+
+### wakeshift_not_enabled
+
+<a id="wakeshift_not_enabled"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Reporting back through Wakeshift is off on this brain (the owner has not run gbrain wakeshift enable, or the key is missing). | Wakeshift is off by default; only the brain owner turns it on, on the brain host, because it sends wake metadata to a third-party service. | Use wait_job (or gbrain jobs wait <id>) instead, or ask the brain owner to run gbrain wakeshift enable. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/wakeshift.md](../../docs/guides/wakeshift.md)
+
+### wakeshift_refused
+
+<a id="wakeshift_refused"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Wakeshift refused the request; the reason carries its error code. Nothing was watched or sent. | Wakeshift checks each request (the signed key, the event and its arguments, the conversation's session key). A refusal other than a rate limit does not go away on retry. | Call wait_job to wait without Wakeshift; the brain owner can run gbrain wakeshift test to check the key and the app. | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/guides/wakeshift.md#troubleshooting](../../docs/guides/wakeshift.md#troubleshooting)
+
+### wakeshift_shared_brain
+
+<a id="wakeshift_shared_brain"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain wakeshift enable refused: this brain has live access members, and this release reports back only on brains that serve their owner alone. | Every member of the brain owner's Wakeshift organization can read the wakes it sends, and Wakeshift's terms make the operator pass its Connector Terms to each member. Shared brains get a terms step in a later release; until then reporting back stays off there. | Leave reporting back off on this brain; agents can use wait_job or gbrain jobs wait <id>. | user | `gbrain doctor --json` | 1 | no |
+
+More: [docs/guides/wakeshift.md#who-it-is-for](../../docs/guides/wakeshift.md#who-it-is-for)
+
+### wakeshift_unavailable
+
+<a id="wakeshift_unavailable"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| Wakeshift could not be reached or answered with a server error or rate limit; nothing was watched. | gbrain makes one request with a 10 s timeout and never retries inside a tool call, so a slow or down Wakeshift never holds the call. | Retry in a minute, or call wait_job to wait without Wakeshift. | agent | `gbrain doctor --json` | 1 | yes |
+
+More: [docs/guides/wakeshift.md#troubleshooting](../../docs/guides/wakeshift.md#troubleshooting)
+
### withdrawal_capacity
<a id="withdrawal_capacity"></a>
diff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.md
index 4cad798d83..897fb4b7be 100644
--- a/docs/guides/memory-boundaries.md
+++ b/docs/guides/memory-boundaries.md
@@ -387,6 +387,9 @@ candidate passages; expansion receives the query; synthesis and LLM extraction
receive the relevant retrieved content or source text. Self-hosted providers have
their own deployment boundary. The connected agent's own model also receives
whatever memory its harness includes in context, even on a keyless GBrain setup.
+Reporting back through Wakeshift (off by default, owner opt-in) sends a watched
+job's id, kind, status and times, never page text, titles or slugs; see
+[what leaves the machine](wakeshift.md#what-leaves-the-machine).
Enable paid capabilities and automatic capture only with consent, using the
provider's actual data-handling policy. See [installation capabilities](../../INSTALL_FOR_AGENTS.md#step-2-api-keys)
diff --git a/docs/guides/wakeshift.md b/docs/guides/wakeshift.md
new file mode 100644
index 0000000000..611605961b
--- /dev/null
+++ b/docs/guides/wakeshift.md
@@ -0,0 +1,58 @@
+# Report back to the conversation (Wakeshift)
+
+gbrain can wake an agent's conversation when a background job it started finishes, so the agent doesn't have to poll. It does this through [Wakeshift](https://wakeshift.ai), a hosted service that delivers wake-ups to Claude Code, Codex, Cursor, OpenClaw and other agent programs. It's off by default, and only the brain owner can turn it on, on the brain host.
+
+When it's on, an agent that submits a long job calls `watch_job` with the job id and ends its turn. When the job reaches completed, failed, dead or cancelled, Wakeshift wakes that conversation with one line, for example `gbrain: job 812 (sync) finished ok in 4m12s. Call get_job 812 for the result.`. The agent then reads the result with `get_job`, through gbrain's normal access checks.
+
+Without Wakeshift, `wait_job` (MCP) and `gbrain jobs wait <id>` (CLI) wait for a job with nothing leaving the machine. Harnesses that tell the agent when a background command exits (Claude Code, Codex, Cursor) can run `gbrain jobs wait <id>` in the background instead.
+
+## Turn it on
+
+1. Create an app and a key in your own Wakeshift console (`npx -y @wakeshift/cli init` or the web console). gbrain never signs anyone up or creates keys.
+2. Give gbrain the key, either way:
+ - `gbrain wakeshift enable --key-stdin < key.txt` saves it to `~/.gbrain/wakeshift.key` (mode 0600); or
+ - put `WAKESHIFT_API_KEY=wst_…` in `~/.gbrain/.env`.
+3. Run `gbrain wakeshift enable`. It shows what leaves the machine and asks for consent (`--yes` answers for a non-interactive run), checks the key with Wakeshift, and publishes gbrain's event.
+
+The watch tools (`watch_job`, `list_watches`, `unwatch`) appear on the next `tools/list`. `gbrain wakeshift status` shows the state, and `gbrain wakeshift test` checks the key and app without sending a wake. `gbrain wakeshift disable` hides the tools at once and ends every open watch.
+
+## The key
+
+A Wakeshift key is an Ed25519 private key: `wst_` followed by 50 base58 characters, the last four bytes a checksum, so a mistyped key is caught before anything is sent. Older `test_…`/`live_…` keys are refused; make a new one in the console.
+
+- gbrain reads `WAKESHIFT_API_KEY` once and then removes it from its own environment, so child processes don't inherit it. Otherwise it reads `~/.gbrain/wakeshift.key`, which must be readable by its owner only (a looser file is ignored, and `gbrain doctor` says so).
+- The key never leaves the brain host. Each request carries a fresh signed assertion that expires in two minutes.
+- The key is never stored in the database or printed. `status`, `test` and `doctor` show only its kid, a 22-character fingerprint.
+
+## Who it is for
+
+This release reports back only on brains that serve their owner alone. `gbrain wakeshift enable` refuses a brain with live access members (`gbrain access member list`), because every member of the owner's Wakeshift organization can read the wakes it sends, and Wakeshift's terms make the operator pass its Connector Terms to each member. Shared brains get a terms step in a later release.
+
+A watch belongs to the credential that made it: the OAuth client or token, or the local stdio pipe. `list_watches` and `unwatch` touch only the caller's own watches. `watch_job` runs the same owner check as `get_job`, so an agent-scoped token can watch only the jobs it submitted. A job it doesn't own reads exactly like a missing one, and nothing is sent. If the credential is revoked or its client is deleted before the job finishes, the watch ends without a wake.
+
+## What leaves the machine
+
+| When | To | What |
+| --- | --- | --- |
+| `gbrain wakeshift enable` | your Wakeshift app | the event's name, description and JSON Schemas |
+| `watch_job` | your Wakeshift app | a hashed user id (HMAC under a local secret, never an email or name), the MCP client name, the User-Agent, the tool call's `_meta`, the `harness`, `conversation_id` and `session_key` the agent passed, the event name, the job id, and a reason line ("Watching gbrain job 812") |
+| the job finishes | your Wakeshift app | the line above and a payload of the job id, its kind (handler name), status, start and finish times, duration and the next call |
+
+Never sent: page text, titles or slugs, job data or results, emails, names, tokens, the key, brain paths or hostnames. Wakes are deleted from Wakeshift once delivered. Members of your Wakeshift organization can read sent wakes, and Wakeshift keeps them up to 7 days.
+
+## Delivery and latency
+
+Delivery is a pull, not a hook. `gbrain serve` (stdio and HTTP) and the job worker check open watches every 5 seconds, and `gbrain jobs work` checks once more before it exits. On Postgres, a wake arrives within about 5 seconds of the job finishing. A watch on a job that has already finished wakes at once.
+
+On PGLite there is no background worker. A job submitted from a stdio session runs when `gbrain jobs work` drains the queue, after `gbrain serve` stops, and that run delivers its wakes before it exits. A wake it can't deliver arrives from the next `gbrain serve`.
+
+Each watch lasts 7 days and delivers once. A failed delivery is retried at most 5 times, after 30 s, 2 min, 8 min and 30 min (a rate limit waits its `Retry-After`). Any other refusal is final. A watch that dies is ended at Wakeshift, so the conversation is told. Jobs are never blocked or slowed by Wakeshift: it is down only means the wake comes late or not at all.
+
+Repo-less brains work the same way. Watches are operational database rows, not brain content.
+
+## Troubleshooting
+
+- **The watch tools are missing.** Run `gbrain wakeshift status`. Reporting back is off, or it's enabled but the key is missing, mistyped or in a key file other users can read.
+- **`wakeshift_unavailable`.** Wakeshift was down, slow (10 s timeout) or rate limiting. Retry later, or use `wait_job`.
+- **`wakeshift_refused`.** Wakeshift refused the request, and the reason carries its code. `other_client` means the `session_key` belongs to another program's conversation: call again without it. For anything else, run `gbrain wakeshift test`.
+- **No wake arrived.** The result of `watch_job` says `wakeable: false` when Wakeshift didn't recognize the agent program: pass `harness`. `list_watches` shows each watch's state and last error. `gbrain doctor --only wakeshift` counts dead watches and any `id_reused` refusal (a gbrain bug: please report it).
diff --git a/plugin/README.md b/plugin/README.md
index fdc9580680..97c0132c76 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -8,7 +8,7 @@ addition/exclusion).
## MCP surface note (read once)
-The plugin's MCP server runs `gbrain serve --surface full` — 191
+The plugin's MCP server runs `gbrain serve --surface full` — 194
operations, the same surface every stdio registration gbrain writes pins.
Every gbrain operation the bundled skills name is on it. A harness that caps
its tool count can narrow this machine's plugin surface with
diff --git a/scripts/core-world-reads-baseline.tsv b/scripts/core-world-reads-baseline.tsv
index 2e07f2bd37..946193b635 100644
--- a/scripts/core-world-reads-baseline.tsv
+++ b/scripts/core-world-reads-baseline.tsv
@@ -1143,6 +1143,9 @@ src/core/uncommitted-deletions.ts fs_import 1 W7: filesystem boundary moves to t
src/core/url-clone.ts spawn_import 1 W7: process-wide effects move to src/cli
src/core/utils.ts module_collection 1 W6: per-engine state, or mark as a constant table
src/core/verbs/usage-log.ts fs_import 1 W7: filesystem boundary moves to the local app
+src/core/wakeshift/config.ts fs_import 1 stays: the Wakeshift key and HMAC secret are host files (0600) by design, never engine settings (docs/guides/wakeshift.md#the-key)
+src/core/wakeshift/config.ts load_config 1 stays: wakeshift.enabled is read from the host file plane only, so no DB-plane or remote writer can turn reporting back on
+src/core/wakeshift/config.ts process_env 3 stays: WAKESHIFT_API_KEY is read once and removed from the process environment so child processes do not inherit it
src/core/workspace-push.ts fs_import 1 W7: filesystem boundary moves to the local app
src/core/workspace-push.ts process_env 2 W6: settings plane out of the core
src/core/workspace-push.ts spawn_import 1 W7: process-wide effects move to src/cli
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index b2da91a59f..9dcf5c49ed 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -404,6 +404,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: connectors ships its own printHelp (commands/connectors/index.ts) with the
// per-subcommand usage; keep the generic short-circuit from hiding it.
{ name: 'connectors', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/connectors.ts') },
+ // selfHelp: Wakeshift report-back switch (commands/wakeshift.ts HELP); host-only (it writes the file plane and the key), docs/guides/wakeshift.md.
+ { name: 'wakeshift', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/wakeshift.ts') },
// selfHelp: #3502 sweep: pages + bench print their own usage (pages.ts printHelp, bench-publish.ts
// printHelp). Both were documented but undispatchable — `pages` had a live handleCliOnly case but
// was missing from CLI_ONLY (the #2035 calibration bug class); `bench` was never wired at all.
diff --git a/src/cli/commands/wakeshift.ts b/src/cli/commands/wakeshift.ts
new file mode 100644
index 0000000000..43ecec89f2
--- /dev/null
+++ b/src/cli/commands/wakeshift.ts
@@ -0,0 +1,10 @@
+/**
+ * `gbrain wakeshift`: post-connect dispatch (record in src/cli/command-table.ts); the command lives in
+ * src/commands/wakeshift.ts.
+ */
+import type { BrainEngine } from '../../core/engine.ts';
+
+export async function run(engine: BrainEngine, args: string[]): Promise<void> {
+ const { runWakeshift } = await import('../../commands/wakeshift.ts');
+ await runWakeshift(engine, args);
+}
diff --git a/src/commands/doctor/checks/wakeshift.ts b/src/commands/doctor/checks/wakeshift.ts
new file mode 100644
index 0000000000..9bb1c57bce
--- /dev/null
+++ b/src/commands/doctor/checks/wakeshift.ts
@@ -0,0 +1,52 @@
+/**
+ * wakeshift (plan PR 1 item 9): reporting back through Wakeshift. Off is
+ * `ok` (disabled by choice). It warns when the key file is readable by other
+ * users, when reporting back is enabled but no usable key is found (the watch
+ * tools stay hidden), and when watches died (5 failed attempts or a final
+ * Wakeshift refusal) or hit `id_reused` (a bug signal) in the last 7 days.
+ * Shows the key's kid fingerprint only, never the key. Guide: docs/guides/wakeshift.md.
+ */
+import { loadConfigFileOnly } from '../../../core/config.ts';
+import { parseWakeshiftKey } from '../../../core/wakeshift/client.ts';
+import { readWakeshiftKey, wakeshiftFileConfig, wakeshiftKeyFile } from '../../../core/wakeshift/config.ts';
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+
+const DOCS = 'docs/guides/wakeshift.md#troubleshooting';
+
+async function runWakeshiftCheck(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ const enabled = wakeshiftFileConfig(loadConfigFileOnly()).enabled === true;
+ const read = readWakeshiftKey();
+ let kid: string | null = null;
+ let keyProblem: string | null = read.source === 'none' ? 'no key' : null;
+ if (read.source === 'env' || read.source === 'file') {
+ try { kid = parseWakeshiftKey(read.raw).kid; } catch (e) { keyProblem = (e as Error).message; }
+ }
+ if (read.source === 'file_too_open') {
+ checks.push({ name: 'wakeshift', status: 'warn', message: `${wakeshiftKeyFile()} is readable by other users (mode ${read.mode}); gbrain ignores it until it is 0600. Fix: chmod 600 ${wakeshiftKeyFile()}`, details: { enabled, key_source: read.source, docs: DOCS } });
+ } else if (!enabled) {
+ checks.push({ name: 'wakeshift', status: 'ok', severity: 'info', readiness_state: 'disabled_by_choice', message: 'Reporting back through Wakeshift is off (gbrain wakeshift enable turns it on).', details: { enabled, key_source: read.source, docs: DOCS } });
+ } else if (!kid) {
+ checks.push({ name: 'wakeshift', status: 'warn', message: `Wakeshift is enabled but has no usable key (${keyProblem}), so the watch tools are hidden. Fix: put the key in ${wakeshiftKeyFile()} (0600) or WAKESHIFT_API_KEY, then run gbrain wakeshift test.`, details: { enabled, key_source: read.source, docs: DOCS } });
+ } else {
+ const rows = await connectedEngine(ctx).executeRaw<{ state: string; id_reused: boolean; n: number }>(
+ `SELECT state, (last_error = 'id_reused') AS id_reused, count(*)::int AS n FROM wake_subscriptions
+ WHERE state = 'open' OR updated_at > now() - interval '7 days' GROUP BY 1, 2`);
+ const counts: Record<string, number> = { open: 0, delivered: 0, dead: 0, ended: 0, id_reused: 0 };
+ for (const r of rows) {
+ counts[r.state] = (counts[r.state] ?? 0) + Number(r.n);
+ if (r.id_reused) counts.id_reused! += Number(r.n);
+ }
+ const details = { enabled, key_source: read.source, kid, watches_7d: counts, docs: DOCS };
+ const message = counts.id_reused! > 0
+ ? `${counts.id_reused} watch(es) were refused with id_reused in the last 7 days: a gbrain bug, so please report it with this output.`
+ : counts.dead! > 0
+ ? `${counts.dead} wake(s) died in the last 7 days (5 failed attempts or a final Wakeshift refusal); the agents were told the watch ended. Check the key and the app with gbrain wakeshift test.`
+ : `Reporting back through Wakeshift is on (key kid ${kid}); ${counts.open} open watch(es), ${counts.delivered} delivered in the last 7 days.`;
+ checks.push({ name: 'wakeshift', status: counts.id_reused! > 0 || counts.dead! > 0 ? 'warn' : 'ok', message, details });
+ }
+ return checks;
+}
+
+export const wakeshiftEntry: DoctorEntry = { name: 'wakeshift', emits: ['wakeshift'], run: runWakeshiftCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 68e826c79c..7f12e7c2f8 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -106,6 +106,7 @@ import { retrievalFeedbackEntry } from './checks/retrieval-feedback.ts';
import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';
import { autoChronicleEntry } from './checks/auto-chronicle.ts';
import { factsDrainEntry } from './checks/facts-drain.ts';
+import { wakeshiftEntry } from './checks/wakeshift.ts';
import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { supersessionCalibrationEntry } from './checks/supersession-calibration.ts';
@@ -276,6 +277,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
edgeValidityEntry,
autoChronicleEntry,
factsDrainEntry,
+ wakeshiftEntry,
factTakeVectorsEntry,
plannerStatsEntry,
retrievalFeedbackEntry,
diff --git a/src/commands/wakeshift.ts b/src/commands/wakeshift.ts
new file mode 100644
index 0000000000..7d8f113635
--- /dev/null
+++ b/src/commands/wakeshift.ts
@@ -0,0 +1,200 @@
+/**
+ * `gbrain wakeshift enable | disable | status | test` (plan D4, PR 1): the
+ * trusted local switch for reporting back through Wakeshift. Only this
+ * command writes `wakeshift.enabled` (host file plane), so no MCP or HTTP
+ * caller can turn it on. `enable` asks consent (egress, credentials), refuses
+ * a brain with live access members, checks the key with GET /app and merges
+ * the event manifest; `disable` hides the watch tools at once and ends open
+ * watches; `status` and `test` show the key's kid fingerprint, never the key.
+ * Guide: docs/guides/wakeshift.md.
+ */
+import { chmodSync, readFileSync, writeFileSync } from 'node:fs';
+import type { BrainEngine } from '../core/engine.ts';
+import { loadConfigFileOnly, saveConfig, type GBrainConfig } from '../core/config.ts';
+import { opError } from '../core/ops/contract.ts';
+import { requireConsent } from '../core/consent.ts';
+import { WakeshiftError, WakeshiftKeyError, normalizeWakeshiftUrl, parseWakeshiftKey, wakeshiftClient, type WakeshiftKey } from '../core/wakeshift/client.ts';
+import { readWakeshiftKey, wakeshiftFileConfig, wakeshiftKeyFile, wakeshiftSecret } from '../core/wakeshift/config.ts';
+import { wakeshiftManifest } from '../core/wakeshift/events.ts';
+import { endAtWakeshift } from '../core/wakeshift/drain.ts';
+
+const HELP = `gbrain wakeshift <command> — report back to agent conversations when jobs finish (off by default)
+
+Commands:
+ status [--json] on/off, where the key comes from (its kid fingerprint only) and watch counts
+ enable [--key-stdin] [--url <https url>] [--yes]
+ turn reporting back on: asks consent, checks the key with Wakeshift and
+ publishes gbrain's event; --key-stdin saves the key from stdin to
+ ~/.gbrain/wakeshift.key (0600)
+ disable [--json] turn it off: the watch tools disappear at once and open watches end
+ test [--json] check the key and the app with Wakeshift; sends no wake
+
+The key is read from WAKESHIFT_API_KEY (e.g. in ~/.gbrain/.env) or ~/.gbrain/wakeshift.key.
+gbrain never creates a Wakeshift account or key. Guide: docs/guides/wakeshift.md`;
+
+function flagValue(args: string[], flag: string): string | undefined {
+ const i = args.indexOf(flag);
+ return i >= 0 && args[i + 1] && !args[i + 1]!.startsWith('--') ? args[i + 1] : undefined;
+}
+
+const KEY_HINT = 'Create a key in your Wakeshift console and put it in ~/.gbrain/wakeshift.key (chmod 600) or WAKESHIFT_API_KEY in ~/.gbrain/.env, then run gbrain wakeshift enable again.';
+
+function keyError(reason: string, message: string, suggestion: string): Error {
+ return opError('wakeshift_key_invalid', message, suggestion, { reason });
+}
+
+/** The configured key, parsed, or a wakeshift_key_invalid error that names what to do. */
+function loadKey(): { key: WakeshiftKey; source: 'env' | 'file' } {
+ const read = readWakeshiftKey();
+ if (read.source === 'file_too_open') {
+ throw keyError('file_too_open', `${wakeshiftKeyFile()} is readable by other users (mode ${read.mode}).`, `Run chmod 600 ${wakeshiftKeyFile()}, then run gbrain wakeshift enable again.`);
+ }
+ if (read.source === 'none') throw keyError('missing', 'No Wakeshift key: set WAKESHIFT_API_KEY (in ~/.gbrain/.env) or write ~/.gbrain/wakeshift.key.', KEY_HINT);
+ try {
+ return { key: parseWakeshiftKey(read.raw), source: read.source };
+ } catch (e) {
+ if (e instanceof WakeshiftKeyError) throw keyError(e.reason, e.message, KEY_HINT);
+ throw e;
+ }
+}
+
+async function liveMembers(engine: BrainEngine): Promise<number> {
+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM access_members WHERE disabled_at IS NULL AND tombstoned_at IS NULL');
+ return Number(row?.n ?? 0);
+}
+
+async function watchCounts(engine: BrainEngine): Promise<Record<string, number>> {
+ try {
+ const rows = await engine.executeRaw<{ state: string; last_error: string | null; n: number }>(
+ 'SELECT state, last_error, count(*)::int AS n FROM wake_subscriptions GROUP BY state, last_error');
+ const out: Record<string, number> = { open: 0, delivered: 0, dead: 0, ended: 0, id_reused: 0 };
+ for (const r of rows) {
+ out[r.state] = (out[r.state] ?? 0) + Number(r.n);
+ if (r.last_error === 'id_reused') out.id_reused! += Number(r.n);
+ }
+ return out;
+ } catch {
+ return {};
+ }
+}
+
+function writeFilePlane(update: (w: { enabled?: boolean; url?: string }) => { enabled?: boolean; url?: string }): void {
+ const cfg = (loadConfigFileOnly() ?? { engine: 'pglite' }) as GBrainConfig & { wakeshift?: { enabled?: boolean; url?: string } };
+ cfg.wakeshift = update({ ...(cfg.wakeshift ?? {}) });
+ saveConfig(cfg);
+}
+
+function say(json: boolean, doc: Record<string, unknown>, lines: string[]): void {
+ if (json) console.log(JSON.stringify(doc, null, 2));
+ else for (const l of lines) console.log(l);
+}
+
+function describeWakeshiftError(e: unknown): string {
+ return e instanceof WakeshiftError ? `${e.code} (HTTP ${e.status || 'none'}): ${e.message}` : String(e instanceof Error ? e.message : e);
+}
+
+async function status(engine: BrainEngine, json: boolean): Promise<void> {
+ const file = wakeshiftFileConfig(loadConfigFileOnly());
+ const read = readWakeshiftKey();
+ let kid: string | null = null;
+ let keyProblem: string | null = read.source === 'file_too_open' ? `key file mode ${read.mode} (must be 0600)` : read.source === 'none' ? 'no key' : null;
+ if (read.source === 'env' || read.source === 'file') {
+ try { kid = parseWakeshiftKey(read.raw).kid; } catch (e) { keyProblem = (e as Error).message; }
+ }
+ const counts = await watchCounts(engine);
+ const on = file.enabled === true && kid !== null;
+ say(json, { enabled: file.enabled === true, active: on, url: normalizeWakeshiftUrl(file.url), key: { source: read.source, kid, problem: keyProblem }, watches: counts }, [
+ `Wakeshift reporting back: ${on ? 'on' : file.enabled === true ? 'enabled but inactive' : 'off'}`,
+ ` url: ${normalizeWakeshiftUrl(file.url)}`,
+ ` key: ${kid ? `${read.source} (kid ${kid})` : keyProblem}`,
+ ` watches: ${Object.entries(counts).map(([k, v]) => `${k} ${v}`).join(', ') || 'none'}`,
+ ...(on || file.enabled !== true ? [] : [' The watch tools stay hidden until the key problem above is fixed.']),
+ ]);
+}
+
+async function enable(engine: BrainEngine, args: string[]): Promise<void> {
+ if (args.includes('--key-stdin')) {
+ const raw = readFileSync(0, 'utf8').trim();
+ try { parseWakeshiftKey(raw); } catch (e) { if (e instanceof WakeshiftKeyError) throw keyError(e.reason, e.message, KEY_HINT); throw e; }
+ writeFileSync(wakeshiftKeyFile(), raw + '\n', { mode: 0o600 });
+ chmodSync(wakeshiftKeyFile(), 0o600);
+ console.error(`[wakeshift] saved the key to ${wakeshiftKeyFile()} (0600).`);
+ }
+ const { key, source } = loadKey();
+ const members = await liveMembers(engine);
+ if (members > 0) {
+ throw opError('wakeshift_shared_brain', `This brain has ${members} live access member(s); this release reports back only on a brain that serves its owner alone. Nothing was turned on.`,
+ 'Leave reporting back off on this brain; agents wait for a job with wait_job or gbrain jobs wait and the job id.');
+ }
+ const url = normalizeWakeshiftUrl(flagValue(args, '--url') ?? wakeshiftFileConfig(loadConfigFileOnly()).url);
+ await requireConsent({
+ command: 'wakeshift enable', effects: ['egress', 'credentials'], actor: 'user',
+ what: `Turn on reporting back through Wakeshift (${url}) with the key kid ${key.kid}.`,
+ why: 'Agents can then ask gbrain to wake their conversation when a job finishes, instead of polling.',
+ risk: 'Each watched job sends Wakeshift a pointer: the job id, kind, status, times, a hashed user id, the MCP client name, user agent and request _meta. Never page text, titles or slugs. Members of your Wakeshift organization can read sent wakes.',
+ user_message: 'Turn on gbrain reporting back through Wakeshift? It sends job ids and status (never page text) to Wakeshift when a watched job finishes.',
+ argv: ['gbrain', 'wakeshift', 'enable'], args,
+ });
+ const api = wakeshiftClient(key, { url });
+ let app;
+ try {
+ app = await api.getApp();
+ await api.mergeManifest(wakeshiftManifest());
+ } catch (e) {
+ throw opError(e instanceof WakeshiftError && (e.status === 0 || e.status === 429 || e.status >= 500) ? 'wakeshift_unavailable' : 'wakeshift_refused',
+ `Wakeshift did not accept the key or the manifest: ${describeWakeshiftError(e)}. Nothing was turned on.`,
+ 'Check the key belongs to your Wakeshift app (gbrain wakeshift test) and retry.', { reason: e instanceof WakeshiftError ? e.code : 'error' });
+ }
+ wakeshiftSecret();
+ writeFilePlane(w => ({ ...w, enabled: true, ...(url !== 'https://app.wakeshift.ai' ? { url } : {}) }));
+ say(args.includes('--json'), { enabled: true, url, app: { id: app?.id, name: app?.name }, key: { source, kid: key.kid } }, [
+ `Wakeshift reporting back is on (app ${app?.name ?? '?'}, key kid ${key.kid}, from ${source}).`,
+ 'Agents now see watch_job, list_watches and unwatch; gbrain serve and the job worker deliver wakes.',
+ 'Turn it off with: gbrain wakeshift disable',
+ ]);
+}
+
+async function disable(engine: BrainEngine, json: boolean): Promise<void> {
+ writeFilePlane(w => ({ ...w, enabled: false }));
+ const rows = await engine.executeRaw<{ id: number; wake_user: string; ws_subscription_id: string }>(
+ `UPDATE wake_subscriptions SET state = 'ended', last_error = 'disabled', lease_until = NULL, updated_at = now() WHERE state = 'open'
+ RETURNING id, wake_user, ws_subscription_id`).catch(() => []);
+ let told = 0;
+ if (rows.length > 0) {
+ try {
+ const { key } = loadKey();
+ const api = wakeshiftClient(key, { url: normalizeWakeshiftUrl(wakeshiftFileConfig(loadConfigFileOnly()).url) });
+ for (const row of rows) if (await endAtWakeshift(api, row)) told++;
+ } catch { /* no usable key: Wakeshift's own ttl ends them */ }
+ }
+ say(json, { enabled: false, ended: rows.length, told_wakeshift: told }, [
+ 'Wakeshift reporting back is off: the watch tools are hidden from the next tools/list.',
+ `Ended ${rows.length} open watch(es)${rows.length ? ` (${told} confirmed by Wakeshift)` : ''}.`,
+ ]);
+}
+
+async function test(json: boolean): Promise<void> {
+ const { key, source } = loadKey();
+ const url = normalizeWakeshiftUrl(wakeshiftFileConfig(loadConfigFileOnly()).url);
+ try {
+ const app = await wakeshiftClient(key, { url }).getApp();
+ say(json, { ok: true, url, app: { id: app.id, name: app.name }, key: { source, kid: key.kid, key_id: app.key?.key_id } }, [
+ `ok: Wakeshift accepted the key (app ${app.name}, key ${app.key?.name ?? app.key?.key_id ?? '?'}, kid ${key.kid}).`,
+ ]);
+ } catch (e) {
+ say(json, { ok: false, url, key: { source, kid: key.kid }, error: describeWakeshiftError(e) }, [`fail: ${describeWakeshiftError(e)}`]);
+ process.exitCode = 1;
+ }
+}
+
+export async function runWakeshift(engine: BrainEngine, args: string[]): Promise<void> {
+ const sub = args[0];
+ const json = args.includes('--json');
+ if (!sub || sub === '--help' || sub === '-h' || args.includes('--help')) { console.log(HELP); return; }
+ if (sub === 'status') return status(engine, json);
+ if (sub === 'enable') return enable(engine, args.slice(1));
+ if (sub === 'disable') return disable(engine, json);
+ if (sub === 'test') return test(json);
+ console.error(`Unknown wakeshift command: ${sub}\n\n${HELP}`);
+ process.exitCode = 2;
+}
diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index 4e42d0dfff..82c24eda9d 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -140,6 +140,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'trust': ['--accept-all', '--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--legacy-lock', '--no-accept-pending', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],
'upgrade': ['--accept-reviewed-inventory', '--acknowledge-no-backup', '--admin-intent', '--all', '--all-applied', '--apply', '--apply-clean-hunks', '--backup-confirmed', '--brain', '--catch-up', '--changed', '--channel', '--check', '--concurrency', '--confirm-quiesced', '--confirm-relocated-root', '--content-root', '--cost-estimate', '--dry-run', '--embedding-dimensions', '--embedding-model', '--exit-code', '--expand', '--expected-epoch', '--expected-state', '--explain', '--export-db-only', '--export-source', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--held', '--help', '--host-dir', '--images', '--inject-bootstrap', '--inline', '--install', '--instructions-only', '--interval', '--is-ancestor', '--json', '--limit', '--list', '--manifest', '--markdown', '--max-rss', '--max-usd', '--migrate-only', '--migration', '--mode', '--multimodal', '--name', '--name-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-embed', '--no-expand', '--no-inject', '--no-restart', '--no-worker', '--non-interactive', '--now', '--once', '--only', '--oversized', '--path', '--pause', '--phase', '--quiet', '--reason', '--refs', '--remediation-plan', '--repo', '--require-db', '--restart-only', '--resume', '--retry-global', '--scope', '--search-mode', '--segmented', '--self-transfer', '--skills-dir', '--skip-verify', '--slug', '--source', '--stale', '--statement-timeout', '--status', '--stop-mcp', '--swap-only', '--tags', '--target', '--uninstall', '--user', '--vectors', '--verify', '--version', '--workers', '--yes'],
'waiting': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],
+ 'wakeshift': ['--apply', '--brain', '--expect', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--non-interactive', '--source', '--trust', '--url', '--yes'],
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
'whoknows': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--updated-after', '--url', '--yes'],
};
@@ -233,6 +234,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {
'transcripts': ['--brain', '--source'],
'trust': ['--brain'],
'waiting': ['--brain', '--source'],
+ 'wakeshift': ['--brain'],
'watch': ['--brain', '--source'],
'whoknows': ['--brain'],
};
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 013f679b30..431d6d43eb 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -196,6 +196,7 @@ const ROWS: readonly Row[] = [
['timeline_entries', 'out_of_scope', 'probed_reported', 'source summary detail write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id trust_tier write_origin', 'summary detail'],
['trust_allow_rules', 'out_of_scope', 'no_memory_text', 'source_id uri_prefix reason_family created_by removed_by reason'],
['trust_proposals', 'swept', 'review_rows', 'action source_id target_table related_table before_state after_state proposer proposer_principal_kind proposer_principal_id status decided_principal_kind decided_principal_id'],
+ ['wake_subscriptions', 'out_of_scope', 'no_memory_text', 'event target principal_kind principal_id member_id wake_user ws_subscription_id state delivered_marker last_error'],
['wanted_links', 'out_of_scope', 'probed_reported', 'source_id producer ref_kind target_source_id target_ref link_type context', 'context'],
['write_gate_holds', 'swept', 'review_rows', 'kind source_id slug fingerprint payload write_origin tier reason_families reasons request_id status decided_by'],
['write_gate_receipts', 'out_of_scope', 'text_free_ledger', 'target_table target_id source_id content_hash tier verdict reason_families reasons request_id'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index e56e6d3c0a..2c233a28b5 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -406,6 +406,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'pool_budget',
'progressive_batch_audit_health',
'queue_health',
+ // Wakeshift PR 1: report-back key, enabled state and dead/id_reused watches (doctor/checks/wakeshift.ts).
+ 'wakeshift',
// #4578: brain-wide maintenance jobs dying at their deadline.
'global_maintenance_timeouts',
// GBRA-130 C-6: no completed brain-wide pass while jobs fail or a phase keeps blocking it.
diff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.ts
index 4a5972471b..299e92d5b3 100644
--- a/src/core/operation-loaders.generated.ts
+++ b/src/core/operation-loaders.generated.ts
@@ -57,6 +57,7 @@ const load_timeline = () => import('./ops/timeline.ts') as Promise<Record<string
const load_transcripts = () => import('./ops/transcripts.ts') as Promise<Record<string, unknown>>;
const load_trust = () => import('./ops/trust.ts') as Promise<Record<string, unknown>>;
const load_usage = () => import('./ops/usage.ts') as Promise<Record<string, unknown>>;
+const load_wakeshift = () => import('./ops/wakeshift.ts') as Promise<Record<string, unknown>>;
const load_whois = () => import('./ops/whois.ts') as Promise<Record<string, unknown>>;
const load_verbs = () => import('./verbs.ts') as Promise<Record<string, unknown>>;
@@ -163,6 +164,9 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st
"submit_agent": [load_jobs, "jobsOperations"],
"get_agent_job": [load_jobs, "jobsOperations"],
"get_job_stats": [load_jobs, "jobsOperations"],
+ "watch_job": [load_wakeshift, "wakeshiftOperations"],
+ "list_watches": [load_wakeshift, "wakeshiftOperations"],
+ "unwatch": [load_wakeshift, "wakeshiftOperations"],
"find_orphans": [load_orphans, "orphansOperations"],
"rank_entities": [load_graph_rank, "graphRankOperations"],
"get_calibration_profile": [load_calibration, "calibrationOperations"],
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 771642857f..42b3c26357 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -4213,6 +4213,83 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"scope": "admin",
"area": "jobs"
},
+ {
+ "name": "watch_job",
+ "mutating": true,
+ "idempotent": true,
+ "writeInference": "non_content",
+ "outputRedaction": {
+ "exempt": "watch bookkeeping: job ids, states and times, never retrieved brain text"
+ },
+ "description": "This tool notifies you: it has gbrain wake this conversation through Wakeshift when job id finishes (completed, failed, dead or cancelled), so you can stop polling. Call it right after submitting a long job, then end your turn or keep working. The wake names the job and says to call get_job for the result; it carries no page text. Agent-scoped tokens watch only jobs they own. If no wake arrives, call wait_job.",
+ "params": {
+ "id": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID (from submit_job, submit_agent or list_jobs)."
+ },
+ "session_key": {
+ "type": "string",
+ "description": "This conversation's session_key, from an earlier result (a secret token, or a handle such as claude-code#2). Keep it to this conversation; don't share or log it."
+ },
+ "harness": {
+ "type": "string",
+ "description": "The program you're running in: codex, claude-code, cursor (local CLI or IDE), cursor-cloud (Cursor cloud agent), grok-bot, copilot-cli, opencode, antigravity, openclaw (even when it runs your turns in Codex), hermes, chatgpt, or your program's name if it isn't listed"
+ },
+ "conversation_id": {
+ "type": "string",
+ "description": "Your own ID for this conversation, if your program gives you one. Cursor and Grok Bot: the output of `printenv CURSOR_CONVERSATION_ID`. Codex and Antigravity send it automatically; others leave it empty"
+ }
+ },
+ "scope": "admin",
+ "agentCallable": true,
+ "publishGateKey": "mcp.publish_wakeshift",
+ "cliHints": {
+ "hidden": true
+ },
+ "area": "jobs"
+ },
+ {
+ "name": "list_watches",
+ "mutating": false,
+ "idempotent": true,
+ "outputRedaction": {
+ "exempt": "watch bookkeeping: job ids, states and times, never retrieved brain text"
+ },
+ "description": "List the jobs this connection is watching through Wakeshift (open watches, plus ones that ended in the last day) with their state: open, delivered, dead or ended.",
+ "params": {},
+ "scope": "admin",
+ "agentCallable": true,
+ "publishGateKey": "mcp.publish_wakeshift",
+ "cliHints": {
+ "hidden": true
+ },
+ "area": "jobs"
+ },
+ {
+ "name": "unwatch",
+ "mutating": true,
+ "idempotent": true,
+ "writeInference": "non_content",
+ "outputRedaction": {
+ "exempt": "watch bookkeeping: job ids, states and times, never retrieved brain text"
+ },
+ "description": "Stop watching a job: ends this connection's open Wakeshift watches on it, so no wake comes for it. Returns how many ended (0 when none was open).",
+ "params": {
+ "job": {
+ "type": "number",
+ "required": true,
+ "description": "Job ID you passed to watch_job."
+ }
+ },
+ "scope": "admin",
+ "agentCallable": true,
+ "publishGateKey": "mcp.publish_wakeshift",
+ "cliHints": {
+ "hidden": true
+ },
+ "area": "jobs"
+ },
{
"name": "find_orphans",
"mutating": false,
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index 4d4eafc68c..db6d617a6d 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -206,6 +206,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('timeline_entries', 'user_data', 'Timeline entries with attribution.'),
carry('trust_proposals', 'user_data', 'Pending and decided trust decisions (#5575); dropping them would lose owner review state.'),
carry('trust_allow_rules', 'user_data', 'The owner\'s receipted write-gate allow rules (gbrain trust allow); dropping them would re-quarantine sources the owner allowed.'),
+ carry('wake_subscriptions', 'operational', 'Report-back watches (Wakeshift): open ones point at jobs minion_jobs carries and at Wakeshift subscriptions that outlive the move, so a wake still arrives after graduation.'),
carry('wanted_links', 'user_data', 'Unresolved authored links (wanted pages); the edge appears when the target page is written, so they are not re-derived without a full re-extraction.'),
carry('write_gate_holds', 'user_data', 'Facts and takes the write gate held for the owner\'s review (#5575); dropping them would lose content awaiting release or drop.'),
carry('write_gate_receipts', 'user_data', 'Write-gate verdicts (flag/quarantine) per persisted row (#5575); dropping them would forget which agent-written instructions are unconfirmed.'),
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 3e5c4a952e..6b64222203 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -1214,8 +1214,7 @@ async function dispatchResolvedCall(
// failure renders the envelope's `notices` key (one block).
const notices: Notice[] = [];
ctx.emitNotice = (n) => { if (n) notices.push(n); };
- let tail: ToolTail | undefined;
- ctx.emitToolTail = (t) => { tail = t; };
+ let tail: ToolTail | undefined; ctx.emitToolTail = (t) => { tail = t; }; // Wakeshift's addition, appended last on success
try {
if (ctx.remote !== false && op.requiredScopes?.length) {
@@ -1324,7 +1323,7 @@ async function dispatchResolvedCall(
// BEFORE and independently of the metaHook, so a hot-memory hook
// failure can never drop the retrieval channel. Per-key merge, never
// wholesale assignment. See docs/protocol/MCP_META_CHANNELS.md.
- attachResponseMeta(out, responseMeta, degradedStampFor(name, result, responseMeta, notices));
+ attachResponseMeta(out, responseMeta, degradedStampFor(name, result, responseMeta, notices)); if (tail) appendToolTail(out, tail);
// v0.31 (eD3 + eE4): best-effort _meta.brain_hot_memory injection.
// The hook is wrapped in its own try/catch — any DB blip / cache miss /
// helper crash degrades to no hook keys rather than flipping the whole
@@ -1334,7 +1333,6 @@ async function dispatchResolvedCall(
if (meta && Object.keys(meta).length > 0) out._meta = { ...(out._meta ?? {}), ...meta };
if (failure !== undefined) ctx.logger.warn(`[mcp] _meta hook failed for ${name}: ${failure}; degrading to no hook keys`);
}
- if (tail) appendToolTail(out, tail);
// Large pages: the egress backstop measures the final frame; a read over the connection's cap is refused whole, never cut.
const over = op.mutating ? null : await frameOverCap(out, { remote: ctx.remote, transport: ctx.transport, engine, config: ctx.config });
if (over) return errorResult(resultTooLargeError(name, safeParams, over), opts, { op: name, mutating: false, idempotent: op.idempotent === true });
diff --git a/src/mcp/http-transport.ts b/src/mcp/http-transport.ts
index c03d466fcd..49f9b665af 100644
--- a/src/mcp/http-transport.ts
+++ b/src/mcp/http-transport.ts
@@ -568,8 +568,7 @@ export async function startHttpTransport(opts: HttpTransportOptions) {
transport: 'http', inboundFrameBytes: bodyCap,
takesHoldersAllowList: auth.takesHoldersAllowList,
sourceId: auth.sourceId,
- ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta },
- mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta }, // Wakeshift; shape only
+ ...(localFederated ? { localFederatedSourceIds: localFederated } : {}), onBehalfOf: { header: req.headers.get(ON_BEHALF_OF_HEADER) ?? undefined, requestMeta: params?._meta }, mcpCaller: { client: auth.auth?.clientName, userAgent: req.headers.get('user-agent') ?? undefined, meta: params?._meta },
actor: { header: req.headers.get(ACTOR_HEADER) ?? undefined, audience: req.headers.get(QM_AUDIENCE_HEADER) ?? undefined }, // #1336: thread the token's federated_read grant so read ops scope
// to the operator-granted sources via sourceScopeOpts.
auth: auth.auth,
diff --git a/test/e2e/wakeshift-postgres.test.ts b/test/e2e/wakeshift-postgres.test.ts
new file mode 100644
index 0000000000..9c0002e232
--- /dev/null
+++ b/test/e2e/wakeshift-postgres.test.ts
@@ -0,0 +1,101 @@
+/**
+ * Wakeshift report-back on real Postgres (PGLite coverage: test/wakeshift.serial.test.ts): watch, complete, exactly
+ * one pointer emit; a foreign id answers like a missing one with nothing sent; two concurrent drainers emit a row
+ * once (the lease); the failure schedule ends in dead plus one end call. Against test/helpers/fake-wakeshift.ts.
+ * Skips without DATABASE_URL. Run: DATABASE_URL=... bun test test/e2e/wakeshift-postgres.test.ts
+ */
+import { afterAll, beforeAll, beforeEach, 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 { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { encodeWakeshiftKey } from '../../src/core/wakeshift/client.ts';
+import { drainWakes, WAKE_MAX_ATTEMPTS } from '../../src/core/wakeshift/drain.ts';
+import { resetWakeshiftEnvKeyForTests } from '../../src/core/wakeshift/config.ts';
+import { startFakeWakeshift, type FakeWakeshift } from '../helpers/fake-wakeshift.ts';
+
+const d = hasDatabase() ? describe : describe.skip;
+const KEY = encodeWakeshiftKey(Buffer.alloc(32, 11));
+let fake: FakeWakeshift;
+let home: string;
+const prevHome = process.env.GBRAIN_HOME;
+
+beforeAll(async () => {
+ if (!hasDatabase()) return;
+ await setupDB();
+ home = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-pg-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ process.env.GBRAIN_HOME = home;
+ delete process.env.WAKESHIFT_API_KEY;
+ resetWakeshiftEnvKeyForTests();
+ writeFileSync(join(home, '.gbrain', 'wakeshift.key'), KEY + '\n', { mode: 0o600 });
+ chmodSync(join(home, '.gbrain', 'wakeshift.key'), 0o600);
+ fake = startFakeWakeshift(KEY);
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', wakeshift: { enabled: true, url: fake.url } }), { mode: 0o600 });
+});
+
+afterAll(async () => {
+ if (!hasDatabase()) return;
+ fake.stop();
+ await teardownDB();
+ if (prevHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = prevHome;
+ rmSync(home, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ if (!hasDatabase()) return;
+ fake.calls.length = 0;
+ fake.respond.clear();
+ await getEngine().executeRaw('DELETE FROM wake_subscriptions');
+ await getEngine().executeRaw('DELETE FROM minion_jobs');
+});
+
+async function seedJob(status: string, owner?: string): Promise<number> {
+ const data = { __submitter: 'cli:test', ...(owner ? { __owner_client_id: owner } : {}), slug: 'people/alice-example' };
+ const rows = await getEngine().executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, started_at)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'sync', 'default', $1, $2::jsonb, now()) RETURNING id`, [status, JSON.stringify(data)]);
+ return Number(rows[0]!.id);
+}
+const finish = (id: number) => getEngine().executeRaw("UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1", [id]);
+const stdio = { remote: true, transport: 'stdio' as const, sourceId: 'default', mcpCaller: { client: 'claude-code' } };
+const emits = () => fake.calls.filter(c => c.path === '/events/emit');
+
+d('wakeshift on Postgres', () => {
+ test('watch, complete, one pointer emit with no page text', async () => {
+ const id = await seedJob('active');
+ expect((await dispatchToolCall(getEngine(), 'watch_job', { id }, stdio)).isError).toBeFalsy();
+ await finish(id);
+ const [a, b] = await Promise.all([drainWakes(getEngine()), drainWakes(getEngine())]);
+ expect(a.delivered + b.delivered).toBe(1);
+ expect(emits()).toHaveLength(1);
+ expect(emits()[0]!.body.payload).toMatchObject({ job: id, status: 'completed' });
+ expect(JSON.stringify(emits()[0]!.body)).not.toContain('alice-example');
+ });
+
+ test('a foreign job id answers like a missing one and nothing is sent', async () => {
+ await getEngine().executeRaw("INSERT INTO oauth_clients (client_id, client_name) VALUES ('wk-b', 'wk-b') ON CONFLICT DO NOTHING");
+ const agent = { remote: true, transport: 'http' as const, sourceId: 'default', auth: { token: 't', clientId: 'wk-b', principal: { kind: 'oauth_client' as const, id: 'wk-b' }, member: null, scopes: ['agent'] } };
+ const foreign = await seedJob('active', 'wk-a');
+ const a = await dispatchToolCall(getEngine(), 'watch_job', { id: foreign }, agent);
+ const b = await dispatchToolCall(getEngine(), 'watch_job', { id: foreign + 1000 }, agent);
+ expect(a.content[0]!.text.replaceAll(String(foreign), 'N')).toBe(b.content[0]!.text.replaceAll(String(foreign + 1000), 'N'));
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('failures retry at most 5 times, then the watch dies and is ended once', async () => {
+ const id = await seedJob('active');
+ await dispatchToolCall(getEngine(), 'watch_job', { id }, stdio);
+ await finish(id);
+ fake.respond.set('/events/emit', () => ({ status: 502, body: { error: { code: 'bad_gateway', message: 'x' } } }));
+ for (let i = 0; i < WAKE_MAX_ATTEMPTS + 1; i++) {
+ await drainWakes(getEngine());
+ await getEngine().executeRaw("UPDATE wake_subscriptions SET next_attempt_at = now() - interval '1 second'");
+ }
+ const [row] = await getEngine().executeRaw<{ state: string; attempts: number }>('SELECT state, attempts FROM wake_subscriptions');
+ expect(row).toMatchObject({ state: 'dead', attempts: WAKE_MAX_ATTEMPTS });
+ expect(emits()).toHaveLength(WAKE_MAX_ATTEMPTS);
+ expect(fake.calls.filter(c => c.path === '/event-subscriptions/end')).toHaveLength(1);
+ });
+});
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 431955bb26..a53fcdcefc 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -551,6 +551,13 @@
"trust_proposals.trust_proposals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"trust_proposals.trust_proposals_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'accepted'::text, 'rejected'::text, 'undone'::text, 'superseded'::text])))",
"trust_proposals.trust_proposals_target_table_check": "c CHECK ((target_table = ANY (ARRAY['facts'::text, 'takes'::text, 'timeline_entries'::text, 'pages'::text])))",
+ "wake_subscriptions.wake_subscriptions_event_check": "c CHECK ((event ~ '^gbrain\\.[a-z][a-z0-9._]{0,47}$'::text))",
+ "wake_subscriptions.wake_subscriptions_pkey": "p PRIMARY KEY (id)",
+ "wake_subscriptions.wake_subscriptions_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_stdio'::text])))",
+ "wake_subscriptions.wake_subscriptions_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'delivered'::text, 'dead'::text, 'ended'::text])))",
+ "wake_subscriptions.wake_subscriptions_target_check": "c CHECK (((length(target) >= 1) AND (length(target) <= 128)))",
+ "wake_subscriptions.wake_subscriptions_wake_user_check": "c CHECK ((wake_user ~ '^[0-9a-f]{32}$'::text))",
+ "wake_subscriptions.wake_subscriptions_ws_subscription_id_check": "c CHECK (((length(ws_subscription_id) >= 1) AND (length(ws_subscription_id) <= 200)))",
"wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",
"wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",
@@ -1134,6 +1141,9 @@
"trust_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "wake_subscriptions": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"wanted_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1637,6 +1647,10 @@
"uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)",
"uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",
"uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",
+ "wake_subscriptions_open_idx": "CREATE INDEX wake_subscriptions_open_idx ON public.wake_subscriptions USING btree (next_attempt_at) WHERE (state = 'open'::text)",
+ "wake_subscriptions_open_unique": "CREATE UNIQUE INDEX wake_subscriptions_open_unique ON public.wake_subscriptions USING btree (wake_user, ws_subscription_id) WHERE (state = 'open'::text)",
+ "wake_subscriptions_pkey": "CREATE UNIQUE INDEX wake_subscriptions_pkey ON public.wake_subscriptions USING btree (id)",
+ "wake_subscriptions_principal_idx": "CREATE INDEX wake_subscriptions_principal_idx ON public.wake_subscriptions USING btree (principal_kind, principal_id, created_at DESC)",
"wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",
"wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",
"wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",
@@ -1712,6 +1726,7 @@
"timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",
"trust_allow_rules_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_allow_rules.id",
"trust_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_proposals.id",
+ "wake_subscriptions_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wake_subscriptions.id",
"wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id",
"write_gate_holds_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_holds.id",
"write_gate_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_receipts.id"
@@ -4458,6 +4473,28 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "wake_subscriptions": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wake_subscriptions_id_seq'::regclass)",
+ "2 event text/text NOT NULL",
+ "3 target text/text NOT NULL",
+ "4 principal_kind text/text NOT NULL",
+ "5 principal_id text/text NOT NULL",
+ "6 member_id text/text NULL",
+ "7 wake_user text/text NOT NULL",
+ "8 ws_subscription_id text/text NOT NULL",
+ "9 state text/text NOT NULL DEFAULT 'open'::text",
+ "10 delivered_marker text/text NULL",
+ "11 attempts integer/int4 NOT NULL DEFAULT 0",
+ "12 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "13 lease_until timestamp with time zone/timestamptz NULL",
+ "14 last_error text/text NULL",
+ "15 expires_at timestamp with time zone/timestamptz NOT NULL",
+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "17 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"wanted_links": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 70ea09940c..0000e9004f 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -551,6 +551,13 @@
"trust_proposals.trust_proposals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"trust_proposals.trust_proposals_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'accepted'::text, 'rejected'::text, 'undone'::text, 'superseded'::text])))",
"trust_proposals.trust_proposals_target_table_check": "c CHECK ((target_table = ANY (ARRAY['facts'::text, 'takes'::text, 'timeline_entries'::text, 'pages'::text])))",
+ "wake_subscriptions.wake_subscriptions_event_check": "c CHECK ((event ~ '^gbrain\\.[a-z][a-z0-9._]{0,47}$'::text))",
+ "wake_subscriptions.wake_subscriptions_pkey": "p PRIMARY KEY (id)",
+ "wake_subscriptions.wake_subscriptions_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_stdio'::text])))",
+ "wake_subscriptions.wake_subscriptions_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'delivered'::text, 'dead'::text, 'ended'::text])))",
+ "wake_subscriptions.wake_subscriptions_target_check": "c CHECK (((length(target) >= 1) AND (length(target) <= 128)))",
+ "wake_subscriptions.wake_subscriptions_wake_user_check": "c CHECK ((wake_user ~ '^[0-9a-f]{32}$'::text))",
+ "wake_subscriptions.wake_subscriptions_ws_subscription_id_check": "c CHECK (((length(ws_subscription_id) >= 1) AND (length(ws_subscription_id) <= 200)))",
"wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",
"wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",
@@ -1134,6 +1141,9 @@
"trust_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "wake_subscriptions": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"wanted_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1637,6 +1647,10 @@
"uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)",
"uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",
"uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",
+ "wake_subscriptions_open_idx": "CREATE INDEX wake_subscriptions_open_idx ON public.wake_subscriptions USING btree (next_attempt_at) WHERE (state = 'open'::text)",
+ "wake_subscriptions_open_unique": "CREATE UNIQUE INDEX wake_subscriptions_open_unique ON public.wake_subscriptions USING btree (wake_user, ws_subscription_id) WHERE (state = 'open'::text)",
+ "wake_subscriptions_pkey": "CREATE UNIQUE INDEX wake_subscriptions_pkey ON public.wake_subscriptions USING btree (id)",
+ "wake_subscriptions_principal_idx": "CREATE INDEX wake_subscriptions_principal_idx ON public.wake_subscriptions USING btree (principal_kind, principal_id, created_at DESC)",
"wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",
"wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",
"wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",
@@ -1712,6 +1726,7 @@
"timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",
"trust_allow_rules_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_allow_rules.id",
"trust_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_proposals.id",
+ "wake_subscriptions_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wake_subscriptions.id",
"wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id",
"write_gate_holds_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_holds.id",
"write_gate_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_receipts.id"
@@ -4458,6 +4473,28 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "wake_subscriptions": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wake_subscriptions_id_seq'::regclass)",
+ "2 event text/text NOT NULL",
+ "3 target text/text NOT NULL",
+ "4 principal_kind text/text NOT NULL",
+ "5 principal_id text/text NOT NULL",
+ "6 member_id text/text NULL",
+ "7 wake_user text/text NOT NULL",
+ "8 ws_subscription_id text/text NOT NULL",
+ "9 state text/text NOT NULL DEFAULT 'open'::text",
+ "10 delivered_marker text/text NULL",
+ "11 attempts integer/int4 NOT NULL DEFAULT 0",
+ "12 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "13 lease_until timestamp with time zone/timestamptz NULL",
+ "14 last_error text/text NULL",
+ "15 expires_at timestamp with time zone/timestamptz NOT NULL",
+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "17 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"wanted_links": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index e32d6a2302..b09bcb6053 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -551,6 +551,13 @@
"trust_proposals.trust_proposals_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"trust_proposals.trust_proposals_status_check": "c CHECK ((status = ANY (ARRAY['pending'::text, 'accepted'::text, 'rejected'::text, 'undone'::text, 'superseded'::text])))",
"trust_proposals.trust_proposals_target_table_check": "c CHECK ((target_table = ANY (ARRAY['facts'::text, 'takes'::text, 'timeline_entries'::text, 'pages'::text])))",
+ "wake_subscriptions.wake_subscriptions_event_check": "c CHECK ((event ~ '^gbrain\\.[a-z][a-z0-9._]{0,47}$'::text))",
+ "wake_subscriptions.wake_subscriptions_pkey": "p PRIMARY KEY (id)",
+ "wake_subscriptions.wake_subscriptions_principal_kind_check": "c CHECK ((principal_kind = ANY (ARRAY['oauth_client'::text, 'legacy_token'::text, 'local_stdio'::text])))",
+ "wake_subscriptions.wake_subscriptions_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'delivered'::text, 'dead'::text, 'ended'::text])))",
+ "wake_subscriptions.wake_subscriptions_target_check": "c CHECK (((length(target) >= 1) AND (length(target) <= 128)))",
+ "wake_subscriptions.wake_subscriptions_wake_user_check": "c CHECK ((wake_user ~ '^[0-9a-f]{32}$'::text))",
+ "wake_subscriptions.wake_subscriptions_ws_subscription_id_check": "c CHECK (((length(ws_subscription_id) >= 1) AND (length(ws_subscription_id) <= 200)))",
"wanted_links.wanted_links_origin_page_id_fkey": "f FOREIGN KEY (origin_page_id) REFERENCES pages(id) ON DELETE CASCADE",
"wanted_links.wanted_links_pkey": "p PRIMARY KEY (id)",
"wanted_links.wanted_links_producer_check": "c CHECK ((producer = ANY (ARRAY['body'::text, 'frontmatter'::text])))",
@@ -1134,6 +1141,9 @@
"trust_proposals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "wake_subscriptions": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"wanted_links": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1633,6 +1643,10 @@
"uniq_minion_attachments_job_filename": "CREATE UNIQUE INDEX uniq_minion_attachments_job_filename ON public.minion_attachments USING btree (job_id, filename)",
"uniq_minion_jobs_idempotency": "CREATE UNIQUE INDEX uniq_minion_jobs_idempotency ON public.minion_jobs USING btree (idempotency_key) WHERE (idempotency_key IS NOT NULL)",
"uniq_subagent_messages_idx": "CREATE UNIQUE INDEX uniq_subagent_messages_idx ON public.subagent_messages USING btree (job_id, message_idx)",
+ "wake_subscriptions_open_idx": "CREATE INDEX wake_subscriptions_open_idx ON public.wake_subscriptions USING btree (next_attempt_at) WHERE (state = 'open'::text)",
+ "wake_subscriptions_open_unique": "CREATE UNIQUE INDEX wake_subscriptions_open_unique ON public.wake_subscriptions USING btree (wake_user, ws_subscription_id) WHERE (state = 'open'::text)",
+ "wake_subscriptions_pkey": "CREATE UNIQUE INDEX wake_subscriptions_pkey ON public.wake_subscriptions USING btree (id)",
+ "wake_subscriptions_principal_idx": "CREATE INDEX wake_subscriptions_principal_idx ON public.wake_subscriptions USING btree (principal_kind, principal_id, created_at DESC)",
"wanted_links_pkey": "CREATE UNIQUE INDEX wanted_links_pkey ON public.wanted_links USING btree (id)",
"wanted_links_reference_unique": "CREATE UNIQUE INDEX wanted_links_reference_unique ON public.wanted_links USING btree (origin_page_id, producer, ref_kind, target_source_id, target_ref)",
"wanted_links_source_idx": "CREATE INDEX wanted_links_source_idx ON public.wanted_links USING btree (source_id)",
@@ -1708,6 +1722,7 @@
"timeline_entries_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=timeline_entries.id",
"trust_allow_rules_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_allow_rules.id",
"trust_proposals_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=trust_proposals.id",
+ "wake_subscriptions_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wake_subscriptions.id",
"wanted_links_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=wanted_links.id",
"write_gate_holds_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_holds.id",
"write_gate_receipts_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=write_gate_receipts.id"
@@ -4454,6 +4469,28 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "wake_subscriptions": {
+ "columns": [
+ "1 id bigint/int8 NOT NULL DEFAULT nextval('wake_subscriptions_id_seq'::regclass)",
+ "2 event text/text NOT NULL",
+ "3 target text/text NOT NULL",
+ "4 principal_kind text/text NOT NULL",
+ "5 principal_id text/text NOT NULL",
+ "6 member_id text/text NULL",
+ "7 wake_user text/text NOT NULL",
+ "8 ws_subscription_id text/text NOT NULL",
+ "9 state text/text NOT NULL DEFAULT 'open'::text",
+ "10 delivered_marker text/text NULL",
+ "11 attempts integer/int4 NOT NULL DEFAULT 0",
+ "12 next_attempt_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "13 lease_until timestamp with time zone/timestamptz NULL",
+ "14 last_error text/text NULL",
+ "15 expires_at timestamp with time zone/timestamptz NOT NULL",
+ "16 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "17 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"wanted_links": {
"columns": [
"1 id bigint/int8 NOT NULL DEFAULT nextval('wanted_links_id_seq'::regclass)",
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 303d5cb3cb..0a6f87c019 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -1083,7 +1083,7 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "RLS enabled on 172/172 public tables",
+ "message": "RLS enabled on 173/173 public tables",
"name": "rls",
"status": "ok"
},
@@ -1111,7 +1111,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "All 172 table(s) the applied migrations create exist.",
+ "message": "All 173 table(s) the applied migrations create exist.",
"name": "schema_missing_tables",
"status": "ok"
},
@@ -2797,6 +2797,20 @@
"severity": "info",
"status": "ok"
},
+ {
+ "category": "ops",
+ "details": {
+ "docs": "docs/guides/wakeshift.md#troubleshooting",
+ "enabled": false,
+ "key_source": "none"
+ },
+ "elapsed_ms": "<volatile>",
+ "message": "Reporting back through Wakeshift is off (gbrain wakeshift enable turns it on).",
+ "name": "wakeshift",
+ "readiness_state": "disabled_by_choice",
+ "severity": "info",
+ "status": "ok"
+ },
{
"category": "brain",
"details": {
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 90d47f405a..7d56bbb731 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -913,6 +913,10 @@
"category": "brain",
"name": "facts_drain"
},
+ {
+ "category": "ops",
+ "name": "wakeshift"
+ },
{
"category": "brain",
"name": "fact_take_vectors"
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 8989628686..86d67b1440 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 157, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 158, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });
diff --git a/test/helpers/fake-wakeshift.ts b/test/helpers/fake-wakeshift.ts
new file mode 100644
index 0000000000..d4df410500
--- /dev/null
+++ b/test/helpers/fake-wakeshift.ts
@@ -0,0 +1,78 @@
+/**
+ * A fake Wakeshift (https://wakeshift.ai/docs/http-api) for the report-back tests: Bun.serve on a loopback port
+ * with the endpoints gbrain calls. Every request's assertion is verified against the key's public key (EdDSA,
+ * typ app+jwt, kid, aud, 120 s life, a jti never seen before), and every call is recorded. `respond` overrides an
+ * endpoint's answer (status, body, headers) for failure tests.
+ */
+import { createHash, createPublicKey, verify, type KeyObject } from 'node:crypto';
+import { parseWakeshiftKey } from '../../src/core/wakeshift/client.ts';
+
+export interface FakeCall { path: string; body: any; assertionOk: boolean; problem?: string }
+type Answer = { status: number; body: unknown; headers?: Record<string, string> };
+
+export interface FakeWakeshift {
+ url: string;
+ calls: FakeCall[];
+ respond: Map<string, (body: any) => Answer>;
+ stop(): void;
+}
+
+export function startFakeWakeshift(rawKey: string): FakeWakeshift {
+ const key = parseWakeshiftKey(rawKey);
+ const pub: KeyObject = createPublicKey(key.privateKey);
+ const spki = pub.export({ format: 'der', type: 'spki' });
+ const kid = createHash('sha256').update(spki.subarray(spki.length - 32)).digest().subarray(0, 16).toString('base64url');
+ const seenJti = new Set<string>();
+ const calls: FakeCall[] = [];
+ const respond = new Map<string, (body: any) => Answer>();
+ let subSeq = 0;
+ const subs = new Map<string, string>();
+ const server = Bun.serve({
+ port: 0, hostname: '127.0.0.1',
+ async fetch(req) {
+ const path = new URL(req.url).pathname.replace(/^\/api\/apps\/v1/, '');
+ const text = await req.text();
+ const body = text ? JSON.parse(text) : null;
+ let problem: string | undefined;
+ const token = (req.headers.get('authorization') ?? '').replace(/^Bearer /, '');
+ const [h, c, s] = token.split('.');
+ try {
+ const header = JSON.parse(Buffer.from(h!, 'base64url').toString());
+ const claims = JSON.parse(Buffer.from(c!, 'base64url').toString());
+ if (header.alg !== 'EdDSA' || header.typ !== 'app+jwt' || header.kid !== kid) problem = 'header';
+ else if (claims.iss !== kid || claims.sub !== kid || claims.aud !== `${url}/api/apps`) problem = 'claims';
+ else if (claims.exp - claims.iat !== 120 || Math.abs(claims.iat - Date.now() / 1000) > 60) problem = 'lifetime';
+ else if (!claims.jti || seenJti.has(claims.jti)) problem = 'jti';
+ else if (!verify(null, Buffer.from(`${h}.${c}`), pub, Buffer.from(s!, 'base64url'))) problem = 'signature';
+ seenJti.add(claims.jti);
+ } catch { problem = 'malformed'; }
+ calls.push({ path, body, assertionOk: !problem, ...(problem ? { problem } : {}) });
+ if (problem) return Response.json({ error: { code: 'unauthenticated', message: problem } }, { status: 401 });
+ const override = respond.get(path);
+ if (override) {
+ const a = override(body);
+ return Response.json(a.body, { status: a.status, headers: a.headers ?? {} });
+ }
+ switch (path) {
+ case '/app': return Response.json({ id: 'app_test', name: 'gbrain-test', key: { key_id: 'key_1', name: 'test key' } });
+ case '/manifest/merge': return Response.json({ events: body?.events ?? [] });
+ case '/event-subscriptions': {
+ const k = `${body.call.user}|${body.name}|${JSON.stringify(body.arguments)}`;
+ const created = !subs.has(k);
+ if (created) subs.set(k, `sub_${++subSeq}`);
+ return Response.json({
+ event_subscription: { id: subs.get(k), user: body.call.user, event: body.name, arguments: body.arguments, created, expires_at: new Date(Date.now() + 7 * 86_400_000).toISOString() },
+ session: 'claude-code#1', addition: { text: 'Wakeshift: this conversation is subscribed (secret-addition-text).', meta: { 'wakeshift/session': 'secret-addition-meta' } },
+ agent: { harness: body.call.client === 'claude-code' ? 'claude-code' : null, via: body.call.client === 'claude-code' ? 'client' : null, claimed: body.call.harness ?? null },
+ });
+ }
+ case '/event-subscriptions/unsubscribe': return Response.json({ ended: true });
+ case '/event-subscriptions/end': return Response.json({ ended: true });
+ case '/events/emit': return Response.json({ matched: 1, duplicate: false, unmatched: [], ended: [] });
+ default: return Response.json({ error: { code: 'bad_request', message: `unknown path ${path}` } }, { status: 400 });
+ }
+ },
+ });
+ const url = `http://127.0.0.1:${server.port}`;
+ return { url, calls, respond, stop: () => server.stop(true) };
+}
diff --git a/test/publish-gates.test.ts b/test/publish-gates.test.ts
index e7d63cd4bb..d828fc055d 100644
--- a/test/publish-gates.test.ts
+++ b/test/publish-gates.test.ts
@@ -11,7 +11,7 @@ import { operations, opAllowedForBoundClient, CLIENT_FENCED_WRITE_OPS } from '..
import type { BrainEngine } from '../src/core/engine.ts';
import type { GBrainConfig } from '../src/core/config.ts';
-const GATED_OPS = ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack', 'advisor', 'set_memory_writeback'];
+const GATED_OPS = ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack', 'advisor', 'set_memory_writeback', 'watch_job', 'list_watches', 'unwatch'];
function engineWithConfig(values: Record<string, string | null> | 'throws'): BrainEngine {
return {
diff --git a/test/wakeshift-client.test.ts b/test/wakeshift-client.test.ts
new file mode 100644
index 0000000000..f283e01c69
--- /dev/null
+++ b/test/wakeshift-client.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Wakeshift client (src/core/wakeshift/client.ts) and event rendering (events.ts): key parsing with the documented
+ * format and a mistyped key, the signed assertion verified with the public key, the console-URL rule, the manifest's
+ * routing, the pointer payload (no page text) and emit-id uniqueness.
+ */
+import { describe, test, expect } from 'bun:test';
+import { createPublicKey, verify } from 'node:crypto';
+import { crc32, encodeWakeshiftKey, normalizeWakeshiftUrl, parseWakeshiftKey, wakeshiftAssertion, WakeshiftKeyError } from '../src/core/wakeshift/client.ts';
+import { formatDuration, jobMarker, jobWake, wakeEmitId, wakeshiftManifest, JOB_FINISHED } from '../src/core/wakeshift/events.ts';
+import { wakeshiftUserId } from '../src/core/wakeshift/config.ts';
+
+const SEED = Buffer.alloc(32, 7);
+const KEY = encodeWakeshiftKey(SEED);
+
+describe('wakeshift key', () => {
+ test('crc32 matches the IEEE check value', () => {
+ expect(crc32(Buffer.from('123456789'))).toBe(0xcbf43926);
+ });
+
+ test('a current key is wst_ plus 50 base58 characters and round-trips', () => {
+ expect(KEY).toMatch(/^wst_[1-9A-HJ-NP-Za-km-z]{50}$/);
+ const k = parseWakeshiftKey(` ${KEY}\n`);
+ expect(k.kid).toMatch(/^[A-Za-z0-9_-]{22}$/);
+ expect(parseWakeshiftKey(encodeWakeshiftKey(Buffer.alloc(32, 0))).kid).toMatch(/^[A-Za-z0-9_-]{22}$/);
+ });
+
+ test('a mistyped key fails its checksum, a short one its format, a legacy one is refused', () => {
+ const chars = KEY.split('');
+ chars[10] = chars[10] === 'A' ? 'B' : 'A';
+ const reason = (raw: string) => { try { parseWakeshiftKey(raw); return 'ok'; } catch (e) { return (e as WakeshiftKeyError).reason; } };
+ expect(reason(chars.join(''))).toBe('checksum');
+ expect(reason(KEY.slice(0, -1))).toBe('format');
+ expect(reason('wst_' + '0'.repeat(50))).toBe('format');
+ expect(reason('test_app1_' + Buffer.alloc(32).toString('base64url'))).toBe('legacy');
+ expect(reason('wst_live_app1_abc')).toBe('legacy');
+ });
+});
+
+describe('wakeshift assertion', () => {
+ test('header, claims and an Ed25519 signature the public key verifies', () => {
+ const key = parseWakeshiftKey(KEY);
+ const now = 1_800_000_000;
+ const a = wakeshiftAssertion(key, 'https://app.wakeshift.ai', now);
+ const [h, c, s] = a.split('.');
+ expect(JSON.parse(Buffer.from(h!, 'base64url').toString())).toEqual({ alg: 'EdDSA', typ: 'app+jwt', kid: key.kid });
+ const claims = JSON.parse(Buffer.from(c!, 'base64url').toString());
+ expect(claims).toMatchObject({ iss: key.kid, sub: key.kid, aud: 'https://app.wakeshift.ai/api/apps', iat: now, exp: now + 120 });
+ expect(Buffer.from(claims.jti, 'base64url').length).toBe(16);
+ expect(a).not.toContain('=');
+ expect(verify(null, Buffer.from(`${h}.${c}`), createPublicKey(key.privateKey), Buffer.from(s!, 'base64url'))).toBe(true);
+ expect(wakeshiftAssertion(key, 'https://app.wakeshift.ai', now)).not.toBe(a);
+ });
+
+ test('the key never appears in an assertion', () => {
+ const a = wakeshiftAssertion(parseWakeshiftKey(KEY), 'https://app.wakeshift.ai');
+ expect(a).not.toContain(KEY.slice(4, 20));
+ expect(a).not.toContain(SEED.toString('base64url'));
+ });
+});
+
+describe('wakeshift url', () => {
+ test('https anywhere, http only on loopback, no path', () => {
+ expect(normalizeWakeshiftUrl(undefined)).toBe('https://app.wakeshift.ai');
+ expect(normalizeWakeshiftUrl('https://console.example.com/x/')).toBe('https://console.example.com');
+ expect(normalizeWakeshiftUrl('http://127.0.0.1:4567')).toBe('http://127.0.0.1:4567');
+ expect(() => normalizeWakeshiftUrl('http://wakeshift.example.com')).toThrow(/https/);
+ });
+});
+
+describe('wakeshift events', () => {
+ test('the manifest routes by the job id and is personal and deleted on delivery', () => {
+ const [ev] = wakeshiftManifest().events as any[];
+ expect(ev).toMatchObject({ name: JOB_FINISHED, topic: 'ev/gbrain.job.finished/{job}', personal: true, delete_on_delivery: true });
+ expect(ev.arguments.required).toEqual(['job']);
+ expect(ev.payload.additionalProperties).toBe(false);
+ });
+
+ test('the wake is a pointer: ids, status, times and the next call; under 1000 bytes', () => {
+ const job = { id: 812, name: 'subagent', status: 'completed', started_at: '2026-11-05T10:00:00.000Z', finished_at: '2026-11-05T10:04:12.000Z', finished_us: '1793872252000000' };
+ const w = jobWake(812, job);
+ expect(w.text).toBe('gbrain: job 812 (subagent) finished ok in 4m12s. Call get_job 812 for the result.');
+ expect(Object.keys(w.payload).sort()).toEqual(['duration_ms', 'finished_at', 'job', 'name', 'next', 'started_at', 'status']);
+ expect(w.payload).toMatchObject({ job: 812, status: 'completed', duration_ms: 252000, next: 'get_job 812' });
+ expect(Buffer.byteLength(w.text)).toBeLessThan(1000);
+ expect(jobWake(9, null).payload).toMatchObject({ job: 9, status: 'gone' });
+ expect(jobWake(5, { ...job, id: 5, status: 'dead' }).text).toContain('is dead');
+ });
+
+ test('markers and emit ids differ per status, per run and per watcher', () => {
+ const j = { id: 1, name: 'x', status: 'failed', started_at: null, finished_at: null, finished_us: '100' };
+ expect(jobMarker(j)).toBe('100:failed');
+ expect(jobMarker({ ...j, finished_us: '200' })).not.toBe(jobMarker(j));
+ expect(jobMarker(null)).toBe('gone');
+ expect(wakeEmitId(JOB_FINISHED, '1', '100:failed', 1)).not.toBe(wakeEmitId(JOB_FINISHED, '1', '100:failed', 2));
+ expect(formatDuration(59_000)).toBe('59s');
+ expect(formatDuration(3_725_000)).toBe('1h02m');
+ });
+
+ test('the Wakeshift user is 32 hex and separates principals and brains', () => {
+ const s = Buffer.alloc(32, 1);
+ const u = wakeshiftUserId(s, 'brain-a', 'local_stdio:local');
+ expect(u).toMatch(/^[0-9a-f]{32}$/);
+ expect(wakeshiftUserId(s, 'brain-a', 'oauth_client:c1')).not.toBe(u);
+ expect(wakeshiftUserId(s, 'brain-b', 'local_stdio:local')).not.toBe(u);
+ expect(wakeshiftUserId(Buffer.alloc(32, 2), 'brain-a', 'local_stdio:local')).not.toBe(u);
+ });
+});
diff --git a/test/wakeshift.serial.test.ts b/test/wakeshift.serial.test.ts
new file mode 100644
index 0000000000..59652773b4
--- /dev/null
+++ b/test/wakeshift.serial.test.ts
@@ -0,0 +1,350 @@
+/**
+ * Wakeshift report-back, end to end on a repo-less PGLite brain against a fake Wakeshift (test/helpers/fake-wakeshift.ts):
+ * watch, complete, exactly one emit carrying metadata only; a foreign id reads like a missing one and sends nothing;
+ * an already-finished job wakes at once; a revoked principal ends the watch instead of emitting; two watchers never
+ * collide; the failure schedule is bounded (5 attempts, then dead and ended); disabled means no tools and no fetch.
+ *
+ * Serial: points GBRAIN_HOME at a temporary home holding config.json and the 0600 key file.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disabledOpsForPublishGates } from '../src/mcp/publish-gates.ts';
+import { encodeWakeshiftKey } from '../src/core/wakeshift/client.ts';
+import { drainWakes, WAKE_MAX_ATTEMPTS } from '../src/core/wakeshift/drain.ts';
+import { resetWakeshiftEnvKeyForTests } from '../src/core/wakeshift/config.ts';
+import { startFakeWakeshift, type FakeWakeshift } from './helpers/fake-wakeshift.ts';
+import { runWakeshift } from '../src/commands/wakeshift.ts';
+import { readFileSync } from 'node:fs';
+
+const KEY = encodeWakeshiftKey(Buffer.alloc(32, 9));
+const WATCH_OPS = ['watch_job', 'list_watches', 'unwatch'];
+let engine: PGLiteEngine;
+let fake: FakeWakeshift;
+let home: string;
+const prevHome = process.env.GBRAIN_HOME;
+const prevKey = process.env.WAKESHIFT_API_KEY;
+
+function writeConfig(wakeshift: Record<string, unknown> | null): void {
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...(wakeshift ? { wakeshift } : {}) }), { mode: 0o600 });
+}
+
+beforeAll(async () => {
+ home = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-'));
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ process.env.GBRAIN_HOME = home;
+ delete process.env.WAKESHIFT_API_KEY;
+ resetWakeshiftEnvKeyForTests();
+ writeFileSync(join(home, '.gbrain', 'wakeshift.key'), KEY + '\n', { mode: 0o600 });
+ chmodSync(join(home, '.gbrain', 'wakeshift.key'), 0o600);
+ fake = startFakeWakeshift(KEY);
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ fake.stop();
+ await engine.disconnect();
+ if (prevHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = prevHome;
+ if (prevKey !== undefined) process.env.WAKESHIFT_API_KEY = prevKey;
+ rmSync(home, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ writeConfig({ enabled: true, url: fake.url });
+ fake.calls.length = 0;
+ fake.respond.clear();
+ await engine.executeRaw('DELETE FROM wake_subscriptions');
+ await engine.executeRaw('DELETE FROM minion_jobs');
+});
+
+async function seedJob(status: string, owner?: string): Promise<number> {
+ const data = { __submitter: 'cli:test', ...(owner ? { __owner_client_id: owner } : {}), slug: 'people/alice-example', note: 'private canary text' };
+ const rows = await engine.executeRaw<{ id: number }>(
+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, started_at, finished_at)
+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'sync', 'default', $1, $2::jsonb, now() - interval '3 minutes',
+ CASE WHEN $1 IN ('completed','failed','dead','cancelled') THEN now() END) RETURNING id`, [status, JSON.stringify(data)]);
+ return Number(rows[0]!.id);
+}
+
+const finish = (id: number, status = 'completed') => engine.executeRaw(`UPDATE minion_jobs SET status = $2, finished_at = now() WHERE id = $1`, [id, status]);
+const stdio = { remote: true, transport: 'stdio' as const, sourceId: 'default', mcpCaller: { client: 'claude-code', meta: { 'claudecode/toolUseId': 't1' } } };
+const emits = () => fake.calls.filter(c => c.path === '/events/emit');
+const body = (r: { content: Array<{ text: string }> }) => JSON.parse(r.content[0]!.text);
+
+describe('watch_job → completion → one pointer emit', () => {
+ test('subscribes the conversation, renders the addition last, and emits once with metadata only', async () => {
+ const id = await seedJob('active');
+ const r = await dispatchToolCall(engine, 'watch_job', { id, harness: 'claude-code' }, stdio);
+ expect(r.isError).toBeFalsy();
+ expect(body(r)).toMatchObject({ watching: true, job: id, already_finished: false, status: 'active' });
+ expect(r.content.at(-1)!.text).toContain('secret-addition-text');
+ expect((r._meta as Record<string, unknown>)['wakeshift/session']).toBe('secret-addition-meta');
+
+ const sub = fake.calls.find(c => c.path === '/event-subscriptions')!;
+ expect(sub.assertionOk).toBe(true);
+ expect(sub.body).toMatchObject({ name: 'gbrain.job.finished', arguments: { job: id }, once: true, ttl: '7d' });
+ expect(sub.body.call).toMatchObject({ tool: 'watch_job', client: 'claude-code', harness: 'claude-code', meta: { 'claudecode/toolUseId': 't1' } });
+ expect(sub.body.call.user).toMatch(/^[0-9a-f]{32}$/);
+
+ expect((await drainWakes(engine)).delivered).toBe(0);
+ expect(emits()).toHaveLength(0);
+ await finish(id);
+ expect((await drainWakes(engine)).delivered).toBe(1);
+ expect((await drainWakes(engine)).delivered).toBe(0);
+ expect(emits()).toHaveLength(1);
+ const e = emits()[0]!;
+ expect(e.assertionOk).toBe(true);
+ expect(e.body.name).toBe('gbrain.job.finished');
+ expect(e.body.to).toEqual([{ user: sub.body.call.user, subscription: 'sub_1' }]);
+ expect(e.body.text).toMatch(new RegExp(`^gbrain: job ${id} \\(sync\\) finished ok in 3m0[0-9]s\\. Call get_job ${id} for the result\\.$`));
+ expect(e.body.id).toMatch(new RegExp(`^gbrain\\.job\\.finished:${id}:\\d+:completed:\\d+$`));
+ const raw = JSON.stringify(e.body);
+ expect(raw).not.toContain('alice-example');
+ expect(raw).not.toContain('canary');
+ const [row] = await engine.executeRaw<{ state: string }>('SELECT state FROM wake_subscriptions');
+ expect(row!.state).toBe('delivered');
+ });
+
+ test('a job that already finished wakes during the watch call', async () => {
+ const id = await seedJob('failed');
+ const r = await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ expect(body(r)).toMatchObject({ already_finished: true, status: 'failed' });
+ expect(emits()).toHaveLength(1);
+ expect(emits()[0]!.body.payload).toMatchObject({ job: id, status: 'failed', next: `get_job ${id}` });
+ });
+
+ test('a removed job emits "details gone"', async () => {
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ await engine.executeRaw('DELETE FROM minion_jobs WHERE id = $1', [id]);
+ await drainWakes(engine);
+ expect(emits()[0]!.body.payload).toMatchObject({ job: id, status: 'gone' });
+ });
+});
+
+describe('access', () => {
+ const agent = (clientId: string) => ({ remote: true, transport: 'http' as const, sourceId: 'default', auth: { token: 't', clientId, principal: { kind: 'oauth_client' as const, id: clientId }, member: null, scopes: ['agent'] } });
+
+ test('a foreign job id answers exactly like a missing id, and nothing reaches Wakeshift', async () => {
+ await engine.executeRaw(`INSERT INTO oauth_clients (client_id, client_name) VALUES ('client-b', 'client-b') ON CONFLICT DO NOTHING`);
+ const foreign = await seedJob('active', 'client-a');
+ const missing = foreign + 1000;
+ const a = await dispatchToolCall(engine, 'watch_job', { id: foreign }, agent('client-b'));
+ const b = await dispatchToolCall(engine, 'watch_job', { id: missing }, agent('client-b'));
+ expect(a.isError).toBe(true);
+ expect(a.content[0]!.text.replaceAll(String(foreign), 'N')).toBe(b.content[0]!.text.replaceAll(String(missing), 'N'));
+ expect(fake.calls).toHaveLength(0);
+ const own = await seedJob('active', 'client-b');
+ expect((await dispatchToolCall(engine, 'watch_job', { id: own }, agent('client-b'))).isError).toBeFalsy();
+ });
+
+ test('a principal revoked before completion gets no emit, and its watch is ended at Wakeshift', async () => {
+ await engine.executeRaw(`INSERT INTO oauth_clients (client_id, client_name) VALUES ('client-r', 'client-r') ON CONFLICT DO NOTHING`);
+ const id = await seedJob('active', 'client-r');
+ expect((await dispatchToolCall(engine, 'watch_job', { id }, agent('client-r'))).isError).toBeFalsy();
+ await engine.executeRaw(`UPDATE oauth_clients SET deleted_at = now() WHERE client_id = 'client-r'`);
+ await finish(id);
+ expect(await drainWakes(engine)).toMatchObject({ delivered: 0, ended: 1 });
+ expect(emits()).toHaveLength(0);
+ expect(fake.calls.filter(c => c.path === '/event-subscriptions/end')).toHaveLength(1);
+ const [row] = await engine.executeRaw<{ state: string; last_error: string }>('SELECT state, last_error FROM wake_subscriptions');
+ expect(row).toMatchObject({ state: 'ended', last_error: 'principal_revoked' });
+ });
+
+ test('two watchers of one job each get their own emit with distinct ids', async () => {
+ await engine.executeRaw(`INSERT INTO oauth_clients (client_id, client_name) VALUES ('client-c', 'client-c') ON CONFLICT DO NOTHING`);
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ const admin = { remote: true, transport: 'http' as const, sourceId: 'default', auth: { token: 't', clientId: 'client-c', principal: { kind: 'oauth_client' as const, id: 'client-c' }, member: null, scopes: ['admin'] } };
+ await dispatchToolCall(engine, 'watch_job', { id }, admin);
+ await finish(id);
+ expect((await drainWakes(engine)).delivered).toBe(2);
+ const ids = emits().map(e => e.body.id);
+ expect(new Set(ids).size).toBe(2);
+ expect(new Set(emits().map(e => e.body.to[0].user)).size).toBe(2);
+ });
+
+ test('list_watches and unwatch act only on the caller\'s own watches', async () => {
+ await engine.executeRaw(`INSERT INTO oauth_clients (client_id, client_name) VALUES ('client-d', 'client-d') ON CONFLICT DO NOTHING`);
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ const other = { remote: true, transport: 'http' as const, sourceId: 'default', auth: { token: 't', clientId: 'client-d', principal: { kind: 'oauth_client' as const, id: 'client-d' }, member: null, scopes: ['admin'] } };
+ expect(body(await dispatchToolCall(engine, 'list_watches', {}, other)).watches).toEqual([]);
+ expect(body(await dispatchToolCall(engine, 'unwatch', { job: id }, other))).toMatchObject({ ended: 0 });
+ expect(body(await dispatchToolCall(engine, 'list_watches', {}, stdio)).watches).toHaveLength(1);
+ expect(body(await dispatchToolCall(engine, 'unwatch', { job: id }, stdio))).toMatchObject({ ended: 1 });
+ await finish(id);
+ await drainWakes(engine);
+ expect(emits()).toHaveLength(0);
+ });
+});
+
+describe('failure schedule', () => {
+ const due = () => engine.executeRaw("UPDATE wake_subscriptions SET next_attempt_at = now() - interval '1 second'");
+
+ test('server errors retry on the schedule, then the row dies and is ended once', async () => {
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ await finish(id);
+ fake.respond.set('/events/emit', () => ({ status: 500, body: { error: { code: 'internal', message: 'boom' } } }));
+ const delays: number[] = [];
+ for (let i = 1; i <= WAKE_MAX_ATTEMPTS; i++) {
+ await drainWakes(engine);
+ const [row] = await engine.executeRaw<{ state: string; attempts: number; delay: number }>(
+ 'SELECT state, attempts, round(extract(epoch FROM next_attempt_at - now()))::int AS delay FROM wake_subscriptions');
+ expect(row!.attempts).toBe(i);
+ if (i < WAKE_MAX_ATTEMPTS) { expect(row!.state).toBe('open'); delays.push(row!.delay); await due(); } else expect(row!.state).toBe('dead');
+ }
+ expect(delays).toEqual([30, 120, 480, 1800]);
+ await due();
+ await drainWakes(engine);
+ expect(emits()).toHaveLength(WAKE_MAX_ATTEMPTS);
+ expect(fake.calls.filter(c => c.path === '/event-subscriptions/end')).toHaveLength(1);
+ });
+
+ test('429 waits its Retry-After; another 4xx is final at once; id_reused is recorded', async () => {
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ await finish(id);
+ fake.respond.set('/events/emit', () => ({ status: 429, body: { error: { code: 'rate_limited', message: 'slow' } }, headers: { 'retry-after': '7' } }));
+ await drainWakes(engine);
+ const [r1] = await engine.executeRaw<{ delay: number }>('SELECT round(extract(epoch FROM next_attempt_at - now()))::int AS delay FROM wake_subscriptions');
+ expect(r1!.delay).toBe(7);
+ await due();
+ fake.respond.set('/events/emit', () => ({ status: 409, body: { error: { code: 'id_reused', message: 'x' } } }));
+ await drainWakes(engine);
+ const [r2] = await engine.executeRaw<{ state: string; last_error: string; attempts: number }>('SELECT state, last_error, attempts FROM wake_subscriptions');
+ expect(r2).toMatchObject({ state: 'dead', last_error: 'id_reused', attempts: 2 });
+ });
+
+ test('a lease held by another drainer is never emitted twice', async () => {
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ await finish(id);
+ await engine.executeRaw("UPDATE wake_subscriptions SET lease_until = now() + interval '1 minute'");
+ expect((await drainWakes(engine)).delivered).toBe(0);
+ expect(emits()).toHaveLength(0);
+ });
+
+ test('Wakeshift down during watch_job: a clear error with the wait_job fix and no row', async () => {
+ const id = await seedJob('active');
+ fake.respond.set('/event-subscriptions', () => ({ status: 503, body: { error: { code: 'unavailable', message: 'down' } } }));
+ const r = await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ expect(r.isError).toBe(true);
+ const env = JSON.parse(r.content[0]!.text);
+ expect(env.code ?? env.error).toBe('wakeshift_unavailable');
+ expect(JSON.stringify(env)).toContain('wait_job');
+ expect(await engine.executeRaw('SELECT 1 FROM wake_subscriptions')).toHaveLength(0);
+ });
+});
+
+describe('off means inert', () => {
+ test('disabled: the three tools are hidden, calls refuse, the drainer sends nothing', async () => {
+ writeConfig({ enabled: false, url: fake.url });
+ const disabled = await disabledOpsForPublishGates(engine, null, { transport: 'stdio' });
+ for (const op of WATCH_OPS) expect(disabled.has(op)).toBe(true);
+ const id = await seedJob('completed');
+ const r = await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ expect(r.isError).toBe(true);
+ expect(r.content[0]!.text).toContain('wakeshift_not_enabled');
+ expect(await drainWakes(engine)).toMatchObject({ skipped: 'off' });
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('enabled without a usable key is still off; a DB-plane flag never turns it on', async () => {
+ writeConfig(null);
+ await engine.setConfig('mcp.publish_wakeshift', 'true');
+ try {
+ expect((await disabledOpsForPublishGates(engine, null)).has('watch_job')).toBe(true);
+ } finally {
+ await engine.executeRaw("DELETE FROM config WHERE key = 'mcp.publish_wakeshift'");
+ }
+ writeConfig({ enabled: true, url: fake.url });
+ expect((await disabledOpsForPublishGates(engine, null)).has('watch_job')).toBe(false);
+ chmodSync(join(home, '.gbrain', 'wakeshift.key'), 0o644);
+ try {
+ expect((await disabledOpsForPublishGates(engine, null)).has('watch_job')).toBe(true);
+ } finally {
+ chmodSync(join(home, '.gbrain', 'wakeshift.key'), 0o600);
+ }
+ });
+
+ test('a local CLI caller is told to use gbrain jobs wait', async () => {
+ const id = await seedJob('active');
+ const r = await dispatchToolCall(engine, 'watch_job', { id }, { remote: false });
+ expect(r.isError).toBe(true);
+ expect(r.content[0]!.text).toContain('gbrain jobs wait');
+ expect(fake.calls).toHaveLength(0);
+ });
+});
+
+async function cli(args: string[]): Promise<{ out: string; error?: unknown }> {
+ const orig = console.log;
+ let out = '';
+ console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };
+ try { await runWakeshift(engine, args); return { out }; } catch (error) { return { out, error }; } finally { console.log = orig; }
+}
+
+describe('gbrain wakeshift', () => {
+ test('enable checks the key, merges the manifest and writes only the file plane; status shows the kid, never the key', async () => {
+ writeConfig(null);
+ const r = await cli(['enable', '--yes', '--url', fake.url, '--json']);
+ expect(r.error).toBeUndefined();
+ expect(fake.calls.map(c => c.path)).toEqual(['/app', '/manifest/merge']);
+ expect(fake.calls[1]!.body.events[0].name).toBe('gbrain.job.finished');
+ const cfg = JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8'));
+ expect(cfg.wakeshift).toEqual({ enabled: true, url: fake.url });
+ expect(JSON.stringify(cfg)).not.toContain(KEY.slice(4));
+ const st = await cli(['status', '--json']);
+ const doc = JSON.parse(st.out);
+ expect(doc).toMatchObject({ enabled: true, active: true, key: { source: 'file' } });
+ expect(doc.key.kid).toMatch(/^[A-Za-z0-9_-]{22}$/);
+ expect(st.out + r.out).not.toContain(KEY.slice(4));
+ });
+
+ test('enable refuses a brain with live access members, and nothing is sent or written', async () => {
+ writeConfig(null);
+ await engine.executeRaw("INSERT INTO access_members (id) VALUES ('alice-example') ON CONFLICT DO NOTHING");
+ try {
+ const r = await cli(['enable', '--yes', '--url', fake.url]);
+ expect(String((r.error as Error)?.message)).toContain('live access member');
+ expect(fake.calls).toHaveLength(0);
+ expect(JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')).wakeshift).toBeUndefined();
+ } finally {
+ await engine.executeRaw("DELETE FROM access_members WHERE id = 'alice-example'");
+ }
+ });
+
+ test('enable without --yes off a terminal refuses through consent, sending nothing', async () => {
+ writeConfig(null);
+ const r = await cli(['enable', '--url', fake.url]);
+ expect(r.error).toBeDefined();
+ expect(fake.calls).toHaveLength(0);
+ });
+
+ test('disable hides the tools at once and ends open watches at Wakeshift', async () => {
+ const id = await seedJob('active');
+ await dispatchToolCall(engine, 'watch_job', { id }, stdio);
+ const r = await cli(['disable', '--json']);
+ expect(JSON.parse(r.out)).toMatchObject({ enabled: false, ended: 1, told_wakeshift: 1 });
+ expect((await disabledOpsForPublishGates(engine, null)).has('watch_job')).toBe(true);
+ await finish(id);
+ expect(await drainWakes(engine)).toMatchObject({ skipped: 'off' });
+ expect(emits()).toHaveLength(0);
+ });
+
+ test('test reports the app, and a refused key exits non-zero', async () => {
+ const ok = await cli(['test', '--json']);
+ expect(JSON.parse(ok.out)).toMatchObject({ ok: true, app: { id: 'app_test' } });
+ fake.respond.set('/app', () => ({ status: 401, body: { error: { code: 'unauthenticated', message: 'unknown key' } } }));
+ const bad = await cli(['test', '--json']);
+ expect(JSON.parse(bad.out)).toMatchObject({ ok: false });
+ expect(process.exitCode).toBe(1);
+ process.exitCode = 0;
+ });
+});