Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(wakeshift): write.settled, cron.finished, shared-brain terms, forget on remove (PR 2 core lane)
garrytan4d5cb76764b3
diff --git a/docs/TOOL_CATALOG.md b/docs/TOOL_CATALOG.mdindex 06983e1c48..d3247a1553 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: 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.+Every non-localOnly operation on the MCP surface: 174 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@@ -99,13 +99,14 @@ Every non-localOnly operation on the MCP surface: 171 tools across 26 areas. **S| Tool | Description | Scope | Starter | Gate ||---|---|---|---|---|+| `accept_wakeshift_terms` | Record that the user agreed to the agreement step a watch tool returned (agreement_required): this brain operator's terms and privacy policy and Wakeshift's Connector Terms and Privacy Policy. | write | | `mcp.publish_wakeshift` || `cancel_job` | Cancel a waiting, active or delayed job you may manage. | admin | yes | || `get_agent_job` | Poll a submit_agent job: status, result, queue_position. | agent | yes | || `get_job` | Get job status and details by ID. | admin | | || `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` |+| `list_watches` | List what this connection is watching through Wakeshift (jobs, write requests and crons: open watches, plus ones that ended in the last day) with their state: open, delivered, dead or ended. | write | | `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 | | |@@ -113,9 +114,11 @@ Every non-localOnly operation on the MCP surface: 171 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` |+| `unwatch` | Stop watching: ends this connection's open Wakeshift watches on one job, write request or cron (or one watch by its id), so no wake comes for it. | write | | `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_cron` | This tool notifies you: it has gbrain wake this conversation through Wakeshift the next time the named cron reports its run (ok or failed) with gbrain wakeshift emit. | admin | | `mcp.publish_wakeshift` || `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` |+| `watch_write_request` | This tool notifies you: it has gbrain wake this conversation through Wakeshift when your write request settles (committed, failed, conflict or cancelled), so you can stop polling get_write_request after write_pending. | write | | `mcp.publish_wakeshift` |## linksdiff --git a/docs/architecture/key-files/wakeshift.md b/docs/architecture/key-files/wakeshift.mdindex 76514b6bbb..a272a37cd3 100644--- a/docs/architecture/key-files/wakeshift.md+++ b/docs/architecture/key-files/wakeshift.md@@ -3,4 +3,4 @@[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/core/wakeshift-env-key.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, which `wakeshift-env-key.ts` moves out of the environment on every config load so children never inherit it, the first value seen winning; 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>:<namespace>` (12 hex of the watch's user and creation time, so brains on one key never collide), the claim re-checking backoff and attempts, a settle only under the claim's lease, 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`.+- `src/core/ops/wakeshift.ts` + `src/core/wakeshift/{client,config,events,drain,terms,forget}.ts` + `src/core/wakeshift-env-key.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; endpoints subscribe, unsubscribe, end, emit, manifest merge and `/users/forget`. `config.ts` holds the host-only state: `wakeshift.enabled`/`url`/`terms_url`/`privacy_url`/`manifest_hash` in the file plane, the key (WAKESHIFT_API_KEY, which `wakeshift-env-key.ts` moves out of the environment on every config load so children never inherit it, the first value seen winning; else a 0600 `~/.gbrain/wakeshift.key`), the 0600 HMAC secret and the opaque Wakeshift user (HMAC over brain and principal key: `member:<id>` when bound, else `<kind>:<id>`); `wakeshiftRuntime().file` carries the file plane to the ops and the drainer, so core never reads config twice; `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`). Three events (`events.ts`): `gbrain.job.finished` (`watch_job`, the get_job owner fence from `ops/jobs.ts`), `gbrain.write.settled` (`watch_write_request`, write scope, the receipt read path `receiptAccess`/`receiptVisible`/`receiptNotFound` exported from `ops/persistence.ts`, so a foreign id reads exactly like get_write_request's not_found; `target_ref` holds the `persistence_requests.id`), `gbrain.cron.finished` (`watch_cron`, admin scope, names in `wake_crons`; `gbrain wakeshift emit cron.finished` only inserts a `wake_cron_runs` row and exits 0). Every watch goes through `openWatch` (subscribe `once` 7 d, insert, roll back on failure, wake at once when settled, Wakeshift's addition through `ctx.emitToolTail`); `ctx.mcpCaller` (client name, User-Agent, request `_meta`) is set by the stdio and both HTTP transports. `terms.ts` is the shared-brain agreement step: on a brain with live access members each principal's first `watch_*` returns it until `accept_wakeshift_terms` records (principal key, version = 16 hex of SHA-256 over the two operator links) in `wake_terms_acceptances`. `forget.ts` (`forgetWakePrincipal`, over the scalar SqlQuery) is called by `removeMember` (access/members.ts), `revokeLegacyTokenById` (token-mint.ts) and `auth revoke`/`revoke --id`/`revoke-client` (commands/auth.ts): it ends the principal's open rows (`principal_revoked`), drops its acceptance and queues `wake_forgets` for users not derived from a member that outlives the credential. `drain.ts` is pull reconciliation: `gbrain serve` and `MinionWorker.start` run a 5 s unref'd timer, `gbrain jobs work` (PGLite) a final pass; one candidate query LEFT JOINs each event family (`minion_jobs`, `persistence_requests` committed with no recovery record or failed/conflict/cancelled, the first `wake_cron_runs` row after the watch began), at most 20 leased rows a tick; the emit id `<event>:<target>:<marker>:<row>:<namespace>` (12 hex of the watch's user and creation time, so brains on one key never collide); the claim re-checking backoff and attempts, a settle only under the claim's lease, the principal re-checked before each emit (a revoked one ends and queues its forget), on a shared brain the terms acceptance re-checked (`terms_not_accepted` ends), 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; up to 10 leased queued forgets a tick on the same schedule. Payloads are pointers: ids, status, operation, times, next call; never page text, slugs or cron output. Tables: v290 `wake_subscriptions`, v291 `wake_crons`, `wake_cron_runs`, `wake_terms_acceptances`, `wake_forgets` and `wake_subscriptions.target_ref`. The CLI (`enable` with consent, the terms links on a shared brain, GET /app, the manifest merge and its stored hash; `disable`, `status` with the stale-manifest line, `test`, `cron add|remove|list`, `emit`; `watch` dispatches to `wakeshift-watch.ts`) is the only writer of the file-plane keys. Doctor warns on key mode, no usable key, members without terms links, dead and id_reused rows, forgets older than a day, unregistered cron emits and a stale manifest. Tests: `test/wakeshift-client.test.ts`, `test/wakeshift.serial.test.ts` and `test/wakeshift-pr2.serial.test.ts` (repo-less PGLite against `test/helpers/fake-wakeshift.ts`), `test/e2e/wakeshift-postgres.test.ts` and `test/e2e/wakeshift-pr2-postgres.test.ts`.diff --git a/docs/architecture/managed-mutating-writers.tsv b/docs/architecture/managed-mutating-writers.tsvindex 511d4eb04a..1e332f0631 100644--- a/docs/architecture/managed-mutating-writers.tsv+++ b/docs/architecture/managed-mutating-writers.tsv@@ -46,6 +46,9 @@ op pause_job no_canonical_write Minion queue state only.op resume_job no_canonical_write Minion queue state only.op watch_job no_canonical_write Wake subscription state only (wake_subscriptions).op unwatch no_canonical_write Wake subscription state only (wake_subscriptions).+op watch_write_request no_canonical_write Wake subscription state only (wake_subscriptions).+op watch_cron no_canonical_write Wake subscription state only (wake_subscriptions).+op accept_wakeshift_terms no_canonical_write Wakeshift terms acceptance state only (wake_terms_acceptances).op replay_job no_canonical_write Minion queue state only.op send_job_message no_canonical_write Minion inbox rows only.op submit_agent no_canonical_write Queues a subagent job; its tools write through put_page.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex ad2ee2b9b5..d9bbee0bb4 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -5164,7 +5164,7 @@ More: [docs/guides/wakeshift.md#the-key](../../docs/guides/wakeshift.md#the-key)| 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 |+| A watch tool (watch_job, watch_write_request, watch_cron) 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> for a job, or gbrain write-request -- <request_id> for a write. | agent | `repeat the read that failed` | 1 | no |More: [docs/guides/wakeshift.md#delivery-and-latency](../../docs/guides/wakeshift.md#delivery-and-latency)@@ -5194,9 +5194,9 @@ More: [docs/guides/wakeshift.md#troubleshooting](../../docs/guides/wakeshift.md#| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Reporting back refused (gbrain wakeshift enable, or watch_job after a member was added): 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 |+| Reporting back refused (gbrain wakeshift enable, or a watch tool): this brain has live access members and its operator has not set the terms and privacy links Wakeshift requires. | Wakeshift's terms (6.2, 6.6) make the operator show each person its own terms and privacy policy, which refer them to Wakeshift's Connector Terms and Privacy Policy, before the first wake. gbrain shows that step from the two links the owner sets on the brain host. | Ask the brain owner to run gbrain wakeshift enable --terms-url <https url> --privacy-url <https url>; meanwhile agents can use wait_job or get_write_request. | user | `gbrain doctor --json` | 1 | no |-More: [docs/guides/wakeshift.md#who-it-is-for](../../docs/guides/wakeshift.md#who-it-is-for)+More: [docs/guides/wakeshift.md#shared-brains](../../docs/guides/wakeshift.md#shared-brains)### wakeshift_unavailablediff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 897fb4b7be..8a13e6b05c 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -388,7 +388,8 @@ receive the relevant retrieved content or source text. Self-hosted providers havtheir own deployment boundary. The connected agent's own model also receiveswhatever 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+job's, write request's or cron's id, status and times (and a removed member's+hashed id to forget), 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 thediff --git a/docs/guides/wakeshift.md b/docs/guides/wakeshift.mdindex ac282e466f..1a2b4c8e00 100644--- a/docs/guides/wakeshift.md+++ b/docs/guides/wakeshift.md@@ -1,10 +1,12 @@# 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.+gbrain can wake an agent's conversation when a background job it started finishes, when a pending write settles, or when a scheduled cron reports its run, 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.+The same works for a write that answered `write_pending` (exit 10): `watch_write_request` with its `request_id` wakes the conversation when the write commits, fails, conflicts or is cancelled, and the agent reads the receipt with `get_write_request`. And for your own crons: `watch_cron` wakes the conversation the next time a cron you registered reports its run.++Without Wakeshift, `wait_job` (MCP) and `gbrain jobs wait <id>` (CLI) wait for a job, and `get_write_request` reads a write's receipt, 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@@ -14,9 +16,39 @@ Without Wakeshift, `wait_job` (MCP) and `gbrain jobs wait <id>` (CLI) wait for a- put `WAKESHIFT_API_KEY=wst_…` in `~/.gbrain/.env`.When both are present, `WAKESHIFT_API_KEY` wins (a shell export over a `~/.gbrain/.env` value), and `--key-stdin` refuses while it is set, so it never saves a key gbrain would not use.-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.+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 events. On a brain with access members it also needs your terms and privacy links (see [shared brains](#shared-brains)).++The watch tools (`watch_job`, `watch_write_request`, `watch_cron`, `list_watches`, `unwatch`, and on shared brains `accept_wakeshift_terms`) 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.++After an upgrade that adds events, run `gbrain wakeshift enable` again to publish them: `enable` stores a hash of the event manifest it published, and `gbrain wakeshift status` and `gbrain doctor` say when it is older than the installed gbrain.++## The events++| Event | Watch with | Wakes when | Payload |+| --- | --- | --- | --- |+| `gbrain.job.finished` | `watch_job` (admin scope; agent tokens only their own jobs) | the job is completed, failed, dead or cancelled | job id, kind, status, times, duration, `next: get_job <id>` |+| `gbrain.write.settled` | `watch_write_request` (write scope; only your own receipts) | the write is committed (with no recovery still running), failed, conflict or cancelled | request id, state, operation, source id, accepted and settled times, `next: get_write_request <id>` |+| `gbrain.cron.finished` | `watch_cron` (admin scope; registered names only) | the cron's next run reports ok or failed | cron name, status, finish time, a next line |++Each watch wakes once and lasts 7 days; call the watch tool again for the next job, write or run. `watch_write_request` reads the request through the same check as `get_write_request`, so a request id that isn't yours answers exactly like a missing one and nothing is sent. It works on repo-less brains and on git-backed sources alike. `unwatch` takes `job`, `request_id`, `cron` or a `watch` id from `list_watches`.++## Crons++gbrain doesn't run your crons, so the cron's own script reports its run. Register the name once, then end the script with `gbrain wakeshift emit`:++```bash+gbrain wakeshift cron add nightly-digest # once; names are folded to a-z 0-9 . _ -+```-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.+```bash+#!/usr/bin/env bash+# the cron's job script, run through your gbrain wrapper (docs/guides/cron-schedule.md)+status=ok+/path/to/your-job || status=failed+gbrain-run wakeshift emit cron.finished --name nightly-digest --status "$status"+```++`emit` only records the run (name, status, time) in the brain; the drainer wakes the watchers on its next tick. It never calls Wakeshift itself, never waits, and exits 0 when reporting back is off (with one line on stderr) or when the name isn't registered (it records the run and says so; `gbrain doctor` lists unregistered names it saw). `gbrain wakeshift cron list` shows the names with their last run, and `cron remove <name>` removes one and ends its open watches. Runs older than 30 days are dropped. No report path or slug goes into the wake: the agent reads the output where the cron writes it.## The key@@ -28,23 +60,40 @@ A Wakeshift key is an Ed25519 private key: `wst_` followed by 50 base58 characte## 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. A member added after enable pauses reporting back: watch_job refuses with `wakeshift_shared_brain`, no wakes are sent, and `gbrain doctor` warns. 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.+## Shared brains++On a brain with live access members (`gbrain access member list`), you, the brain owner, are the operator of a Wakeshift app that other people use, and Wakeshift's terms put duties on you:++- **Your terms.** Publish terms and a privacy policy, and pass their links to `gbrain wakeshift enable --terms-url <https url> --privacy-url <https url>`. Without them `enable` refuses (`wakeshift_shared_brain`) and names the flags. Wakeshift's Terms of Service 6.6 require your terms or privacy policy to refer members to Wakeshift's [Connector Terms](https://wakeshift.ai/connector-terms) and [Privacy Policy](https://wakeshift.ai/privacy), incorporate them (or require members to agree to them), and name Clawvisor Inc. as a third-party beneficiary of the Connector Terms. Your privacy policy must say that wakes pass through Wakeshift, operated by Clawvisor Inc. as your service provider, and what is sent, why, to whom and for how long (the table below).+- **Controller and processor.** Under Wakeshift's [Data Processing Addendum](https://wakeshift.ai/dpa) you are the controller of your members' wake data and Wakeshift is your processor. You answer members' requests to access or delete their data; removing a member makes gbrain ask Wakeshift to forget them (below).+- **Minimum age.** Wakeshift's terms make you set a minimum age for your members under the laws that apply to them, including laws on children's data. Say it in your terms.++Each person then sees one agreement step before their first watch: the first `watch_*` call returns `agreement_required` with what watching does, your two links, the Wakeshift disclosure and the Connector Terms and Privacy Policy links, and an instruction to ask the user. After the user agrees, the agent calls `accept_wakeshift_terms` with the step's `terms_version`, and gbrain records the acceptance (the person's member id or credential, the version and the time). The version is a hash of your two links, so changing either asks everyone again. A brain with no live members skips the step.++The drainer re-checks this before every wake: on a shared brain a watch whose person hasn't accepted the current terms ends with `last_error: terms_not_accepted` instead of waking. A member added after enable, on a brain whose links were never set, makes every watch refuse with `wakeshift_shared_brain` and `gbrain doctor` warn until you run `enable` with the links.++## Removing someone++`gbrain access member remove`, `gbrain auth revoke` (by name or `--id`; also a token revoked from the admin API or replaced by a harness token rotation) and `gbrain auth revoke-client` end that person's or credential's open watches (`last_error: principal_revoked`), drop its terms acceptance, and queue a Wakeshift Forget User call for the hashed user it watched under, which deletes everything Wakeshift holds for it. The command never waits on the network and works with reporting back off: `gbrain serve` or the job worker sends queued forgets on their next tick (at most 10 a tick, 5 attempts on the delivery schedule), so while reporting back is off they wait. A credential bound to a member watched under the member's user, which outlives that one credential: its watches end, and the member's user is forgotten when the member is removed. A credential deleted some other way is caught when its watch would wake: the watch ends and its forget is queued. `gbrain doctor` warns about a forget waiting more than a day. A member added again later is a new member id with its own acceptance.+## 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") |+| `gbrain wakeshift enable` | your Wakeshift app | the three events' names, descriptions and JSON Schemas |+| a watch call (`watch_job`, `watch_write_request`, `watch_cron`) | 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, request id or cron name, 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 |+| the write settles | your Wakeshift app | a line and a payload of the request id, state, operation name (for example `put_page`), source id, accepted and settled times and the next call |+| the cron reports its run | your Wakeshift app | a line and a payload of the cron name, status, finish time and a next line |+| a member is removed, a token revoked or a client deleted | your Wakeshift app | a Forget User call naming the hashed user id |-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.+`accept_wakeshift_terms` and `gbrain wakeshift emit` send nothing; they write rows in the brain. Never sent: page text, titles or slugs, job data or results, write content or outcomes, cron output or report paths, 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 on PGLite `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.+Delivery is a pull, not a hook: nothing is added to the job queue or the write path. `gbrain serve` (stdio and HTTP) and the job worker check open watches every 5 seconds, and on PGLite `gbrain jobs work` checks once more before it exits. On Postgres, a wake arrives within about 5 seconds of the job finishing, the write settling or the cron's `emit`. A watch on a job or write that has already settled 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`.@@ -57,4 +106,6 @@ Repo-less brains work the same way. Watches are operational database rows, not b- **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`.+- **`agreement_required` instead of a watch.** The brain has members: show the user the step and call `accept_wakeshift_terms` after they agree. `wakeshift_shared_brain` means the owner hasn't set the terms links yet.+- **`watch_cron` says not_found.** The name isn't registered: the brain owner runs `gbrain wakeshift cron add <name>`.- **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.mdindex 8108affb2d..c2d43968bf 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` — 194+The plugin's MCP server runs `gbrain serve --surface full` — 197operations, the same surface every stdio registration gbrain writes pins.Every gbrain operation the bundled skills name is on it. A harness that capsits tool count can narrow this machine's plugin surface withdiff --git a/src/commands/auth.ts b/src/commands/auth.tsindex 3579944cd8..3d51e9bf1e 100644--- a/src/commands/auth.ts+++ b/src/commands/auth.ts@@ -217,8 +217,9 @@ async function revoke(name: string) {const rows = await sql`UPDATE access_tokens SET revoked_at = now()WHERE name = ${name} AND revoked_at IS NULL- RETURNING 1+ RETURNING id`;+ for (const row of rows) await (await import('../core/wakeshift/forget.ts')).forgetWakePrincipal(sql, { kind: 'legacy_token', id: String(row.id) });if (rows.length === 0) {console.error(`No active token found with name "${name}".`);process.exit(1);@@ -249,6 +250,7 @@ async function revokeById(id: string) {console.error(`No active token found with id "${id}".`);process.exit(1);}+ await (await import('../core/wakeshift/forget.ts')).forgetWakePrincipal(sql, { kind: 'legacy_token', id });console.log(`Token "${rows[0].name}" (${id}) revoked.`);});}@@ -391,6 +393,7 @@ async function revokeClient(clientId: string) {console.error(`No client found with id "${clientId}"`);process.exit(1);}+ await (await import('../core/wakeshift/forget.ts')).forgetWakePrincipal(sql, { kind: 'oauth_client', id: clientId });console.log(`OAuth client revoked: "${rows[0].client_name}" (${clientId})`);console.log('Tokens and authorization codes purged via cascade.');});diff --git a/src/commands/doctor/checks/wakeshift.ts b/src/commands/doctor/checks/wakeshift.tsindex afef509203..f110ffe83d 100644--- a/src/commands/doctor/checks/wakeshift.ts+++ b/src/commands/doctor/checks/wakeshift.ts@@ -1,16 +1,21 @@/**- * wakeshift (plan PR 1 item 9): reporting back through Wakeshift. Off is+ * wakeshift (plan PR 1 item 9, PR 2): 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), when the brain gained live access members after enable- * (reporting back pauses), 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.+ * tools stay hidden), when the brain has live access members but no operator+ * terms links (every watch refuses), when watches died (5 failed attempts or a+ * final Wakeshift refusal) or hit `id_reused` (a bug signal) in the last 7+ * days, when `gbrain wakeshift emit` reported runs of crons nobody registered,+ * when a queued Wakeshift forget is older than a day, and when the published+ * manifest is older than this build. 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 { liveAccessMembers } from '../../../core/wakeshift/drain.ts';+import { wakeshiftManifestHash } from '../../../core/wakeshift/events.ts';+import { operatorTerms } from '../../../core/wakeshift/terms.ts';import type { Check } from '../../doctor.ts';import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';@@ -18,7 +23,8 @@ const DOCS = 'docs/guides/wakeshift.md#troubleshooting';async function runWakeshiftCheck(ctx: DoctorContext): Promise<Check[]> {const checks: Check[] = [];- const enabled = wakeshiftFileConfig(loadConfigFileOnly()).enabled === true;+ const file = wakeshiftFileConfig(loadConfigFileOnly());+ const enabled = file.enabled === true;const read = readWakeshiftKey();let kid: string | null = null;let keyProblem: string | null = read.source === 'none' ? 'no key' : null;@@ -40,16 +46,33 @@ async function runWakeshiftCheck(ctx: DoctorContext): Promise<Check[]> {counts[r.state] = (counts[r.state] ?? 0) + Number(r.n);if (r.id_reused) counts.id_reused! += Number(r.n);}- const members = await liveAccessMembers(connectedEngine(ctx));- const details = { enabled, key_source: read.source, kid, watches_7d: counts, live_members: members, docs: DOCS };- const message = members > 0- ? `Reporting back is paused: this brain now has ${members} live access member(s), and this release reports back only on a brain that serves its owner alone. watch_job refuses and no wakes are sent. Fix: gbrain wakeshift disable, or remove the members.`+ const engine = connectedEngine(ctx);+ const members = await liveAccessMembers(engine);+ const termsMissing = members > 0 && !operatorTerms(file);+ const [extra] = await engine.executeRaw<{ unregistered: string[] | null; stale_forgets: number }>(+ `SELECT (SELECT array_agg(DISTINCT r.name ORDER BY r.name) FROM wake_cron_runs r+ WHERE r.finished_at > now() - interval '7 days' AND NOT EXISTS (SELECT 1 FROM wake_crons c WHERE c.name = r.name)) AS unregistered,+ (SELECT count(*)::int FROM wake_forgets WHERE state = 'pending' AND created_at < now() - interval '1 day') AS stale_forgets`);+ const unregistered = (extra?.unregistered ?? []).slice(0, 10);+ const staleForgets = Number(extra?.stale_forgets ?? 0);+ const manifestStale = file.manifest_hash !== wakeshiftManifestHash();+ const details = { enabled, key_source: read.source, kid, watches_7d: counts, live_members: members, terms_set: !termsMissing,+ unregistered_crons_7d: unregistered, stale_forgets: staleForgets, manifest_current: !manifestStale, docs: DOCS };+ const message = termsMissing+ ? `This brain has ${members} live access member(s) but no operator terms links, so every watch refuses and open watches end without a wake. Fix: gbrain wakeshift enable --terms-url <https url> --privacy-url <https url>`: 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: members > 0 || counts.id_reused! > 0 || counts.dead! > 0 ? 'warn' : 'ok', message, details });+ : staleForgets > 0+ ? `${staleForgets} Wakeshift forget(s) for removed members or revoked credentials have waited over a day; gbrain serve or the job worker sends them. Check gbrain wakeshift test, and that one of them runs.`+ : unregistered.length > 0+ ? `gbrain wakeshift emit reported runs of unregistered cron(s) in the last 7 days (${unregistered.join(', ')}), which no agent can watch. Fix: gbrain wakeshift cron add <name>, or fix the name in the cron script.`+ : manifestStale+ ? 'The published Wakeshift event manifest is older than this build, so agents cannot watch the newer events. Fix: gbrain wakeshift enable'+ : `Reporting back through Wakeshift is on (key kid ${kid}); ${counts.open} open watch(es), ${counts.delivered} delivered in the last 7 days.`;+ const warn = termsMissing || counts.id_reused! > 0 || counts.dead! > 0 || staleForgets > 0 || unregistered.length > 0 || manifestStale;+ checks.push({ name: 'wakeshift', status: warn ? 'warn' : 'ok', message, details });}return checks;}diff --git a/src/commands/wakeshift.ts b/src/commands/wakeshift.tsindex 00cedb394b..494da0408d 100644--- a/src/commands/wakeshift.ts+++ b/src/commands/wakeshift.ts@@ -1,12 +1,16 @@/**- * `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.+ * `gbrain wakeshift enable | disable | status | test | cron | emit` (plan D2,+ * D4, D5): the trusted local switch for reporting back through Wakeshift.+ * Only this command writes the `wakeshift.*` keys (host file plane), so no+ * MCP or HTTP caller can turn it on. `enable` asks consent (egress,+ * credentials), requires the operator's terms and privacy links on a brain+ * with live access members, checks the key with GET /app, merges the event+ * manifest and stores its hash; `disable` hides the watch tools at once and+ * ends open watches; `status` and `test` show the key's kid fingerprint,+ * never the key, and `status` says when the published manifest is older than+ * this build. `cron add|remove|list` keeps the names watch_cron accepts;+ * `emit cron.finished` records a run for the drainer and never calls+ * Wakeshift or fails the cron script. Guide: docs/guides/wakeshift.md.*/import { readFileSync, renameSync, writeFileSync } from 'node:fs';import type { BrainEngine } from '../core/engine.ts';@@ -14,21 +18,30 @@ import { loadConfigFileOnly, saveConfig, type GBrainConfig } from '../core/confiimport { 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, wakeshiftPublished, wakeshiftSecret } from '../core/wakeshift/config.ts';-import { wakeshiftManifest } from '../core/wakeshift/events.ts';+import { readWakeshiftKey, wakeshiftFileConfig, wakeshiftKeyFile, wakeshiftPublished, wakeshiftRuntime, wakeshiftSecret, type WakeshiftFileConfig } from '../core/wakeshift/config.ts';+import { CRON_FINISHED, cronName, wakeshiftManifest, wakeshiftManifestHash } from '../core/wakeshift/events.ts';import { endAtWakeshift, liveAccessMembers } from '../core/wakeshift/drain.ts';+import { WAKESHIFT_CONNECTOR_TERMS_URL, WAKESHIFT_PRIVACY_URL, httpsUrl, operatorTerms } from '../core/wakeshift/terms.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { shellQuote } from '../core/agent-output.ts';-const HELP = `gbrain wakeshift <command> — report back to agent conversations when jobs finish (off by default)+const HELP = `gbrain wakeshift <command> — report back to agent conversations when jobs, writes and crons 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]+ status [--json] on/off, where the key comes from (its kid fingerprint only), watch counts,+ and whether the published manifest is older than this build+ enable [--key-stdin] [--url <https url>] [--terms-url <https url> --privacy-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)+ publishes gbrain's events; --key-stdin saves the key from stdin to+ ~/.gbrain/wakeshift.key (0600). A brain with access members needs your+ terms and privacy links; each member accepts them before a first watchdisable [--json] turn it off: the watch tools disappear at once and open watches endtest [--json] check the key and the app with Wakeshift; sends no wake+ cron add <name> | remove <name> | list [--json]+ the cron names agents may watch with watch_cron+ emit cron.finished --name <name> --status ok|failed+ record a cron run at the end of the cron's script; the drainer wakes its+ watchers. Never calls Wakeshift itself, and exits 0 when reporting back is offThe 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`;@@ -74,8 +87,8 @@ async function watchCounts(engine: BrainEngine): Promise<Record<string, number>>}}-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 } };+function writeFilePlane(update: (w: WakeshiftFileConfig) => WakeshiftFileConfig): void {+ const cfg = (loadConfigFileOnly() ?? { engine: 'pglite' }) as GBrainConfig & { wakeshift?: WakeshiftFileConfig };cfg.wakeshift = update({ ...(cfg.wakeshift ?? {}) });saveConfig(cfg);}@@ -99,12 +112,20 @@ async function status(engine: BrainEngine, json: boolean): Promise<void> {}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 }, [+ const manifestStale = file.enabled === true && file.manifest_hash !== wakeshiftManifestHash();+ const terms = operatorTerms(file);+ say(json, {+ enabled: file.enabled === true, active: on, url: normalizeWakeshiftUrl(file.url), key: { source: read.source, kid, problem: keyProblem }, watches: counts,+ manifest: { current: !manifestStale, ...(manifestStale ? { fix: shellQuote(['gbrain', 'wakeshift', 'enable']) } : {}) },+ terms: terms ? { terms_url: terms.terms_url, privacy_url: terms.privacy_url, version: terms.version } : null,+ }, [`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'}`,+ ...(terms ? [` terms: ${terms.terms_url} and ${terms.privacy_url} (version ${terms.version})`] : []),...(on || file.enabled !== true ? [] : [' The watch tools stay hidden until the key problem above is fixed.']),+ ...(manifestStale ? [' The published event manifest is older than this build: run gbrain wakeshift enable to publish the new events.'] : []),]);}@@ -121,18 +142,31 @@ async function enable(engine: BrainEngine, args: string[]): Promise<void> {loaded = loadKey();}const { key, source } = loaded;+ const saved = wakeshiftFileConfig(loadConfigFileOnly());+ const links: Pick<WakeshiftFileConfig, 'terms_url' | 'privacy_url'> = {};+ for (const [flag, field] of [['--terms-url', 'terms_url'], ['--privacy-url', 'privacy_url']] as const) {+ const raw = flagValue(args, flag);+ if (raw === undefined) continue;+ const url = httpsUrl(raw);+ if (!url) throw opError('invalid_params', `${flag} must be an absolute https URL (got ${JSON.stringify(raw.slice(0, 80))}).`, `Pass the https address of your published ${field === 'terms_url' ? 'terms' : 'privacy policy'}.`);+ links[field] = url;+ }+ const terms = operatorTerms({ ...saved, ...links });const members = await liveAccessMembers(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.');+ if (members > 0 && !terms) {+ throw opError('wakeshift_shared_brain', `This brain has ${members} live access member(s), and Wakeshift's terms make you, the operator, show each of them your own terms and privacy policy before any wake. Nothing was turned on.`,+ 'Run gbrain wakeshift enable --terms-url <https url> --privacy-url <https url> with your published terms and privacy policy (they must refer members to Wakeshift\'s Connector Terms and Privacy Policy); each member then accepts them once before a first watch.');}- const url = normalizeWakeshiftUrl(flagValue(args, '--url') ?? wakeshiftFileConfig(loadConfigFileOnly()).url);+ const url = normalizeWakeshiftUrl(flagValue(args, '--url') ?? saved.url);+ const operatorDuty = members > 0+ ? ` This brain has ${members} access member(s): as the operator you are the controller of their wake data and Wakeshift is your processor (its DPA). Your terms (${terms!.terms_url}) and privacy policy (${terms!.privacy_url}) must refer members to Wakeshift's Connector Terms (${WAKESHIFT_CONNECTOR_TERMS_URL}) and Privacy Policy (${WAKESHIFT_PRIVACY_URL}), incorporate them and name Clawvisor Inc. as a third-party beneficiary (Wakeshift ToS 6.6), state a minimum age for members, and say that wakes pass through Wakeshift. Each member accepts your terms once before a first watch.`+ : '';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.',+ why: 'Agents can then ask gbrain to wake their conversation when a job, a pending write or a scheduled cron finishes, instead of polling.',+ risk: `Each watched job, write request or cron sends Wakeshift a pointer: its id or cron name, 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.${operatorDuty}`,+ user_message: `Turn on gbrain reporting back through Wakeshift? It sends ids and status (never page text) to Wakeshift when a watched job, write or cron finishes.${members > 0 ? ' This brain has members, so your terms and privacy policy must refer them to Wakeshift\'s Connector Terms and Privacy Policy.' : ''}`,argv: ['gbrain', 'wakeshift', 'enable'], args,});const api = wakeshiftClient(key, { url });@@ -153,13 +187,14 @@ async function enable(engine: BrainEngine, args: string[]): Promise<void> {}wakeshiftSecret();writeFilePlane(w => {- const next: { enabled?: boolean; url?: string } = { ...w, enabled: true, url };+ const next: WakeshiftFileConfig = { ...w, ...links, enabled: true, url, manifest_hash: wakeshiftManifestHash() };if (url === 'https://app.wakeshift.ai') delete next.url;return next;});- say(args.includes('--json'), { enabled: true, url, app: { id: app?.id, name: app?.name }, key: { source, kid: key.kid } }, [+ say(args.includes('--json'), { enabled: true, url, app: { id: app?.id, name: app?.name }, key: { source, kid: key.kid }, ...(terms ? { terms_version: terms.version } : {}) }, [`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.',+ 'Agents now see watch_job, watch_write_request, watch_cron, list_watches and unwatch; gbrain serve and the job worker deliver wakes.',+ ...(members > 0 ? [`Members see your terms (version ${terms!.version}) on their first watch and accept them with accept_wakeshift_terms; changing a link asks again.`] : []),'Turn it off with: gbrain wakeshift disable',]);}@@ -197,6 +232,65 @@ async function test(json: boolean): Promise<void> {}}+/** `cron add|remove|list`: the names watch_cron accepts (slugged to [a-z0-9._-], at most 64). Local state; works with reporting back off. */+async function cron(engine: BrainEngine, args: string[], json: boolean): Promise<void> {+ const [verb, raw] = args;+ if (verb === 'list') {+ const rows = await engine.executeRaw<{ name: string; created_at: Date | string; last_status: string | null; last_finished_at: Date | string | null }>(+ `SELECT c.name, c.created_at, r.status AS last_status, r.finished_at AS last_finished_at FROM wake_crons c+ LEFT JOIN LATERAL (SELECT status, finished_at FROM wake_cron_runs WHERE name = c.name ORDER BY finished_at DESC, id DESC LIMIT 1) r ON true+ ORDER BY c.name`);+ say(json, { crons: rows }, rows.length ? rows.map(r => `${r.name}${r.last_status ? ` last run: ${r.last_status} at ${new Date(r.last_finished_at!).toISOString()}` : ' no run reported yet'}`) : ['No crons registered (gbrain wakeshift cron add <name>).']);+ return;+ }+ const name = cronName(raw);+ if ((verb !== 'add' && verb !== 'remove') || !name) {+ console.error('Usage: gbrain wakeshift cron add <name> | remove <name> | list [--json]');+ setCliExitVerdict(2);+ return;+ }+ const renamed = name !== raw ? ` (stored as ${name})` : '';+ if (verb === 'add') {+ await engine.executeRaw('INSERT INTO wake_crons (name) VALUES ($1) ON CONFLICT (name) DO NOTHING', [name]);+ say(json, { name, registered: true }, [`Registered cron ${name}${renamed}. End its script with: gbrain wakeshift emit cron.finished --name ${name} --status ok (or failed).`]);+ return;+ }+ await engine.executeRaw('DELETE FROM wake_crons WHERE name = $1', [name]);+ const ended = await engine.executeRaw<{ id: number; wake_user: string; ws_subscription_id: string }>(+ `UPDATE wake_subscriptions SET state = 'ended', last_error = 'cron_removed', lease_until = NULL, updated_at = now()+ WHERE state = 'open' AND event = $1 AND target = $2 RETURNING id, wake_user, ws_subscription_id`, [CRON_FINISHED, name]);+ const api = ended.length ? wakeshiftRuntime()?.api : undefined;+ if (api) for (const row of ended) await endAtWakeshift(api, row);+ say(json, { name, registered: false, ended: ended.length }, [`Removed cron ${name}${renamed}; ended ${ended.length} open watch(es) on it.`]);+}++/**+ * `emit cron.finished --name <name> --status ok|failed`: record the run for the drainer and return. Never calls+ * Wakeshift and exits 0 whatever happens after the arguments parse (off, unregistered, a database error), with one+ * stderr line, so the cron script's own exit status stays its own.+ */+async function emit(engine: BrainEngine, args: string[]): Promise<void> {+ const name = cronName(flagValue(args, '--name'));+ const status = flagValue(args, '--status');+ if (args[0] !== 'cron.finished' || !name || (status !== 'ok' && status !== 'failed')) {+ console.error('Usage: gbrain wakeshift emit cron.finished --name <name> --status ok|failed');+ setCliExitVerdict(2);+ return;+ }+ if (!wakeshiftPublished()) {+ console.error(`[wakeshift] reporting back is off, so the ${name} run was not recorded (gbrain wakeshift status).`);+ return;+ }+ try {+ await engine.executeRaw('INSERT INTO wake_cron_runs (name, status) VALUES ($1, $2)', [name, status]);+ await engine.executeRaw("DELETE FROM wake_cron_runs WHERE name = $1 AND finished_at < now() - interval '30 days'", [name]);+ const registered = await engine.executeRaw('SELECT 1 FROM wake_crons WHERE name = $1', [name]);+ if (registered.length === 0) console.error(`[wakeshift] cron ${name} is not registered, so no agent can watch it: run gbrain wakeshift cron add ${name}.`);+ } catch (e) {+ console.error(`[wakeshift] could not record the ${name} run: ${e instanceof Error ? e.message : String(e)}`);+ }+}+/** `gbrain config get mcp.publish_wakeshift`: the runtime gate, which never reads the DB plane. */export function printWakeshiftGate(): void {console.log(String(wakeshiftPublished()));@@ -211,6 +305,9 @@ export async function runWakeshift(engine: BrainEngine, args: string[]): Promiseif (sub === 'enable') return enable(engine, args.slice(1));if (sub === 'disable') return disable(engine, json);if (sub === 'test') return test(json);+ if (sub === 'cron') return cron(engine, args.slice(1), json);+ if (sub === 'emit') return emit(engine, args.slice(1));+ if (sub === 'watch') return (await import('./wakeshift-watch.ts')).runWakeshiftWatch(engine, args.slice(1));console.error(`Unknown wakeshift command: ${sub}\n\n${HELP}`);setCliExitVerdict(2);}diff --git a/src/core/access/members.ts b/src/core/access/members.tsindex c9778bba91..1b7cbfc148 100644--- a/src/core/access/members.ts+++ b/src/core/access/members.ts@@ -12,7 +12,8 @@* member is refused at verification (`verifiedMember`, access_member_disabled).*/import type { BrainEngine } from '../engine.ts';-import type { SqlQuery } from '../sql-query.ts';+import { sqlQueryForEngine, type SqlQuery } from '../sql-query.ts';+import { forgetWakePrincipal } from '../wakeshift/forget.ts';import { opError, type OperationError } from '../ops/contract.ts';import type { Action } from '../agent-output.ts';import { ACCESS_ID_RE, identityFor, normalizePrincipal } from './principals.ts';@@ -209,6 +210,7 @@ export async function removeMember(engine: BrainEngine, rawId: unknown): Promiseawait tx.executeRaw('UPDATE access_members SET tombstoned_at = now(), disabled_at = COALESCE(disabled_at, now()), updated_at = now() WHERE id = $1', [preview.member.id]);await tx.executeRaw('DELETE FROM access_group_members WHERE member_id = $1', [preview.member.id]);});+ await forgetWakePrincipal(sqlQueryForEngine(engine), { member: preview.member.id });return { ...preview, member: (await getMember(engine, preview.member.id))! };}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex a9ea34cd65..dd6f2222a1 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -26,14 +26,14 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'backup': ['--accept-pending', '--as', '--background', '--brain', '--confirm-authority-reviewed', '--confirm-backup-compatible', '--confirm-quiesced', '--dir', '--explain', '--follow', '--full', '--help', '--into', '--json', '--mode', '--no-accept-pending', '--output', '--path', '--progress-interval', '--progress-json', '--purge-mirror', '--quiet', '--restore-only', '--source', '--timeout', '--timings', '--wait'],'beliefs': ['--apply', '--archived-at', '--brain', '--from-url-env', '--help', '--json', '--probe', '--purge-mirror', '--since', '--source'],'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],- 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],+ 'book-mirror': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--author', '--background', '--body', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--client', '--context-file', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-turns', '--max-usd', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-follow', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--privacy-url', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--surface', '--terms-url', '--timeout', '--timeout-ms', '--timings', '--title', '--to', '--updated-after', '--url', '--wait', '--yes'],'bootstrap': ['--abbrev-ref', '--accept-visibility-change-consequences', '--active', '--add', '--adopt', '--advertise', '--all', '--allow-unverified-remote', '--auto', '--autostash', '--batch-check', '--bearer-token-env-var', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--dry-run', '--enable', '--env', '--error-unmatch', '--exclude-standard', '--expect-remote', '--ff-only', '--file', '--force', '--gbrain-bin', '--get', '--get-all', '--git-dir', '--git-path', '--hard', '--harness', '--header', '--heads', '--help', '--home', '--host', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--issuer-url', '--jq', '--json', '--keep-checkout', '--local', '--local-env-vars', '--mcp-even-if-plugin', '--mcp-only', '--mcp-url', '--minimal', '--name', '--name-only', '--no-autostash', '--no-capture', '--no-cron', '--no-hooks', '--no-instructions', '--no-seat', '--no-tags', '--no-verify', '--oauth-client-id', '--oauth-client-secret', '--only', '--operations', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pull', '--pure', '--push-only', '--quiet', '--rebase', '--refresh-operations', '--refresh-skills', '--remove', '--repair', '--require-clean', '--resolve', '--scope', '--scopes', '--seat', '--set', '--short', '--show', '--show-toplevel', '--skill-loading', '--skills', '--skip', '--source', '--sources', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],'brainstorm': ['--admin-intent', '--brain', '--confirm-relocated-root', '--dir', '--expected-epoch', '--expected-state', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--manifest', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--path', '--probe', '--resume', '--save', '--self-transfer', '--source', '--source-id', '--stale', '--strict-budget', '--yes'],'bundled-skill': ['--asset', '--brain', '--help', '--json', '--source'],'cache': ['--brain', '--help', '--json', '--source', '--yes'],- 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],+ 'calibration': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--holder', '--http', '--id', '--include', '--include-deleted', '--json', '--key-prefix', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--regenerate', '--row', '--scopes', '--scrub-gstack', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--terms-url', '--to', '--undo-wave', '--updated-after', '--url', '--with-calibration', '--yes'],'call': ['--brain', '--help', '--json', '--source'],- 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],+ 'capture': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--depth', '--entities', '--expect-tail', '--expected-revision', '--explain', '--federated-read', '--file', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--privacy-url', '--progress-interval', '--progress-json', '--purge', '--quiet', '--recent', '--refresh-operations', '--region', '--request-id', '--row', '--scopes', '--separator', '--session', '--since', '--slug', '--slugs', '--source', '--sources', '--stale', '--stdin', '--surface', '--terms-url', '--timeout', '--timings', '--to', '--type', '--updated-after', '--url', '--wait', '--what', '--where', '--who', '--yes'],'check-backlinks': ['--accept-pending', '--as', '--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],'check-update': ['--brain', '--channel', '--exit-code', '--ff-only', '--force-retry', '--help', '--is-ancestor', '--json', '--markdown', '--migrate-only', '--no-autopilot-install', '--no-bun-floor-check', '--no-restart', '--non-interactive', '--quiet', '--refresh-cache', '--refs', '--remediation-plan', '--restart-only', '--source', '--stop-mcp', '--swap-only', '--tags', '--version', '--yes'],@@ -43,7 +43,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'code-def': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'code-refs': ['--all-sources', '--brain', '--force', '--help', '--json', '--lang', '--limit', '--no-embed', '--no-json', '--probe', '--source', '--yes'],'compile-context': ['--brain', '--budget', '--check', '--error-unmatch', '--git-path', '--help', '--include', '--include-core', '--json', '--out', '--remove-core', '--revision', '--show-toplevel', '--source', '--stdout', '--target'],- 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--as', '--background', '--brain', '--budget-ms', '--call-site', '--claims', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--gbrain-bin', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--key-stdin', '--kind', '--limit', '--markdown', '--min', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],+ 'config': ['--accept-pending', '--admin-intent', '--all', '--all-from', '--apply', '--as', '--background', '--brain', '--budget-ms', '--call-site', '--claims', '--confirm-quiesced', '--coverage-override', '--dataset', '--db-url', '--diff-filter', '--dim', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--exclude', '--expected-state', '--explain', '--file', '--fix', '--follow', '--force', '--format', '--from', '--full', '--gbrain-bin', '--hard-deadline', '--harness', '--help', '--http', '--id', '--include-hidden', '--include-withdrawals', '--input', '--items-out', '--json', '--key-stdin', '--kind', '--limit', '--markdown', '--min', '--name', '--name-only', '--no-accept-pending', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-extract', '--no-hard-deadline', '--no-hooks', '--no-llm', '--no-pull', '--no-renames', '--no-schema-pack', '--only', '--out', '--path', '--pattern', '--phase', '--privacy-url', '--probe', '--progress-interval', '--progress-json', '--provider', '--publish', '--query', '--quiet', '--raw', '--recommended', '--remediate', '--remediation-plan', '--remove', '--repo', '--revision', '--session', '--shadow', '--since', '--slot', '--source', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--suite', '--surface', '--target', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--url', '--wait', '--what-if-threshold', '--working-tree', '--yes'],'connect': ['--advertise', '--agent', '--auto', '--bearer-token-env-var', '--bind', '--brain', '--client-id', '--client-secret', '--credentials-file', '--env', '--force', '--fresh-token', '--gbrain-bin', '--grant-types', '--harness', '--header', '--help', '--http', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--mcp-only', '--mcp-url', '--name', '--no-instructions', '--oauth', '--oauth-client-id', '--oauth-client-secret', '--only', '--public-url', '--pure', '--register', '--remove', '--root', '--runtime', '--scope', '--scopes', '--show-token', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--url', '--version', '--workspace', '--yes'],'connectors': ['--accept-pending', '--all', '--as', '--background', '--brain', '--channels', '--cookie', '--deadline', '--dry-run', '--embed', '--explain', '--follow', '--force', '--full', '--help', '--install', '--json', '--kind', '--limit', '--max-requests', '--no-accept-pending', '--no-browser', '--probe', '--progress-interval', '--progress-json', '--provider', '--quiet', '--source', '--timeout', '--timings', '--token', '--try-oauth', '--wait', '--window-days', '--workers', '--yes'],'conversation-parser': ['--brain', '--help', '--json', '--source'],@@ -51,15 +51,15 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--content-root', '--db-only', '--embedding-dimensions', '--embedding-model', '--expansion-model', '--force', '--git', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-git', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--plan', '--prefer-postgres', '--provenance', '--provider', '--query', '--schema-pack', '--scopes', '--search-mode', '--skip-embed-check', '--source', '--status', '--supabase', '--surface', '--to', '--url', '--version'],'db-repair': ['--accept-pending', '--apply', '--apply-rewrites', '--as', '--background', '--brain', '--break-lock', '--db-url', '--dry-run', '--explain', '--filter', '--follow', '--force', '--force-retry', '--format', '--help', '--http', '--json', '--legacy-lock', '--locks', '--name', '--no-accept-pending', '--path', '--prefer-postgres', '--probe', '--progress-interval', '--progress-json', '--quiet', '--remediate', '--restart', '--skip-verify', '--source', '--statement-timeout', '--supabase', '--timeout', '--timings', '--undo-last-rewrite', '--url', '--version', '--wait', '--yes'],'decide': ['--accept-all', '--all', '--all-from', '--apply', '--brain', '--call-site', '--claims', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--expect', '--from', '--help', '--include-withdrawals', '--input', '--items-out', '--json', '--kind', '--limit', '--max-cost', '--max-usd', '--min', '--non-interactive', '--out', '--provenance', '--provider', '--query', '--rate', '--reason', '--reason-family', '--recommended', '--remove', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--trust', '--undo', '--uri-prefix', '--version', '--what-if-threshold', '--yes'],- 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--to', '--updated-after', '--url', '--yes'],- 'doctor': ['--abandon', '--abbrev-ref', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],+ 'diag': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--budget-ms', '--client', '--count', '--cursor', '--date', '--dated-since', '--days', '--detach', '--entities', '--expect', '--expected-revision', '--federated-read', '--follow', '--format', '--from-index', '--full', '--fuzzy', '--group-by', '--held', '--help', '--http', '--id', '--include', '--include-ambiguous', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--no-pull', '--no-walk', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--purge', '--query', '--recent', '--refresh-operations', '--replace', '--restart-only', '--reverse', '--row', '--scopes', '--session', '--side', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--state', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],+ 'doctor': ['--abandon', '--abbrev-ref', '--accept-all', '--accept-capabilities', '--accept-pending', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt', '--adopt-columns', '--adopt-permissions', '--advertise', '--after', '--aggressive', '--aliases', '--all', '--all-drifted', '--all-from', '--allow-old-serve', '--allow-outside-source-root', '--allow-shell-jobs', '--allow-unverified-remote', '--allowed-operations', '--applied', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--auto-fix', '--autostash', '--background', '--batch', '--batch-check', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--cached', '--cacheinfo', '--call-site', '--catch-up', '--channel', '--check', '--cherry-mark', '--claims', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--concurrency', '--confidence', '--confirm', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--content-root', '--continue', '--conversation', '--count', '--credentials-file', '--cursor', '--cwd', '--dataset', '--day', '--db-url', '--deadline', '--delegated-namespace', '--delegated-slug-prefixes', '--delete-brain', '--dest', '--detach', '--detail', '--diff-filter', '--dim', '--dimensions', '--dir', '--disable', '--drain', '--drain-timeout', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--enable', '--enable-dcr', '--end-of-options', '--entity', '--env', '--error-unmatch', '--exclude', '--exclude-standard', '--exit-code', '--expand', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--federated', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-remove', '--force-retry', '--force-schema', '--force-with-lease', '--format', '--fresh', '--fresh-token', '--from', '--from-meetings', '--from-pages', '--full', '--full-tree', '--fuzzy', '--gbrain-bin', '--generation', '--get', '--get-all', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--grammar', '--group', '--group-by', '--hard', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--holds', '--home', '--http', '--id', '--if-version', '--ignore-env-override', '--ignore-missing', '--images', '--include-ambiguous', '--include-cross-entity', '--include-deleted', '--include-failures', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--include-withdrawals', '--index-audit', '--index-info', '--infer-dates', '--init', '--input', '--install', '--instructions', '--instructions-only', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--items-out', '--job-isolation', '--jq', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--local', '--local-env-vars', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-count', '--max-facts', '--max-jobs', '--max-requests', '--max-rss', '--max-runtime', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--merge-base', '--migrate-legacy', '--migrate-only', '--migration', '--min', '--min-n', '--mode', '--model', '--multimodal', '--name', '--name-only', '--name-status', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-autostash', '--no-capture', '--no-commit-id', '--no-confirm', '--no-cron', '--no-delegate', '--no-edit', '--no-embed', '--no-embed-cache', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-gpg-sign', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-merges', '--no-migrate', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-seat', '--no-tags', '--no-verify', '--no-walk', '--no-write-fetch-head', '--non-interactive', '--not', '--now', '--of', '--older-than', '--once', '--only', '--operation', '--operations', '--others', '--out', '--output', '--oversized', '--overwrite', '--page', '--parallel', '--params', '--parents', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--port', '--prefer', '--prefer-postgres', '--prefix', '--preset', '--preview', '--principal', '--privacy-url', '--private-pages', '--probe', '--probe-pglite', '--profile', '--progress-interval', '--progress-json', '--project', '--provenance', '--provider', '--providers', '--prune-orphans', '--public-url', '--pull', '--pure', '--purge', '--push', '--push-only', '--qm', '--query', '--question', '--queue', '--quiet', '--rate', '--reader-mode', '--readers', '--reauth', '--rebase', '--rebuild', '--recommended', '--redact-paths', '--reference-date', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--relative', '--relower', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--repair', '--repair-unknown-markers', '--replace', '--repo', '--request', '--request-id', '--require-clean', '--reranker', '--reset', '--reset-checkpoint', '--reset-default', '--resolve', '--restart-only', '--restore-only', '--resume', '--retire', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--reverse', '--review-lower', '--revision', '--right-only', '--rollback-to-source', '--root', '--rules', '--run', '--runtime', '--sample', '--save', '--scope', '--scopes', '--search-mode', '--seat', '--section', '--segmented', '--select', '--self-transfer', '--semantic', '--session', '--session-id', '--set', '--set-upstream-to', '--shadow', '--shared-skills', '--short', '--show-current', '--show-object-format', '--show-prefix', '--show-token', '--show-toplevel', '--side', '--since', '--since-last-run', '--skill-loading', '--skills-dir', '--skills-index-only', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slugs', '--source', '--source-id', '--source-ids', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--statement-timeout', '--status', '--stdin', '--stop-mcp', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--swap-only', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--terms-url', '--threshold', '--tier', '--timeout', '--timings', '--to', '--token', '--token-ttl', '--top-k', '--topo-order', '--trust', '--type', '--types', '--unindexed', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--unsettle', '--unshallow', '--untracked-files', '--url', '--url-env', '--user', '--vacuum', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--warn-only', '--watch', '--what-if-threshold', '--window', '--workers', '--working-tree', '--workspace', '--write-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--phase', '--probe', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],- 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--updated-after', '--url', '--yes'],+ 'edge-proposals': ['--access', '--add', '--all', '--all-applied', '--all-held', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--as', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--client', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--gbrain-bin', '--group', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-null-signature', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-facts', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--no-embed', '--no-embedding', '--no-hooks', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--scopes', '--section', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--surface', '--timeout', '--timings', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--as', '--background', '--brain', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--timings', '--to', '--wait', '--yes'],'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--http', '--json', '--legacy-lock', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],- 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--of', '--only', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],+ 'enrich': ['--accept-pending', '--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--audit', '--background', '--body', '--bound-slug-prefixes', '--brain', '--client', '--concurrency', '--confirm-destructive', '--conflicts', '--cursor', '--date', '--dated-since', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--expect', '--explain', '--federated-read', '--follow', '--force', '--from-index', '--full', '--fuzzy', '--group', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--input', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--no-confirm', '--non-interactive', '--of', '--only', '--order', '--output', '--page', '--params', '--path', '--phase', '--prefer', '--preview', '--privacy-url', '--progress-interval', '--progress-json', '--purge', '--quiet', '--rate', '--recent', '--reenrich-after', '--refresh-operations', '--resume', '--row', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--surface', '--terms-url', '--thin', '--thin-threshold', '--timeout', '--timings', '--to', '--trust', '--types', '--updated-after', '--url', '--wait', '--workers', '--yes'],'errors': ['--brain', '--changed', '--help', '--json', '--source'],'eval': ['--ab-relational', '--accept-pending', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--as', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--call-plan', '--call-plan-gate', '--candidate', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--decide', '--decide-calibration', '--decide-dataset', '--decide-force-on', '--decide-provider', '--decide-threshold', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--draws', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--error-unmatch', '--eval-pool-depth', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fact-extractor', '--fact-keys', '--fact-keys-max-usd', '--fact-keys-model', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-accept-pending', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--op-expand', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--porcelain', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--reader-max-tokens', '--reader-mode', '--receipt-dir', '--record', '--refresh-cache', '--request-id', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--status', '--strategy', '--suite', '--suites', '--supabase', '--synopsis-cache', '--synopsis-concurrency', '--synopsis-max-usd', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--time-scope', '--time-scope-pool', '--timeout', '--timings', '--tool', '--top-k', '--top-regressions', '--until', '--untracked-files', '--update-baseline', '--usefulness-min', '--vectors', '--verbose', '--verify', '--via-operation', '--wait', '--with-code-intel', '--yes'],'export': ['--accept-pending', '--access-policy', '--as', '--background', '--body', '--brain', '--dir', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--timings', '--type', '--wait'],@@ -81,30 +81,30 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'init': ['--accept-all', '--accept-capabilities', '--access', '--access-policy', '--acknowledge-managed', '--adopt', '--advertise', '--after', '--aliases', '--all', '--all-drifted', '--allow-create-db', '--allow-docker', '--allow-outside-source-root', '--applied', '--apply', '--as', '--assign-corpus', '--attest-actor', '--attest-ops', '--audit', '--auto', '--auto-additive', '--background', '--batch', '--bound-slug-prefixes', '--brain', '--branch', '--break-lock', '--budget-ms', '--budget-policy', '--budget-tokens', '--budget-usd', '--by-mention', '--catch-up', '--channel', '--chat-model', '--check', '--class', '--clear', '--clear-never-installed', '--cli-socket', '--client', '--close', '--code', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--content-root', '--continue', '--conversation', '--cursor', '--db-only', '--deadline', '--dest', '--detach', '--detail', '--dim', '--disable', '--drain', '--embedding-dimensions', '--embedding-model', '--enable', '--entity', '--exclude', '--expand', '--expansion-model', '--expect', '--expect-local', '--expect-remote', '--expect-upstream', '--explain', '--facts', '--fast', '--federated', '--file', '--fix', '--force', '--force-retry', '--format', '--fresh-token', '--from', '--from-meetings', '--full', '--git', '--grammar', '--grant-types', '--group-by', '--harness', '--held', '--help', '--hold-state', '--holds', '--http', '--id', '--images', '--include-ambiguous', '--include-cross-entity', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--infer-dates', '--input', '--install', '--instructions-only', '--issuer-url', '--job-isolation', '--json', '--keep', '--keep-checkout', '--key', '--kind', '--lanes', '--legacy-lock', '--limit', '--link', '--list', '--local-postgres', '--markdown', '--max-cost-usd', '--max-facts', '--max-requests', '--max-rss', '--max-usd', '--may-act-for', '--mcp-only', '--mcp-url', '--member', '--migrate-only', '--migration', '--min-n', '--mode', '--model', '--no-autopilot-install', '--no-autostash', '--no-delegate', '--no-embed', '--no-embedding', '--no-expand', '--no-extract', '--no-federated', '--no-filters', '--no-git', '--no-hooks', '--no-instructions', '--no-lanes', '--no-llm', '--no-probe', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--of', '--older-than', '--once', '--only', '--operation', '--output', '--oversized', '--page', '--params', '--parked-code', '--parked-pushes', '--pat-file', '--path', '--pending', '--pglite', '--phase', '--plan', '--prefer', '--prefer-postgres', '--prefix', '--preview', '--private-pages', '--probe', '--profile', '--provenance', '--providers', '--pull', '--purge', '--push-only', '--qm', '--query', '--question', '--quiet', '--readers', '--rebase', '--rebuild', '--redact-paths', '--reference-date', '--remediate', '--remove', '--repair', '--repair-unknown-markers', '--repo', '--request', '--request-id', '--require-clean', '--reset', '--resolve', '--restart-only', '--resume', '--retire', '--retry-failed', '--retry-parked', '--runtime', '--save', '--schema-pack', '--scope', '--scopes', '--search-mode', '--section', '--segmented', '--self-transfer', '--semantic', '--session', '--session-id', '--shared-skills', '--show-toplevel', '--side', '--since', '--since-last-run', '--skip', '--skip-embed-check', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--stop-mcp', '--strategy', '--supabase', '--surface', '--swap-only', '--tier', '--timeout', '--to', '--token', '--touchpoint', '--type', '--types', '--unsettle', '--url', '--url-env', '--user', '--vacuum', '--verbose', '--version', '--wait', '--warn-only', '--watch', '--working-tree', '--workspace', '--yes'],'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],'integrity': ['--accept-pending', '--as', '--auto', '--backend', '--background', '--body', '--brain', '--check', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--timeout', '--timings', '--type', '--wait'],- 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],+ 'jobs': ['--abbrev-ref', '--access', '--access-policy', '--account', '--acknowledge-managed', '--add', '--admin-intent', '--adopt-slug-path', '--aliases', '--all', '--all-sources', '--allow-empty', '--allow-shell-jobs', '--allowed-operations', '--apply', '--as', '--asof', '--assign-corpus', '--attest-actor', '--attest-ops', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--body', '--bound-slug-prefixes', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--channel', '--check', '--clear', '--cli-path', '--client', '--close', '--cluster-errors', '--code', '--concurrency', '--confidence', '--confirm-destructive', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--date', '--dated-since', '--days', '--delay', '--detach', '--detail', '--diff-filter', '--dir', '--drain', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--entities', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-state', '--explain', '--facts', '--federated-read', '--ff-only', '--file', '--filters', '--finished-since', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-index', '--from-meetings', '--full', '--full-history', '--fuzzy', '--git', '--grammar', '--grammar-diagnostics', '--group', '--group-by', '--hard-deadline', '--health-interval', '--held', '--help', '--hold-state', '--http', '--id', '--idempotency-key', '--ids', '--images', '--include', '--include-ambiguous', '--include-deleted', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--input', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--keep', '--kind', '--lanes', '--legacy-lock', '--limit', '--list', '--local', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--may-act-for', '--mcp-only', '--member', '--migration', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-confirm', '--no-delegate', '--no-embed', '--no-embedding', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-restart', '--no-schema-pack', '--no-verify', '--no-worker', '--non-interactive', '--now', '--of', '--older-than', '--once', '--only', '--order', '--others', '--output', '--override-disabled', '--oversized', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--parked-code', '--pat-file', '--path', '--pause', '--pglite', '--phase', '--pid-file', '--plan', '--port', '--prefer', '--preview', '--priority', '--privacy-url', '--probe', '--prune-orphans', '--pull', '--purge', '--qm', '--question', '--queue', '--queue-only', '--quiet', '--rate', '--reason', '--reason-scan-limit', '--rebuild', '--recent', '--record', '--redact-paths', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--refresh-operations', '--remediate', '--repo', '--request-id', '--reset-checkpoint', '--restart-only', '--resume', '--retry-failed', '--retry-global', '--retry-held', '--retry-parked', '--review-lower', '--row', '--save', '--scope', '--scopes', '--section', '--segment-limit', '--segmented', '--select', '--self-transfer', '--serial', '--session', '--show-toplevel', '--side', '--sigkill-rescue', '--since', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-guard', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--state', '--statement-timeout', '--status', '--stop-mcp', '--strategy', '--suites', '--surface', '--swap-only', '--target', '--terms-url', '--thin', '--thin-threshold', '--tier', '--timeout', '--timeout-ms', '--to', '--token', '--token-env', '--trust', '--type', '--types', '--uninstall', '--updated-after', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],'lint': ['--abbrev-ref', '--accept-pending', '--add', '--admin-intent', '--adopt-slug-path', '--as', '--audit', '--autostash', '--background', '--brain', '--branch', '--cached', '--client', '--confirm-relocated-root', '--conflicts', '--dry-run', '--enable', '--exclude', '--expect-remote', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--ff-only', '--file', '--fix', '--follow', '--force', '--get', '--get-all', '--git-dir', '--git-path', '--grammar-diagnostics', '--hard', '--help', '--id', '--infer-entity', '--is-inside-work-tree', '--json', '--keep', '--keep-checkout', '--local', '--local-env-vars', '--manifest', '--max-cost-usd', '--no-accept-pending', '--no-autostash', '--no-cron', '--no-pull', '--no-tags', '--no-verify', '--older-than', '--only', '--pat-file', '--path', '--prefer', '--preview', '--probe', '--progress-interval', '--progress-json', '--provenance', '--pull', '--purge', '--push-only', '--quiet', '--rebase', '--require-clean', '--resolve', '--scopes', '--self-transfer', '--short', '--show-toplevel', '--slug', '--slugs', '--source', '--source-id', '--timeout', '--timings', '--unset-all', '--wait', '--yes'],'loops': ['--all', '--as-of', '--brain', '--dry-run', '--fail-fast', '--help', '--json', '--note', '--source', '--stale-ok', '--status', '--tools-json', '--top', '--type'],'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--max-usd', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],- 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],+ 'maintain': ['--account', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-outside-source-root', '--apply', '--assign-corpus', '--audit', '--background', '--brain', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--class', '--clear', '--client', '--concurrency', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cwd', '--detach', '--detail', '--dim', '--dir', '--drain', '--dry-run', '--enable', '--entity', '--expect', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--format', '--from-meetings', '--full', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--json', '--keep-checkout', '--kind', '--lang', '--left-right', '--limit', '--link-source', '--link-type', '--list', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--multimodal', '--name', '--name-only', '--ner', '--no-autopilot-install', '--no-capture', '--no-delegate', '--no-embed', '--no-instructions', '--no-pull', '--no-renames', '--once', '--only', '--operations', '--output', '--oversized', '--pack', '--page', '--parallel', '--params', '--path', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--preview', '--privacy-url', '--probe', '--probe-pglite', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--reader-mode', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--request-id', '--reset', '--reset-default', '--restart-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--safe', '--scope', '--scopes', '--session', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--staged', '--stale', '--stat', '--state', '--status', '--supabase', '--surface', '--symbol-kind', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--to', '--token', '--top-k', '--type', '--unindexed', '--url-env', '--verbose', '--verify', '--version', '--window', '--workers', '--workspace', '--yes'],'mcp': ['--admin-token-file', '--advertise', '--agent', '--arg', '--bearer-token-env-var', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--enable-dcr', '--federated-read', '--flow', '--force', '--funnel', '--harness', '--header', '--help', '--if-version', '--install', '--issuer-url', '--json', '--limit', '--mcp-only', '--mcp-url', '--no-install', '--no-service', '--no-tailscale', '--oauth-client-id', '--oauth-client-secret', '--oauth-request', '--port', '--profile', '--queue', '--redirect-uri', '--remove', '--resume', '--root', '--scope', '--scopes', '--skills', '--source', '--status', '--surface', '--timeout-ms', '--token', '--token-endpoint-auth-method', '--token-ttl', '--url', '--yes'],'migrate': ['--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--drain-timeout', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--follow', '--force', '--force-retry', '--harness', '--held', '--help', '--ignore-env-override', '--images', '--include-null-signature', '--json', '--locks', '--manifest', '--max-cost', '--max-cost-usd', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-migrate', '--non-interactive', '--only', '--oversized', '--pace', '--pace-max-concurrency', '--path', '--pglite', '--plan', '--priority', '--probe', '--progress-interval', '--progress-json', '--quiet', '--replace', '--reranker', '--resume', '--retarget', '--rollback-to-source', '--scope', '--skip-verify', '--slugs', '--source', '--stale', '--statement-timeout', '--status', '--timeout', '--timings', '--to', '--trigger-bypass', '--trust', '--url', '--url-env', '--wait', '--yes'],'models': ['--batch', '--brain', '--concurrent', '--cycles', '--dim', '--dimensions', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--limit', '--max-tokens', '--max-usd', '--output', '--receipt-dir', '--skip', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--source', '--status', '--task', '--to', '--yes'],'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--status', '--target-high', '--target-low', '--target-medium'],'notices': ['--brain', '--help', '--json', '--source'],- 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--to', '--updated-after', '--url', '--yes'],+ 'onboard': ['--access', '--add', '--all', '--allowed-operations', '--apply', '--as', '--asof', '--auto', '--body', '--bound-slug-prefixes', '--brain', '--check', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--from-index', '--from-pages', '--full', '--fuzzy', '--group-by', '--help', '--history', '--http', '--id', '--images', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--privacy-url', '--probe', '--purge', '--recent', '--refresh-operations', '--remediate', '--remediation-plan', '--resume', '--row', '--save', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--target-score', '--terms-url', '--to', '--updated-after', '--url', '--yes'],'orphans': ['--accept-pending', '--all', '--as', '--background', '--brain', '--count', '--cursor', '--explain', '--follow', '--force', '--help', '--include-pseudo', '--json', '--limit', '--mode', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'pages': ['--brain', '--dry-run', '--force', '--help', '--json', '--limit', '--literal-pathspecs', '--name-only', '--older-than', '--quiet', '--retry-parked', '--show-toplevel', '--source', '--source-id', '--state', '--verify', '--yes'],'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--expect', '--help', '--http', '--json', '--legacy-lock', '--path', '--probe', '--source', '--vectors', '--yes'],'post-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', '--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'],'pricing': ['--brain', '--help', '--input', '--json', '--max-cost', '--max-runtime', '--output', '--rate', '--source'],'projections': ['--advertise', '--brain', '--dry-run', '--enable-dcr', '--help', '--http', '--images', '--install', '--json', '--limit', '--now', '--only', '--port', '--public-url', '--remove', '--source', '--stale', '--status', '--surface', '--user'],- 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--to', '--token', '--updated-after', '--url', '--yes'],+ 'protocol': ['--access', '--add', '--all', '--allowed-operations', '--as', '--asof', '--body', '--bound-slug-prefixes', '--brain', '--client', '--cursor', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--json', '--kind', '--limit', '--max-usd', '--model', '--multimodal', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--phase', '--prefer', '--privacy-url', '--provenance', '--purge', '--recent', '--refresh-operations', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--synthesize', '--target', '--terms-url', '--to', '--token', '--updated-after', '--url', '--yes'],'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--accept-all', '--accept-pending', '--admin-intent', '--all', '--apply', '--as', '--background', '--body', '--brain', '--break-lock', '--client', '--confirm-relocated-root', '--db-url', '--dir', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--help', '--http', '--id', '--include-flagged', '--json', '--kind', '--legacy-lock', '--limit', '--manifest', '--no-accept-pending', '--no-embed', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--remove', '--resume', '--scopes', '--self-transfer', '--since', '--source', '--source-id', '--stale', '--timeout', '--timings', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],- 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],+ 'recall': ['--accept-pending', '--access', '--add', '--all', '--all-subjects', '--allowed-operations', '--as', '--as-context', '--asof', '--background', '--body', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--continue', '--cursor', '--date', '--dated-since', '--days', '--entities', '--entity', '--explain', '--federated-read', '--follow', '--from-index', '--full', '--fuzzy', '--grep', '--group-by', '--help', '--http', '--id', '--include', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--match', '--max-usd', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--of', '--only', '--page', '--params', '--path', '--pending', '--phase', '--prefer', '--privacy-url', '--progress-interval', '--progress-json', '--purge', '--query', '--question', '--quiet', '--reason', '--reason-scan-limit', '--recent', '--refresh-operations', '--request-id', '--rollup', '--row', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--status', '--supersessions', '--surface', '--terms-url', '--timeout', '--timings', '--to', '--today', '--updated-after', '--url', '--vacuum', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--as', '--background', '--body', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--timings', '--wait'],'reindex': ['--accept-pending', '--admin-intent', '--aliases', '--all-drifted', '--apply', '--as', '--background', '--body', '--brain', '--class', '--close', '--concurrency', '--confirm-relocated-root', '--cost-estimate', '--cursor', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--expected-epoch', '--expected-state', '--explain', '--follow', '--force', '--force-rechunk', '--from', '--held', '--help', '--include-ambiguous', '--include-cross-entity', '--json', '--keep', '--limit', '--manifest', '--markdown', '--max-cost', '--max-runtime', '--max-usd', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--no-llm', '--only', '--oversized', '--path', '--plan', '--prefer', '--progress-interval', '--progress-json', '--provenance', '--quiet', '--repo', '--request', '--request-id', '--segmented', '--self-transfer', '--side', '--since', '--skip', '--slug', '--source', '--stale', '--state', '--status', '--supabase', '--timeout', '--timings', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],'reindex-code': ['--accept-pending', '--apply', '--as', '--background', '--brain', '--break-lock', '--client', '--concurrency', '--db-url', '--dry-run', '--embedding-dimensions', '--embedding-model', '--expect', '--explain', '--follow', '--force', '--help', '--http', '--id', '--json', '--legacy-lock', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--no-accept-pending', '--no-embed', '--non-interactive', '--only', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--scopes', '--source', '--status', '--timeout', '--timings', '--trust', '--wait', '--workers', '--yes'],@@ -133,16 +133,16 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'status': ['--abbrev-ref', '--acknowledge-managed', '--all', '--allow-empty', '--apply', '--brain', '--break-lock', '--cached', '--check', '--code', '--concurrency', '--confirm-destructive', '--count', '--cursor', '--deadline-ms', '--delete', '--detail', '--diff-filter', '--empty', '--enable', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--funnel', '--hard-deadline', '--help', '--hold-state', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--lanes', '--limit', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-bulk', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--others', '--parallel', '--path', '--prefer', '--preview', '--priority', '--quiet', '--redact-paths', '--repo', '--request-id', '--reset-checkpoint', '--retry-failed', '--retry-held', '--reverse', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],'storage': ['--brain', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--as', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--source-id', '--stale', '--timeout', '--timings', '--wait'],- 'sync': ['--abbrev-ref', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],+ 'sync': ['--abbrev-ref', '--accept-pending', '--access-policy', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--after', '--all', '--allow-empty', '--allow-outside-source-root', '--apply', '--apply-rewrites', '--as', '--assign-corpus', '--audit', '--auto', '--background', '--batch', '--batch-check', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--check', '--class', '--clear', '--client', '--close', '--code', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--continue', '--conversation', '--count', '--cursor', '--cwd', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--end-of-options', '--entity', '--exclude', '--exclude-standard', '--expect', '--expect-local', '--expect-upstream', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--grammar', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--hold-state', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--input', '--install', '--instructions-only', '--interval', '--is-ancestor', '--is-inside-work-tree', '--is-shallow-repository', '--json', '--keep-checkout', '--kind', '--lanes', '--lang', '--left-right', '--legacy-lock', '--limit', '--link-source', '--link-type', '--list', '--literal-pathspecs', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--may-act-for', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-instructions', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--no-walk', '--once', '--only', '--operations', '--others', '--output', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pending', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--privacy-url', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--pull', '--purge', '--push-only', '--query', '--question', '--queue', '--quiet', '--raw', '--reader-mode', '--reauth', '--rebuild', '--redact-paths', '--refresh', '--regenerate', '--relative', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restart-only', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--retry-parked', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--session', '--short', '--show-current', '--show-toplevel', '--side', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--stat', '--state', '--status', '--stdin', '--strategy', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--terms-url', '--tier', '--timeout', '--timings', '--to', '--token', '--token-env', '--top-k', '--type', '--unindexed', '--unshallow', '--url', '--url-env', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--workspace', '--yes'],'takes': ['--about', '--accept', '--applied', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--failed', '--force', '--from-pages', '--group-by', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--min-confidence', '--min-n', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--retry-failed', '--row', '--semantic', '--since', '--slug', '--sort', '--source', '--source-id', '--stale', '--state', '--status', '--supabase', '--to', '--unapplied', '--unit', '--until', '--value', '--verdict', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--images', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--request-id', '--rounds', '--save', '--since', '--source', '--source-id', '--stale', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--as', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--timings', '--wait'],'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'],+ 'wakeshift': ['--apply', '--brain', '--expect', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--name', '--non-interactive', '--privacy-url', '--probe', '--source', '--status', '--terms-url', '--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'],+ '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', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],};// Routing flags a fix naming each CLI-only command carries (A1 render-time pin,diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 431d6d43eb..270826057a 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -196,7 +196,11 @@ 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'],+ ['wake_cron_runs', 'out_of_scope', 'no_memory_text', 'name status'],+ ['wake_crons', 'out_of_scope', 'no_memory_text', 'name'],+ ['wake_forgets', 'out_of_scope', 'no_memory_text', 'wake_user state last_error'],+ ['wake_subscriptions', 'out_of_scope', 'no_memory_text', 'event target target_ref principal_kind principal_id member_id wake_user ws_subscription_id state delivered_marker last_error'],+ ['wake_terms_acceptances', 'out_of_scope', 'no_memory_text', 'principal_key terms_version'],['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/error-registry.ts b/src/core/error-registry.tsindex 999f15865e..75a2d6cdc3 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -845,10 +845,10 @@ export const CODES = {visibility_noncanonical: { class: 'caller', summary: "A file asks for visibility: private in a spelling page privacy does not read, so sync or import held it instead of storing it world-readable.", why: "Page privacy reads only the exact lowercase key and value visibility: private. A file that spells it another way (Visibility: private, visibility: Private, a block scalar, a list, a flow mapping or a merge key) would be stored as a world page while its author believes it is private (#7848); put_page, edit_page, capture, ingest_capture, brainstorm --save and sources reconcile refuse the same request as visibility_not_applied.", docs: 'docs/guides/write-refusals.md#visibility_noncanonical', suggestion: 'Write visibility: private on its own frontmatter line (lowercase key and value), then commit and sync, or import the file again.' },visibility_not_applied: { class: 'caller', reasons: ['noncanonical_value', 'not_kept'], summary: "A page write asked for visibility: private, but the page would have stayed world-readable, so nothing was written.", why: "A write that reports success while the page stays world-readable leaves the caller believing it is hidden. Page privacy reads only the exact lowercase key and value visibility: private (#7841). When the frontmatter is unreadable or ambiguous, the write is refused invalid_frontmatter instead.", docs: 'docs/guides/write-refusals.md#visibility_not_applied', suggestion: 'Read the page and its revision, write visibility: private on its own frontmatter line (lowercase key and value), then submit again with a new request_id.', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], consent: [], actor: 'agent', why: 'Read-only: shows the page as it is now, with its revision.', requires_exclusive: false } },wakeshift_key_invalid: { class: 'caller', actor: 'user', reasons: ['format', 'checksum', 'legacy', 'file_too_open', 'missing'], summary: "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.", why: "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.", docs: 'docs/guides/wakeshift.md#the-key', suggestion: '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.' },- wakeshift_needs_conversation: { class: 'caller', summary: "watch_job wakes an MCP conversation, and a local CLI run has none to wake.", docs: 'docs/guides/wakeshift.md#delivery-and-latency', suggestion: 'Run gbrain jobs wait <id> to block until the job finishes.' },+ wakeshift_needs_conversation: { class: 'caller', summary: "A watch tool (watch_job, watch_write_request, watch_cron) wakes an MCP conversation, and a local CLI run has none to wake.", docs: 'docs/guides/wakeshift.md#delivery-and-latency', suggestion: 'Run gbrain jobs wait <id> for a job, or gbrain write-request -- <request_id> for a write.' },wakeshift_not_enabled: { class: 'caller', summary: "Reporting back through Wakeshift is off on this brain (the owner has not run gbrain wakeshift enable, or the key is missing).", why: "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.", docs: 'docs/guides/wakeshift.md#turn-it-on', suggestion: 'Use wait_job (or gbrain jobs wait <id>) instead, or ask the brain owner to run gbrain wakeshift enable.' },wakeshift_refused: { class: 'caller', summary: "Wakeshift refused the request; the reason carries its error code. Nothing was watched or sent.", why: "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.", docs: 'docs/guides/wakeshift.md#troubleshooting', suggestion: 'Call wait_job to wait without Wakeshift; the brain owner can run gbrain wakeshift test to check the key and the app.' },- wakeshift_shared_brain: { class: 'host_only', actor: 'user', summary: "Reporting back refused (gbrain wakeshift enable, or watch_job after a member was added): this brain has live access members, and this release reports back only on brains that serve their owner alone.", why: "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.", docs: 'docs/guides/wakeshift.md#who-it-is-for', suggestion: 'Leave reporting back off on this brain; agents can use wait_job or gbrain jobs wait <id>.' },+ wakeshift_shared_brain: { class: 'host_only', actor: 'user', summary: "Reporting back refused (gbrain wakeshift enable, or a watch tool): this brain has live access members and its operator has not set the terms and privacy links Wakeshift requires.", why: "Wakeshift's terms (6.2, 6.6) make the operator show each person its own terms and privacy policy, which refer them to Wakeshift's Connector Terms and Privacy Policy, before the first wake. gbrain shows that step from the two links the owner sets on the brain host.", docs: 'docs/guides/wakeshift.md#shared-brains', suggestion: 'Ask the brain owner to run gbrain wakeshift enable --terms-url <https url> --privacy-url <https url>; meanwhile agents can use wait_job or get_write_request.' },wakeshift_unavailable: { class: 'unavailable', retryable: true, summary: "Wakeshift could not be reached or answered with a server error or rate limit; nothing was watched.", why: "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.", docs: 'docs/guides/wakeshift.md#troubleshooting', suggestion: 'Retry in a minute, or call wait_job to wait without Wakeshift.' },withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },withdrawal_mirror_failed: { class: 'unavailable', summary: "A page's Git or embedding work is withheld because its withdrawal mirror failed before rewriting the page's file; the file may still hold the withdrawn text.", why: "A withdrawal's Git and embedding effects touch only the pages whose file its mirror recorded rewriting (GBRA-130 A-12); Git never commits a page the mirror passed without rewriting its file. Retrying the request's effects reruns the mirror for this page; once the mirror commits, the withheld work is re-armed automatically.", suggestion: 'Read the parked effects with gbrain doctor --only parked_effects, fix the cause the mirror recorded, then preview gbrain sources writer retry-effects <source> --request-id <id> --dry-run and run it without --dry-run.' },diff --git a/src/core/operation-load.ts b/src/core/operation-load.tsindex 1696485200..5cf1117ae7 100644--- a/src/core/operation-load.ts+++ b/src/core/operation-load.ts@@ -83,6 +83,7 @@ const OP_AREAS: Record<string, string> = {// jobs (Minions + agent lane)submit_job: 'jobs', get_job: 'jobs', wait_job: 'jobs', list_jobs: 'jobs', cancel_job: 'jobs',retry_job: 'jobs', get_job_progress: 'jobs', pause_job: 'jobs', watch_job: 'jobs', list_watches: 'jobs', unwatch: 'jobs',+ watch_write_request: 'jobs', watch_cron: 'jobs', accept_wakeshift_terms: 'jobs',resume_job: 'jobs', replay_job: 'jobs', send_job_message: 'jobs',submit_agent: 'jobs', get_agent_job: 'jobs',// takes + thinkdiff --git a/src/core/operation-loaders.generated.ts b/src/core/operation-loaders.generated.tsindex 299e92d5b3..6dccbace0b 100644--- a/src/core/operation-loaders.generated.ts+++ b/src/core/operation-loaders.generated.ts@@ -165,6 +165,9 @@ export const OPERATION_LOADERS: Record<string, readonly [() => Promise<Record<st"get_agent_job": [load_jobs, "jobsOperations"],"get_job_stats": [load_jobs, "jobsOperations"],"watch_job": [load_wakeshift, "wakeshiftOperations"],+ "watch_write_request": [load_wakeshift, "wakeshiftOperations"],+ "watch_cron": [load_wakeshift, "wakeshiftOperations"],+ "accept_wakeshift_terms": [load_wakeshift, "wakeshiftOperations"],"list_watches": [load_wakeshift, "wakeshiftOperations"],"unwatch": [load_wakeshift, "wakeshiftOperations"],"find_orphans": [load_orphans, "orphansOperations"],diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.tsindex a46e398bd1..6a8eda5ec4 100644--- a/src/core/operation-manifest.generated.ts+++ b/src/core/operation-manifest.generated.ts@@ -4220,7 +4220,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["idempotent": true,"writeInference": "non_content","outputRedaction": {- "exempt": "watch bookkeeping: job ids, states and times, never retrieved brain text"+ "exempt": "watch bookkeeping: job, request and cron 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": {@@ -4250,16 +4250,111 @@ export const OPERATION_MANIFEST: OperationMeta[] = [},"area": "jobs"},+ {+ "name": "watch_write_request",+ "mutating": true,+ "idempotent": true,+ "writeInference": "non_content",+ "outputRedaction": {+ "exempt": "watch bookkeeping: job, request and cron ids, states and times, never retrieved brain text"+ },+ "description": "This tool notifies you: it has gbrain wake this conversation through Wakeshift when your write request settles (committed, failed, conflict or cancelled), so you can stop polling get_write_request after write_pending. The wake names the request and says to call get_write_request; it carries no slug or page text. You can watch only your own receipts. If no wake arrives, call get_write_request.",+ "params": {+ "request_id": {+ "type": "string",+ "required": true,+ "description": "The request_id you sent with the write, or the one its receipt shows."+ },+ "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": "write",+ "agentCallable": true,+ "publishGateKey": "mcp.publish_wakeshift",+ "cliHints": {+ "hidden": true+ },+ "area": "jobs"+ },+ {+ "name": "watch_cron",+ "mutating": true,+ "idempotent": true,+ "writeInference": "non_content",+ "outputRedaction": {+ "exempt": "watch bookkeeping: job, request and cron ids, states and times, never retrieved brain text"+ },+ "description": "This tool notifies you: it has gbrain wake this conversation through Wakeshift the next time the named cron reports its run (ok or failed) with gbrain wakeshift emit. One wake per watch; call it again for the run after. The wake names the cron and the status; read the output where the cron writes it. Only crons the brain owner registered with gbrain wakeshift cron add can be watched.",+ "params": {+ "name": {+ "type": "string",+ "required": true,+ "description": "The cron name the owner registered (letters, digits, dot, underscore and dash)."+ },+ "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",+ "publishGateKey": "mcp.publish_wakeshift",+ "cliHints": {+ "hidden": true+ },+ "area": "jobs"+ },+ {+ "name": "accept_wakeshift_terms",+ "mutating": true,+ "idempotent": true,+ "writeInference": "non_content",+ "outputRedaction": {+ "exempt": "watch bookkeeping: job, request and cron ids, states and times, never retrieved brain text"+ },+ "description": "Record that the user agreed to the agreement step a watch tool returned (agreement_required): this brain operator's terms and privacy policy and Wakeshift's Connector Terms and Privacy Policy. Call it only after showing the user that step and getting their agreement, then call the watch tool again.",+ "params": {+ "terms_version": {+ "type": "string",+ "required": true,+ "description": "The terms_version from the agreement step."+ }+ },+ "scope": "write",+ "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"+ "exempt": "watch bookkeeping: job, request and cron 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.",+ "description": "List what this connection is watching through Wakeshift (jobs, write requests and crons: open watches, plus ones that ended in the last day) with their state: open, delivered, dead or ended.","params": {},- "scope": "admin",+ "scope": "write","agentCallable": true,"publishGateKey": "mcp.publish_wakeshift","cliHints": {@@ -4273,17 +4368,28 @@ export const OPERATION_MANIFEST: OperationMeta[] = ["idempotent": true,"writeInference": "non_content","outputRedaction": {- "exempt": "watch bookkeeping: job ids, states and times, never retrieved brain text"+ "exempt": "watch bookkeeping: job, request and cron 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).",+ "description": "Stop watching: ends this connection's open Wakeshift watches on one job, write request or cron (or one watch by its id), 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."+ },+ "request_id": {+ "type": "string",+ "description": "Request id you passed to watch_write_request."+ },+ "cron": {+ "type": "string",+ "description": "Cron name you passed to watch_cron."+ },+ "watch": {+ "type": "number",+ "description": "A watch id from list_watches."}},- "scope": "admin",+ "scope": "write","agentCallable": true,"publishGateKey": "mcp.publish_wakeshift","cliHints": {diff --git a/src/core/operations.ts b/src/core/operations.tsindex a542507ca0..f3ba5bff4c 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -185,7 +185,7 @@ export const operations: Operation[] = [...filesOperations,// Jobs (Minions: submit_job, get_job, list_jobs, cancel_job, retry_job,// get_job_progress, pause_job, resume_job, replay_job, send_job_message)- // + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts; Wakeshift watches (watch_job, list_watches, unwatch) — ops/wakeshift.ts+ // + v0.38 Slice 3 agent lane (submit_agent, get_agent_job) — ops/jobs.ts; Wakeshift watches (watch_job, watch_write_request, watch_cron, list_watches, unwatch, accept_wakeshift_terms) — ops/wakeshift.ts...jobsOperations, ...wakeshiftOperations,// Orphans (find_orphans) — ops/orphans.ts; rank_entities — ops/graph-rank.ts...orphansOperations, ...graphRankOperations,diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 2dbf62fd68..8cbaa46b2b 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -12,6 +12,8 @@ import type { LocalGrant } from '../persistence/identity.ts';import type { WriteHealthFacts } from '../persistence/health.ts';const RECEIPT_NAMES = ['get_write_request', 'list_write_requests', 'cancel_write_request'] as const;+/** The receipt read path, shared with watch_write_request (ops/wakeshift.ts) so a watch sees exactly what get_write_request sees. */+export { receiptAccess, visible as receiptVisible, missing as receiptNotFound, callerSource as receiptCallerSource };type ReceiptOperation = typeof RECEIPT_NAMES[number];const denied = () => opError('permission_denied', 'This writer grant does not include the requested receipt operation.','Explicitly regrant the required receipt operation. Existing operation snapshots do not expand during upgrades.');diff --git a/src/core/ops/wakeshift.ts b/src/core/ops/wakeshift.tsindex b406171f75..f64fb746bf 100644--- a/src/core/ops/wakeshift.ts+++ b/src/core/ops/wakeshift.ts@@ -1,26 +1,34 @@/**- * Report-back watches over Wakeshift (plan D6, D7): `watch_job`,+ * Report-back watches over Wakeshift (plan D2, D5, D6, D7): `watch_job`,+ * `watch_write_request`, `watch_cron`, `accept_wakeshift_terms`,* `list_watches`, `unwatch`. Listed only while the owner has run* `gbrain wakeshift enable` and a usable key is on the host (publish gate* `mcp.publish_wakeshift`, file plane plus key presence; no DB plane, so no- * remote caller can flip it). `watch_job` runs the get_job owner fence first,- * so a foreign id reads exactly like a missing one and nothing is sent. A- * watch belongs to the principal that made it; list and unwatch touch only- * that principal's rows. What leaves the machine: docs/guides/wakeshift.md.- * Never import from '../operations.ts' here (cycle).+ * remote caller can flip it). Each watch runs its target's own read check+ * first: the get_job owner fence, the get_write_request receipt path, or a+ * registered cron name under admin scope, so a foreign id reads exactly like+ * a missing one and nothing is sent. On a brain with live access members a+ * principal's first watch returns the agreement step (terms.ts) until it+ * calls accept_wakeshift_terms. A watch belongs to the principal that made it;+ * list and unwatch touch only that principal's rows. What leaves the machine:+ * docs/guides/wakeshift.md. Never import from '../operations.ts' here (cycle).*/import { opError, type Operation, type OperationContext, type OperationError } from './contract.ts';import { readFix } from './op-fix.ts';import { agentOwnerFence, assertJobOwned, jobNotFound } from './jobs.ts';+import { receiptAccess, receiptCallerSource, receiptNotFound, receiptVisible } from './persistence.ts';import { memberIdentityFor } from '../access/caller.ts';+import { parseWriteRequestId } from '../persistence/preconditions.ts';import { WakeshiftError, type WakeshiftCall } from '../wakeshift/client.ts';-import { wakeshiftBrainKey, wakeshiftRuntime, wakeshiftSecret, wakeshiftUserId } from '../wakeshift/config.ts';-import { JOB_FINISHED } from '../wakeshift/events.ts';+import { wakeshiftBrainKey, wakeshiftRuntime, wakeshiftSecret, wakeshiftUserId, type WakeshiftRuntime } from '../wakeshift/config.ts';+import { CRON_FINISHED, JOB_FINISHED, WRITE_SETTLED, cronName } from '../wakeshift/events.ts';import { drainWakes, endAtWakeshift, liveAccessMembers } from '../wakeshift/drain.ts';+import { agreementStep, operatorTerms, recordAcceptance, termsAccepted, wakePrincipalKey, type WakePrincipalRef } from '../wakeshift/terms.ts';const WATCH_TTL = '7d';const TERMINAL = new Set(['completed', 'failed', 'dead', 'cancelled']);-const REDACTION = { exempt: 'watch bookkeeping: job ids, states and times, never retrieved brain text' } as const;+const REDACTION = { exempt: 'watch bookkeeping: job, request and cron ids, states and times, never retrieved brain text' } as const;+type Fix = ReturnType<typeof readFix>;/** The three arguments Wakeshift asks a subscribing tool to take (its HTTP API, "The caller"). */const CALLER_PARAMS = {@@ -29,14 +37,28 @@ const CALLER_PARAMS = {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' },} as const;-function waitFix(id: number) {+function waitFix(id: number): Fix {return readFix('Waits for the job without Wakeshift (at most 55 s a call; call again while terminal is false).',{ argv: ['gbrain', 'jobs', 'wait', String(id)], mcp: { tool: 'wait_job', arguments: { id } } });}+function receiptFix(requestId: string): Fix {+ return readFix('Reads the write receipt without Wakeshift; read again at retry_after_ms until the state is final.',+ { argv: ['gbrain', 'write-request', '--', requestId], mcp: { tool: 'get_write_request', arguments: { request_id: requestId } } });+}+function notEnabled(): OperationError {return opError('wakeshift_not_enabled', 'Reporting back through Wakeshift is off on this brain.',- 'Use wait_job instead, or ask the brain owner to run gbrain wakeshift enable on the brain host.');+ 'Use wait_job or get_write_request instead, or ask the brain owner to run gbrain wakeshift enable on the brain host.');+}++function needsConversation(tool: string, suggestion: string, fix?: Fix): OperationError {+ return opError('wakeshift_needs_conversation', `${tool} wakes an MCP conversation; a CLI run has none to wake.`, suggestion, fix ? { fix } : {});+}++function termsUnset(): OperationError {+ return opError('wakeshift_shared_brain', 'This brain has access members and its operator has not set the terms and privacy links Wakeshift requires, so nothing was watched.',+ 'Ask the brain owner to run gbrain wakeshift enable --terms-url <https url> --privacy-url <https url> on the brain host; meanwhile use wait_job or get_write_request.');}export interface WatchPrincipal { kind: 'oauth_client' | 'legacy_token' | 'local_stdio'; id: string; member: string | null }@@ -51,30 +73,106 @@ export async function watchPrincipal(ctx: OperationContext): Promise<WatchPrincireturn { ...base, member: identity.find(i => i.startsWith('member:'))?.slice('member:'.length) ?? null };}-const principalKey = (p: WatchPrincipal) => (p.member ? `member:${p.member}` : `${p.kind}:${p.id}`);+const principalRef = (p: WatchPrincipal): WakePrincipalRef => ({ principal_kind: p.kind, principal_id: p.id, member_id: p.member });function optString(v: unknown, max: number): string | undefined {return typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined;}-function wakeshiftFailure(e: WakeshiftError, id: number): OperationError {- const fix = waitFix(id);+function wakeshiftFailure(e: WakeshiftError, tool: string, fallback: string, fix: Fix): OperationError {if (e.code === 'other_client') {return opError('wakeshift_refused', 'Wakeshift refused the session_key: it belongs to a conversation in another program.',- 'Call watch_job again without session_key.', { reason: e.code, fix });+ `Call ${tool} again without session_key.`, { reason: e.code, fix });}if (e.status === 0 || e.status === 429 || e.status >= 500) {return opError('wakeshift_unavailable', `Wakeshift could not take the watch (${e.code}); nothing was watched.`,- `Retry watch_job in a minute, or call wait_job ${id} to wait without it.`, { reason: e.code, fix });+ `Retry ${tool} in a minute, or ${fallback} to wait without it.`, { reason: e.code, fix });}return opError('wakeshift_refused', `Wakeshift refused the watch (${e.code}): ${e.message}`,- `Call wait_job ${id} to wait without Wakeshift; the brain owner can check the setup with gbrain wakeshift test.`, { reason: e.code, fix });+ `${fallback[0]!.toUpperCase()}${fallback.slice(1)} to wait without Wakeshift; the brain owner can check the setup with gbrain wakeshift test.`, { reason: e.code, fix });}-interface WatchRow { id: number; event: string; target: string; state: string; attempts: number; last_error: string | null; created_at: Date | string; expires_at: Date | string }+/**+ * The agreement step this principal still owes on a brain with live access members (null when none is owed); refuses+ * when the operator never set the two links.+ */+async function termsStep(ctx: OperationContext, runtime: WakeshiftRuntime, principal: WatchPrincipal, tool: string): Promise<Record<string, unknown> | null> {+ if (await liveAccessMembers(ctx.engine) === 0) return null;+ const terms = operatorTerms(runtime.file);+ if (!terms) throw termsUnset();+ return await termsAccepted(ctx.engine, principalRef(principal), terms) ? null : agreementStep(terms, tool);+}-function publicWatch(r: WatchRow) {- return { watch: Number(r.id), event: r.event, job: Number(r.target), state: r.state, attempts: r.attempts, last_error: r.last_error, created_at: r.created_at, expires_at: r.expires_at };+interface WatchSpec {+ tool: string;+ event: string;+ target: string;+ targetRef?: string;+ args: Record<string, unknown>;+ reason: string;+ settledNow: boolean;+ fallback: string;+ fix: Fix;+}++/**+ * Subscribe this conversation at Wakeshift (once, ttl 7d), record the watch, roll the subscription back when the+ * insert fails, wake at once when the target already settled, and render Wakeshift's addition as the last block.+ */+async function openWatch(ctx: OperationContext, runtime: WakeshiftRuntime, principal: WatchPrincipal, p: Record<string, unknown>, spec: WatchSpec): Promise<{ rowId: number; recognized: boolean }> {+ const user = wakeshiftUserId(wakeshiftSecret(), wakeshiftBrainKey(ctx.config), wakePrincipalKey(principalRef(principal)));+ const caller = ctx.mcpCaller;+ const call: WakeshiftCall = {+ user, tool: spec.tool,+ ...(optString(caller?.client, 200) ? { client: optString(caller?.client, 200) } : {}),+ ...(caller?.meta && typeof caller.meta === 'object' ? { meta: caller.meta } : {}),+ ...(optString(caller?.userAgent, 400) ? { user_agent: optString(caller?.userAgent, 400) } : {}),+ ...(optString(p.session_key, 100) ? { session: optString(p.session_key, 100) } : {}),+ ...(optString(p.harness, 100) ? { harness: optString(p.harness, 100) } : {}),+ ...(optString(p.conversation_id, 200) ? { conversation: optString(p.conversation_id, 200) } : {}),+ };+ let sub;+ try {+ sub = await runtime.api.subscribe({ call, name: spec.event, arguments: spec.args, ttl: WATCH_TTL, once: true, reason: spec.reason });+ } catch (e) {+ if (e instanceof WakeshiftError) throw wakeshiftFailure(e, spec.tool, spec.fallback, spec.fix);+ throw e;+ }+ let rowId: number;+ try {+ const expires = sub.event_subscription.expires_at && !Number.isNaN(Date.parse(sub.event_subscription.expires_at))+ ? sub.event_subscription.expires_at : new Date(Date.now() + 7 * 86_400_000).toISOString();+ const [row] = await ctx.engine.executeRaw<{ id: number }>(+ `INSERT INTO wake_subscriptions (event, target, target_ref, principal_kind, principal_id, member_id, wake_user, ws_subscription_id, expires_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::timestamptz)+ ON CONFLICT (wake_user, ws_subscription_id) WHERE state = 'open'+ DO UPDATE SET expires_at = EXCLUDED.expires_at, updated_at = now()+ RETURNING id`,+ [spec.event, spec.target, spec.targetRef ?? null, principal.kind, principal.id, principal.member, user, String(sub.event_subscription.id), expires]);+ rowId = Number(row!.id);+ } catch (e) {+ if (sub.event_subscription.created !== false) {+ await runtime.api.unsubscribe({ call, name: spec.event, arguments: spec.args, reason: 'rolled_back' }).catch(() => {});+ }+ throw e;+ }+ if (spec.settledNow) await drainWakes(ctx.engine, { ids: [rowId], runtime }).catch(() => {});+ if (sub.addition && (sub.addition.text || sub.addition.meta)) ctx.emitToolTail?.({ text: sub.addition.text, meta: sub.addition.meta });+ return { rowId, recognized: sub.agent ? sub.agent.harness !== null || sub.agent.claimed !== null : true };+}++function unrecognized(tool: string) {+ return { wakeable: false, note: `Wakeshift did not recognize this agent program, so it may not be able to wake you: call ${tool} again with harness set to your program.` };+}++/** The live runtime and the watching principal, after the checks every watch shares. */+async function watchContext(ctx: OperationContext, tool: string, cliSuggestion: string, fix?: Fix): Promise<{ runtime: WakeshiftRuntime; principal: WatchPrincipal }> {+ if (ctx.remote === false) throw needsConversation(tool, cliSuggestion, fix);+ const runtime = wakeshiftRuntime();+ if (!runtime) throw notEnabled();+ const principal = await watchPrincipal(ctx);+ if (!principal) throw notEnabled();+ return { runtime, principal };}const watch_job: Operation = {@@ -100,78 +198,152 @@ const watch_job: Operation = {if (!Number.isSafeInteger(id) || id <= 0) {throw opError('invalid_params', `watch_job: id must be a positive job id (got ${JSON.stringify(p.id)}).`, 'Pass the id submit_job or list_jobs returned.');}- if (ctx.remote === false) {- throw opError('wakeshift_needs_conversation', 'watch_job wakes an MCP conversation; a CLI run has none to wake.',- `Run gbrain jobs wait ${id} to block until the job finishes.`, { fix: waitFix(id) });- }- const runtime = wakeshiftRuntime();- if (!runtime) throw notEnabled();- if (await liveAccessMembers(ctx.engine) > 0) {- throw opError('wakeshift_shared_brain', 'This brain now has live access members, so reporting back is paused; nothing was watched.',- `Call wait_job ${id} to wait for the job.`, { fix: waitFix(id) });- }+ const { runtime, principal } = await watchContext(ctx, 'watch_job', `Run gbrain jobs wait ${id} to block until the job finishes.`, waitFix(id));+ const step = await termsStep(ctx, runtime, principal, 'watch_job');+ if (step) return step;const owner = agentOwnerFence(ctx, 'watch_job');if (owner !== null) await assertJobOwned(ctx, id, owner);const [job] = await ctx.engine.executeRaw<{ status: string }>('SELECT status FROM minion_jobs WHERE id = $1', [id]);if (!job) throw jobNotFound(`Job not found: ${id}`);- const principal = await watchPrincipal(ctx);- if (!principal) throw notEnabled();if (ctx.dryRun) return { dry_run: true, action: 'watch_job', job: id };-- const user = wakeshiftUserId(wakeshiftSecret(), wakeshiftBrainKey(ctx.config), principalKey(principal));- const caller = ctx.mcpCaller;- const call: WakeshiftCall = {- user, tool: 'watch_job',- ...(optString(caller?.client, 200) ? { client: optString(caller?.client, 200) } : {}),- ...(caller?.meta && typeof caller.meta === 'object' ? { meta: caller.meta } : {}),- ...(optString(caller?.userAgent, 400) ? { user_agent: optString(caller?.userAgent, 400) } : {}),- ...(optString(p.session_key, 100) ? { session: optString(p.session_key, 100) } : {}),- ...(optString(p.harness, 100) ? { harness: optString(p.harness, 100) } : {}),- ...(optString(p.conversation_id, 200) ? { conversation: optString(p.conversation_id, 200) } : {}),- };- const args = { job: id };- let sub;- try {- sub = await runtime.api.subscribe({ call, name: JOB_FINISHED, arguments: args, ttl: WATCH_TTL, once: true, reason: `Watching gbrain job ${id}` });- } catch (e) {- if (e instanceof WakeshiftError) throw wakeshiftFailure(e, id);- throw e;- }- let rowId: number;- try {- const expires = sub.event_subscription.expires_at && !Number.isNaN(Date.parse(sub.event_subscription.expires_at))- ? sub.event_subscription.expires_at : new Date(Date.now() + 7 * 86_400_000).toISOString();- const [row] = await ctx.engine.executeRaw<{ id: number }>(- `INSERT INTO wake_subscriptions (event, target, principal_kind, principal_id, member_id, wake_user, ws_subscription_id, expires_at)- VALUES ($1, $2, $3, $4, $5, $6, $7, $8::timestamptz)- ON CONFLICT (wake_user, ws_subscription_id) WHERE state = 'open'- DO UPDATE SET expires_at = EXCLUDED.expires_at, updated_at = now()- RETURNING id`,- [JOB_FINISHED, String(id), principal.kind, principal.id, principal.member, user, String(sub.event_subscription.id), expires]);- rowId = Number(row!.id);- } catch (e) {- if (sub.event_subscription.created !== false) {- await runtime.api.unsubscribe({ call, name: JOB_FINISHED, arguments: args, reason: 'rolled_back' }).catch(() => {});- }- throw e;- }const finished = TERMINAL.has(job.status);- if (finished) await drainWakes(ctx.engine, { ids: [rowId], api: runtime.api }).catch(() => {});- if (sub.addition && (sub.addition.text || sub.addition.meta)) ctx.emitToolTail?.({ text: sub.addition.text, meta: sub.addition.meta });- const recognized = sub.agent ? sub.agent.harness !== null || sub.agent.claimed !== null : true;+ const { rowId, recognized } = await openWatch(ctx, runtime, principal, p, {+ tool: 'watch_job', event: JOB_FINISHED, target: String(id), args: { job: id }, reason: `Watching gbrain job ${id}`,+ settledNow: finished, fallback: `call wait_job ${id}`, fix: waitFix(id),+ });return {watching: true, watch: rowId, job: id, event: JOB_FINISHED, status: job.status, already_finished: finished,expires_in: WATCH_TTL,- ...(recognized ? {} : { wakeable: false, note: 'Wakeshift did not recognize this agent program, so it may not be able to wake you: call watch_job again with harness set to your program.' }),+ ...(recognized ? {} : unrecognized('watch_job')),fallback: `If no wake arrives, call wait_job ${id} (or run gbrain jobs wait ${id}).`,};},};-async function ownRows(ctx: OperationContext, extra: string, params: unknown[]): Promise<WatchRow[]> {+const watch_write_request: Operation = {+ name: 'watch_write_request',+ mutating: true,+ idempotent: true,+ writeInference: 'non_content',+ outputRedaction: REDACTION,+ description: 'This tool notifies you: it has gbrain wake this conversation through Wakeshift when your write request settles '+ + '(committed, failed, conflict or cancelled), so you can stop polling get_write_request after write_pending. The wake names the '+ + 'request and says to call get_write_request; it carries no slug or page text. You can watch only your own receipts. If no wake arrives, call get_write_request.',+ params: {+ request_id: { type: 'string', required: true, description: 'The request_id you sent with the write, or the one its receipt shows.' },+ ...CALLER_PARAMS,+ },+ scope: 'write',+ agentCallable: true,+ publishGateKey: 'mcp.publish_wakeshift',+ cliHints: { hidden: true },+ handler: async (ctx, p) => {+ const requestId = parseWriteRequestId(p.request_id);+ if (!requestId) throw opError('invalid_params', 'request_id is required.', 'Pass the request_id you sent with the write, or the one its receipt shows; list_write_requests shows recent ones.');+ const { runtime, principal } = await watchContext(ctx, 'watch_write_request', `Run gbrain write-request -- ${requestId} to read the receipt.`, receiptFix(requestId));+ const step = await termsStep(ctx, runtime, principal, 'watch_write_request');+ if (step) return step;+ const { principal: writer } = await receiptAccess(ctx, 'get_write_request');+ const { getWriteRequest } = await import('../persistence/journal.ts');+ const row = await getWriteRequest(ctx.engine, writer, requestId);+ if (!row || !await receiptVisible(ctx, row)) throw receiptNotFound(receiptCallerSource(ctx));+ if (ctx.dryRun) return { dry_run: true, action: 'watch_write_request', request_id: row.request_id };+ const settled = ['failed', 'conflict', 'cancelled'].includes(row.state) || (row.state === 'committed' && row.recovery == null);+ const { rowId, recognized } = await openWatch(ctx, runtime, principal, p, {+ tool: 'watch_write_request', event: WRITE_SETTLED, target: row.request_id, targetRef: row.id, args: { request_id: row.request_id },+ reason: `Watching gbrain write request ${row.request_id}`, settledNow: settled,+ fallback: `call get_write_request ${row.request_id}`, fix: receiptFix(row.request_id),+ });+ return {+ watching: true, watch: rowId, request_id: row.request_id, event: WRITE_SETTLED, state: row.state, already_settled: settled,+ expires_in: WATCH_TTL,+ ...(recognized ? {} : unrecognized('watch_write_request')),+ fallback: `If no wake arrives, call get_write_request ${row.request_id} (or run gbrain write-request -- ${row.request_id}).`,+ };+ },+};++const watch_cron: Operation = {+ name: 'watch_cron',+ mutating: true,+ idempotent: true,+ writeInference: 'non_content',+ outputRedaction: REDACTION,+ description: 'This tool notifies you: it has gbrain wake this conversation through Wakeshift the next time the named cron reports its run '+ + '(ok or failed) with gbrain wakeshift emit. One wake per watch; call it again for the run after. The wake names the cron and the status; '+ + 'read the output where the cron writes it. Only crons the brain owner registered with gbrain wakeshift cron add can be watched.',+ params: {+ name: { type: 'string', required: true, description: 'The cron name the owner registered (letters, digits, dot, underscore and dash).' },+ ...CALLER_PARAMS,+ },+ scope: 'admin',+ publishGateKey: 'mcp.publish_wakeshift',+ cliHints: { hidden: true },+ handler: async (ctx, p) => {+ const name = cronName(p.name);+ if (!name) throw opError('invalid_params', 'watch_cron: name is required.', 'Pass the cron name the brain owner registered (gbrain wakeshift cron list shows them).');+ const { runtime, principal } = await watchContext(ctx, 'watch_cron', 'Check the cron output where it writes it.');+ const step = await termsStep(ctx, runtime, principal, 'watch_cron');+ if (step) return step;+ const registered = await ctx.engine.executeRaw('SELECT 1 FROM wake_crons WHERE name = $1', [name]);+ if (registered.length === 0) {+ throw opError('not_found', 'No registered cron has that name.',+ `Check the name with the brain owner: gbrain wakeshift cron list shows the registered crons, and gbrain wakeshift cron add ${name} registers this one.`);+ }+ if (ctx.dryRun) return { dry_run: true, action: 'watch_cron', cron: name };+ const fix = readFix('Lists the watches this connection holds and their state.', { mcp: { tool: 'list_watches', arguments: {} } });+ const { rowId, recognized } = await openWatch(ctx, runtime, principal, p, {+ tool: 'watch_cron', event: CRON_FINISHED, target: name, args: { name }, reason: `Watching gbrain cron ${name}`,+ settledNow: false, fallback: 'check the cron output where it writes it', fix,+ });+ return {+ watching: true, watch: rowId, cron: name, event: CRON_FINISHED, wakes: 'once, on the next run', expires_in: WATCH_TTL,+ ...(recognized ? {} : unrecognized('watch_cron')),+ fallback: 'If no wake arrives, read the cron output where it writes it.',+ };+ },+};++const accept_wakeshift_terms: Operation = {+ name: 'accept_wakeshift_terms',+ mutating: true,+ idempotent: true,+ writeInference: 'non_content',+ outputRedaction: REDACTION,+ description: 'Record that the user agreed to the agreement step a watch tool returned (agreement_required): this brain operator\'s terms and privacy policy '+ + 'and Wakeshift\'s Connector Terms and Privacy Policy. Call it only after showing the user that step and getting their agreement, then call the watch tool again.',+ params: {+ terms_version: { type: 'string', required: true, description: 'The terms_version from the agreement step.' },+ },+ scope: 'write',+ agentCallable: true,+ publishGateKey: 'mcp.publish_wakeshift',+ cliHints: { hidden: true },+ handler: async (ctx, p) => {+ const { runtime, principal } = await watchContext(ctx, 'accept_wakeshift_terms', 'Watching needs an MCP conversation; nothing to accept from the CLI.');+ if (await liveAccessMembers(ctx.engine) === 0) {+ return { accepted: false, required: false, note: 'This brain serves its owner alone, so no agreement step is needed; call the watch tool directly.' };+ }+ const terms = operatorTerms(runtime.file);+ if (!terms) throw termsUnset();+ if (p.terms_version !== terms.version) return { ...agreementStep(terms, 'Watching'), note: 'The operator\'s terms changed or the version did not match: show the user this step and pass its terms_version.' };+ if (ctx.dryRun) return { dry_run: true, action: 'accept_wakeshift_terms', terms_version: terms.version };+ await recordAcceptance(ctx.engine, principalRef(principal), terms);+ return { accepted: true, terms_version: terms.version, next: 'Call the watch tool again.' };+ },+};++interface WatchRow { id: number; event: string; target: string; state: string; attempts: number; last_error: string | null; created_at: Date | string; expires_at: Date | string }++function publicWatch(r: WatchRow) {+ const key = r.event === JOB_FINISHED ? { job: Number(r.target) } : r.event === WRITE_SETTLED ? { request_id: r.target } : r.event === CRON_FINISHED ? { cron: r.target } : {};+ return { watch: Number(r.id), event: r.event, target: r.target, ...key, state: r.state, attempts: r.attempts, last_error: r.last_error, created_at: r.created_at, expires_at: r.expires_at };+}++async function ownRows(ctx: OperationContext, extra: string, params: unknown[]): Promise<Array<WatchRow & { wake_user: string; ws_subscription_id: string }>> {const principal = await watchPrincipal(ctx);if (!principal) return [];- return ctx.engine.executeRaw<WatchRow>(+ return ctx.engine.executeRaw(`SELECT id, event, target, state, attempts, last_error, created_at, expires_at, wake_user, ws_subscription_id FROM wake_subscriptionsWHERE principal_kind = $1 AND principal_id = $2 ${extra} ORDER BY created_at DESC, id DESC LIMIT 50`,[principal.kind, principal.id, ...params]);@@ -182,9 +354,9 @@ const list_watches: Operation = {mutating: false,idempotent: true,outputRedaction: REDACTION,- 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.',+ description: 'List what this connection is watching through Wakeshift (jobs, write requests and crons: open watches, plus ones that ended in the last day) with their state: open, delivered, dead or ended.',params: {},- scope: 'admin',+ scope: 'write',agentCallable: true,publishGateKey: 'mcp.publish_wakeshift',cliHints: { hidden: true },@@ -195,25 +367,52 @@ const list_watches: Operation = {},};+/** The one target an unwatch names, as a row filter. */+function unwatchFilter(p: Record<string, unknown>): { key: Record<string, unknown>; extra: string; params: unknown[] } {+ const given = (['job', 'request_id', 'cron', 'watch'] as const).filter(k => p[k] !== undefined && p[k] !== null);+ const usage = () => opError('invalid_params', 'unwatch: pass exactly one of job, request_id, cron or watch.', 'Pass the id you watched; list_watches shows your watches and their ids.');+ if (given.length !== 1) throw usage();+ const k = given[0]!;+ if (k === 'job' || k === 'watch') {+ const n = p[k] as number;+ if (!Number.isSafeInteger(n) || n <= 0) throw usage();+ return k === 'job'+ ? { key: { job: n }, extra: 'AND event = $3 AND target = $4', params: [JOB_FINISHED, String(n)] }+ : { key: { watch: n }, extra: 'AND id = $3', params: [n] };+ }+ if (k === 'request_id') {+ const id = parseWriteRequestId(p.request_id);+ if (!id) throw usage();+ return { key: { request_id: id }, extra: 'AND event = $3 AND target = $4', params: [WRITE_SETTLED, id] };+ }+ const name = cronName(p.cron);+ if (!name) throw usage();+ return { key: { cron: name }, extra: 'AND event = $3 AND target = $4', params: [CRON_FINISHED, name] };+}+const unwatch: Operation = {name: 'unwatch',mutating: true,idempotent: true,writeInference: 'non_content',outputRedaction: REDACTION,- 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',+ description: 'Stop watching: ends this connection\'s open Wakeshift watches on one job, write request or cron (or one watch by its id), so no wake comes for it. Returns how many ended (0 when none was open).',+ params: {+ job: { type: 'number', description: 'Job ID you passed to watch_job.' },+ request_id: { type: 'string', description: 'Request id you passed to watch_write_request.' },+ cron: { type: 'string', description: 'Cron name you passed to watch_cron.' },+ watch: { type: 'number', description: 'A watch id from list_watches.' },+ },+ scope: 'write',agentCallable: true,publishGateKey: 'mcp.publish_wakeshift',cliHints: { hidden: true },handler: async (ctx, p) => {const runtime = wakeshiftRuntime();if (!runtime) throw notEnabled();- const job = p.job as number;- if (!Number.isSafeInteger(job) || job <= 0) throw opError('invalid_params', 'unwatch: job must be a positive job id.', 'Pass the job id you watched (list_watches shows them).');- if (ctx.dryRun) return { dry_run: true, action: 'unwatch', job };- const rows = await ownRows(ctx, "AND state = 'open' AND event = $3 AND target = $4", [JOB_FINISHED, String(job)]) as Array<WatchRow & { wake_user: string; ws_subscription_id: string }>;+ const { key, extra, params } = unwatchFilter(p);+ if (ctx.dryRun) return { dry_run: true, action: 'unwatch', ...key };+ const rows = await ownRows(ctx, `AND state = 'open' ${extra}`, params);let ended = 0;for (const row of rows) {const done = await ctx.engine.executeRaw(`UPDATE wake_subscriptions SET state = 'ended', last_error = 'unwatched', lease_until = NULL, updated_at = now() WHERE id = $1 AND state = 'open' RETURNING id`, [row.id]);@@ -221,8 +420,8 @@ const unwatch: Operation = {ended++;await endAtWakeshift(runtime.api, row);}- return { job, ended };+ return { ...key, ended };},};-export const wakeshiftOperations: Operation[] = [watch_job, list_watches, unwatch];+export const wakeshiftOperations: Operation[] = [watch_job, watch_write_request, watch_cron, accept_wakeshift_terms, list_watches, unwatch];diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex db6d617a6d..4afa418157 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -206,7 +206,11 @@ 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_cron_runs', 'operational', 'Cron runs gbrain wakeshift emit recorded (Wakeshift); an open cron watch reconciles against them, so a run reported just before the move still wakes its watcher.'),+ carry('wake_crons', 'operational', 'The cron names the owner registered for watch_cron (Wakeshift); dropping them would make every cron watch read not_found.'),+ carry('wake_forgets', 'operational', 'Queued Wakeshift forget-user calls for removed members and revoked credentials; dropping them would skip a deletion the operator owes (Wakeshift ToS 8.2).'),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('wake_terms_acceptances', 'operational', 'Members\' acceptances of the operator\'s Wakeshift terms; dropping them would ask every member to agree again.'),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/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex c794939689..e9b5222f7a 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 290;+export const LATEST_SCHEMA_VERSION = 291;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 9f437a9af7..777920beed 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -291,6 +291,7 @@ import { v287 } from './v287-multi-page-recovery-record.ts';import { v288 } from './v288-decide-proposals-claim-pair-index.ts';import { v289 } from './v289-page-change-reasons.ts';import { v290 } from './v290-wake-subscriptions.ts';+import { v291 } from './v291-wake-events.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -580,4 +581,5 @@ export const MIGRATIONS: Migration[] = [v288,v289,v290,+ v291,];diff --git a/src/core/schema-migrations/v291-wake-events.ts b/src/core/schema-migrations/v291-wake-events.tsnew file mode 100644index 0000000000..eb2dbe6001--- /dev/null+++ b/src/core/schema-migrations/v291-wake-events.ts@@ -0,0 +1,65 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Wakeshift PR 2 (plan D2, D5, D6): the tables behind gbrain.write.settled,+// gbrain.cron.finished, the shared-brain agreement step and forget-on-remove.+// - wake_subscriptions.target_ref: the persistence_requests row a+// write.settled watch points at (request ids are unique per principal only);+// - wake_crons: cron names the owner registered with gbrain wakeshift cron add;+// - wake_cron_runs: (name, status, time) recorded by gbrain wakeshift emit,+// which the drainer reconciles, so a cron script never waits on Wakeshift;+// - wake_terms_acceptances: a principal's acceptance of the operator's terms+// version (a hash of the two links) on a brain with access members;+// - wake_forgets: queued Wakeshift forget-user calls for removed members,+// revoked tokens and deleted OAuth clients, sent by the drainer.+// Operational state, never brain content: a repo-less brain gets it+// unchanged, and it stays empty unless the owner turned reporting back on.+// Nothing is rewritten on upgrade. No schema.sql mirror, like v290.+export const v291: Migration = {+ version: 291,+ name: 'wake_events',+ idempotent: true,+ sql: `+ALTER TABLE wake_subscriptions ADD COLUMN IF NOT EXISTS target_ref TEXT;+CREATE TABLE IF NOT EXISTS wake_crons (+ name TEXT PRIMARY KEY CHECK (name ~ '^[a-z0-9._-]{1,64}$'),+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE TABLE IF NOT EXISTS wake_cron_runs (+ id BIGSERIAL PRIMARY KEY,+ name TEXT NOT NULL CHECK (name ~ '^[a-z0-9._-]{1,64}$'),+ status TEXT NOT NULL CHECK (status IN ('ok', 'failed')),+ finished_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS wake_cron_runs_name_idx ON wake_cron_runs (name, finished_at);+CREATE TABLE IF NOT EXISTS wake_terms_acceptances (+ principal_key TEXT NOT NULL CHECK (length(principal_key) BETWEEN 1 AND 300),+ terms_version TEXT NOT NULL CHECK (terms_version ~ '^[0-9a-f]{16}$'),+ accepted_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (principal_key, terms_version)+);+CREATE TABLE IF NOT EXISTS wake_forgets (+ id BIGSERIAL PRIMARY KEY,+ wake_user TEXT NOT NULL CHECK (wake_user ~ '^[0-9a-f]{32}$'),+ state TEXT NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'done', 'dead')),+ attempts INTEGER NOT NULL DEFAULT 0,+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ lease_until TIMESTAMPTZ,+ last_error TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE UNIQUE INDEX IF NOT EXISTS wake_forgets_pending_unique ON wake_forgets (wake_user) WHERE state = 'pending';+CREATE INDEX IF NOT EXISTS wake_forgets_due_idx ON wake_forgets (next_attempt_at) WHERE state = 'pending';+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles pr WHERE pg_has_role(current_user, pr.oid, 'USAGE') AND (pr.rolbypassrls OR pr.rolsuper)) THEN+ ALTER TABLE wake_crons ENABLE ROW LEVEL SECURITY;+ ALTER TABLE wake_cron_runs ENABLE ROW LEVEL SECURITY;+ ALTER TABLE wake_terms_acceptances ENABLE ROW LEVEL SECURITY;+ ALTER TABLE wake_forgets ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+`,+};diff --git a/src/core/token-mint.ts b/src/core/token-mint.tsindex 16fca7d4e8..95feb5c621 100644--- a/src/core/token-mint.ts+++ b/src/core/token-mint.ts@@ -19,6 +19,7 @@import type { BrainEngine } from './engine.ts';import { ALLOWED_SCOPES_LIST, assertAllowedScopes } from './scope.ts';import type { SqlQuery } from './sql-query.ts';+import { forgetWakePrincipal } from './wakeshift/forget.ts';import { opError } from './ops/contract.ts';import { generateToken, hashToken, isUndefinedColumnError } from './utils.ts';import { permissionsMirror, tokenGrantColumnValues, tokenGrantFromPermissions, TOKEN_GRANT_COLUMNS, type GrantSources, type PrincipalGrant } from './grants/model.ts';@@ -139,6 +140,7 @@ export async function revokeLegacyTokenById(sql: SqlQuery, id: string): Promise<WHERE id = ${id}::uuid AND revoked_at IS NULLRETURNING 1 AS ok`;+ if (rows.length > 0) await forgetWakePrincipal(sql, { kind: 'legacy_token', id });return rows.length > 0;}diff --git a/src/core/wakeshift/client.ts b/src/core/wakeshift/client.tsindex 5e2348c3ba..ba4807706c 100644--- a/src/core/wakeshift/client.ts+++ b/src/core/wakeshift/client.ts@@ -1,5 +1,5 @@/**- * Wakeshift HTTP API client (plan D1): the five endpoints gbrain uses, with no+ * Wakeshift HTTP API client (plan D1): the endpoints gbrain uses, with no* SDK. A key is an Ed25519 seed (`wst_` + 50 base58 characters whose last 4* bytes are the seed's CRC32); each request carries a fresh compact JWS signed* with it (EdDSA, typ app+jwt, 2 minutes, unique jti), so the key itself never@@ -119,6 +119,8 @@ export interface WakeshiftApi {unsubscribe(body: { call: WakeshiftCall; name: string; arguments: Record<string, unknown>; reason?: string }): Promise<{ ended: boolean }>;end(body: { user: string; id: string }): Promise<{ ended: boolean }>;emit(body: { name: string; arguments: Record<string, unknown>; payload: Record<string, unknown>; text: string; id: string; to: unknown[] }): Promise<EmitResult>;+ /** Forget User (POST /users/forget): deletes everything Wakeshift holds for the user; `forgotten` is false when there was nothing. */+ forget(body: { user: string }): Promise<{ forgotten: boolean }>;}export function wakeshiftClient(key: WakeshiftKey, opts: { url?: string; fetch?: typeof fetch; timeoutMs?: number } = {}): WakeshiftApi {@@ -157,5 +159,6 @@ export function wakeshiftClient(key: WakeshiftKey, opts: { url?: string; fetch?:unsubscribe: body => request('POST', '/event-subscriptions/unsubscribe', body),end: body => request('POST', '/event-subscriptions/end', body),emit: body => request('POST', '/events/emit', body),+ forget: body => request('POST', '/users/forget', body),};}diff --git a/src/core/wakeshift/config.ts b/src/core/wakeshift/config.tsindex dbf3e9ba65..90a5e00319 100644--- a/src/core/wakeshift/config.ts+++ b/src/core/wakeshift/config.ts@@ -49,14 +49,18 @@ export function readWakeshiftKey(env: NodeJS.ProcessEnv = process.env): KeyRead}-export interface WakeshiftFileConfig { enabled?: boolean; url?: string }+/**+ * The file-plane keys: on/off, the console URL, the operator's terms and privacy links (required on a brain with+ * access members, D5), and the hash of the manifest `enable` last published.+ */+export interface WakeshiftFileConfig { enabled?: boolean; url?: string; terms_url?: string; privacy_url?: string; manifest_hash?: string }export function wakeshiftFileConfig(config: GBrainConfig | null | undefined): WakeshiftFileConfig {const raw = (config as { wakeshift?: unknown } | null | undefined)?.wakeshift;return raw && typeof raw === 'object' ? raw as WakeshiftFileConfig : {};}-export interface WakeshiftRuntime { key: WakeshiftKey; url: string; api: WakeshiftApi }+export interface WakeshiftRuntime { key: WakeshiftKey; url: string; api: WakeshiftApi; file: WakeshiftFileConfig }/*** The live runtime when reporting back is on and the key parses, else null. Reads the file plane fresh (never a@@ -70,7 +74,7 @@ export function wakeshiftRuntime(opts: { config?: GBrainConfig | null; fetch?: ttry {const key = parseWakeshiftKey(read.raw);const url = normalizeWakeshiftUrl(file.url);- return { key, url, api: wakeshiftClient(key, { url, ...(opts.fetch ? { fetch: opts.fetch } : {}) }) };+ return { key, url, file, api: wakeshiftClient(key, { url, ...(opts.fetch ? { fetch: opts.fetch } : {}) }) };} catch {return null;}diff --git a/src/core/wakeshift/drain.ts b/src/core/wakeshift/drain.tsindex a3ae2fc23c..52ce5a16c1 100644--- a/src/core/wakeshift/drain.ts+++ b/src/core/wakeshift/drain.ts@@ -1,38 +1,51 @@/*** Wake delivery by pull reconciliation (plan D7). No outbox and no hook in the- * job queue: jobs reach a terminal state in many places and- * `remove_on_complete` deletes rows, so the drainer joins open watches to- * `minion_jobs` instead and emits when a job's terminal marker- * (`<finished_us>:<status>`, or `gone`) differs from what the watch- * delivered. It runs on a 5 s timer inside `gbrain serve` (stdio and HTTP) and- * the job worker, once more at the end of `gbrain jobs work`, and inside- * watch_job for a job that already finished.+ * job queue or the write path: jobs and write requests reach a terminal state+ * in many places and rows can be removed, so the drainer joins open watches+ * to what they watch and emits once it is settled:+ * - gbrain.job.finished: `minion_jobs` completed, failed, dead or cancelled+ * (marker `<finished_us>:<status>`, or `gone`);+ * - gbrain.write.settled: `persistence_requests` committed with no live+ * recovery record, failed, conflict or cancelled (marker+ * `<state>:<settled_us>`, or `gone`);+ * - gbrain.cron.finished: the first `wake_cron_runs` row for the name after+ * the watch began (marker `<run id>:<status>`).+ * It runs on a 5 s timer inside `gbrain serve` (stdio and HTTP) and the job+ * worker, once more at the end of `gbrain jobs work`, and inside a watch call+ * whose target already settled.*- * Bounded: at most 20 rows a tick; a lease (conditional UPDATE) so two hosts- * never emit one row; 5 attempts backing off 30 s, 2 m, 8 m, 30 m (a 429 waits- * its Retry-After within the same cap); any other 4xx is final. A dead,+ * Bounded: at most 20 watches a tick; a lease (conditional UPDATE) so two+ * hosts never emit one row; 5 attempts backing off 30 s, 2 m, 8 m, 30 m (a 429+ * waits its Retry-After within the same cap); any other 4xx is final. A dead,* revoked or expired watch is ended at Wakeshift once, so the conversation is- * told. Off or keyless: the tick returns before touching the database. A brain- * with live access members sends nothing (watch_job refuses there too).+ * told. On a brain with live access members a watch whose principal has not+ * accepted the operator's current terms ends with terms_not_accepted instead+ * of emitting (terms.ts). Queued forgets (forget.ts) go out under the same+ * attempt schedule, at most 10 a tick. Off or keyless: the tick returns before+ * touching the database.*/import { createHash } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { memberIdentityFor } from '../access/caller.ts';import { WakeshiftError, type WakeshiftApi } from './client.ts';-import { wakeshiftRuntime } from './config.ts';-import { JOB_FINISHED, jobMarker, jobWake, wakeEmitId, type JobSnapshot } from './events.ts';+import { wakeshiftRuntime, type WakeshiftRuntime } from './config.ts';+import { CRON_FINISHED, JOB_FINISHED, WRITE_SETTLED, cronMarker, cronWake, jobMarker, jobWake, wakeEmitId, writeMarker, writeWake, type JobSnapshot, type WriteSnapshot } from './events.ts';+import { operatorTerms, termsAccepted, type OperatorTerms } from './terms.ts';export const WAKE_RETRY_SCHEDULE_S = [30, 120, 480, 1800] as const;export const WAKE_MAX_ATTEMPTS = 5;export const WAKE_DRAIN_BATCH = 20;export const WAKE_DRAIN_TICK_MS = 5_000;+export const FORGET_DRAIN_BATCH = 10;const LEASE_S = 60;const TERMINAL = `('completed', 'failed', 'dead', 'cancelled')`;+const WRITE_TERMINAL = `('failed', 'conflict', 'cancelled')`;export interface WakeRow {id: number;event: string;target: string;+ target_ref: string | null;principal_kind: 'oauth_client' | 'legacy_token' | 'local_stdio';principal_id: string;member_id: string | null;@@ -46,21 +59,45 @@ export interface WakeRow {started_at: Date | string | null;finished_at: Date | string | null;finished_us: string | null;+ req_id: string | null;+ req_state: string | null;+ req_operation: string | null;+ req_source_id: string | null;+ req_created_at: Date | string | null;+ req_settled_at: Date | string | null;+ req_settled_us: string | null;+ run_id: number | string | null;+ run_status: string | null;+ run_finished_at: Date | string | null;}-export interface DrainReport { delivered: number; retried: number; dead: number; ended: number; skipped?: 'off' | 'shared' }+export interface DrainReport { delivered: number; retried: number; dead: number; ended: number; forgotten?: number; skipped?: 'off' }+const US = (col: string) => `(floor(extract(epoch FROM ${col}) * 1000000))::bigint::text`;++/**+ * Open, due, unleased watches whose target settled, one row per watch across the three event families (each LEFT JOIN+ * matches only its own event), at most 20.+ */const CANDIDATES_SQL = (byId: boolean) => `-SELECT w.id, w.event, w.target, w.principal_kind, w.principal_id, w.member_id, w.wake_user, w.ws_subscription_id, w.attempts,- (floor(extract(epoch FROM w.created_at) * 1000000))::bigint::text AS created_us,- j.id AS job_id, j.name AS job_name, j.status AS job_status, j.started_at, j.finished_at,- (floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text AS finished_us+SELECT w.id, w.event, w.target, w.target_ref, w.principal_kind, w.principal_id, w.member_id, w.wake_user, w.ws_subscription_id, w.attempts,+ ${US('w.created_at')} AS created_us,+ j.id AS job_id, j.name AS job_name, j.status AS job_status, j.started_at, j.finished_at, ${US('j.finished_at')} AS finished_us,+ r.id::text AS req_id, r.state AS req_state, r.operation AS req_operation, r.source_id AS req_source_id, r.created_at AS req_created_at,+ COALESCE(r.completed_at, r.updated_at) AS req_settled_at, ${US('COALESCE(r.completed_at, r.updated_at)')} AS req_settled_us,+ c.id AS run_id, c.status AS run_status, c.finished_at AS run_finished_atFROM wake_subscriptions w- LEFT JOIN minion_jobs j ON w.event = '${JOB_FINISHED}' AND j.id = CASE WHEN w.target ~ '^[0-9]{1,18}$' THEN w.target::bigint END+ LEFT JOIN minion_jobs j ON w.event = '${JOB_FINISHED}' AND j.id = CASE WHEN w.event = '${JOB_FINISHED}' AND w.target ~ '^[0-9]{1,18}$' THEN w.target::bigint END+ LEFT JOIN persistence_requests r ON w.event = '${WRITE_SETTLED}'+ AND r.id = CASE WHEN w.event = '${WRITE_SETTLED}' AND w.target_ref ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' THEN w.target_ref::uuid END+ LEFT JOIN LATERAL (SELECT cr.id, cr.status, cr.finished_at FROM wake_cron_runs cr+ WHERE w.event = '${CRON_FINISHED}' AND cr.name = w.target AND cr.finished_at >= w.created_at ORDER BY cr.finished_at, cr.id LIMIT 1) c ON trueWHERE w.state = 'open' AND w.next_attempt_at <= now() AND (w.lease_until IS NULL OR w.lease_until < now())- AND (j.id IS NULL OR j.status IN ${TERMINAL})- AND w.delivered_marker IS DISTINCT FROM CASE WHEN j.id IS NULL THEN 'gone' ELSE- COALESCE((floor(extract(epoch FROM j.finished_at) * 1000000))::bigint::text, '0') || ':' || j.status END+ AND CASE w.event+ WHEN '${JOB_FINISHED}' THEN (j.id IS NULL OR j.status IN ${TERMINAL})+ WHEN '${WRITE_SETTLED}' THEN (r.id IS NULL OR r.state IN ${WRITE_TERMINAL} OR (r.state = 'committed' AND r.recovery IS NULL))+ WHEN '${CRON_FINISHED}' THEN c.id IS NOT NULL+ ELSE false END${byId ? 'AND w.id = ANY($1::bigint[])' : ''}ORDER BY w.next_attempt_at, w.idLIMIT ${WAKE_DRAIN_BATCH}`;@@ -89,7 +126,7 @@ async function settle(engine: BrainEngine, id: number, lease: string, state: 'opreturn rows.length > 0;}-/** Live access members: reporting back runs only on a brain that serves its owner alone (docs/guides/wakeshift.md#who-it-is-for). */+/** Live access members: on a brain with any, every watch needs its principal's acceptance of the operator's terms (terms.ts). */export async function liveAccessMembers(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);@@ -124,7 +161,31 @@ function jobOf(row: WakeRow): JobSnapshot | null {return row.job_id == null ? null : { id: Number(row.job_id), name: row.job_name, status: row.job_status, started_at: row.started_at, finished_at: row.finished_at, finished_us: row.finished_us };}-async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, report: DrainReport): Promise<void> {+function writeOf(row: WakeRow): WriteSnapshot | null {+ return row.req_id == null ? null : { state: row.req_state, operation: row.req_operation, source_id: row.req_source_id, created_at: row.req_created_at, settled_at: row.req_settled_at, settled_us: row.req_settled_us };+}++/** The emit for a settled watch: its marker, arguments (the manifest's), payload and line. */+function wakeFor(row: WakeRow): { marker: string; args: Record<string, unknown>; payload: Record<string, unknown>; text: string } {+ if (row.event === WRITE_SETTLED) {+ const req = writeOf(row);+ return { marker: writeMarker(req), args: { request_id: row.target }, ...writeWake(row.target, req) };+ }+ if (row.event === CRON_FINISHED) {+ const run = { id: row.run_id!, status: row.run_status!, finished_at: row.run_finished_at };+ return { marker: cronMarker(run), args: { name: row.target }, ...cronWake(row.target, run) };+ }+ const job = jobOf(row);+ return { marker: jobMarker(job), args: { job: Number(row.target) }, ...jobWake(Number(row.target), job) };+}++/** Queue a Wakeshift forget for a revoked credential's own user (a member's user is forgotten when the member is removed, forget.ts). */+async function queueForget(engine: BrainEngine, row: WakeRow): Promise<void> {+ if (row.member_id || row.principal_kind === 'local_stdio') return;+ await engine.executeRaw(`INSERT INTO wake_forgets (wake_user) VALUES ($1) ON CONFLICT (wake_user) WHERE state = 'pending' DO NOTHING`, [row.wake_user]);+}++async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, report: DrainReport, terms: { shared: boolean; current: OperatorTerms | null }): Promise<void> {const claimed = await claim(engine, row.id);if (!claimed) return;const { lease } = claimed;@@ -132,16 +193,20 @@ async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, reptry {if (!(await principalLive(engine, row))) {await endAtWakeshift(api, row);+ await queueForget(engine, row);if (await settle(engine, row.id, lease, 'ended', { error: 'principal_revoked' })) report.ended++;return;}- const job = jobOf(row);- const marker = jobMarker(job);- const { payload, text } = jobWake(Number(row.target), job);+ if (terms.shared && !(await termsAccepted(engine, row, terms.current))) {+ await endAtWakeshift(api, row);+ if (await settle(engine, row.id, lease, 'ended', { error: 'terms_not_accepted' })) report.ended++;+ return;+ }+ const { marker, args, payload, text } = wakeFor(row);let sent;try {sent = await api.emit({- name: row.event, arguments: { job: Number(row.target) }, payload, text,+ name: row.event, arguments: args, payload, text,id: wakeEmitId(row.event, row.target, marker, row.id, createHash('sha256').update(`${row.wake_user}:${row.created_us}`).digest('hex').slice(0, 12)),to: [{ user: row.wake_user, subscription: row.ws_subscription_id }],});@@ -170,23 +235,53 @@ async function deliver(engine: BrainEngine, api: WakeshiftApi, row: WakeRow, rep}}+/** Send up to 10 due queued forgets (forget.ts) under a lease; `forgotten: false` (nothing held) also completes one. */+async function drainForgets(engine: BrainEngine, api: WakeshiftApi, report: DrainReport): Promise<void> {+ const due = await engine.executeRaw<{ id: number; wake_user: string; attempts: number; lease: string }>(+ `UPDATE wake_forgets SET lease_until = now() + interval '${LEASE_S} seconds', updated_at = now()+ WHERE id IN (SELECT id FROM wake_forgets WHERE state = 'pending' AND next_attempt_at <= now() AND (lease_until IS NULL OR lease_until < now())+ ORDER BY next_attempt_at, id LIMIT ${FORGET_DRAIN_BATCH})+ AND state = 'pending' AND (lease_until IS NULL OR lease_until < now())+ RETURNING id, wake_user, attempts, ${US('lease_until')} AS lease`);+ const done = (id: number, lease: string, state: 'pending' | 'done' | 'dead', attempts: number, error: string | null, delayS?: number) => engine.executeRaw(+ `UPDATE wake_forgets SET state = $2, attempts = $3, last_error = $4, lease_until = NULL, updated_at = now(),+ next_attempt_at = CASE WHEN $5::int IS NULL THEN next_attempt_at ELSE now() + make_interval(secs => $5::int) END+ WHERE id = $1 AND state = 'pending' AND ${US('lease_until')} = $6`, [id, state, attempts, error, delayS ?? null, lease]);+ for (const row of due) {+ const attempts = Number(row.attempts) + 1;+ try {+ await api.forget({ user: row.wake_user });+ await done(row.id, row.lease, 'done', attempts, null);+ report.forgotten = (report.forgotten ?? 0) + 1;+ } catch (e) {+ const err = e instanceof WakeshiftError ? e : new WakeshiftError(0, 'network', String(e));+ const retryable = err.status === 0 || err.status === 429 || err.status >= 500;+ if (!retryable || attempts >= WAKE_MAX_ATTEMPTS) await done(row.id, row.lease, 'dead', attempts, err.code);+ else await done(row.id, row.lease, 'pending', attempts, err.code, retryDelayS(attempts, err));+ }+ }+}+/**- * One reconciliation pass: ends expired watches, then delivers up to 20 due ones (only `ids` when given). Returns- * `skipped: 'off'` without a query when reporting back is off or keyless. `api` is a test seam.+ * One reconciliation pass: ends expired watches, sends queued forgets, then delivers up to 20 due watches (only `ids`+ * when given). Returns `skipped: 'off'` without a query when reporting back is off or keyless. `runtime` is the+ * caller's (the watch tools) or a test seam.*/-export async function drainWakes(engine: BrainEngine, opts: { ids?: number[]; api?: WakeshiftApi } = {}): Promise<DrainReport> {+export async function drainWakes(engine: BrainEngine, opts: { ids?: number[]; runtime?: WakeshiftRuntime } = {}): Promise<DrainReport> {const report: DrainReport = { delivered: 0, retried: 0, dead: 0, ended: 0 };- const api = opts.api ?? wakeshiftRuntime()?.api;- if (!api) return { ...report, skipped: 'off' };- if (await liveAccessMembers(engine) > 0) return { ...report, skipped: 'shared' };+ const runtime = opts.runtime ?? wakeshiftRuntime();+ if (!runtime) return { ...report, skipped: 'off' };+ const { api } = runtime;+ const terms = { shared: await liveAccessMembers(engine) > 0, current: operatorTerms(runtime.file) };const expired = await engine.executeRaw<{ id: number; wake_user: string; ws_subscription_id: string }>(`UPDATE wake_subscriptions SET state = 'ended', last_error = 'expired', updated_at = now()WHERE state = 'open' AND expires_at < now() RETURNING id, wake_user, ws_subscription_id`);report.ended += expired.length;+ if (opts.ids === undefined) await drainForgets(engine, api, report);const rows = await engine.executeRaw<WakeRow>(CANDIDATES_SQL(opts.ids !== undefined), opts.ids !== undefined ? [opts.ids] : []);let failure: unknown = null;for (const row of rows) {- try { await deliver(engine, api, row, report); } catch (e) { failure ??= e; }+ try { await deliver(engine, api, row, report, terms); } catch (e) { failure ??= e; }}if (failure !== null) throw failure;return report;@@ -201,7 +296,8 @@ export async function drainWakesUntilIdle(engine: BrainEngine): Promise<DrainReptry { r = await drainWakes(engine); } catch (e) { failure ??= e; continue; }if (r.skipped) return { ...total, skipped: r.skipped };total.delivered += r.delivered; total.retried += r.retried; total.dead += r.dead; total.ended += r.ended;- if (r.delivered + r.dead + r.ended === 0) break;+ if (r.forgotten) total.forgotten = (total.forgotten ?? 0) + r.forgotten;+ if (r.delivered + r.dead + r.ended + (r.forgotten ?? 0) === 0) break;}if (failure !== null) throw failure;return total;diff --git a/src/core/wakeshift/events.ts b/src/core/wakeshift/events.tsindex ad496b0fde..18adf4875c 100644--- a/src/core/wakeshift/events.ts+++ b/src/core/wakeshift/events.ts@@ -1,13 +1,19 @@/**- * The events gbrain offers Wakeshift (plan D2, D3). PR 1 ships one:- * `gbrain.job.finished`, a minion job reaching completed, failed, dead or- * cancelled. Every event is personal (only the named subscription gets an- * occurrence) and deleted on delivery. The payload is a pointer: ids, status,+ * The events gbrain offers Wakeshift (plan D2, D3): `gbrain.job.finished`, a+ * minion job reaching completed, failed, dead or cancelled;+ * `gbrain.write.settled`, a write request reaching committed, failed,+ * conflict or cancelled; `gbrain.cron.finished`, a registered cron's run+ * reported by `gbrain wakeshift emit`. Every event is personal (only the+ * named subscription gets an occurrence) and deleted on delivery. The payload is a pointer: ids, status,* kind, times and the exact next call. Never page text, titles or slugs, so a* wake cannot widen readable_by, folder rules or private pages; the agent's* follow-up read goes through gbrain's own access checks.*/+import { createHash } from 'node:crypto';+export const JOB_FINISHED = 'gbrain.job.finished';+export const WRITE_SETTLED = 'gbrain.write.settled';+export const CRON_FINISHED = 'gbrain.cron.finished';const JOB_PAYLOAD = {type: 'object',@@ -24,21 +30,66 @@ const JOB_PAYLOAD = {additionalProperties: false,} as const;+const TIME = { type: ['string', 'null'] } as const;++const WRITE_PAYLOAD = {+ type: 'object',+ properties: {+ request_id: { type: 'string', maxLength: 64 },+ state: { type: 'string', enum: ['committed', 'failed', 'conflict', 'cancelled', 'gone'] },+ operation: { type: ['string', 'null'], maxLength: 100 },+ source_id: { type: ['string', 'null'], maxLength: 100 },+ accepted_at: TIME,+ settled_at: TIME,+ next: { type: 'string', maxLength: 200 },+ },+ required: ['request_id', 'state', 'next'],+ additionalProperties: false,+} as const;++const CRON_PAYLOAD = {+ type: 'object',+ properties: {+ name: { type: 'string', maxLength: 64 },+ status: { type: 'string', enum: ['ok', 'failed'] },+ finished_at: TIME,+ next: { type: 'string', maxLength: 200 },+ },+ required: ['name', 'status', 'next'],+ additionalProperties: false,+} as const;+/** The manifest `gbrain wakeshift enable` merges (POST /manifest/merge); topic as the SDK would build it. */export function wakeshiftManifest(): { events: Record<string, unknown>[] } {+ const event = (name: string, description: string, arg: string, argSchema: Record<string, unknown>, payload: unknown) => ({+ name, description,+ arguments: { type: 'object', properties: { [arg]: argSchema }, required: [arg], additionalProperties: false },+ payload, topic: `ev/${name}/{${arg}}`, personal: true, delete_on_delivery: true,+ });return {- events: [{- name: JOB_FINISHED,- description: 'A gbrain background job you are watching reached completed, failed, dead or cancelled. The payload is a pointer: call get_job with the id for the result.',- arguments: { type: 'object', properties: { job: { type: 'integer', minimum: 1 } }, required: ['job'], additionalProperties: false },- payload: JOB_PAYLOAD,- topic: `ev/${JOB_FINISHED}/{job}`,- personal: true,- delete_on_delivery: true,- }],+ events: [+ event(JOB_FINISHED, 'A gbrain background job you are watching reached completed, failed, dead or cancelled. The payload is a pointer: call get_job with the id for the result.',+ 'job', { type: 'integer', minimum: 1 }, JOB_PAYLOAD),+ event(WRITE_SETTLED, 'A gbrain write request you are watching reached committed, failed, conflict or cancelled. The payload is a pointer: call get_write_request with the id for the receipt.',+ 'request_id', { type: 'string', pattern: '^[0-9a-f-]{36}$' }, WRITE_PAYLOAD),+ event(CRON_FINISHED, 'A scheduled gbrain cron you are watching reported its run as ok or failed. The payload names the cron and the status; read its output where the cron writes it.',+ 'name', { type: 'string', pattern: '^[a-z0-9._-]{1,64}$' }, CRON_PAYLOAD),+ ],};}+/** A short hash of the manifest this build publishes; `enable` stores it so status and doctor can tell a stale one. */+export function wakeshiftManifestHash(): string {+ return createHash('sha256').update(JSON.stringify(wakeshiftManifest())).digest('hex').slice(0, 16);+}++/** A cron name as gbrain stores it: lowercased, any run of other characters folded to '-', at most 64 characters; null when nothing is left. */+export function cronName(raw: unknown): string | null {+ if (typeof raw !== 'string') return null;+ const name = raw.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64);+ return name || null;+}+export interface JobSnapshot {id: number;name: string | null;@@ -96,3 +147,52 @@ export function jobWake(jobId: number, job: JobSnapshot | null): { payload: Reco: `gbrain: job ${jobId}${kind} ${PHRASE[status] ?? status}${took}. Call get_job ${jobId} for the result.`,};}++export interface WriteSnapshot {+ state: string | null;+ operation: string | null;+ source_id: string | null;+ created_at: Date | string | null;+ settled_at: Date | string | null;+ /** settled_at in microseconds since the epoch, null when the request row is gone. */+ settled_us: string | null;+}++/** A write request's settled marker `<state>:<settled_us>` (`gone` when the receipt row was removed). */+export function writeMarker(req: WriteSnapshot | null): string {+ return req?.state ? `${req.state}:${req.settled_us ?? '0'}` : 'gone';+}++const WRITE_PHRASE: Record<string, string> = { committed: 'committed', failed: 'failed', conflict: 'ended in a conflict', cancelled: 'was cancelled' };++/** Payload and line for a watched write request: ids, state, operation, source and times, never the slug, title or text. */+export function writeWake(requestId: string, req: WriteSnapshot | null): { payload: Record<string, unknown>; text: string } {+ const state = req?.state ?? 'gone';+ const next = state === 'gone' ? `list_write_requests (request ${requestId} is no longer kept)` : `get_write_request ${requestId}`;+ const op = req?.operation ? ` (${req.operation.slice(0, 100)})` : '';+ return {+ payload: {+ request_id: requestId, state, operation: req?.operation?.slice(0, 100) ?? null, source_id: req?.source_id?.slice(0, 100) ?? null,+ accepted_at: iso(req?.created_at ?? null), settled_at: iso(req?.settled_at ?? null), next,+ },+ text: state === 'gone'+ ? `gbrain: write request ${requestId} settled; its receipt is no longer kept. Call list_write_requests to see recent ones.`+ : `gbrain: write request ${requestId}${op} ${WRITE_PHRASE[state] ?? state}. Call get_write_request ${requestId} for the receipt.`,+ };+}++export interface CronRun { id: number | string; status: string; finished_at: Date | string | null }++/** A cron run's marker `<run id>:<status>`. */+export function cronMarker(run: CronRun): string {+ return `${run.id}:${run.status}`;+}++/** Payload and line for a watched cron's run. No report slug: the agent reads the output where the cron writes it. */+export function cronWake(name: string, run: CronRun): { payload: Record<string, unknown>; text: string } {+ const next = `watch_cron ${name} to hear about its next run`;+ return {+ payload: { name, status: run.status, finished_at: iso(run.finished_at), next },+ text: `gbrain: cron ${name} finished ${run.status === 'ok' ? 'ok' : 'with a failure'}. Read its output where it writes it; call watch_cron ${name} to hear about the next run.`,+ };+}diff --git a/src/core/wakeshift/forget.ts b/src/core/wakeshift/forget.tsnew file mode 100644index 0000000000..80ff1a5540--- /dev/null+++ b/src/core/wakeshift/forget.ts@@ -0,0 +1,41 @@+/**+ * Forget on remove (plan D6, review F12; Wakeshift ToS 7.1, 8.2). Removing a+ * member, revoking a token or deleting an OAuth client ends that principal's+ * open watches (state ended, last_error principal_revoked), drops its terms+ * acceptance and queues a Wakeshift Forget User call for each hashed user it+ * watched under. The queue (wake_forgets) is drained by the wake drainer+ * (drain.ts), so the CLI never waits on the network and works with reporting+ * back off. A credential bound to a member watched under the member's user,+ * which outlives that one credential: its watches end, and the member's user+ * is forgotten when the member is removed.+ *+ * Written over the scalar-only SqlQuery so auth.ts and token-mint.ts can call+ * it with the handle they already hold. Best effort: a failure prints one+ * stderr line and never fails the removal.+ */+import type { SqlQuery } from '../sql-query.ts';++export type ForgetTarget = { member: string } | { kind: 'oauth_client' | 'legacy_token'; id: string };++export async function forgetWakePrincipal(sql: SqlQuery, who: ForgetTarget): Promise<{ ended: number; queued: number }> {+ try {+ if ('member' in who) {+ const ended = await sql`UPDATE wake_subscriptions SET state = 'ended', last_error = 'principal_revoked', lease_until = NULL, updated_at = now()+ WHERE member_id = ${who.member} AND state = 'open' RETURNING id`;+ const queued = await sql`INSERT INTO wake_forgets (wake_user) SELECT DISTINCT wake_user FROM wake_subscriptions WHERE member_id = ${who.member}+ ON CONFLICT (wake_user) WHERE state = 'pending' DO NOTHING RETURNING id`;+ await sql`DELETE FROM wake_terms_acceptances WHERE principal_key = ${`member:${who.member}`}`;+ return { ended: ended.length, queued: queued.length };+ }+ const ended = await sql`UPDATE wake_subscriptions SET state = 'ended', last_error = 'principal_revoked', lease_until = NULL, updated_at = now()+ WHERE principal_kind = ${who.kind} AND principal_id = ${who.id} AND state = 'open' RETURNING id`;+ const queued = await sql`INSERT INTO wake_forgets (wake_user) SELECT DISTINCT wake_user FROM wake_subscriptions+ WHERE principal_kind = ${who.kind} AND principal_id = ${who.id} AND member_id IS NULL+ ON CONFLICT (wake_user) WHERE state = 'pending' DO NOTHING RETURNING id`;+ await sql`DELETE FROM wake_terms_acceptances WHERE principal_key = ${`${who.kind}:${who.id}`}`;+ return { ended: ended.length, queued: queued.length };+ } catch (e) {+ console.error(`[wakeshift] could not end the removed principal's watches or queue its forget: ${e instanceof Error ? e.message : String(e)}`);+ return { ended: 0, queued: 0 };+ }+}diff --git a/src/core/wakeshift/terms.ts b/src/core/wakeshift/terms.tsnew file mode 100644index 0000000000..536734a8b7--- /dev/null+++ b/src/core/wakeshift/terms.ts@@ -0,0 +1,75 @@+/**+ * The shared-brain agreement step (plan D5, D6; Wakeshift ToS 6.2, 6.3, 6.6).+ * On a brain with live access members, the operator (the brain owner, who+ * holds the Wakeshift app) must show each person one step before the first+ * wake: what watching does, the operator's own terms and privacy links, the+ * Wakeshift disclosure and Wakeshift's Connector Terms and Privacy Policy.+ * `gbrain wakeshift enable` stores the two operator links in the file plane;+ * the terms version is a hash of them, so changing a link asks everyone again.+ * Acceptances live in wake_terms_acceptances, keyed by the principal (the bound+ * member when there is one). A brain with no live members skips the step.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { WakeshiftFileConfig } from './config.ts';++export const WAKESHIFT_CONNECTOR_TERMS_URL = 'https://wakeshift.ai/connector-terms';+export const WAKESHIFT_PRIVACY_URL = 'https://wakeshift.ai/privacy';++export interface OperatorTerms { terms_url: string; privacy_url: string; version: string }++/** An absolute https URL (at most 500 characters), else null. */+export function httpsUrl(raw: unknown): string | null {+ if (typeof raw !== 'string' || raw.length > 500) return null;+ try {+ const url = new URL(raw.trim());+ return url.protocol === 'https:' && url.hostname ? url.toString() : null;+ } catch {+ return null;+ }+}++/** The operator's links from the file plane with their version (first 16 hex of SHA-256 over both), or null when either is missing. */+export function operatorTerms(file: WakeshiftFileConfig): OperatorTerms | null {+ const terms = httpsUrl(file.terms_url);+ const privacy = httpsUrl(file.privacy_url);+ if (!terms || !privacy) return null;+ return { terms_url: terms, privacy_url: privacy, version: createHash('sha256').update(`${terms}\n${privacy}`).digest('hex').slice(0, 16) };+}++export interface WakePrincipalRef { principal_kind: string; principal_id: string; member_id: string | null }++/** The key a principal accepts under, and the input to its hashed Wakeshift user: `member:<id>` when bound, else `<kind>:<id>`. */+export function wakePrincipalKey(p: WakePrincipalRef): string {+ return p.member_id ? `member:${p.member_id}` : `${p.principal_kind}:${p.principal_id}`;+}++export async function termsAccepted(engine: BrainEngine, p: WakePrincipalRef, terms: OperatorTerms | null): Promise<boolean> {+ if (!terms) return false;+ const rows = await engine.executeRaw('SELECT 1 FROM wake_terms_acceptances WHERE principal_key = $1 AND terms_version = $2', [wakePrincipalKey(p), terms.version]);+ return rows.length > 0;+}++export async function recordAcceptance(engine: BrainEngine, p: WakePrincipalRef, terms: OperatorTerms): Promise<void> {+ await engine.executeRaw(+ 'INSERT INTO wake_terms_acceptances (principal_key, terms_version) VALUES ($1, $2) ON CONFLICT (principal_key, terms_version) DO NOTHING',+ [wakePrincipalKey(p), terms.version]);+}++/** What a watch_* call returns instead of subscribing, until this principal accepts the current terms version. */+export function agreementStep(terms: OperatorTerms, tool: string): Record<string, unknown> {+ return {+ watching: false,+ agreement_required: true,+ terms_version: terms.version,+ what: `${tool} asks gbrain to wake this conversation through Wakeshift when the thing you watch finishes. Each wake sends Wakeshift a pointer (an id, a status, times, a hashed user id and your MCP client name), never page text, titles or slugs. You can stop any watch with unwatch.`,+ operator_terms_url: terms.terms_url,+ operator_privacy_url: terms.privacy_url,+ wakeshift_disclosure: 'Wakes pass through Wakeshift, operated by Clawvisor Inc. as this brain operator\'s service provider. Wakeshift\'s Connector Terms and Privacy Policy apply to that delivery and to the wakeshift program, if your agent needs it.',+ wakeshift_connector_terms_url: WAKESHIFT_CONNECTOR_TERMS_URL,+ wakeshift_privacy_url: WAKESHIFT_PRIVACY_URL,+ agreement: 'Continuing means agreeing to this brain operator\'s terms and privacy policy and to Wakeshift\'s Connector Terms and Privacy Policy (links above).',+ user_message: 'Show the user what watching does, the four links and the agreement line. Call accept_wakeshift_terms only after they agree, then call this tool again.',+ next: { tool: 'accept_wakeshift_terms', arguments: { terms_version: terms.version } },+ };+}diff --git a/test/e2e/wakeshift-pr2-postgres.test.ts b/test/e2e/wakeshift-pr2-postgres.test.tsnew file mode 100644index 0000000000..c42947ab51--- /dev/null+++ b/test/e2e/wakeshift-pr2-postgres.test.ts@@ -0,0 +1,126 @@+/**+ * Wakeshift PR 2 on real Postgres (PGLite coverage: test/wakeshift-pr2.serial.test.ts): a real put_page's write+ * request watched with watch_write_request wakes once with a pointer payload, a pending one wakes when it fails, and a+ * foreign id reads like get_write_request's not_found; removing a member ends its watches and the drainer sends one+ * Wakeshift forget, with two concurrent drainers sending it once (the lease). Against test/helpers/fake-wakeshift.ts.+ * Skips without DATABASE_URL. Run: DATABASE_URL=... bun test test/e2e/wakeshift-pr2-postgres.test.ts+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+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 } from '../../src/core/wakeshift/drain.ts';+import { resetWakeshiftEnvKeyForTests } from '../../src/core/wakeshift/config.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { removeMember } from '../../src/core/access/members.ts';+import { startFakeWakeshift, type FakeWakeshift } from '../helpers/fake-wakeshift.ts';+import { withEnv } from '../helpers/with-env.ts';++const d = hasDatabase() ? describe : describe.skip;+const KEY = encodeWakeshiftKey(Buffer.alloc(32, 23));+let fake: FakeWakeshift;+let home: string;++const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, WAKESHIFT_API_KEY: undefined }, async () => {+ resetWakeshiftEnvKeyForTests();+ return fn();+});+const writeConfig = (wakeshift: Record<string, unknown>) =>+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', wakeshift: { enabled: true, url: fake.url, ...wakeshift } }), { mode: 0o600 });++beforeAll(async () => {+ if (!hasDatabase()) return;+ await setupDB();+ home = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-pr2-pg-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'wakeshift.key'), KEY + '\n', { mode: 0o600 });+ fake = startFakeWakeshift(KEY);+ await inHome(() => registerLocalWriter(getEngine(), 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null }));+}, 120_000);++afterAll(async () => {+ if (!hasDatabase()) return;+ fake.stop();+ await disposePersistenceConsumer(getEngine());+ await teardownDB();+ rmSync(home, { recursive: true, force: true });+});++beforeEach(async () => {+ if (!hasDatabase()) return;+ writeConfig({});+ fake.calls.length = 0;+ fake.respond.clear();+ for (const table of ['wake_subscriptions', 'wake_terms_acceptances', 'wake_forgets', 'minion_jobs']) await getEngine().executeRaw(`DELETE FROM ${table}`);+});++const log = { info() {}, warn() {}, error() {} };+const stdio = { remote: true, transport: 'stdio' as const, sourceId: 'default', config: { engine: 'postgres' }, logger: log, mcpCaller: { client: 'claude-code' } };+const client = (id: string) => ({ remote: true, transport: 'http' as const, sourceId: 'default', config: { engine: 'postgres' }, logger: log,+ auth: { token: 't', clientId: id, principal: { kind: 'oauth_client' as const, id }, scopes: ['read', 'write', 'admin'] } });+const call = (op: string, params: Record<string, unknown>, ctx: object = stdio) => inHome(() => dispatchToolCall(getEngine(), op, params, ctx as never));+const body = (r: { content: Array<{ text: string }> }) => JSON.parse(r.content[0]!.text);+const envelope = (r: { content: Array<{ text: string }> }, id: string) => { const { notices: _, ...rest } = JSON.parse(r.content[0]!.text.replaceAll(id, 'ID')); return rest; };+const emits = () => fake.calls.filter(c => c.path === '/events/emit');++async function writeNote(slug: string): Promise<string> {+ const id = randomUUID();+ const r = await call('put_page', { slug, content: `---\ntitle: Canary\n---\n\nalice-example canary body for ${slug}.\n`, request_id: id });+ expect(r.isError).toBeFalsy();+ await disposePersistenceConsumer(getEngine());+ return id;+}++d('wakeshift PR 2 on Postgres', () => {+ test('write.settled: a committed write wakes at once; a pending one wakes once it fails; no slug or text leaves', async () => {+ const a = await writeNote('notes/pg-settled-a');+ expect(body(await call('watch_write_request', { request_id: a }))).toMatchObject({ watching: true, state: 'committed', already_settled: true });+ expect(emits()).toHaveLength(1);+ expect(emits()[0]!.body.payload).toMatchObject({ request_id: a, state: 'committed', operation: 'put_page', next: `get_write_request ${a}` });+ const b = await writeNote('notes/pg-settled-b');+ await getEngine().executeRaw("UPDATE persistence_requests SET state = 'queued' WHERE request_id = $1::uuid", [b]);+ expect(body(await call('watch_write_request', { request_id: b }))).toMatchObject({ watching: true, already_settled: false });+ expect((await inHome(() => drainWakes(getEngine()))).delivered).toBe(0);+ await getEngine().executeRaw("UPDATE persistence_requests SET state = 'failed', error_code = 'storage_error', completed_at = now() WHERE request_id = $1::uuid", [b]);+ const [x, y] = await inHome(() => Promise.all([drainWakes(getEngine()), drainWakes(getEngine())]));+ expect(x.delivered + y.delivered).toBe(1);+ expect(emits()).toHaveLength(2);+ expect(emits()[1]!.body.payload).toMatchObject({ request_id: b, state: 'failed' });+ for (const e of emits()) for (const leak of ['pg-settled', 'canary', 'alice-example']) expect(JSON.stringify(e.body)).not.toContain(leak);+ });++ test('write.settled: a foreign request id reads like a missing one and like get_write_request', async () => {+ await getEngine().executeRaw("INSERT INTO oauth_clients (client_id, client_name, scope) VALUES ('wk2-b', 'wk2-b', 'read write admin') ON CONFLICT DO NOTHING");+ const foreign = await writeNote('notes/pg-settled-c');+ const missing = randomUUID();+ const a = await call('watch_write_request', { request_id: foreign }, client('wk2-b'));+ const b = await call('watch_write_request', { request_id: missing }, client('wk2-b'));+ const g = await call('get_write_request', { request_id: foreign }, client('wk2-b'));+ expect(envelope(a, foreign)).toEqual(envelope(b, missing));+ expect(envelope(a, foreign)).toEqual(envelope(g, foreign));+ expect(fake.calls).toHaveLength(0);+ });++ test('forget: member remove ends the watch and two concurrent drainers send one forget', async () => {+ await getEngine().executeRaw("INSERT INTO access_members (id) VALUES ('alice-example') ON CONFLICT (id) DO UPDATE SET disabled_at = NULL, tombstoned_at = NULL");+ await getEngine().executeRaw("INSERT INTO oauth_clients (client_id, client_name, scope, member_id) VALUES ('wk2-m', 'wk2-m', 'read write admin', 'alice-example') ON CONFLICT (client_id) DO UPDATE SET member_id = 'alice-example'");+ writeConfig({ terms_url: 'https://example.com/terms', privacy_url: 'https://example.com/privacy' });+ const [job] = await getEngine().executeRaw<{ id: number }>(`INSERT INTO minion_jobs (submission_authority, name, queue, status, data)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'sync', 'default', 'active', '{"__submitter":"cli:test"}'::jsonb) RETURNING id`);+ const step = body(await call('watch_job', { id: Number(job!.id) }, client('wk2-m')));+ expect(step).toMatchObject({ agreement_required: true });+ expect(body(await call('accept_wakeshift_terms', { terms_version: step.terms_version }, client('wk2-m')))).toMatchObject({ accepted: true });+ expect(body(await call('watch_job', { id: Number(job!.id) }, client('wk2-m')))).toMatchObject({ watching: true });+ const user = fake.calls.find(c => c.path === '/event-subscriptions')!.body.call.user;+ await removeMember(getEngine(), 'alice-example');+ expect(await getEngine().executeRaw('SELECT state, last_error FROM wake_subscriptions')).toEqual([{ state: 'ended', last_error: 'principal_revoked' }]);+ const [x, y] = await inHome(() => Promise.all([drainWakes(getEngine()), drainWakes(getEngine())]));+ expect((x.forgotten ?? 0) + (y.forgotten ?? 0)).toBe(1);+ expect(fake.calls.filter(c => c.path === '/users/forget').map(c => c.body)).toEqual([{ user }]);+ });+});diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 86d67b1440..b98e838da3 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: 158, rebind: 2, rebuild: 3, discard: 9, schema_owned: 4 });+ expect(counts).toEqual({ carry: 162, 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.tsindex 811cf4d353..ab4f8a3245 100644--- a/test/helpers/fake-wakeshift.ts+++ b/test/helpers/fake-wakeshift.ts@@ -1,6 +1,6 @@/*** 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,+ * with the endpoints gbrain calls (subscribe, unsubscribe, end, emit for any event, manifest merge, users/forget). 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.*/@@ -75,6 +75,7 @@ export function startFakeWakeshift(rawKey: string): FakeWakeshift {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: [] });+ case '/users/forget': return Response.json({ forgotten: true });default: return Response.json({ error: { code: 'bad_request', message: `unknown path ${path}` } }, { status: 400 });}},diff --git a/test/operations-coverage-ledger.test.ts b/test/operations-coverage-ledger.test.tsindex d12ad26738..266d2bef74 100644--- a/test/operations-coverage-ledger.test.ts+++ b/test/operations-coverage-ledger.test.ts@@ -201,6 +201,9 @@ const LEDGER: Record<string, string> = {watch_job: 'test/wakeshift.serial.test.ts',list_watches: 'test/wakeshift.serial.test.ts',unwatch: 'test/wakeshift.serial.test.ts',+ watch_write_request: 'test/wakeshift-pr2.serial.test.ts',+ watch_cron: 'test/wakeshift-pr2.serial.test.ts',+ accept_wakeshift_terms: 'test/wakeshift-pr2.serial.test.ts',pause_job: 'test/jobs-lifecycle-ops.test.ts',resume_job: 'test/jobs-lifecycle-ops.test.ts',replay_job: 'test/jobs-lifecycle-ops.test.ts',diff --git a/test/publish-gates.test.ts b/test/publish-gates.test.tsindex d828fc055d..8bf1f131c3 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', 'watch_job', 'list_watches', 'unwatch'];+const GATED_OPS = ['list_skills', 'get_skill', 'get_skill_asset', 'list_brain_skillpack', 'advisor', 'set_memory_writeback', 'watch_job', 'list_watches', 'unwatch', 'watch_write_request', 'watch_cron', 'accept_wakeshift_terms'];function engineWithConfig(values: Record<string, string | null> | 'throws'): BrainEngine {return {diff --git a/test/remote-privacy-sweep.test.ts b/test/remote-privacy-sweep.test.tsindex 6157dbcb95..924e0e8706 100644--- a/test/remote-privacy-sweep.test.ts+++ b/test/remote-privacy-sweep.test.ts@@ -444,6 +444,9 @@ const EXPECTED_OUTCOME: Record<string, Outcome> = {watch_job: 'error',list_watches: 'error',unwatch: 'error',+ watch_write_request: 'error',+ watch_cron: 'error',+ accept_wakeshift_terms: 'error',cancel_job: 'error',retry_job: 'error',get_job_progress: 'error',diff --git a/test/wakeshift-pr2.serial.test.ts b/test/wakeshift-pr2.serial.test.tsnew file mode 100644index 0000000000..19f53bd178--- /dev/null+++ b/test/wakeshift-pr2.serial.test.ts@@ -0,0 +1,442 @@+/**+ * Wakeshift PR 2 on a repo-less PGLite brain against a fake Wakeshift (test/helpers/fake-wakeshift.ts):+ * gbrain.write.settled (committed, failed, recovering, a foreign id reading like get_write_request's not_found, and a+ * git-canonical source), gbrain.cron.finished (unregistered name, registered run, emit while off), the shared-brain+ * agreement step (enable needs links, accept, changed links re-ask, an unaccepted watch ends), forget on remove+ * (member remove, token revoke, client delete) and the gate staying inert when off.+ *+ * Serial: every test runs under withEnv with 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+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 } from '../src/core/wakeshift/drain.ts';+import { resetWakeshiftEnvKeyForTests } from '../src/core/wakeshift/config.ts';+import { wakeshiftManifest, wakeshiftManifestHash } from '../src/core/wakeshift/events.ts';+import { forgetWakePrincipal } from '../src/core/wakeshift/forget.ts';+import { WAKESHIFT_CONNECTOR_TERMS_URL, WAKESHIFT_PRIVACY_URL } from '../src/core/wakeshift/terms.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { removeMember } from '../src/core/access/members.ts';+import { mintLegacyToken, revokeLegacyTokenById } from '../src/core/token-mint.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { runWakeshift } from '../src/commands/wakeshift.ts';+import { wakeshiftEntry } from '../src/commands/doctor/checks/wakeshift.ts';+import type { DoctorContext } from '../src/commands/doctor/context.ts';+import { startFakeWakeshift, type FakeWakeshift } from './helpers/fake-wakeshift.ts';+import { withEnv } from './helpers/with-env.ts';++const KEY = encodeWakeshiftKey(Buffer.alloc(32, 21));+const PR2_OPS = ['watch_write_request', 'watch_cron', 'accept_wakeshift_terms', 'watch_job', 'list_watches', 'unwatch'];+const TERMS = 'https://example.com/terms';+const PRIVACY = 'https://example.com/privacy';+let engine: PGLiteEngine;+let fake: FakeWakeshift;+let home: string;+let writer: Awaited<ReturnType<typeof registerLocalWriter>>;++const inHome = <T>(fn: () => Promise<T>) => withEnv({ GBRAIN_HOME: home, WAKESHIFT_API_KEY: undefined }, async () => {+ resetWakeshiftEnvKeyForTests();+ return fn();+});++function writeConfig(wakeshift: Record<string, unknown> | null): void {+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...(wakeshift ? { wakeshift } : {}) }), { mode: 0o600 });+}+const fileConfig = () => JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8'));++beforeAll(async () => {+ home = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-pr2-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'wakeshift.key'), KEY + '\n', { mode: 0o600 });+ fake = startFakeWakeshift(KEY);+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ writer = await inHome(() => registerLocalWriter(engine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null }));+}, 120_000);++afterAll(async () => {+ fake.stop();+ await disposePersistenceConsumer(engine);+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+});++beforeEach(async () => {+ writeConfig({ enabled: true, url: fake.url, manifest_hash: wakeshiftManifestHash() });+ fake.calls.length = 0;+ fake.respond.clear();+ for (const table of ['wake_subscriptions', 'wake_crons', 'wake_cron_runs', 'wake_terms_acceptances', 'wake_forgets', 'minion_jobs']) await engine.executeRaw(`DELETE FROM ${table}`);+ await engine.executeRaw('UPDATE access_members SET tombstoned_at = COALESCE(tombstoned_at, now()), disabled_at = COALESCE(disabled_at, now())');+});++const log = { info() {}, warn() {}, error() {} };+const stdio = { remote: true, transport: 'stdio' as const, sourceId: 'default', config: { engine: 'pglite' }, logger: log, mcpCaller: { client: 'claude-code' } };+const client = (clientId: string, scopes = ['admin', 'write', 'read']) => ({ remote: true, transport: 'http' as const, sourceId: 'default', config: { engine: 'pglite' }, logger: log,+ auth: { token: 't', clientId, principal: { kind: 'oauth_client' as const, id: clientId }, scopes } });+const doctorChecks = () => inHome(async () => {+ const out = await wakeshiftEntry.run({ engine, args: [], jsonOutput: true, fastMode: false, doFix: false, dryRun: false } as unknown as DoctorContext);+ if (!Array.isArray(out)) throw new Error('the wakeshift doctor entry stopped doctor');+ return out;+});+const call = (op: string, params: Record<string, unknown>, ctx: object = stdio) => inHome(() => dispatchToolCall(engine, op, params, ctx as never));+const drain = () => inHome(() => drainWakes(engine));+const body = (r: { content: Array<{ text: string }> }) => JSON.parse(r.content[0]!.text);+const envelope = (r: { content: Array<{ text: string }> }, id: string) => { const { notices: _, ...rest } = JSON.parse(r.content[0]!.text.replaceAll(id, 'ID')); return rest; };+const emits = () => fake.calls.filter(c => c.path === '/events/emit');+const paths = (p: string) => fake.calls.filter(c => c.path === p);++async function addClient(id: string, member?: string): Promise<void> {+ await engine.executeRaw(`INSERT INTO oauth_clients (client_id, client_name, scope, member_id) VALUES ($1, $1, 'read write admin', $2)+ ON CONFLICT (client_id) DO UPDATE SET deleted_at = NULL, member_id = EXCLUDED.member_id`, [id, member ?? null]);+}++async function addMember(id: string): Promise<void> {+ await engine.executeRaw("INSERT INTO access_members (id) VALUES ($1) ON CONFLICT (id) DO UPDATE SET disabled_at = NULL, tombstoned_at = NULL", [id]);+}++async function seedJob(status = 'active'): Promise<number> {+ const rows = await engine.executeRaw<{ id: number }>(+ `INSERT INTO minion_jobs (submission_authority, name, queue, status, data, started_at)+ VALUES ('{"version":1,"kind":"application"}'::jsonb, 'sync', 'default', $1, '{"__submitter":"cli:test"}'::jsonb, now()) RETURNING id`, [status]);+ return Number(rows[0]!.id);+}++/** A real put_page over stdio on this repo-less brain; returns the committed request's id. */+async function writeNote(slug: string): Promise<string> {+ const requestId = randomUUID();+ const r = await call('put_page', { slug, content: `---\ntitle: Private canary\n---\n\nalice-example canary body for ${slug}.\n`, request_id: requestId });+ expect(r.isError).toBeFalsy();+ await disposePersistenceConsumer(engine);+ return requestId;+}++async function cli(args: string[]): Promise<{ out: string; err: string; error?: unknown }> {+ const [log0, err0] = [console.log, console.error];+ let out = '', err = '';+ console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };+ console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };+ try { await inHome(() => runWakeshift(engine, args)); return { out, err }; } catch (error) { return { out, err, error }; } finally { console.log = log0; console.error = err0; }+}++describe('gbrain.write.settled', () => {+ test('a committed write wakes during the watch call with a pointer payload and no slug or text', async () => {+ const id = await writeNote('notes/settled-a');+ const r = await call('watch_write_request', { request_id: id, harness: 'claude-code' });+ expect(r.isError).toBeFalsy();+ expect(body(r)).toMatchObject({ watching: true, request_id: id, event: 'gbrain.write.settled', state: 'committed', already_settled: true });+ const sub = paths('/event-subscriptions')[0]!;+ expect(sub.body).toMatchObject({ name: 'gbrain.write.settled', arguments: { request_id: id }, once: true, ttl: '7d' });+ expect(emits()).toHaveLength(1);+ const e = emits()[0]!.body;+ expect(e.payload).toMatchObject({ request_id: id, state: 'committed', operation: 'put_page', source_id: 'default', next: `get_write_request ${id}` });+ expect(e.text).toBe(`gbrain: write request ${id} (put_page) committed. Call get_write_request ${id} for the receipt.`);+ expect(e.id).toMatch(new RegExp(`^gbrain\\.write\\.settled:${id}:committed:\\d+:\\d+:[0-9a-f]{12}$`));+ const raw = JSON.stringify(e);+ for (const leak of ['notes/settled-a', 'canary', 'alice-example', 'Private']) expect(raw).not.toContain(leak);+ expect((await drain()).delivered).toBe(0);+ });++ test('a pending write wakes once it fails; a committed write with a live recovery record waits', async () => {+ const id = await writeNote('notes/settled-b');+ await engine.executeRaw("UPDATE persistence_requests SET state = 'queued' WHERE request_id = $1::uuid", [id]);+ expect(body(await call('watch_write_request', { request_id: id }))).toMatchObject({ watching: true, state: 'queued', already_settled: false });+ expect((await drain()).delivered).toBe(0);+ await engine.executeRaw(`UPDATE persistence_requests SET state = 'committed', recovery = '{"kind":"test"}'::jsonb WHERE request_id = $1::uuid`, [id]);+ expect((await drain()).delivered).toBe(0);+ await engine.executeRaw("UPDATE persistence_requests SET state = 'failed', recovery = NULL, error_code = 'storage_error', completed_at = now() WHERE request_id = $1::uuid", [id]);+ expect((await drain()).delivered).toBe(1);+ expect(emits()).toHaveLength(1);+ expect(emits()[0]!.body.payload).toMatchObject({ request_id: id, state: 'failed', next: `get_write_request ${id}` });+ expect((await drain()).delivered).toBe(0);+ });++ test('a foreign request id reads exactly like a missing one and like get_write_request, and nothing is sent', async () => {+ await addClient('client-w');+ const foreign = await writeNote('notes/settled-c');+ const missing = randomUUID();+ const a = await call('watch_write_request', { request_id: foreign }, client('client-w'));+ const b = await call('watch_write_request', { request_id: missing }, client('client-w'));+ const g = await call('get_write_request', { request_id: foreign }, client('client-w'));+ expect(a.isError).toBe(true);+ expect(envelope(a, foreign)).toEqual(envelope(b, missing));+ expect(envelope(a, foreign)).toEqual(envelope(g, foreign));+ expect(envelope(a, foreign).code ?? envelope(a, foreign).error).toBe('not_found');+ expect(fake.calls).toHaveLength(0);+ });++ test('a watch on a git-canonical source wakes when the write commits to the checkout', async () => {+ const repo = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-repo-'));+ const gitEngine = new PGLiteEngine();+ await gitEngine.connect({});+ await gitEngine.initSchema();+ try {+ await gitEngine.setConfig('sync.repo_path', repo);+ await inHome(() => registerLocalWriter(gitEngine, 'stdio', { sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null }));+ const id = randomUUID();+ const put = await inHome(() => dispatchToolCall(gitEngine, 'put_page', { slug: 'notes/settled-git', content: '---\ntitle: Git\n---\n\nbody.\n', request_id: id }, stdio as never));+ expect(put.isError).toBeFalsy();+ expect(existsSync(join(repo, 'notes', 'settled-git.md'))).toBe(true);+ const r = await inHome(() => dispatchToolCall(gitEngine, 'watch_write_request', { request_id: id }, stdio as never));+ expect(body(r)).toMatchObject({ watching: true, state: 'committed', already_settled: true });+ expect(emits()).toHaveLength(1);+ expect(emits()[0]!.body.payload).toMatchObject({ request_id: id, state: 'committed', operation: 'put_page' });+ expect(JSON.stringify(emits()[0]!.body)).not.toContain('settled-git');+ } finally {+ await disposePersistenceConsumer(gitEngine);+ await gitEngine.disconnect();+ rmSync(repo, { recursive: true, force: true });+ }+ }, 120_000);++ test('list_watches names the target generically, and unwatch takes a request_id, a cron or a watch id', async () => {+ const id = await writeNote('notes/settled-d');+ await engine.executeRaw("UPDATE persistence_requests SET state = 'queued' WHERE request_id = $1::uuid", [id]);+ await call('watch_write_request', { request_id: id });+ const job = await seedJob();+ await call('watch_job', { id: job });+ await engine.executeRaw("INSERT INTO wake_crons (name) VALUES ('nightly-digest')");+ await call('watch_cron', { name: 'nightly-digest' });+ const listed = body(await call('list_watches', {})).watches;+ expect(listed.map((w: Record<string, unknown>) => [w.event, w.target])).toEqual([+ ['gbrain.cron.finished', 'nightly-digest'], ['gbrain.job.finished', String(job)], ['gbrain.write.settled', id]]);+ expect(listed[1].job).toBe(job);+ expect(listed[2].request_id).toBe(id);+ expect(body(await call('unwatch', { request_id: id }))).toMatchObject({ request_id: id, ended: 1 });+ expect(body(await call('unwatch', { cron: 'Nightly Digest' }))).toMatchObject({ cron: 'nightly-digest', ended: 1 });+ expect(body(await call('unwatch', { watch: listed[1].watch }))).toMatchObject({ ended: 1 });+ expect((await call('unwatch', { job, cron: 'x' })).isError).toBe(true);+ await engine.executeRaw("UPDATE persistence_requests SET state = 'committed' WHERE request_id = $1::uuid", [id]);+ await drain();+ expect(emits()).toHaveLength(0);+ });+});++describe('gbrain.cron.finished', () => {+ test('an unregistered name reads not_found and nothing reaches Wakeshift', async () => {+ const r = await call('watch_cron', { name: 'never-added' });+ expect(r.isError).toBe(true);+ expect(body(r).code ?? body(r).error).toBe('not_found');+ expect(fake.calls).toHaveLength(0);+ });++ test('a registered cron wakes its watcher once on the next run, not on an earlier one', async () => {+ expect((await cli(['cron', 'add', 'Nightly Digest'])).out).toContain('stored as nightly-digest');+ expect((await cli(['emit', 'cron.finished', '--name', 'nightly-digest', '--status', 'ok'])).err).toBe('');+ await engine.executeRaw("UPDATE wake_cron_runs SET finished_at = now() - interval '1 minute'");+ const r = await call('watch_cron', { name: 'nightly-digest' });+ expect(body(r)).toMatchObject({ watching: true, cron: 'nightly-digest', event: 'gbrain.cron.finished', wakes: 'once, on the next run' });+ expect(paths('/event-subscriptions')[0]!.body).toMatchObject({ name: 'gbrain.cron.finished', arguments: { name: 'nightly-digest' }, once: true, ttl: '7d' });+ expect((await drain()).delivered).toBe(0);+ const emitted = await cli(['emit', 'cron.finished', '--name', 'nightly-digest', '--status', 'failed']);+ expect(emitted.error).toBeUndefined();+ expect(fake.calls.filter(c => c.path === '/events/emit')).toHaveLength(0);+ expect((await drain()).delivered).toBe(1);+ expect((await drain()).delivered).toBe(0);+ const e = emits()[0]!.body;+ expect(e.payload).toMatchObject({ name: 'nightly-digest', status: 'failed', next: 'watch_cron nightly-digest to hear about its next run' });+ expect(e.payload.finished_at).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ expect(e.id).toMatch(/^gbrain\.cron\.finished:nightly-digest:\d+:failed:\d+:[0-9a-f]{12}$/);+ const listed = await cli(['cron', 'list', '--json']);+ expect(JSON.parse(listed.out).crons).toMatchObject([{ name: 'nightly-digest', last_status: 'failed' }]);+ });++ test('emit while reporting back is off exits 0 with one stderr line, records nothing and sends nothing', async () => {+ writeConfig({ enabled: false, url: fake.url });+ await engine.executeRaw("INSERT INTO wake_crons (name) VALUES ('nightly-digest')");+ process.exitCode = 0;+ const r = await cli(['emit', 'cron.finished', '--name', 'nightly-digest', '--status', 'ok']);+ expect(r.error).toBeUndefined();+ expect(process.exitCode ?? 0).toBe(0);+ expect(r.err.trim().split('\n')).toHaveLength(1);+ expect(r.err).toContain('reporting back is off');+ expect(await engine.executeRaw('SELECT 1 FROM wake_cron_runs')).toHaveLength(0);+ expect(fake.calls).toHaveLength(0);+ });++ test('an unregistered emit is recorded with a stderr hint, and doctor names it', async () => {+ const r = await cli(['emit', 'cron.finished', '--name', 'typo-cron', '--status', 'ok']);+ expect(r.err).toContain('gbrain wakeshift cron add typo-cron');+ const checks = await doctorChecks();+ expect(checks[0]).toMatchObject({ status: 'warn', details: { unregistered_crons_7d: ['typo-cron'] } });+ });+});++describe('shared-brain terms', () => {+ test('enable on a brain with members refuses without links, and with links stores them and the manifest hash', async () => {+ await addMember('alice-example');+ writeConfig(null);+ const refused = await cli(['enable', '--yes', '--url', fake.url]);+ expect(String((refused.error as Error)?.message)).toContain('live access member');+ expect(JSON.stringify(refused.error)).toContain('--terms-url');+ expect(fake.calls).toHaveLength(0);+ const bad = await cli(['enable', '--yes', '--url', fake.url, '--terms-url', 'http://example.com/terms', '--privacy-url', PRIVACY]);+ expect(bad.error).toBeDefined();+ const ok = await cli(['enable', '--yes', '--url', fake.url, '--terms-url', TERMS, '--privacy-url', PRIVACY, '--json']);+ expect(ok.error).toBeUndefined();+ expect(fileConfig().wakeshift).toEqual({ enabled: true, url: fake.url, terms_url: TERMS, privacy_url: PRIVACY, manifest_hash: wakeshiftManifestHash() });+ expect(fake.calls.find(c => c.path === '/manifest/merge')!.body.events.map((e: { name: string }) => e.name))+ .toEqual(['gbrain.job.finished', 'gbrain.write.settled', 'gbrain.cron.finished']);+ expect(JSON.parse(ok.out).terms_version).toMatch(/^[0-9a-f]{16}$/);+ const again = await cli(['enable', '--yes', '--url', fake.url]);+ expect(again.error).toBeUndefined();+ });++ test('the first watch returns the agreement step, accept records it, and the watch then subscribes and wakes', async () => {+ await addMember('alice-example');+ await addClient('client-m', 'alice-example');+ writeConfig({ enabled: true, url: fake.url, terms_url: TERMS, privacy_url: PRIVACY });+ const job = await seedJob();+ const step = body(await call('watch_job', { id: job }, client('client-m')));+ expect(step).toMatchObject({ watching: false, agreement_required: true, operator_terms_url: TERMS, operator_privacy_url: PRIVACY,+ wakeshift_connector_terms_url: WAKESHIFT_CONNECTOR_TERMS_URL, wakeshift_privacy_url: WAKESHIFT_PRIVACY_URL,+ next: { tool: 'accept_wakeshift_terms', arguments: { terms_version: step.terms_version } } });+ expect(step.wakeshift_disclosure).toContain('Clawvisor Inc.');+ expect(fake.calls).toHaveLength(0);+ expect(body(await call('accept_wakeshift_terms', { terms_version: '0000000000000000' }, client('client-m')))).toMatchObject({ agreement_required: true });+ expect(body(await call('accept_wakeshift_terms', { terms_version: step.terms_version }, client('client-m')))).toMatchObject({ accepted: true });+ expect(await engine.executeRaw('SELECT principal_key FROM wake_terms_acceptances')).toEqual([{ principal_key: 'member:alice-example' }]);+ expect(body(await call('watch_job', { id: job }, client('client-m')))).toMatchObject({ watching: true, job });+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1", [job]);+ expect((await drain()).delivered).toBe(1);+ writeConfig({ enabled: true, url: fake.url, terms_url: 'https://example.com/terms-v2', privacy_url: PRIVACY });+ const reask = body(await call('watch_job', { id: job }, client('client-m')));+ expect(reask).toMatchObject({ agreement_required: true, operator_terms_url: 'https://example.com/terms-v2' });+ expect(reask.terms_version).not.toBe(step.terms_version);+ });++ test('a watch whose principal never accepted the current terms ends with terms_not_accepted instead of waking', async () => {+ await addClient('client-n');+ const job = await seedJob();+ expect(body(await call('watch_job', { id: job }, client('client-n')))).toMatchObject({ watching: true });+ await addMember('alice-example');+ writeConfig({ enabled: true, url: fake.url, terms_url: TERMS, privacy_url: PRIVACY });+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed', finished_at = now() WHERE id = $1", [job]);+ expect(await drain()).toMatchObject({ delivered: 0, ended: 1 });+ expect(emits()).toHaveLength(0);+ expect(paths('/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: 'terms_not_accepted' });+ });++ test('owner-only brains skip the step', async () => {+ const job = await seedJob();+ expect(body(await call('watch_job', { id: job }, stdio))).toMatchObject({ watching: true });+ expect(body(await call('accept_wakeshift_terms', { terms_version: '0000000000000000' }, stdio))).toMatchObject({ required: false });+ });+});++describe('forget on remove', () => {+ test('member remove ends its watches, drops its acceptance and the drainer sends one forget', async () => {+ await addMember('alice-example');+ await addClient('client-f', 'alice-example');+ writeConfig({ enabled: true, url: fake.url, terms_url: TERMS, privacy_url: PRIVACY });+ const step = body(await call('watch_job', { id: await seedJob() }, client('client-f')));+ await call('accept_wakeshift_terms', { terms_version: step.terms_version }, client('client-f'));+ expect(body(await call('watch_job', { id: await seedJob() }, client('client-f')))).toMatchObject({ watching: true });+ const user = paths('/event-subscriptions')[0]!.body.call.user;+ fake.calls.length = 0;+ await removeMember(engine, 'alice-example');+ expect(fake.calls).toHaveLength(0);+ expect(await engine.executeRaw('SELECT state, last_error FROM wake_subscriptions')).toEqual([{ state: 'ended', last_error: 'principal_revoked' }]);+ expect(await engine.executeRaw('SELECT 1 FROM wake_terms_acceptances')).toHaveLength(0);+ expect(await drain()).toMatchObject({ forgotten: 1 });+ expect(paths('/users/forget').map(c => c.body)).toEqual([{ user }]);+ expect(await engine.executeRaw('SELECT state FROM wake_forgets')).toEqual([{ state: 'done' }]);+ expect((await drain()).forgotten ?? 0).toBe(0);+ });++ test('token revoke ends the token\'s watches and queues its forget, with reporting back off and no network', async () => {+ const minted = await mintLegacyToken(engine, { name: 'wake-token', takesHolders: ['world'], scopes: ['read', 'write', 'admin'] });+ const ctx = { remote: true, transport: 'http' as const, sourceId: 'default', config: { engine: 'pglite' }, logger: log,+ auth: { token: 't', clientId: minted.id, principal: { kind: 'legacy_token' as const, id: minted.id }, scopes: ['read', 'write', 'admin'] } };+ expect(body(await call('watch_job', { id: await seedJob() }, ctx))).toMatchObject({ watching: true });+ writeConfig({ enabled: false, url: fake.url });+ fake.calls.length = 0;+ expect(await revokeLegacyTokenById(sqlQueryForEngine(engine), minted.id)).toBe(true);+ expect(await engine.executeRaw('SELECT state, last_error FROM wake_subscriptions')).toEqual([{ state: 'ended', last_error: 'principal_revoked' }]);+ expect(await engine.executeRaw("SELECT state FROM wake_forgets")).toEqual([{ state: 'pending' }]);+ expect(await drain()).toMatchObject({ skipped: 'off' });+ expect(fake.calls).toHaveLength(0);+ writeConfig({ enabled: true, url: fake.url });+ expect(await drain()).toMatchObject({ forgotten: 1 });+ });++ test('OAuth client delete: the revoke-client hook ends and queues; a delete the hook never saw is caught at emit time', async () => {+ await addClient('client-d1');+ await addClient('client-d2');+ const [j1, j2] = [await seedJob(), await seedJob()];+ await call('watch_job', { id: j1 }, client('client-d1'));+ await call('watch_job', { id: j2 }, client('client-d2'));+ await engine.executeRaw("DELETE FROM oauth_clients WHERE client_id = 'client-d1'");+ expect(await inHome(() => forgetWakePrincipal(sqlQueryForEngine(engine), { kind: 'oauth_client', id: 'client-d1' }))).toEqual({ ended: 1, queued: 1 });+ await engine.executeRaw("UPDATE oauth_clients SET deleted_at = now() WHERE client_id = 'client-d2'");+ await engine.executeRaw("UPDATE minion_jobs SET status = 'completed', finished_at = now()");+ expect(await drain()).toMatchObject({ delivered: 0, ended: 1, forgotten: 1 });+ expect(emits()).toHaveLength(0);+ expect(await drain()).toMatchObject({ forgotten: 1 });+ expect(paths('/users/forget')).toHaveLength(2);+ expect(new Set(paths('/users/forget').map(c => c.body.user)).size).toBe(2);+ });++ test('a refused forget is retried on the schedule and then dies', async () => {+ await engine.executeRaw("INSERT INTO wake_forgets (wake_user) VALUES ('0123456789abcdef0123456789abcdef')");+ fake.respond.set('/users/forget', () => ({ status: 503, body: { error: { code: 'unavailable', message: 'down' } } }));+ await drain();+ const [r1] = 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_forgets");+ expect(r1).toMatchObject({ state: 'pending', attempts: 1, delay: 30 });+ fake.respond.set('/users/forget', () => ({ status: 400, body: { error: { code: 'bad_request', message: 'no' } } }));+ await engine.executeRaw("UPDATE wake_forgets SET next_attempt_at = now() - interval '1 second'");+ await drain();+ expect(await engine.executeRaw('SELECT state, last_error FROM wake_forgets')).toEqual([{ state: 'dead', last_error: 'bad_request' }]);+ });+});++describe('status, doctor and the gate', () => {+ test('status and doctor say when the published manifest is older than this build', async () => {+ writeConfig({ enabled: true, url: fake.url, manifest_hash: 'feedfacefeedface' });+ const st = JSON.parse((await cli(['status', '--json'])).out);+ expect(st.manifest).toEqual({ current: false, fix: 'gbrain wakeshift enable' });+ const checks = await doctorChecks();+ expect(checks[0]).toMatchObject({ status: 'warn', details: { manifest_current: false } });+ expect(checks[0]!.message).toContain('gbrain wakeshift enable');+ writeConfig({ enabled: true, url: fake.url, manifest_hash: wakeshiftManifestHash() });+ expect(JSON.parse((await cli(['status', '--json'])).out).manifest).toEqual({ current: true });+ });++ test('doctor warns about a queued forget older than a day', async () => {+ await engine.executeRaw("INSERT INTO wake_forgets (wake_user, created_at) VALUES ('0123456789abcdef0123456789abcdef', now() - interval '2 days')");+ const checks = await doctorChecks();+ expect(checks[0]).toMatchObject({ status: 'warn', details: { stale_forgets: 1 } });+ });++ test('the manifest carries both new events, personal and deleted on delivery', () => {+ const events = wakeshiftManifest().events as Array<Record<string, any>>;+ for (const name of ['gbrain.write.settled', 'gbrain.cron.finished']) {+ const e = events.find(x => x.name === name)!;+ expect(e).toMatchObject({ personal: true, delete_on_delivery: true });+ expect(e.payload.additionalProperties).toBe(false);+ expect(Object.keys(e.payload.properties)).not.toContain('slug');+ }+ });++ test('gate off: every watch tool is hidden and refuses, and nothing is fetched', async () => {+ writeConfig({ enabled: false, url: fake.url });+ const disabled = await inHome(() => disabledOpsForPublishGates(engine, null, { transport: 'stdio' }));+ for (const op of PR2_OPS) expect(disabled.has(op)).toBe(true);+ await engine.executeRaw("INSERT INTO wake_crons (name) VALUES ('nightly-digest')");+ for (const [op, params] of [['watch_write_request', { request_id: randomUUID() }], ['watch_cron', { name: 'nightly-digest' }], ['accept_wakeshift_terms', { terms_version: '0000000000000000' }]] as const) {+ const r = await call(op, params);+ expect(r.isError).toBe(true);+ expect(r.content[0]!.text).toContain('wakeshift_not_enabled');+ }+ expect(fake.calls).toHaveLength(0);+ });+});diff --git a/test/wakeshift.serial.test.ts b/test/wakeshift.serial.test.tsindex 10327e3152..8f7eb9023f 100644--- a/test/wakeshift.serial.test.ts+++ b/test/wakeshift.serial.test.ts@@ -14,6 +14,7 @@ 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 { wakeshiftManifestHash } from '../src/core/wakeshift/events.ts';import { drainWakes, WAKE_MAX_ATTEMPTS } from '../src/core/wakeshift/drain.ts';import { readWakeshiftKey, resetWakeshiftEnvKeyForTests } from '../src/core/wakeshift/config.ts';import { loadConfig } from '../src/core/config.ts';@@ -286,7 +287,7 @@ describe('failure schedule', () => {expect(rows).toEqual([{ target: String(a), state: 'ended', last_error: 'unmatched' }, { target: String(b), state: 'delivered', last_error: null }]);});- test('a member added after enable pauses reporting back: watch_job refuses and the drainer sends nothing', async () => {+ test('a member added after enable without terms links: watch_job refuses and the drainer ends the open watch unaccepted', async () => {const id = await seedJob('active');await dispatchToolCall(engine, 'watch_job', { id }, stdio);await finish(id);@@ -298,8 +299,10 @@ describe('failure schedule', () => {const env = JSON.parse(r.content[0]!.text);expect(env.code ?? env.error).toBe('wakeshift_shared_brain');expect(JSON.stringify(env)).not.toMatch(/\d+ live access member/);- expect(await drainWakes(engine)).toMatchObject({ skipped: 'shared' });+ expect(await drainWakes(engine)).toMatchObject({ delivered: 0, ended: 1 });expect(emits()).toHaveLength(0);+ const [row] = await engine.executeRaw<{ state: string; last_error: string }>('SELECT state, last_error FROM wake_subscriptions');+ expect(row).toMatchObject({ state: 'ended', last_error: 'terms_not_accepted' });expect(fake.calls.filter(c => c.path === '/event-subscriptions')).toHaveLength(1);} finally {await engine.executeRaw("DELETE FROM access_members WHERE id = 'alice-example'");@@ -413,7 +416,7 @@ describe('gbrain wakeshift', () => {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(cfg.wakeshift).toEqual({ enabled: true, url: fake.url, manifest_hash: wakeshiftManifestHash() });expect(JSON.stringify(cfg)).not.toContain(KEY.slice(4));const st = await cli(['status', '--json']);const doc = JSON.parse(st.out);@@ -500,7 +503,7 @@ describe('gbrain wakeshift', () => {globalThis.fetch = realFetch;}expect([...new Set(hosts)]).toEqual(['https://app.wakeshift.ai']);- expect(JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')).wakeshift).toEqual({ enabled: true });+ expect(JSON.parse(readFileSync(join(home, '.gbrain', 'config.json'), 'utf8')).wakeshift).toEqual({ enabled: true, manifest_hash: wakeshiftManifestHash() });});test('enable without --yes off a terminal refuses through consent, sending nothing', async () => {