Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(wakeshift): setup row, coaching notice, thin-client watch route, setup openclaw --wakeshift (PR 2 surface lane)

garrytanc665b0a095fd
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index d9bbee0bb4..126f834512 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -3182,6 +3182,16 @@ More: [docs/guides/write-refusals.md#on_behalf_of_not_permitted](../../docs/guid
More: [docs/guides/write-refusals.md#on_behalf_of_unknown_member](../../docs/guides/write-refusals.md#on_behalf_of_unknown_member)
+### openclaw_not_found
+
+<a id="openclaw_not_found"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| gbrain setup openclaw --wakeshift found no openclaw on PATH, so Wakeshift's OpenClaw plugin was not installed; nothing changed. | The plugin installs through OpenClaw's own installer where the gateway runs, so setup never writes OpenClaw's plugin directory itself. | Run gbrain setup openclaw --wakeshift where the OpenClaw gateway runs (in its container, if it is in one). | agent | `repeat the read that failed` | 1 | no |
+
+More: [docs/mcp/OPENCLAW.md#have-gbrain-report-back-to-this-chat](../../docs/mcp/OPENCLAW.md#have-gbrain-report-back-to-this-chat)
+
### origin_twin_mass_merge_refused
<a id="origin_twin_mass_merge_refused"></a>
diff --git a/docs/guides/grok-bot.md b/docs/guides/grok-bot.md
index 4e4e131041..febe79ea16 100644
--- a/docs/guides/grok-bot.md
+++ b/docs/guides/grok-bot.md
@@ -148,6 +148,18 @@ with provenance, and verify active recall. For deletion, use the returned fact
ID with `forget`; retained history and older backups need separate consideration.
See the [worked round trip](in-agent-setup.md#3-prove-the-first-memory-round-trip).
+## Have gbrain report back to this chat
+
+When the brain owner has turned on [reporting back](wakeshift.md)
+(`gbrain wakeshift enable` on the brain host), the Bot can ask to be woken when
+a long job finishes instead of polling. Through the thin CLI:
+`<launcher> wakeshift watch job <id> --harness grok-bot` (also `watch write
+<request_id>` and `watch cron <name>`). It calls the brain's `watch_job` over
+MCP; Wakeshift's instructions, when it sends any, are the last line of output.
+Wakeshift wakes Grok Bot only while it waits for events in the foreground;
+otherwise the wake arrives with its next gbrain call. Without Wakeshift, wait
+with `<launcher> jobs wait <id>`.
+
## Local installation maintenance and recovery
These steps apply when GBrain runs inside the Bot. For a hosted connection,
diff --git a/docs/guides/muse.md b/docs/guides/muse.md
index efb52a694e..5f310e8ee0 100644
--- a/docs/guides/muse.md
+++ b/docs/guides/muse.md
@@ -168,6 +168,16 @@ are part of the [hosted setup](hosted-harness-access.md); finish them through th
actual product's supported flow. A denied request is a reported setup boundary,
not a reason to try another route around it.
+## Have gbrain report back to this chat
+
+Unverified in Muse. When the brain owner has turned on
+[reporting back](wakeshift.md) (`gbrain wakeshift enable` on the brain host),
+the thin CLI can ask to wake the conversation when a long job finishes:
+`<launcher> wakeshift watch job <id> --harness muse`. Wakeshift doesn't list
+Muse as an agent it can wake, and Sentinel controls Muse's egress, so expect
+the wake at best on Muse's next gbrain call. Without Wakeshift, wait with
+`<launcher> jobs wait <id>`.
+
## Local installation maintenance, backup, and recovery
These steps apply when GBrain runs inside Muse. A hosted connection instead
diff --git a/docs/guides/wakeshift.md b/docs/guides/wakeshift.md
index 1a2b4c8e00..49893c9288 100644
--- a/docs/guides/wakeshift.md
+++ b/docs/guides/wakeshift.md
@@ -109,3 +109,11 @@ Repo-less brains work the same way. Watches are operational database rows, not b
- **`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).
+
+## From a thin client
+
+On a thin client (`gbrain init --mcp-only`), `gbrain wakeshift watch job <id>` (also `watch write <request_id>` and `watch cron <name>`) calls the brain host's watch tool over MCP and prints Wakeshift's instructions as the last line; `--session-key`, `--harness` and `--conversation-id` pass through per call and are never saved.
+
+## OpenClaw
+
+`gbrain setup openclaw --wakeshift` installs Wakeshift's OpenClaw plugin (pinned `@wakeshift/[email protected]`) after consent and prints Wakeshift's `allowNetworkHooks` question without answering it ([OpenClaw guide](../mcp/OPENCLAW.md#have-gbrain-report-back-to-this-chat)).
diff --git a/docs/mcp/OPENCLAW.md b/docs/mcp/OPENCLAW.md
index 9be826b9dd..4598071ef9 100644
--- a/docs/mcp/OPENCLAW.md
+++ b/docs/mcp/OPENCLAW.md
@@ -130,6 +130,30 @@ On a managed brain, scripts commit the files they write with
keeps it current
([scripts and the managed checkout](../guides/shared-checkout-git.md#scripts-and-the-managed-checkout)).
+## Have gbrain report back to this chat
+
+When the brain owner has turned on [reporting back](../guides/wakeshift.md)
+(`gbrain wakeshift enable` on the brain host), gbrain can wake an OpenClaw
+session when a job, a pending write or a cron run it watches finishes. OpenClaw
+needs Wakeshift's own plugin for that. Where the gateway runs (in its container,
+if it's in one):
+
+```bash
+gbrain setup openclaw --wakeshift
+```
+
+It asks for consent, then runs OpenClaw's installer for the pinned
+`@wakeshift/[email protected]` (`openclaw plugins install npm:@wakeshift/[email protected] --force --accept-capabilities`,
+then `openclaw plugins enable wakeshift --accept-capabilities`) and checks that
+the plugin loads. The plugin turns on OpenClaw's hooks endpoint with its own
+token. On a gateway that listens beyond this computer, setup prints
+Wakeshift's question about that endpoint; agreeing is yours to do
+(`openclaw config set plugins.entries.wakeshift.config.allowNetworkHooks true --strict-json`),
+and gbrain never sets it. The session shows a note starting `Wakeshift: connected`
+after its first watch. `gbrain doctor` warns when the installed plugin is not
+the pinned version. Remove it with
+`openclaw wakeshift reset && openclaw plugins uninstall wakeshift --force`.
+
## Verify
`openclaw mcp list` should show `gbrain`. Then start an agent turn and ask it
diff --git a/llms-full.txt b/llms-full.txt
index d4fee13208..b781c0ebe7 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -733,6 +733,18 @@ with provenance, and verify active recall. For deletion, use the returned fact
ID with `forget`; retained history and older backups need separate consideration.
See the [worked round trip](in-agent-setup.md#3-prove-the-first-memory-round-trip).
+## Have gbrain report back to this chat
+
+When the brain owner has turned on [reporting back](wakeshift.md)
+(`gbrain wakeshift enable` on the brain host), the Bot can ask to be woken when
+a long job finishes instead of polling. Through the thin CLI:
+`<launcher> wakeshift watch job <id> --harness grok-bot` (also `watch write
+<request_id>` and `watch cron <name>`). It calls the brain's `watch_job` over
+MCP; Wakeshift's instructions, when it sends any, are the last line of output.
+Wakeshift wakes Grok Bot only while it waits for events in the foreground;
+otherwise the wake arrives with its next gbrain call. Without Wakeshift, wait
+with `<launcher> jobs wait <id>`.
+
## Local installation maintenance and recovery
These steps apply when GBrain runs inside the Bot. For a hosted connection,
@@ -961,6 +973,16 @@ are part of the [hosted setup](hosted-harness-access.md); finish them through th
actual product's supported flow. A denied request is a reported setup boundary,
not a reason to try another route around it.
+## Have gbrain report back to this chat
+
+Unverified in Muse. When the brain owner has turned on
+[reporting back](wakeshift.md) (`gbrain wakeshift enable` on the brain host),
+the thin CLI can ask to wake the conversation when a long job finishes:
+`<launcher> wakeshift watch job <id> --harness muse`. Wakeshift doesn't list
+Muse as an agent it can wake, and Sentinel controls Muse's egress, so expect
+the wake at best on Muse's next gbrain call. Without Wakeshift, wait with
+`<launcher> jobs wait <id>`.
+
## Local installation maintenance, backup, and recovery
These steps apply when GBrain runs inside Muse. A hosted connection instead
diff --git a/plugin/skills/minion-orchestrator/SKILL.md b/plugin/skills/minion-orchestrator/SKILL.md
index 9b4c897e86..68715d2303 100644
--- a/plugin/skills/minion-orchestrator/SKILL.md
+++ b/plugin/skills/minion-orchestrator/SKILL.md
@@ -532,7 +532,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Don't spawn > 5 concurrent agents without checking `gbrain jobs stats` first
- Don't resubmit when a submit reports `coalesced` — the work is already queued; monitor the matched job id instead
- For subagent work, don't use `sessions_spawn` with `runtime: "subagent"` when Minions is available (use `gbrain agent run` instead)
-- Don't poll `get_job` in a tight loop (use `get_job_progress` for lightweight checks)
+- Don't poll `get_job` in a tight loop: after a long submit, offer `watch_job` when it's listed so gbrain reports back when the job finishes (else `get_job_progress`); on OpenClaw offer `gbrain setup openclaw --wakeshift`, never run it unasked
- Don't run an operation expected to exceed ~2 minutes as a bare background shell — it dies with the session; route through the Durable execution ladder
- Don't say "I'll report back when it finishes" without an armed deadman or a scheduled check that will actually fire
- Don't let a deadman post noise when the completion arrived normally — check reported-state first, stay silent, self-delete
diff --git a/plugin/skills/remote-mcp/SKILL.md b/plugin/skills/remote-mcp/SKILL.md
index e1fd0955f2..1863e38291 100644
--- a/plugin/skills/remote-mcp/SKILL.md
+++ b/plugin/skills/remote-mcp/SKILL.md
@@ -307,7 +307,7 @@ retain its returned ID, verify recall in a new conversation, correct it, and
withdraw it. Private facts cannot be recalled or withdrawn through these remote
operations; never change real private content to pass a test. With read-only
access, observe an authenticated read without adding write authority. Report
-registration, setup delivery, server checks, native calls, and cleanup separately.
+registration, setup delivery, server checks, native calls, and cleanup separately. For two-way use (gbrain reporting back when a long job or cron run finishes), offer `watch_job` after a long submit when it's listed, and `gbrain setup openclaw --wakeshift` on OpenClaw; never run setup unasked.
Host-side check at any time: `gbrain mcp expose --status` (without a receipt
it reports leftovers as `leftovers_without_receipt`, exit 1, with the exact
diff --git a/skills/minion-orchestrator/SKILL.md b/skills/minion-orchestrator/SKILL.md
index 0b81c26495..b14de27a7e 100644
--- a/skills/minion-orchestrator/SKILL.md
+++ b/skills/minion-orchestrator/SKILL.md
@@ -531,7 +531,7 @@ Follow the [agent operator protocol](../conventions/agent-operator-protocol.md)
- Don't spawn > 5 concurrent agents without checking `gbrain jobs stats` first
- Don't resubmit when a submit reports `coalesced` — the work is already queued; monitor the matched job id instead
- For subagent work, don't use `sessions_spawn` with `runtime: "subagent"` when Minions is available (use `gbrain agent run` instead)
-- Don't poll `get_job` in a tight loop (use `get_job_progress` for lightweight checks)
+- Don't poll `get_job` in a tight loop: after a long submit, offer `watch_job` when it's listed so gbrain reports back when the job finishes (else `get_job_progress`); on OpenClaw offer `gbrain setup openclaw --wakeshift`, never run it unasked
- Don't run an operation expected to exceed ~2 minutes as a bare background shell — it dies with the session; route through the Durable execution ladder
- Don't say "I'll report back when it finishes" without an armed deadman or a scheduled check that will actually fire
- Don't let a deadman post noise when the completion arrived normally — check reported-state first, stay silent, self-delete
diff --git a/skills/remote-mcp/SKILL.md b/skills/remote-mcp/SKILL.md
index 4aee2616c2..a4d0c5c00a 100644
--- a/skills/remote-mcp/SKILL.md
+++ b/skills/remote-mcp/SKILL.md
@@ -306,7 +306,7 @@ retain its returned ID, verify recall in a new conversation, correct it, and
withdraw it. Private facts cannot be recalled or withdrawn through these remote
operations; never change real private content to pass a test. With read-only
access, observe an authenticated read without adding write authority. Report
-registration, setup delivery, server checks, native calls, and cleanup separately.
+registration, setup delivery, server checks, native calls, and cleanup separately. For two-way use (gbrain reporting back when a long job or cron run finishes), offer `watch_job` after a long submit when it's listed, and `gbrain setup openclaw --wakeshift` on OpenClaw; never run setup unasked.
Host-side check at any time: `gbrain mcp expose --status` (without a receipt
it reports leftovers as `leftovers_without_receipt`, exit 1, with the exact
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 393a105ad7..5f5607e08d 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -189,7 +189,7 @@
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
"migrations/v0.9.0.md": "773fab0a8d7f330576265a3f510c1f318f47789b6136c46d43e08121acbc20eb",
"migrations/v0.9.1.md": "75761bad6c0ad37b69ec8197c6a678bb6a1484f9a76e4b70f2d1e86dc80102b3",
- "minion-orchestrator/SKILL.md": "c6b2dcdb88b31d10242d4d05298d23adbf559bd2c463bbefd9c5a1c87ef928a5",
+ "minion-orchestrator/SKILL.md": "08c058b42ec0491fbc777731e4ffb93bc9835a9c3daaa86992139b2099558518",
"minion-orchestrator/routing-eval.jsonl": "501ed2e19cb16847ff8425219d246b7a774de1accd42cb28fd44edbb64204992",
"perplexity-research/SKILL.md": "1d6cf9f752b4a1618a04789a2f24a7f18d6feaa4ada578515842860bd5869997",
"perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",
@@ -200,7 +200,7 @@
"publish/SKILL.md": "271bd9ba87279429cd934509071dd032b859d59264038c38829c9af46f15c13b",
"query/SKILL.md": "81f1f4d8d18a364bc5d90c65cc731f73e77be6c28dc86797aaebfad7430e552d",
"query/routing-eval.jsonl": "74f5a91e52fabc54e0e9403fa17db87ee26bb7ebb8ae8005148c51142abc62fe",
- "remote-mcp/SKILL.md": "753d4df2c6b8c837d00a9c0593028220bdceb1a83b08b29a1d9b973242b789c5",
+ "remote-mcp/SKILL.md": "e95c229368fd6af297a1614acdf3f1950259a1a5faa958a7bb7fe917c4e733a7",
"remote-mcp/routing-eval.jsonl": "7287693135c9fe2d6495d81d22746ddf41b116254db4b6e683dbdee251e08f8e",
"repo-architecture/SKILL.md": "c57c629d31676ef02f4f42f6dd55dd432e02e0d3a6397aacbbd1037138493763",
"reports/SKILL.md": "3d3ad45a4ebe82251244f74c98c29f633c1b4b98745ad88fdbc01bd6e43b6dec",
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index 9dcf5c49ed..994e763717 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -404,8 +404,9 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp
// selfHelp: connectors ships its own printHelp (commands/connectors/index.ts) with the
// per-subcommand usage; keep the generic short-circuit from hiding it.
{ name: 'connectors', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/connectors.ts') },
- // selfHelp: Wakeshift report-back switch (commands/wakeshift.ts HELP); host-only (it writes the file plane and the key), docs/guides/wakeshift.md.
- { name: 'wakeshift', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/wakeshift.ts') },
+ // selfHelp: Wakeshift report-back switch (commands/wakeshift.ts HELP), docs/guides/wakeshift.md. Thin client: only
+ // `watch` routes (watch_job / watch_write_request / watch_cron over MCP); the rest writes the host file plane and key.
+ { name: 'wakeshift', phase: 'post-connect', thinClient: 'route-then-refuse', selfHelp: true, load: () => import('./commands/wakeshift.ts') },
// selfHelp: #3502 sweep: pages + bench print their own usage (pages.ts printHelp, bench-publish.ts
// printHelp). Both were documented but undispatchable — `pages` had a live handleCliOnly case but
// was missing from CLI_ONLY (the #2035 calibration bug class); `bench` was never wired at all.
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 26a08c9780..9f47196519 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -1875,6 +1875,7 @@ const THIN_CLIENT_REFUSE_HINTS: Record<string, string> = {
quarantine: '`quarantine list` routes to the brain host automatically (quarantine_list MCP op). scan/clear are host-bound (bulk re-import; the clear trust decision) — run those on the host.',
advisor: 'advisor ranks next actions from the host brain. Use the `advisor` MCP tool from your agent (when the host publishes it), or run `gbrain advisor` on the host.',
export: 'export dumps the host brain to disk and has no MCP equivalent. Run `gbrain export` on the host, or read pages with the `get_page` MCP tool.',
+ wakeshift: '`wakeshift watch job|write|cron` routes to the brain host automatically (watch_job / watch_write_request / watch_cron MCP tools). enable, disable, status and test read or change the brain host\'s Wakeshift key and settings: run those on the brain host.',
recall: '`recall --query`/`--budget-tokens` without `--budget-policy` runs the recall op locally. Add `--budget-policy facts_first` to send it to the brain host (`recall` MCP op).',
};
diff --git a/src/commands/doctor/checks/wakeshift-openclaw.ts b/src/commands/doctor/checks/wakeshift-openclaw.ts
new file mode 100644
index 0000000000..9e9a6a5633
--- /dev/null
+++ b/src/commands/doctor/checks/wakeshift-openclaw.ts
@@ -0,0 +1,28 @@
+/**
+ * wakeshift_openclaw (Wakeshift plan D11): drift between Wakeshift's OpenClaw plugin as installed and the version
+ * this gbrain pins (WAKESHIFT_OPENCLAW_VERSION, which `gbrain setup openclaw --wakeshift` installs). Runs only
+ * where openclaw is on PATH; reads `openclaw plugins inspect wakeshift --runtime --json` with a 15 s cap. A
+ * different version is a warning, never a failure: the fix reruns setup, which reinstalls the pinned version.
+ */
+import type { Check } from '../../doctor.ts';
+import type { DoctorEntry } from '../context.ts';
+import { defaultOpenclawRun, findOpenclawBin, installedWakeshiftOpenclawVersion, WAKESHIFT_OPENCLAW_VERSION, type OpenclawRun } from '../../setup-openclaw-wakeshift.ts';
+
+/** The check for this machine; none when openclaw is not on PATH. `opts` injects the binary and runner (tests). */
+export async function runWakeshiftOpenclawCheck(_ctx: unknown, opts: { bin?: string | null; run?: OpenclawRun } = {}): Promise<Check[]> {
+ const checks: Check[] = [];
+ const bin = opts.bin !== undefined ? opts.bin : findOpenclawBin();
+ if (!bin) return checks;
+ const installed = installedWakeshiftOpenclawVersion(opts.run ?? ((argv) => defaultOpenclawRun(argv, 15_000)), bin);
+ const details = { pinned: WAKESHIFT_OPENCLAW_VERSION, installed, docs: 'docs/mcp/OPENCLAW.md#have-gbrain-report-back-to-this-chat' };
+ if (installed === null) {
+ checks.push({ name: 'wakeshift_openclaw', status: 'ok', severity: 'info', message: "Wakeshift's OpenClaw plugin is not installed here (gbrain setup openclaw --wakeshift installs it).", details });
+ } else if (installed === WAKESHIFT_OPENCLAW_VERSION) {
+ checks.push({ name: 'wakeshift_openclaw', status: 'ok', message: `Wakeshift's OpenClaw plugin ${installed} matches the version this gbrain pins.`, details });
+ } else {
+ checks.push({ name: 'wakeshift_openclaw', status: 'warn', message: `Wakeshift's OpenClaw plugin is ${installed}; this gbrain pins ${WAKESHIFT_OPENCLAW_VERSION}. Fix: gbrain setup openclaw --wakeshift (reinstalls the pinned version).`, details });
+ }
+ return checks;
+}
+
+export const wakeshiftOpenclawEntry: DoctorEntry = { name: 'wakeshift_openclaw', emits: ['wakeshift_openclaw'], run: runWakeshiftOpenclawCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 7f12e7c2f8..87a3089cc3 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -107,6 +107,7 @@ import { transcriptSecretExposureEntry } from './checks/transcript-secrets.ts';
import { autoChronicleEntry } from './checks/auto-chronicle.ts';
import { factsDrainEntry } from './checks/facts-drain.ts';
import { wakeshiftEntry } from './checks/wakeshift.ts';
+import { wakeshiftOpenclawEntry } from './checks/wakeshift-openclaw.ts';
import { factTakeVectorsEntry } from './checks/vector-coverage.ts';
import { decideHealthEntry } from './checks/decide.ts';
import { supersessionCalibrationEntry } from './checks/supersession-calibration.ts';
@@ -278,6 +279,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
autoChronicleEntry,
factsDrainEntry,
wakeshiftEntry,
+ wakeshiftOpenclawEntry,
factTakeVectorsEntry,
plannerStatsEntry,
retrievalFeedbackEntry,
diff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.ts
index ac6325a2d5..702d856851 100644
--- a/src/commands/init-first-run.ts
+++ b/src/commands/init-first-run.ts
@@ -120,8 +120,11 @@ export function buildInitFirstRunNotices(inputs: InitFirstRunInputs): Notice[] {
* time: the agent relays them in the reply that reports the install instead
* of ending it on a question whose answer needs another turn (Cat 41 wave 2).
* Open decisions keep returning in later sessions until answered or muted.
+ * The Report back (Wakeshift) row states whether gbrain wakes the agent's
+ * conversation when a job finishes (`opts.reportBack`: published) and the
+ * one command that flips it.
*/
-export function setupFirstRunNotices(initNotices: readonly unknown[], harness: string): Notice[] {
+export function setupFirstRunNotices(initNotices: readonly unknown[], harness: string, opts: { reportBack?: boolean } = {}): Notice[] {
const bundle = initNotices.find((n): n is Notice => (n as Notice | null)?.code === 'first_run_decisions');
const decisions = (bundle?.decisions ?? []).filter(d => d.id !== 'harness_wiring');
if (decisions.length === 0) return [];
@@ -131,13 +134,16 @@ export function setupFirstRunNotices(initNotices: readonly unknown[], harness: s
...(decisions.some(d => d.id === 'writeback') ? ['agents save only what you ask them to remember, until you turn on automatic saving (gbrain recommends salient: durable facts you state, saved with provenance)'] : []),
];
if (inEffect.length === 0) return [];
+ const reportBack = opts.reportBack
+ ? 'Report back (Wakeshift): on. gbrain wakeshift disable turns it off.'
+ : 'Report back (Wakeshift): off. gbrain wakeshift enable turns it on.';
return [{
code: 'first_run_decisions',
kind: 'ask',
why: `Setup is complete: the brain is ready and ${harness} is wired, so memory works now. These first-run settings are in effect as listed; none blocks memory or needs a new session to answer. `
+ 'Relay them once, in the reply that reports this install, as the current settings and how to change them; do not hold the install open or end it waiting on an answer. '
+ 'When the user picks an option, run its command. Automatic saving (`writeback`) is separate from setup\'s capture decision (Stop/SessionEnd hooks); while unanswered it comes back in a later session until the user answers or mutes it.',
- user_message: `gbrain is set up and ${harness} is wired, so memory works now. In effect: ${inEffect.join('; ')}.${searchMode ? ` ${costMatrixSentence()}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
+ user_message: `gbrain is set up and ${harness} is wired, so memory works now. In effect: ${inEffect.join('; ')}. ${reportBack}${searchMode ? ` ${costMatrixSentence()}` : ''} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
decisions,
}];
}
diff --git a/src/commands/setup-openclaw-wakeshift.ts b/src/commands/setup-openclaw-wakeshift.ts
new file mode 100644
index 0000000000..cc488f17b3
--- /dev/null
+++ b/src/commands/setup-openclaw-wakeshift.ts
@@ -0,0 +1,107 @@
+/**
+ * `gbrain setup openclaw --wakeshift` (Wakeshift plan D11): install Wakeshift's own OpenClaw plugin, pinned, so
+ * gbrain's report-back wakes can start a turn in an OpenClaw session. gbrain builds no bridge and vendors nothing:
+ * after consent (persistent install, egress) it runs exactly OpenClaw's documented npm install and enable,
+ * through an injectable runner (tests never run openclaw). `--force` is how OpenClaw installs from npm instead of
+ * ClawHub; `--accept-capabilities` accepts the plugin's tool-result filter where nothing can prompt.
+ *
+ * The plugin turns on OpenClaw's hooks endpoint. On a gateway that listens beyond this computer, Wakeshift asks
+ * first (`allowNetworkHooks`): setup prints that question and never sets the key itself. Verification reads
+ * `openclaw plugins inspect wakeshift --runtime --json`; the "Wakeshift: connected" note appears in the agent's
+ * own session after its first watch, which no openclaw command shows, so setup reports it as pending unless the
+ * inspect output carries it. The pinned version lives in WAKESHIFT_OPENCLAW_VERSION; doctor's
+ * `wakeshift_openclaw` check warns when the installed plugin differs.
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { bunSpawnSync } from '../core/spawn.ts';
+import { openclawConfigPath, parseJson5ish } from '../core/setup/brain-first.ts';
+
+export const WAKESHIFT_OPENCLAW_PACKAGE = '@wakeshift/openclaw';
+export const WAKESHIFT_OPENCLAW_VERSION = '1.4.31';
+export const WAKESHIFT_OPENCLAW_PLUGIN_ID = 'wakeshift';
+export const WAKESHIFT_CONNECTED_NOTE = 'Wakeshift: connected';
+export const ALLOW_NETWORK_HOOKS_ARGV = ['openclaw', 'config', 'set', `plugins.entries.${WAKESHIFT_OPENCLAW_PLUGIN_ID}.config.allowNetworkHooks`, 'true', '--strict-json'];
+
+export type OpenclawRun = (argv: string[]) => { ok: boolean; output: string };
+
+export function defaultOpenclawRun(argv: string[], timeoutMs = 180_000): { ok: boolean; output: string } {
+ const r = bunSpawnSync(argv, { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe', env: process.env, timeout: timeoutMs });
+ return { ok: r.exitCode === 0, output: `${r.stdout.toString()}${r.stderr.toString()}`.trim() };
+}
+
+export function findOpenclawBin(): string | null {
+ try { return Bun.which('openclaw', { PATH: process.env.PATH ?? '' }); } catch { return null; }
+}
+
+/** The exact install and enable commands, in order. */
+export function wakeshiftOpenclawInstallArgv(bin = 'openclaw'): string[][] {
+ return [
+ [bin, 'plugins', 'install', `npm:${WAKESHIFT_OPENCLAW_PACKAGE}@${WAKESHIFT_OPENCLAW_VERSION}`, '--force', '--accept-capabilities'],
+ [bin, 'plugins', 'enable', WAKESHIFT_OPENCLAW_PLUGIN_ID, '--accept-capabilities'],
+ ];
+}
+
+export const inspectArgv = (bin = 'openclaw') => [bin, 'plugins', 'inspect', WAKESHIFT_OPENCLAW_PLUGIN_ID, '--runtime', '--json'];
+
+/** The gateway's `gateway.bind` from openclaw.json, or null when unset or unreadable. */
+export function openclawGatewayBind(): string | null {
+ try {
+ const path = openclawConfigPath();
+ if (!existsSync(path)) return null;
+ const bind = (parseJson5ish(readFileSync(path, 'utf8')) as { gateway?: { bind?: unknown } } | undefined)?.gateway?.bind;
+ return typeof bind === 'string' && bind.trim() ? bind.trim() : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Wakeshift's question about the hooks endpoint, when the gateway listens beyond this computer (a bind other than
+ * loopback), else null. Printed for the user to answer; gbrain never sets allowNetworkHooks.
+ */
+export function networkHooksQuestion(bind: string | null): string | null {
+ if (!bind || bind === 'loopback') return null;
+ return `Your OpenClaw gateway listens beyond this computer (gateway.bind: ${bind}). Wakeshift's plugin turns on OpenClaw's hooks endpoint, `
+ + 'with a token of its own and only for conversations that connect through Wakeshift, and on this gateway that endpoint is reachable wherever the gateway is. '
+ + `The plugin turns nothing on there until you agree. To agree, run: ${ALLOW_NETWORK_HOOKS_ARGV.join(' ')} (and block /hooks/ from other machines with a firewall or proxy rule). gbrain never sets this for you.`;
+}
+
+/** The installed plugin's version from `openclaw plugins inspect`, or null when it is not installed or the output names none. */
+export function installedWakeshiftOpenclawVersion(run: OpenclawRun, bin: string): string | null {
+ const r = run(inspectArgv(bin));
+ if (!r.ok) return null;
+ return /"version"\s*:\s*"([^"]+)"/.exec(r.output)?.[1] ?? null;
+}
+
+export interface WakeshiftOpenclawResult {
+ action: 'installed' | 'dry_run' | 'failed';
+ version: string;
+ commands: string[];
+ failed_command?: string;
+ output?: string;
+ network_hooks_question: string | null;
+ verify: { loaded: boolean; connected: 'seen' | 'pending'; message: string } | null;
+}
+
+const shown = (argv: string[]) => argv.map((a) => (/^[\w./:=@-]+$/.test(a) ? a : `'${a.replace(/'/g, `'\\''`)}'`)).join(' ');
+
+/** Run the pinned install and enable (consent already given), then inspect. Never throws. */
+export function installWakeshiftOpenclaw(opts: { bin: string; run?: OpenclawRun; dryRun: boolean; bind?: string | null }): WakeshiftOpenclawResult {
+ const run = opts.run ?? defaultOpenclawRun;
+ const argvs = wakeshiftOpenclawInstallArgv(opts.bin);
+ const base = { version: WAKESHIFT_OPENCLAW_VERSION, commands: argvs.map(shown), network_hooks_question: networkHooksQuestion(opts.bind === undefined ? openclawGatewayBind() : opts.bind) };
+ if (opts.dryRun) return { ...base, action: 'dry_run', verify: null };
+ for (const argv of argvs) {
+ const r = run(argv);
+ if (!r.ok) return { ...base, action: 'failed', failed_command: shown(argv), output: r.output.split('\n').slice(-5).join('\n'), verify: null };
+ }
+ const inspect = run(inspectArgv(opts.bin));
+ const loaded = inspect.ok && /"status"\s*:\s*"loaded"|"imported"\s*:\s*true|"enabled"\s*:\s*true/.test(inspect.output) && !/"status"\s*:\s*"(?:error|disabled)"/.test(inspect.output);
+ const connected = inspect.output.includes(WAKESHIFT_CONNECTED_NOTE) ? 'seen' as const : 'pending' as const;
+ const message = !loaded
+ ? `\`${shown(inspectArgv(opts.bin))}\` does not show the wakeshift plugin loaded; restart the gateway and check again.`
+ : connected === 'seen'
+ ? `The wakeshift plugin is loaded and reports "${WAKESHIFT_CONNECTED_NOTE}".`
+ : `The wakeshift plugin is loaded. "${WAKESHIFT_CONNECTED_NOTE}" appears in the OpenClaw session itself once the agent first watches a job; no openclaw command shows it, so ask the agent to watch one and look for that note.`;
+ return { ...base, action: 'installed', verify: { loaded, connected, message } };
+}
diff --git a/src/commands/setup.ts b/src/commands/setup.ts
index acbed945e0..ee30dc994b 100644
--- a/src/commands/setup.ts
+++ b/src/commands/setup.ts
@@ -32,6 +32,10 @@ import { opError, OperationError } from '../core/ops/contract.ts';
import { cliRenderContext, renderCliError, renderNotice, type Action, type Notice } from '../core/agent-output.ts';
import { writeCliNotices } from '../core/interop-notices.ts';
import { setupFirstRunNotices } from './init-first-run.ts';
+import { wakeshiftPublished } from '../core/wakeshift/config.ts';
+import { findOpenclawBin, installWakeshiftOpenclaw, networkHooksQuestion, openclawGatewayBind, wakeshiftOpenclawInstallArgv, WAKESHIFT_OPENCLAW_PACKAGE, WAKESHIFT_OPENCLAW_VERSION, type OpenclawRun } from './setup-openclaw-wakeshift.ts';
+import { requireConsent } from '../core/consent.ts';
+import { writeCliError } from '../cli/cli-error.ts';
import { hostedOptionMuted, hostedOptionNotice, writeHostedOption } from '../core/onboard/hosted-option.ts';
import { writeJsonDocument } from '../core/cli-force-exit.ts';
import { configDir, gbrainPath, isThinClient, loadConfig, type GBrainConfig } from '../core/config.ts';
@@ -161,6 +165,9 @@ Flags:
matches (gbrain bundled-skill <name>, from this gbrain).
off removes an index an earlier run wrote. The
choice is remembered; GBRAIN_SKILL_LOADING sets it too.
+ --wakeshift OpenClaw: install Wakeshift's OpenClaw plugin (@wakeshift/openclaw, pinned)
+ so gbrain can wake an OpenClaw session when a job finishes. Asks
+ consent (--yes), runs OpenClaw's own installer, changes nothing else.
--skills-index-only Refresh every skills index recorded for this harness (its
file, launcher and skill set as recorded) and change
nothing else; with --skill-loading off, remove them.
@@ -220,6 +227,7 @@ interface SetupFlags {
instructions?: boolean;
instructionsOnly: boolean;
skillsIndexOnly: boolean;
+ wakeshift: boolean;
workspace?: string;
skillLoading?: SkillLoading;
}
@@ -265,6 +273,7 @@ function parseFlags(args: string[]): SetupFlags | string {
instructions: args.includes('--instructions') ? true : args.includes('--no-instructions') ? false : undefined,
instructionsOnly: args.includes('--instructions-only'),
skillsIndexOnly: args.includes('--skills-index-only'),
+ wakeshift: args.includes('--wakeshift'),
workspace,
skillLoading: skillLoading as SkillLoading | undefined,
};
@@ -361,7 +370,7 @@ function describeConsent(c: SetupConsent, events: string[], out: Out, harness: S
say(out, ` providers ${c.providers.value}${c.providers.value === 'declined' ? ' (keyless: setup configures no paid provider; accept with --providers)' : ''} ${src(c.providers.source)}`);
}
-export async function runSetup(args: string[]): Promise<number> {
+export async function runSetup(args: string[], deps: { openclaw?: { bin?: string | null; run?: OpenclawRun } } = {}): Promise<number> {
if (args.includes('--help') || args.includes('-h') || args.length === 0) {
console.log(SETUP_HELP);
return 0;
@@ -376,6 +385,7 @@ export async function runSetup(args: string[]): Promise<number> {
const adapter = HARNESS_ADAPTERS.find((a) => a.id === flags.harness);
const mcpWired = flags.harness === 'claude-code' || flags.harness === 'codex';
if (flags.skillsIndexOnly) return runSkillsIndexOnly(flags, out);
+ if (flags.wakeshift) return runWakeshiftOpenclaw(flags, args, out, deps.openclaw ?? {});
if ((flags.instructionsOnly && (isBrainFirstHarness(flags.harness) || adapter)) || (isBrainFirstHarness(flags.harness) && !mcpWired)) {
return runInstructionsOnly(flags, out);
}
@@ -582,7 +592,7 @@ function runBrainInit(initArgv: string[], out: Out, harness: SetupHarnessId): No
try {
const doc = JSON.parse(initOut) as { path?: string; notices?: unknown[] };
if (doc.path) say(out, `Brain ready at ${doc.path}`);
- return [...setupFirstRunNotices(doc.notices ?? [], HARNESS_LABEL[harness]), ...(hosted ? [hosted] : [])];
+ return [...setupFirstRunNotices(doc.notices ?? [], HARNESS_LABEL[harness], { reportBack: wakeshiftPublished() }), ...(hosted ? [hosted] : [])];
} catch { process.stderr.write(initOut); return hosted ? [hosted] : []; }
}
@@ -865,6 +875,61 @@ async function runInstructionsOnly(flags: SetupFlags, out: Out): Promise<number>
return code;
}
+/**
+ * --wakeshift (OpenClaw only): consent, then Wakeshift's pinned OpenClaw plugin through OpenClaw's own installer
+ * (src/commands/setup-openclaw-wakeshift.ts). Prints Wakeshift's allowNetworkHooks question and never answers it.
+ */
+async function runWakeshiftOpenclaw(flags: SetupFlags, args: string[], out: Out, deps: { bin?: string | null; run?: OpenclawRun }): Promise<number> {
+ const remove = 'openclaw wakeshift reset && openclaw plugins uninstall wakeshift --force';
+ if (flags.harness !== 'openclaw') {
+ return refuse(opError('invalid_params', `--wakeshift installs Wakeshift's OpenClaw plugin, so it applies to gbrain setup openclaw only (got ${flags.harness ?? 'no harness'}).`, 'Run gbrain setup openclaw --wakeshift where the OpenClaw gateway runs.'), out);
+ }
+ if (flags.remove) {
+ return refuse(opError('invalid_params', "setup does not remove Wakeshift's plugin; OpenClaw's own commands do, and they also undo the hooks settings it changed.", `Run: ${remove}`), out);
+ }
+ const bin = deps.bin !== undefined ? deps.bin : findOpenclawBin();
+ const commands = wakeshiftOpenclawInstallArgv().map((a) => a.join(' ')).join(' && ');
+ if (!bin) {
+ return refuse(opError('openclaw_not_found', "openclaw is not on PATH, so Wakeshift's OpenClaw plugin was not installed; nothing changed.",
+ `Run gbrain setup openclaw --wakeshift where the OpenClaw gateway runs (in its container, if it is in one), or run there: ${commands}`,
+ { fix: { argv: ['gbrain', 'setup', 'openclaw', '--wakeshift'], consent: ['persistent_install', 'egress'], actor: 'user', requires_exclusive: false,
+ why: 'The plugin installs where the OpenClaw gateway runs, with openclaw on PATH.' } }), out);
+ }
+ const bind = openclawGatewayBind();
+ if (!flags.dryRun) {
+ try {
+ await requireConsent({
+ command: 'setup openclaw --wakeshift', effects: ['persistent_install', 'egress'], actor: 'user',
+ what: `Install Wakeshift's OpenClaw plugin ${WAKESHIFT_OPENCLAW_PACKAGE}@${WAKESHIFT_OPENCLAW_VERSION} from npm and enable it: ${commands}`,
+ why: 'gbrain can then wake this OpenClaw session when a job, write or cron run it watches finishes, instead of the agent polling.',
+ risk: "OpenClaw downloads the package from npm (published by Wakeshift with npm provenance). The plugin talks to Wakeshift's service and turns on OpenClaw's hooks endpoint with its own token, for conversations that connect through Wakeshift."
+ + (networkHooksQuestion(bind) ? ' This gateway listens beyond this computer; the plugin asks before using the endpoint there.' : ''),
+ user_message: "Install Wakeshift's OpenClaw plugin so gbrain can report back to this OpenClaw chat when long jobs or cron runs finish?",
+ argv: ['gbrain', 'setup', 'openclaw', '--wakeshift', '--yes'], args,
+ });
+ } catch (e) {
+ return writeCliError(e, 'setup', { json: out.json });
+ }
+ }
+ const result = installWakeshiftOpenclaw({ bin, run: deps.run, dryRun: flags.dryRun, bind });
+ const code = result.action === 'failed' || (result.verify && !result.verify.loaded) ? 1 : 0;
+ if (out.json) {
+ await writeJsonDocument(`${JSON.stringify({ harness: 'openclaw', dry_run: flags.dryRun, wakeshift: { ...result, remove } }, null, 2)}\n`, (t) => process.stdout.write(t));
+ return code;
+ }
+ say(out, `Wakeshift for OpenClaw (${WAKESHIFT_OPENCLAW_PACKAGE}@${result.version}):`);
+ const verb = result.action === 'dry_run' ? 'would run' : 'ran';
+ for (const c of result.commands) {
+ if (result.action === 'failed' && c === result.failed_command) { say(out, ` failed ${c}${result.output ? `\n ${result.output.replace(/\n/g, '\n ')}` : ''}`); break; }
+ say(out, ` ${verb.padEnd(8)} ${c}`);
+ }
+ if (result.verify) say(out, `Verify: ${result.verify.message}`);
+ if (result.network_hooks_question) say(out, `Question from Wakeshift (answer it yourself): ${result.network_hooks_question}`);
+ if (result.action === 'installed') say(out, 'Next: the brain owner turns reporting back on with gbrain wakeshift enable on the brain host; agents then offer watch_job after a long submit.');
+ say(out, `Remove: ${remove}`);
+ return code;
+}
+
/** --skills-index-only: refresh (or, with --skill-loading off, remove) the recorded skills indexes for one harness; nothing else is touched. */
async function runSkillsIndexOnly(flags: SetupFlags, out: Out): Promise<number> {
const harness = flags.harness;
diff --git a/src/commands/thin-client-routing.ts b/src/commands/thin-client-routing.ts
index eee95bf867..b7d72af531 100644
--- a/src/commands/thin-client-routing.ts
+++ b/src/commands/thin-client-routing.ts
@@ -2,7 +2,8 @@
* CLI→MCP gap-closure wave [OV6] — per-subcommand thin-client routing for the
* commands whose reads/writes gained MCP ops: takes (list/search/scorecard/
* calibration + the write verbs), search (modes/stats/tune, read-only forms),
- * jobs stats, cache stats, and quarantine list. The salience/anomalies/
+ * jobs stats, cache stats, quarantine list, and wakeshift watch (watch_job /
+ * watch_write_request / watch_cron). The salience/anomalies/
* graph-query precedent, engine-free: each routable subcommand maps onto its
* op over callRemoteTool; everything else returns false so the caller falls
* through to refuseThinClient's pinpoint hint.
@@ -156,6 +157,12 @@ export async function routeThinClientCommand(
return false; // modes --reset / modes --mode|--source (the reset dry-run) / tune --apply / diagnose — host-side config or live probe
}
+ if (command === 'wakeshift' && sub === 'watch') {
+ const { runWakeshiftWatchRemote } = await import('./wakeshift-watch.ts');
+ await runWakeshiftWatchRemote(cfg, rest);
+ return true;
+ }
+
if (command === 'jobs' && sub === 'stats') {
printJson(await call(cfg, 'get_job_stats', { ...(flagValue(rest, '--queue') ? { queue: flagValue(rest, '--queue') } : {}) }));
return true;
diff --git a/src/commands/wakeshift-watch.ts b/src/commands/wakeshift-watch.ts
new file mode 100644
index 0000000000..56fd629b8c
--- /dev/null
+++ b/src/commands/wakeshift-watch.ts
@@ -0,0 +1,134 @@
+/**
+ * `gbrain wakeshift watch job <id> | write <request_id> | cron <name>` (Wakeshift plan D8): have gbrain wake
+ * this conversation when a job, a pending write or a cron run finishes, from a shell. On a thin client
+ * (`gbrain init --mcp-only`: Muse, Grok Bot) it calls the brain host's watch_job, watch_write_request or
+ * watch_cron over MCP; on a brain host it calls the op with the trusted local context, whose refusal names the
+ * local wait (gbrain jobs wait <id>), because a CLI run has no conversation to wake. The result prints as text or
+ * one JSON line, and Wakeshift's addition (the tool tail) is always the last stdout line, where the agent reads
+ * it. `--session-key`, `--harness` and `--conversation-id` pass through per call, exactly as given: the
+ * session key is never written to disk, config or a log.
+ */
+import type { BrainEngine } from '../core/engine.ts';
+import type { GBrainConfig } from '../core/config.ts';
+
+export const WAKESHIFT_WATCH_HELP = `gbrain wakeshift watch — have gbrain wake this conversation when something finishes
+
+Usage:
+ gbrain wakeshift watch job <id> a job (submit_job, submit_agent, gbrain jobs submit)
+ gbrain wakeshift watch write <request_id> a pending write (exit 10, write_pending)
+ gbrain wakeshift watch cron <name> a scheduled run registered with gbrain wakeshift cron add
+
+Flags:
+ --session-key K this conversation's session_key from an earlier result (a secret: never logged or saved)
+ --harness H the program you run in (claude-code, codex, cursor, grok-bot, openclaw, ...)
+ --conversation-id C your own id for this conversation, if your program gives you one
+ --json print the result as one JSON line
+
+On a thin client it calls the brain host over MCP. Wakeshift's instructions, when it sends any, are the last
+line of output: follow them. Without Wakeshift, wait with gbrain jobs wait <id>. Guide: docs/guides/wakeshift.md`;
+
+const TARGETS = {
+ job: { tool: 'watch_job', param: 'id' },
+ write: { tool: 'watch_write_request', param: 'request_id' },
+ cron: { tool: 'watch_cron', param: 'name' },
+} as const;
+
+const VALUE_FLAGS = { '--session-key': 'session_key', '--harness': 'harness', '--conversation-id': 'conversation_id' } as const;
+
+export interface WatchCall { tool: string; params: Record<string, unknown>; json: boolean }
+
+/** Parse the watch arguments into the op and its params; a string is the usage problem. */
+export function parseWatchArgs(args: readonly string[]): WatchCall | string {
+ const params: Record<string, unknown> = {};
+ const positionals: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ const a = args[i]!;
+ if (a === '--json') continue;
+ if (a in VALUE_FLAGS) {
+ const v = args[i + 1];
+ if (v === undefined || v.startsWith('--')) return `${a} needs a value`;
+ params[VALUE_FLAGS[a as keyof typeof VALUE_FLAGS]] = v;
+ i++;
+ continue;
+ }
+ if (a.startsWith('-')) return `unknown flag ${a}`;
+ positionals.push(a);
+ }
+ const [kind, target, extra] = positionals;
+ if (!kind || !(kind in TARGETS)) return 'name what to watch: job <id>, write <request_id> or cron <name>';
+ if (!target || extra !== undefined) return `watch ${kind} takes exactly one ${TARGETS[kind as keyof typeof TARGETS].param}`;
+ const spec = TARGETS[kind as keyof typeof TARGETS];
+ if (kind === 'job' && !/^[1-9]\d{0,15}$/.test(target)) return `job id must be a positive number (got ${target})`;
+ return { tool: spec.tool, params: { [spec.param]: kind === 'job' ? Number(target) : target, ...params }, json: args.includes('--json') };
+}
+
+/** Wakeshift's addition in a remote result: the last text block after the JSON body, unless it is gbrain's own. */
+export function remoteToolTail(res: unknown): string | undefined {
+ const content = (res as { content?: Array<{ type?: string; text?: unknown }> } | undefined)?.content;
+ if (!Array.isArray(content) || content.length < 2) return undefined;
+ const last = content.at(-1)!;
+ return last.type === 'text' && typeof last.text === 'string' && last.text.trim() && !last.text.startsWith('[gbrain ') ? last.text : undefined;
+}
+
+/** Print the result (text or one JSON line), then the tail as the last stdout line. */
+export function printWatchResult(result: unknown, tail: string | undefined, json: boolean): void {
+ if (json) {
+ console.log(JSON.stringify(result));
+ } else {
+ const r = (result ?? {}) as Record<string, unknown>;
+ const target = r.job ?? r.request_id ?? r.name ?? r.target;
+ if (r.watching === true) {
+ console.log(`Watching ${String(r.event ?? 'it')}${target !== undefined ? ` for ${String(target)}` : ''}: this conversation wakes when it finishes${r.expires_in ? ` (watch ${String(r.watch)}, lasts ${String(r.expires_in)})` : ''}.`);
+ if (r.already_finished === true) console.log('It has already finished, so the wake goes out now.');
+ if (typeof r.note === 'string') console.log(r.note);
+ if (typeof r.fallback === 'string') console.log(r.fallback);
+ } else {
+ console.log(JSON.stringify(result, null, 2));
+ }
+ }
+ if (tail) console.log(tail.trimEnd());
+}
+
+function usage(problem: string): void {
+ console.error(`gbrain wakeshift watch: ${problem}\n\n${WAKESHIFT_WATCH_HELP}`);
+}
+
+/** Thin client: the brain host's watch op over MCP. Remote errors propagate to the CLI dispatcher, like every routed command. */
+export async function runWakeshiftWatchRemote(cfg: GBrainConfig, args: string[]): Promise<void> {
+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');
+ if (args.includes('--help') || args.includes('-h')) { console.log(WAKESHIFT_WATCH_HELP); return; }
+ const call = parseWatchArgs(args);
+ if (typeof call === 'string') { usage(call); setCliExitVerdict(2); return; }
+ const { callRemoteTool, unpackToolResult } = await import('../core/mcp-client.ts');
+ const res = await callRemoteTool(cfg, call.tool, call.params);
+ printWatchResult(unpackToolResult(res), remoteToolTail(res), call.json);
+}
+
+/**
+ * Brain host: the op with the trusted local context (remote = false). watch_job refuses it with the local wait as
+ * its fix, which prints like any CLI error; a result's tail still prints last.
+ */
+export async function runWakeshiftWatch(engine: BrainEngine, args: string[]): Promise<void> {
+ const { setCliExitVerdict } = await import('../core/cli-force-exit.ts');
+ if (args.includes('--help') || args.includes('-h')) { console.log(WAKESHIFT_WATCH_HELP); return; }
+ const call = parseWatchArgs(args);
+ if (typeof call === 'string') { usage(call); setCliExitVerdict(2); return; }
+ const { operationsByName } = await import('../core/operations.ts');
+ const { OperationError, opError } = await import('../core/ops/contract.ts');
+ const { writeCliError } = await import('../cli/cli-error.ts');
+ const { loadConfig } = await import('../core/config.ts');
+ let tail: string | undefined;
+ try {
+ const op = operationsByName[call.tool];
+ if (!op) throw opError('unknown_tool', `This gbrain has no ${call.tool} operation.`, 'Upgrade gbrain on the brain host (gbrain upgrade).');
+ const ctx = {
+ engine, config: loadConfig() ?? ({ engine: engine.kind } as GBrainConfig), dryRun: false, remote: false as const,
+ logger: { info: (m: string) => console.error(m), warn: (m: string) => console.error(m), error: (m: string) => console.error(m) },
+ emitToolTail: (t: { text?: string }) => { tail = t.text; },
+ };
+ printWatchResult(await op.handler(ctx as Parameters<typeof op.handler>[0], call.params), tail, call.json);
+ } catch (e) {
+ if (!(e instanceof OperationError)) throw e;
+ setCliExitVerdict(writeCliError(e, 'wakeshift', { json: call.json }));
+ }
+}
diff --git a/src/commands/wakeshift.ts b/src/commands/wakeshift.ts
index 494da0408d..be2aae4018 100644
--- a/src/commands/wakeshift.ts
+++ b/src/commands/wakeshift.ts
@@ -42,6 +42,9 @@ Commands:
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 off
+ watch job <id> | write <request_id> | cron <name>
+ from a thin client or agent shell: wake this conversation when it finishes
+ (gbrain wakeshift watch --help)
The key is read from WAKESHIFT_API_KEY (e.g. in ~/.gbrain/.env) or ~/.gbrain/wakeshift.key.
gbrain never creates a Wakeshift account or key. Guide: docs/guides/wakeshift.md`;
@@ -300,6 +303,7 @@ export function printWakeshiftGate(): void {
export async function runWakeshift(engine: BrainEngine, args: string[]): Promise<void> {
const sub = args[0];
const json = args.includes('--json');
+ if (sub === 'watch') return (await import('./wakeshift-watch.ts')).runWakeshiftWatch(engine, args.slice(1));
if (!sub || args.includes('--help') || args.includes('-h')) { console.log(HELP); return; }
if (sub === 'status') return status(engine, json);
if (sub === 'enable') return enable(engine, args.slice(1));
@@ -307,7 +311,6 @@ export async function runWakeshift(engine: BrainEngine, args: string[]): Promise
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/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.ts
index dd6f2222a1..3a723585d1 100644
--- a/src/core/cli-flag-registry.generated.ts
+++ b/src/core/cli-flag-registry.generated.ts
@@ -52,7 +52,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'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', '--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'],
+ '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', '--strict-json', '--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', '--wakeshift', '--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', '--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'],
@@ -81,11 +81,11 @@ 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', '--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'],
+ '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', '--wakeshift', '--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', '--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'],
+ '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', '--wakeshift', '--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'],
@@ -123,7 +123,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
'schema': ['--alias', '--apply', '--as-filing-rules', '--brain', '--dims', '--expert', '--expert-routing', '--extractable', '--fields', '--force', '--help', '--inverse', '--json', '--kind', '--no-prefix', '--pack', '--page-type', '--path', '--prefix', '--primitive', '--schema-pack', '--since', '--source', '--source-id', '--target-type', '--to', '--with-db'],
'self-upgrade': ['--apply', '--brain', '--channel', '--check-only', '--clear-never-installed', '--exit-code', '--ff-only', '--force', '--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'],
'serve': ['--access', '--add', '--adopt-columns', '--adopt-permissions', '--advertise', '--all-new', '--apply-rewrites', '--attest-actor', '--attest-ops', '--bind', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--cli-socket', '--client', '--days', '--delegated-namespace', '--delegated-slug-prefixes', '--enable-dcr', '--enable-dcr-insecure', '--expect', '--fail-fast', '--federated-read', '--grant-types', '--harness', '--help', '--http', '--id', '--if-version', '--json', '--log-full-params', '--may-act-for', '--member', '--migrate-legacy', '--min-trust', '--no-embedding', '--no-pull', '--oauth-request', '--only', '--operations', '--path', '--pglite', '--port', '--prefer-postgres', '--print-admin-token', '--private-pages', '--profile', '--provenance', '--public-url', '--read-sources', '--redirect-uri', '--refresh-operations', '--repair', '--reset-default', '--retry-failed', '--scopes', '--source', '--source-guard', '--source-id', '--sources', '--stale', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--takes-holders', '--token', '--token-endpoint-auth-method', '--token-ttl', '--tools-json', '--url', '--usage', '--yes'],
- 'setup': ['--accept-capabilities', '--advertise', '--agent', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--surface', '--token', '--url', '--workspace', '--yes'],
+ 'setup': ['--accept-capabilities', '--advertise', '--agent', '--apply', '--auto', '--bearer-token-env-var', '--brain', '--break-lock', '--capture', '--credentials-file', '--dry-run', '--env', '--expect', '--force', '--gbrain-bin', '--harness', '--header', '--help', '--http', '--images', '--install', '--instructions', '--instructions-only', '--issuer-url', '--json', '--legacy-lock', '--link', '--max-cost', '--max-usd', '--mcp-only', '--mcp-url', '--name', '--no-capture', '--no-embedding', '--no-hooks', '--no-instructions', '--no-providers', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--only', '--path', '--pglite', '--probe', '--providers', '--pure', '--remove', '--root', '--runtime', '--save', '--scope', '--skill-loading', '--skills-index-only', '--source', '--source-ids', '--stale', '--strict-json', '--surface', '--token', '--trust', '--url', '--wakeshift', '--workspace', '--yes'],
'skillify': ['--brain', '--description', '--dry-run', '--force', '--help', '--json', '--mutating', '--recent', '--skills-dir', '--source', '--strict', '--triggers', '--writes-pages', '--writes-to'],
'skillopt': ['--all', '--allow-mutate-bundled', '--background', '--batch-size', '--benchmark', '--bootstrap-from-routing', '--bootstrap-from-skill', '--bootstrap-reviewed', '--bootstrap-tasks', '--brain', '--brain-wide-max-cost-usd', '--dry-run', '--epochs', '--follow', '--force', '--held-out', '--help', '--json', '--judge-model', '--loop', '--lr', '--lr-schedule', '--max-cost-usd', '--max-runtime-min', '--max-usd', '--models-strict', '--no-max-cost', '--no-mutate', '--optimizer-model', '--patch', '--reflect-max-tokens', '--resume', '--rewrite', '--skills-dir', '--source', '--split', '--status', '--target-model', '--target-models'],
'skillpack': ['--all', '--apply-clean-hunks', '--author', '--auto', '--brain', '--dest', '--dry-run', '--env', '--exit-code', '--fast', '--fix', '--force-unlock', '--format', '--from', '--full', '--harness', '--help', '--homepage', '--json', '--license', '--list', '--minimal', '--name-only', '--no-cache', '--no-lint', '--note', '--out', '--overwrite-local', '--persona', '--probe', '--pure', '--push', '--quick', '--quiet', '--refresh', '--repo', '--schema-pack', '--scope', '--short', '--since', '--skill', '--skills', '--skills-dir', '--skip-doctor', '--source', '--strict', '--stub', '--supabase', '--target', '--tier', '--trust', '--url', '--verify', '--version', '--workspace', '--yes'],
@@ -133,14 +133,14 @@ 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', '--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'],
+ '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', '--wakeshift', '--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', '--name', '--non-interactive', '--privacy-url', '--probe', '--source', '--status', '--terms-url', '--trust', '--url', '--yes'],
+ 'wakeshift': ['--apply', '--brain', '--conversation-id', '--expect', '--harness', '--help', '--json', '--key-stdin', '--max-cost', '--max-usd', '--name', '--non-interactive', '--privacy-url', '--probe', '--session-key', '--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', '--privacy-url', '--purge', '--recent', '--refresh-operations', '--request-id', '--row', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--surface', '--terms-url', '--to', '--updated-after', '--url', '--yes'],
};
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 2c233a28b5..89276bbb93 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -408,6 +408,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([
'queue_health',
// Wakeshift PR 1: report-back key, enabled state and dead/id_reused watches (doctor/checks/wakeshift.ts).
'wakeshift',
+ // Wakeshift PR 2: installed @wakeshift/openclaw vs the pinned version (doctor/checks/wakeshift-openclaw.ts).
+ 'wakeshift_openclaw',
// #4578: brain-wide maintenance jobs dying at their deadline.
'global_maintenance_timeouts',
// GBRA-130 C-6: no completed brain-wide pass while jobs fail or a phase keeps blocking it.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 75a2d6cdc3..88ed37ff07 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -700,6 +700,7 @@ export const CODES = {
docs: 'docs/guides/write-refusals.md#settle_mismatch',
suggestion: 'Run gbrain doctor --json and gbrain sources writer status --source <id> --json (both read-only), fix or report what they name with the gbrain version, then gbrain sources retry-held <id> and gbrain sync --source <id> --no-pull.',
fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Read-only: names a broken writer, a stuck effect or a damaged record.', requires_exclusive: false } },
+ openclaw_not_found: { class: 'caller', summary: "gbrain setup openclaw --wakeshift found no openclaw on PATH, so Wakeshift's OpenClaw plugin was not installed; nothing changed.", why: 'The plugin installs through OpenClaw\'s own installer where the gateway runs, so setup never writes OpenClaw\'s plugin directory itself.', docs: 'docs/mcp/OPENCLAW.md#have-gbrain-report-back-to-this-chat', suggestion: 'Run gbrain setup openclaw --wakeshift where the OpenClaw gateway runs (in its container, if it is in one).' },
setup_harness_unsupported: { class: 'caller', summary: "gbrain setup does not wire this harness yet; its guide has the manual connection steps.", why: 'Only harnesses with a supported row in the setup capability table are wired automatically, so setup never guesses another host\'s config format.', docs: 'docs/guides/repair.md#setup-harness-unsupported', exit: 2, fix: { argv: ['gbrain', 'setup', '--help'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Lists the harnesses setup wires and the guide for each.' } },
setup_hosted_connection: { class: 'caller', summary: "This machine already reaches a hosted brain, so gbrain setup will not create a second, local brain.", why: 'A new local brain would split memory: sessions would read and write the empty local brain while useful memory stays on the hosted one.', docs: 'docs/guides/repair.md#setup-hosted-connection', fix: { argv: ['gbrain', 'doctor', '--only', 'harness_wiring', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows which brain the harness registration reaches.' } },
setup_owner_conflict: { class: 'caller', summary: "Another owner holds what gbrain setup would change: a live server owns this PGLite brain, or the harness configuration holds an entry setup did not write.", why: 'A PGLite brain has one writer, so a second server would fail on its lock; an entry setup did not record by hash is the user\'s or another install\'s and is never overwritten.', reasons: ['live_serve', 'unowned_entry', 'other_install', 'harness_lane'], docs: 'docs/guides/repair.md#setup-owner-conflict', fix: { argv: ['gbrain', 'setup', 'claude-code', '--dry-run', '--json'], consent: [], actor: 'agent', requires_exclusive: false, why: 'Shows the resolved target and which owner blocks it, without writing anything.' } },
@@ -932,6 +933,7 @@ export const NOTICE_CODES = {
socket_identity_mismatch: { kind: 'degraded', summary: 'The running serve\'s warm CLI socket refused this CLI call because an identity part (named, never its value) differs from the serve\'s, so the call ran on the slower cold path; doctor `cli_socket_refusals` counts these.' },
sync_retry_failed_deprecated: { kind: 'coaching', summary: '`gbrain sync --retry-failed` is a deprecated alias for a plain sync, accepted for two releases: a plain sync retries a failure the previous run recorded by itself. Drop the flag.' },
reason_not_committed: { kind: 'degraded', summary: 'A write\'s reason is in gbrain\'s page history but in no Git commit: on a non-strict source a newer write to the same file committed first, carrying only its own reason. Nothing needs fixing and retrying the write is wrong (docs/guides/page-history.md#reasons).' },
+ wakeshift_report_back: { kind: 'coaching', summary: 'A remote submit_job or submit_agent was accepted: gbrain can wake this conversation when the job finishes (watch_job, when reporting back through Wakeshift is on; otherwise the brain owner turns it on with gbrain wakeshift enable). Once per session; mute with `gbrain notices mute wakeshift_report_back`.' },
skillopt_loop_deprecated: { kind: 'coaching', summary: 'SkillOpt\'s iterative loop (the skillopt loop flag, `run_skillopt` `optimizer_mode: "reflect"`, a resumed loop run or a queued loop job) is deprecated and is removed on or after 2026-12-03; the run continues unchanged. Nothing replaces it: edit the skill directly, or run the default one-shot rewrite.' },
sync_tail_degraded: { kind: 'degraded', summary: 'A managed sync ended synced, but its post-checkpoint tail (planner statistics, link extraction for the imported pages) failed, was cut off at its budget or did not start before the run\'s deadline; the step stays scheduled for the next sync, and the fix runs it now (`gbrain extract --stale --source-id <id>`, or doctor for the statistics).' },
no_resident: { kind: 'degraded', summary: 'gbrain sync trigger recorded the request (and queued a job or nudged the serve), but no resident (gbrain serve, gbrain jobs work or the autopilot daemon) watches the source, so the recorded request waits until one starts or a sync reaches it; the fix syncs the checkout HEAD now (`gbrain sync --source <id> --no-pull`). docs/guides/on-commit-sync.md#no-resident' },
diff --git a/src/core/ops/jobs.ts b/src/core/ops/jobs.ts
index 02e9b63e48..9d5efbb91a 100644
--- a/src/core/ops/jobs.ts
+++ b/src/core/ops/jobs.ts
@@ -54,6 +54,7 @@ import { opError, type OperationError } from './contract.ts';
import type { Action } from '../agent-output.ts';
import { hostFix, invalidParam, readFix, scopeDeniedError } from './op-fix.ts';
import { hasScope } from '../scope.ts';
+import { emitReportBackNotice } from '../report-back-notice.ts';
import { LIST_JOBS_DEFAULT_LIMIT, LIST_JOBS_REMOTE_MAX_LIMIT, pagingLimit, reportJobPage } from './read-paging.ts';
import { SOURCE_ID_RE } from '../source-id.ts';
import {
@@ -270,6 +271,7 @@ const submit_job: Operation = {
// fail-open). The job is already persisted; a probe failure degrades to
// {probe_failed: true}, never an error on a successful submission.
await emitNoWorkerNotice(ctx, job.queue);
+ emitReportBackNotice(ctx, job.id);
return { ...publicJob(job), queue_state: await probeQueueStateSafe(ctx, job.queue, [name]) };
},
};
@@ -493,6 +495,7 @@ const submit_agent: Operation = {
});
} catch { /* never block submission */ }
+ emitReportBackNotice(ctx, job.id);
// Amendments 24/25: the returned job id means nothing if the lane is
// dead — attach a time-bounded, fail-open queue-state probe.
return {
diff --git a/src/core/report-back-notice.ts b/src/core/report-back-notice.ts
new file mode 100644
index 0000000000..f7ccbfc625
--- /dev/null
+++ b/src/core/report-back-notice.ts
@@ -0,0 +1,34 @@
+/**
+ * The `wakeshift_report_back` coaching notice (Wakeshift plan D9). A remote caller that submits a job
+ * (`submit_job`, `submit_agent`) holds an id it would otherwise poll, so the submit result tells it once that
+ * gbrain can report back instead: with reporting back published (`mcp.publish_wakeshift`), the watch_job call that
+ * wakes this conversation; without it, the owner's switch. Every remote submit qualifies: gbrain cannot tell a job's
+ * runtime at submit (a sync of one file or ten thousand), remote submit_job only takes sync, import, lint and
+ * lint-fix, and submit_agent is a model loop. The notice ledger keeps it to once per session (HTTP: per principal),
+ * inside the coaching budget, and `mute_notice` / `gbrain notices mute wakeshift_report_back` silence it.
+ * A trusted local CLI submit gets none: it has no conversation to wake.
+ */
+import type { Notice } from './agent-output.ts';
+import type { OperationContext } from './ops/contract.ts';
+import { wakeshiftPublished } from './wakeshift/config.ts';
+
+export const REPORT_BACK_NOTICE_CODE = 'wakeshift_report_back';
+
+/** The notice for a submitted job, in the published or the off wording. */
+export function reportBackNotice(jobId: number, published: boolean): Notice {
+ return {
+ code: REPORT_BACK_NOTICE_CODE,
+ kind: 'coaching',
+ why: published
+ ? `Want this conversation woken when it's done? Call watch_job with id ${jobId}.`
+ : 'gbrain can report back when this finishes, through Wakeshift: ask the brain owner to run gbrain wakeshift enable.',
+ };
+}
+
+/** Emit the notice on a remote caller's accepted submit. Advice only: never throws. */
+export function emitReportBackNotice(ctx: OperationContext, jobId: number): void {
+ if (ctx.remote === false || !ctx.emitNotice) return;
+ try {
+ ctx.emitNotice(reportBackNotice(jobId, wakeshiftPublished()));
+ } catch { /* advice never fails a committed submission */ }
+}
diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.ts
index af369e973a..28f0a797c8 100644
--- a/src/mcp/instructions.ts
+++ b/src/mcp/instructions.ts
@@ -22,6 +22,7 @@ import type { ReadinessEntry } from '../core/readiness.ts';
import { buildAmbientWritebackSection } from '../core/facts/writeback-instructions.ts';
import type { AmbientWritebackOpts } from '../core/facts/writeback-instructions.ts';
import { readEntityReferencesConfig } from '../core/entity-references-config.ts';
+import { wakeshiftPublished } from '../core/wakeshift/config.ts';
/**
* GST-359 C1: initialize's serverInfo.description on every transport, at most 120 characters: the brain-first rule
@@ -64,6 +65,8 @@ export type GoverningRule = typeof GOVERNING_RULES[number];
export interface InstructionContent {
references?: InstructionReferences;
governingRule?: GoverningRule;
+ /** Reporting back through Wakeshift is published (`mcp.publish_wakeshift`); absent or false adds nothing. */
+ reportBack?: boolean;
}
/** Brain config behind InstructionContent. Fail-closed: a read error yields the defaults. */
@@ -74,6 +77,7 @@ export async function readInstructionContent(engine: { getConfig(key: string): P
return {
references: { namesRow: refs.namesRow, records: refs.recordTypes.length > 0 },
governingRule: rule?.trim() === 'newest' ? 'newest' : 'in_effect',
+ ...(wakeshiftPublished() ? { reportBack: true } : {}),
};
}
@@ -147,6 +151,8 @@ function contractClauses(c: CallablePredicate, writeback?: AmbientWritebackOpts
if (c('put_skill') && c('delete_skill')) {
out.push('Shared-skill editing requires separate skill_editor authority. Read the current revision, then use put_skill or delete_skill with a fresh request_id and expected_revision; retry an accepted request only with the same ID and intent. Never use put_page or file uploads to bypass shared-skill publication. Publishing scripts or broader requirements needs separate owner approval; downloading a skill does not authorize executing scripts, installing packages, spending money, or acquiring new permissions.');
}
+ // Wakeshift (D9): last, so it renumbers nothing and stays past the 2,048 characters capped harnesses read.
+ if (content?.reportBack && c('watch_job')) out.push('After you submit a long job (submit_job, submit_agent), offer to call `watch_job` with its id: gbrain then wakes this conversation when it finishes, so you need not poll.');
return out;
}
diff --git a/test/cli-thin-client-refusal-matrix.test.ts b/test/cli-thin-client-refusal-matrix.test.ts
index 34b28aec23..7c98e3dc5d 100644
--- a/test/cli-thin-client-refusal-matrix.test.ts
+++ b/test/cli-thin-client-refusal-matrix.test.ts
@@ -61,6 +61,8 @@ const ROUTING_ROWS: string[][] = [
['recall', 'q'],
['query', 'q'],
['get', 'alice-example'],
+ ['wakeshift', 'watch', 'job', '1'],
+ ['wakeshift', 'status'],
];
const VOLATILE_ROWS: string[][] = [['status'], ['capture', 'hello']];
diff --git a/test/fixtures/goldens/cli/thin-client-cases.json b/test/fixtures/goldens/cli/thin-client-cases.json
index 27fa1d0ceb..392b4541b0 100644
--- a/test/fixtures/goldens/cli/thin-client-cases.json
+++ b/test/fixtures/goldens/cli/thin-client-cases.json
@@ -752,8 +752,9 @@
"argv": "wakeshift",
"exitCode": 1,
"stderr": [
- "Error [requires_local_engine]: `gbrain wakeshift` requires a local engine. This install is a thin client of http://127.0.0.1:1/mcp.",
+ "Error [requires_local_engine]: `gbrain wakeshift` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
"Fix: gbrain wakeshift",
+ "Why: `wakeshift watch job|write|cron` routes to the brain host automatically (watch_job / watch_write_request / watch_cron MCP tools). enable, disable, status and test read or change the brain host's Wakeshift key and settings: run those on the brain host.",
"Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
],
"stdout": []
diff --git a/test/fixtures/goldens/cli/thin-client-routing.json b/test/fixtures/goldens/cli/thin-client-routing.json
index a6c15d9726..2f7f8b1b7b 100644
--- a/test/fixtures/goldens/cli/thin-client-routing.json
+++ b/test/fixtures/goldens/cli/thin-client-routing.json
@@ -265,6 +265,27 @@
"Cannot reach http://127.0.0.1:1/mcp. Run `gbrain remote doctor` for details."
],
"stdout": []
+ },
+ {
+ "argv": "wakeshift watch job 1",
+ "exitCode": 1,
+ "stderr": [
+ "Error [unavailable]: OAuth discovery failed: OAuth discovery network error: ECONNREFUSED: Unable to connect. Is the computer able to access the url?",
+ "Fix: gbrain remote doctor",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#unavailable"
+ ],
+ "stdout": []
+ },
+ {
+ "argv": "wakeshift status",
+ "exitCode": 1,
+ "stderr": [
+ "Error [requires_local_engine]: `gbrain wakeshift` is not routable (thin-client of http://127.0.0.1:1/mcp); run it on the brain host.",
+ "Fix: gbrain wakeshift status",
+ "Why: `wakeshift watch job|write|cron` routes to the brain host automatically (watch_job / watch_write_request / watch_cron MCP tools). enable, disable, status and test read or change the brain host's Wakeshift key and settings: run those on the brain host.",
+ "Docs: https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#requires_local_engine"
+ ],
+ "stdout": []
}
],
"normalizer": "cli-thin-client-v1"
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index 7d56bbb731..60c706e3c4 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -917,6 +917,10 @@
"category": "ops",
"name": "wakeshift"
},
+ {
+ "category": "ops",
+ "name": "wakeshift_openclaw"
+ },
{
"category": "brain",
"name": "fact_take_vectors"
diff --git a/test/init-first-run.test.ts b/test/init-first-run.test.ts
index afc5d2b078..67d0cbf01d 100644
--- a/test/init-first-run.test.ts
+++ b/test/init-first-run.test.ts
@@ -69,6 +69,7 @@ describe('setupFirstRunNotices (gbrain setup <harness>)', () => {
expect(n.user_message).toBe(
'gbrain is set up and Claude Code is wired, so memory works now. In effect: search mode balanced; agents save only what you ask them to remember, '
+ 'until you turn on automatic saving (gbrain recommends salient: durable facts you state, saved with provenance). '
+ + 'Report back (Wakeshift): off. gbrain wakeshift enable turns it on. '
+ `${costMatrixSentence()} Nothing needs an answer now; tell me any time if you want to change any of these, and I'll apply it.`,
);
expect(n.user_message).not.toContain("Reply 'defaults'");
@@ -84,6 +85,16 @@ describe('setupFirstRunNotices (gbrain setup <harness>)', () => {
expect(n.user_message).not.toContain('automatic saving');
});
+ test('every harness gets the Report back (Wakeshift) row: off by default, on once reporting back is published', () => {
+ for (const harness of ['Claude Code', 'Codex']) {
+ const [off] = setupFirstRunNotices(fromInit({ searchMode }), harness);
+ expect(off.user_message).toContain('Report back (Wakeshift): off. gbrain wakeshift enable turns it on.');
+ const [on] = setupFirstRunNotices(fromInit({ searchMode }), harness, { reportBack: true });
+ expect(on.user_message).toContain('Report back (Wakeshift): on. gbrain wakeshift disable turns it off.');
+ expect(on.user_message).not.toContain('Report back (Wakeshift): off');
+ }
+ });
+
test('nothing left to relay → no notice; foreign or missing notices are ignored', () => {
expect(setupFirstRunNotices([{ code: 'first_run_decisions', kind: 'ask', why: 'x', decisions: [wiring] }], 'Claude Code')).toEqual([]);
expect(setupFirstRunNotices([{ code: 'other', kind: 'info', why: 'x' }, null], 'Claude Code')).toEqual([]);
diff --git a/test/setup-openclaw-wakeshift.serial.test.ts b/test/setup-openclaw-wakeshift.serial.test.ts
new file mode 100644
index 0000000000..266ba144a6
--- /dev/null
+++ b/test/setup-openclaw-wakeshift.serial.test.ts
@@ -0,0 +1,121 @@
+/**
+ * \`gbrain setup openclaw --wakeshift\` (Wakeshift plan D11) with an injected command runner: no test runs openclaw.
+ * After consent (persistent install, egress) it runs exactly OpenClaw's pinned npm install and enable, then
+ * inspects; a gateway that listens beyond this computer gets Wakeshift's allowNetworkHooks question printed and
+ * never answered; no openclaw on PATH refuses with a fix line. Doctor's wakeshift_openclaw check compares the
+ * installed version with the pinned constant, as a warning only.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { runSetup } from '../src/commands/setup.ts';
+import { WAKESHIFT_OPENCLAW_VERSION, wakeshiftOpenclawInstallArgv } from '../src/commands/setup-openclaw-wakeshift.ts';
+import { runWakeshiftOpenclawCheck } from '../src/commands/doctor/checks/wakeshift-openclaw.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const sandbox = mkdtempSync(join(tmpdir(), 'gbrain-openclaw-wakeshift-'));
+const stateDir = join(sandbox, 'openclaw');
+const BIN = '/opt/example/bin/openclaw';
+const INSTALL = [BIN, 'plugins', 'install', 'npm:@wakeshift/[email protected]', '--force', '--accept-capabilities'];
+const ENABLE = [BIN, 'plugins', 'enable', 'wakeshift', '--accept-capabilities'];
+const INSPECT = [BIN, 'plugins', 'inspect', 'wakeshift', '--runtime', '--json'];
+const LOADED = JSON.stringify({ id: 'wakeshift', version: '1.4.31', status: 'loaded', enabled: true });
+
+let out = '';
+let err = '';
+let ran: string[][] = [];
+const orig = { log: console.log, error: console.error, out: process.stdout.write.bind(process.stdout), err: process.stderr.write.bind(process.stderr) };
+const env = { HOME: join(sandbox, 'home'), GBRAIN_HOME: join(sandbox, 'home'), CLAUDE_CONFIG_DIR: undefined, CODEX_HOME: undefined, OPENCLAW_STATE_DIR: stateDir, OPENCLAW_CONFIG_PATH: undefined, OPENCLAW_PROFILE: undefined, GBRAIN_CONSENT_PREAPPROVE: undefined };
+
+function runner(answers: Record<string, { ok: boolean; output: string }> = {}) {
+ return (argv: string[]) => { ran.push(argv); return answers[argv.slice(1, 3).join(' ')] ?? { ok: true, output: argv[2] === 'inspect' ? LOADED : '' }; };
+}
+const setup = (args: string[], deps: Parameters<typeof runSetup>[1]) => withEnv(env, () => runSetup(['openclaw', '--wakeshift', ...args], deps));
+
+beforeAll(() => { mkdirSync(join(sandbox, 'home'), { recursive: true }); mkdirSync(stateDir, { recursive: true }); });
+afterAll(() => rmSync(sandbox, { recursive: true, force: true }));
+beforeEach(() => {
+ out = ''; err = ''; ran = [];
+ rmSync(join(stateDir, 'openclaw.json'), { force: true });
+ console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };
+ console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };
+ process.stdout.write = ((c: string | Uint8Array) => { out += String(c); return true; }) as typeof process.stdout.write;
+ process.stderr.write = ((c: string | Uint8Array) => { err += String(c); return true; }) as typeof process.stderr.write;
+});
+afterEach(() => { console.log = orig.log; console.error = orig.error; process.stdout.write = orig.out; process.stderr.write = orig.err; });
+
+describe('gbrain setup openclaw --wakeshift', () => {
+ test('the pinned version lives in one constant and the commands are exactly OpenClaw\'s documented install', () => {
+ expect(WAKESHIFT_OPENCLAW_VERSION).toBe('1.4.31');
+ expect(wakeshiftOpenclawInstallArgv(BIN)).toEqual([INSTALL, ENABLE]);
+ });
+
+ test('with consent it runs install then enable, then verifies, and reports the connected note as pending', async () => {
+ const code = await setup(['--yes', '--json'], { openclaw: { bin: BIN, run: runner() } });
+ expect(code).toBe(0);
+ expect(ran).toEqual([INSTALL, ENABLE, INSPECT]);
+ const doc = JSON.parse(out);
+ expect(doc.wakeshift).toMatchObject({ action: 'installed', version: '1.4.31', network_hooks_question: null, verify: { loaded: true, connected: 'pending' } });
+ expect(doc.wakeshift.verify.message).toContain('Wakeshift: connected');
+ });
+
+ test('without consent nothing runs (exit 3, confirmation_required)', async () => {
+ const code = await setup(['--json'], { openclaw: { bin: BIN, run: runner() } });
+ expect(code).toBe(3);
+ expect(ran).toEqual([]);
+ expect(out + err).toContain('confirmation_required');
+ });
+
+ test('a gateway that listens beyond this computer gets Wakeshift\'s question, and gbrain never sets allowNetworkHooks', async () => {
+ writeFileSync(join(stateDir, 'openclaw.json'), '{ gateway: { bind: "lan" } }');
+ const code = await setup(['--yes'], { openclaw: { bin: BIN, run: runner() } });
+ expect(code).toBe(0);
+ expect(out).toContain('Question from Wakeshift');
+ expect(out).toContain('openclaw config set plugins.entries.wakeshift.config.allowNetworkHooks true --strict-json');
+ expect(ran.some(argv => argv.join(' ').includes('allowNetworkHooks'))).toBe(false);
+ writeFileSync(join(stateDir, 'openclaw.json'), '{ gateway: { bind: "loopback" } }');
+ out = '';
+ await setup(['--yes'], { openclaw: { bin: BIN, run: runner() } });
+ expect(out).not.toContain('Question from Wakeshift');
+ });
+
+ test('no openclaw on PATH refuses with a fix line and runs nothing', async () => {
+ const code = await setup(['--yes'], { openclaw: { bin: null, run: runner() } });
+ expect(code).not.toBe(0);
+ expect(ran).toEqual([]);
+ expect(err).toContain('openclaw_not_found');
+ expect(err).toContain('Fix: gbrain setup openclaw --wakeshift');
+ });
+
+ test('--dry-run lists the commands and runs nothing; a failed install exits 1 and stops before enable', async () => {
+ expect(await setup(['--dry-run'], { openclaw: { bin: BIN, run: runner() } })).toBe(0);
+ expect(ran).toEqual([]);
+ expect(out).toContain('would run');
+ expect(out).toContain('npm:@wakeshift/[email protected]');
+ const code = await setup(['--yes', '--json'], { openclaw: { bin: BIN, run: runner({ 'plugins install': { ok: false, output: 'npm error 404' } }) } });
+ expect(code).toBe(1);
+ expect(ran).toEqual([INSTALL]);
+ expect(JSON.parse(out.slice(out.indexOf('{'))).wakeshift).toMatchObject({ action: 'failed', output: 'npm error 404' });
+ });
+
+ test('--wakeshift on another harness is refused', async () => {
+ const code = await withEnv(env, () => runSetup(['claude-code', '--wakeshift', '--yes'], { openclaw: { bin: BIN, run: runner() } }));
+ expect(code).not.toBe(0);
+ expect(ran).toEqual([]);
+ expect(err).toContain('applies to gbrain setup openclaw only');
+ });
+});
+
+describe('doctor wakeshift_openclaw', () => {
+ const inspect = (version: string | null) => (argv: string[]) => (version === null ? { ok: false, output: 'plugin not found' } : { ok: argv[2] === 'inspect', output: JSON.stringify({ id: 'wakeshift', version }) });
+
+ test('warns on drift from the pinned version, ok when it matches, info when not installed, silent without openclaw', async () => {
+ const [drift] = await runWakeshiftOpenclawCheck(null, { bin: BIN, run: inspect('1.4.30') });
+ expect(drift).toMatchObject({ name: 'wakeshift_openclaw', status: 'warn' });
+ expect(drift!.message).toContain('gbrain setup openclaw --wakeshift');
+ expect((await runWakeshiftOpenclawCheck(null, { bin: BIN, run: inspect('1.4.31') }))[0]).toMatchObject({ status: 'ok' });
+ expect((await runWakeshiftOpenclawCheck(null, { bin: BIN, run: inspect(null) }))[0]).toMatchObject({ status: 'ok', severity: 'info' });
+ expect(await runWakeshiftOpenclawCheck(null, { bin: null, run: inspect('1.4.30') })).toEqual([]);
+ });
+});
diff --git a/test/setup.test.ts b/test/setup.test.ts
index 6b1b415d7e..b28a864429 100644
--- a/test/setup.test.ts
+++ b/test/setup.test.ts
@@ -99,6 +99,7 @@ describe('gbrain setup claude-code: install lifecycle', () => {
expect(bundle).toMatchObject({ code: 'first_run_decisions', kind: 'ask' });
expect(bundle.decisions.map((d: any) => d.id)).not.toContain('harness_wiring');
expect(bundle.user_message).not.toContain("Reply 'defaults'");
+ expect(bundle.user_message).toContain('Report back (Wakeshift): off. gbrain wakeshift enable turns it on.');
const before = [readFileSync(claudeJson(b), 'utf8'), readFileSync(settings(b), 'utf8'), readFileSync(receipt(b), 'utf8')];
const second = await setup(b, ['claude-code', '--json']);
@@ -134,6 +135,7 @@ describe('gbrain setup claude-code: install lifecycle', () => {
expect(hosted).toBeGreaterThan(r.stdout.indexOf('[first_run_decisions]'));
expect(r.stdout.slice(block, hosted)).toContain('in the reply that reports this install');
expect(r.stdout.slice(block, hosted)).toContain('(id: search_mode)');
+ expect(r.stdout.slice(block, hosted)).toContain('Report back (Wakeshift): off. gbrain wakeshift enable turns it on.');
expect(r.stdout.slice(hosted)).toContain('https://gbrain.io/?ref=cli-setup');
expect(r.stdout.trimEnd().endsWith('[/AGENT]')).toBe(true);
});
@@ -557,6 +559,7 @@ describe('gbrain setup codex: install lifecycle', () => {
expect(first.doc.states).toEqual(['configured', 'connection-verified', 'native-verified']);
expect(first.doc.capability).toMatchObject({ harness: 'codex', setup: 'supported', push: 'native-verified', read_events: ['SessionStart', 'UserPromptSubmit'] });
expect(first.doc.consent.capture).toMatchObject({ value: 'declined', source: 'default' });
+ expect(first.doc.notices.find((n: any) => n.code === 'first_run_decisions').user_message).toContain('Report back (Wakeshift): off. gbrain wakeshift enable turns it on.');
expect(readJson(join(b.gbrainHome, '.gbrain', 'config.json')).embedding_disabled).toBe(true);
expect(toml(b).mcp_servers.gbrain).toEqual({ command: launcher(b), args: [b.bin, 'serve', '--surface', 'starter', '--advertise', 'verbs'], env: { GBRAIN_HOME: b.gbrainHome } });
expect(Object.keys(readJson(hooksJson(b)).hooks).sort()).toEqual(['SessionStart', 'UserPromptSubmit']);
diff --git a/test/thin-client-routing.test.ts b/test/thin-client-routing.test.ts
index 8ae5f7057f..d6cfabb935 100644
--- a/test/thin-client-routing.test.ts
+++ b/test/thin-client-routing.test.ts
@@ -308,3 +308,63 @@ describe('routeThinClientCommand — (c) malformed routable forms print usage +
await expectUsageExit('takes', ['supersede', 'people/alice-example', '--row', '1']);
});
});
+
+describe('routeThinClientCommand — wakeshift watch (Wakeshift report-back over MCP)', () => {
+ const TAIL = 'Wakeshift: run \`wakeshift wait --session sk-example\` in the background to be woken.';
+ function respond(result: unknown, extra: Array<{ type: string; text: string }>): void {
+ callSpy.mockImplementationOnce(async (_cfg: GBrainConfig, tool: string, args: Record<string, unknown> = {}) => {
+ calls.push({ tool, args });
+ return { content: [{ type: 'text', text: JSON.stringify(result) }, ...extra] };
+ });
+ }
+ const watching = { watching: true, watch: 3, job: 812, event: 'gbrain.job.finished', status: 'active', already_finished: false, expires_in: '7d', fallback: 'If no wake arrives, call wait_job 812 (or run gbrain jobs wait 812).' };
+
+ test('watch job routes to watch_job with the caller params as given, and the tail is the last stdout line', async () => {
+ respond(watching, [{ type: 'text', text: TAIL }]);
+ expect(await routeThinClientCommand(cfg, 'wakeshift', ['watch', 'job', '812', '--session-key', 'sk-example', '--harness', 'grok-bot', '--conversation-id', 'conv-1'])).toBe(true);
+ expect(soleCall()).toEqual({ tool: 'watch_job', args: { id: 812, session_key: 'sk-example', harness: 'grok-bot', conversation_id: 'conv-1' } });
+ expect(logs.at(-1)).toBe(TAIL);
+ expect(logs.join('\n')).toContain('wait_job 812');
+ expect(errs.join('\n')).not.toContain('sk-example');
+ });
+
+ test('no --harness sends no harness; write and cron route to their own ops', async () => {
+ respond(watching, []);
+ expect(await routeThinClientCommand(cfg, 'wakeshift', ['watch', 'job', '9'])).toBe(true);
+ expect(calls.at(-1)).toEqual({ tool: 'watch_job', args: { id: 9 } });
+ respond({ watching: true, request_id: 'req-example' }, []);
+ expect(await routeThinClientCommand(cfg, 'wakeshift', ['watch', 'write', 'req-example', '--harness', 'muse'])).toBe(true);
+ expect(calls.at(-1)).toEqual({ tool: 'watch_write_request', args: { request_id: 'req-example', harness: 'muse' } });
+ respond({ watching: true, name: 'nightly-digest' }, []);
+ expect(await routeThinClientCommand(cfg, 'wakeshift', ['watch', 'cron', 'nightly-digest'])).toBe(true);
+ expect(calls.at(-1)).toEqual({ tool: 'watch_cron', args: { name: 'nightly-digest' } });
+ });
+
+ test('--json prints the result as one JSON line, then the tail last; a gbrain notice block is never taken for the tail', async () => {
+ respond(watching, [{ type: 'text', text: TAIL }]);
+ expect(await routeThinClientCommand(cfg, 'wakeshift', ['watch', 'job', '812', '--json'])).toBe(true);
+ expect(JSON.parse(logs[0]!)).toEqual(watching);
+ expect(logs.at(-1)).toBe(TAIL);
+ logs.length = 0;
+ respond(watching, [{ type: 'text', text: '[gbrain notice no_worker kind=info]\nwhy: no worker' }]);
+ expect(await routeThinClientCommand(cfg, 'wakeshift', ['watch', 'job', '812', '--json'])).toBe(true);
+ expect(logs).toHaveLength(1);
+ expect(JSON.parse(logs[0]!)).toEqual(watching);
+ });
+
+ test('only watch routes: every other wakeshift subcommand is host-bound', async () => {
+ for (const sub of ['status', 'enable', 'disable', 'test']) {
+ expect(await routeThinClientCommand(cfg, 'wakeshift', [sub])).toBe(false);
+ }
+ expect(calls).toHaveLength(0);
+ });
+
+ test('a malformed watch is a usage error with nothing sent', async () => {
+ for (const args of [['watch'], ['watch', 'job'], ['watch', 'job', 'abc'], ['watch', 'page', 'x'], ['watch', 'job', '1', '--harness']]) {
+ expect(await routeThinClientCommand(cfg, 'wakeshift', args)).toBe(true);
+ expect(currentExitCode()).toBe(2);
+ _resetCliExitVerdictForTests();
+ }
+ expect(calls).toHaveLength(0);
+ });
+});
diff --git a/test/wakeshift-nudge.serial.test.ts b/test/wakeshift-nudge.serial.test.ts
new file mode 100644
index 0000000000..37ea4dd317
--- /dev/null
+++ b/test/wakeshift-nudge.serial.test.ts
@@ -0,0 +1,157 @@
+/**
+ * Wakeshift PR 2 nudges (plan D9) on a repo-less PGLite brain: the `wakeshift_report_back` coaching notice on
+ * remote submit_job and submit_agent (once per principal session, never again, never after mute_notice; the
+ * watch_job line only while reporting back is published), and the one MCP instructions sentence that exists only
+ * while it is published, so an off brain serves byte-identical instructions and hides every watch tool.
+ *
+ * Serial: GBRAIN_HOME (config.json, the 0600 key file, the mute store) is a temporary home set through withEnv.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall, type ToolResult } from '../src/mcp/dispatch.ts';
+import { NoticeLedger } from '../src/core/notice-ledger.ts';
+import { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';
+import { sqlQueryForEngine } from '../src/core/sql-query.ts';
+import { encodeWakeshiftKey } from '../src/core/wakeshift/client.ts';
+import { resetWakeshiftEnvKeyForTests } from '../src/core/wakeshift/config.ts';
+import { NOTICE_CODES } from '../src/core/error-registry.ts';
+import { operationsByName, type OperationContext } from '../src/core/operations.ts';
+import { buildMcpInstructions, readInstructionContent } from '../src/mcp/instructions.ts';
+import { disabledOpsForPublishGates } from '../src/mcp/publish-gates.ts';
+import { OPERATION_MANIFEST } from '../src/core/operation-manifest.generated.ts';
+import type { AuthInfo } from '../src/core/ops/contract.ts';
+import type { Notice } from '../src/core/agent-output.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const KEY = encodeWakeshiftKey(Buffer.alloc(32, 7));
+const OFF_TEXT = 'gbrain can report back when this finishes, through Wakeshift: ask the brain owner to run gbrain wakeshift enable.';
+const sandbox = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-nudge-'));
+const home = join(sandbox, 'home');
+const root = join(sandbox, 'notes');
+let engine: PGLiteEngine;
+let auth: AuthInfo;
+
+const isolated = <T>(fn: () => T | Promise<T>) => withEnv({ GBRAIN_HOME: home, WAKESHIFT_API_KEY: undefined }, fn);
+
+function writeConfig(enabled: boolean): void {
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', ...(enabled ? { wakeshift: { enabled: true, url: 'http://127.0.0.1:1' } } : {}) }), { mode: 0o600 });
+}
+
+function noticeCodes(r: ToolResult): string[] {
+ return ((r._meta?.gbrain_notices ?? []) as Array<{ code: string }>).map(n => n.code);
+}
+const reportBack = (r: ToolResult) => r.content.map(b => b.text).filter(t => t.startsWith('[gbrain notice wakeshift_report_back'));
+const http = (ledger: NoticeLedger) => ({ remote: true, transport: 'http' as const, sourceId: 'default', auth, noticeLedger: ledger });
+const jobId = (r: ToolResult) => Number(JSON.parse(r.content[0]!.text).id);
+
+beforeAll(async () => isolated(async () => {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ mkdirSync(root);
+ writeFileSync(join(home, '.gbrain', 'wakeshift.key'), KEY + '\n', { mode: 0o600 });
+ resetWakeshiftEnvKeyForTests();
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await engine.executeRaw("UPDATE sources SET config = '{}'::jsonb, archived = false, local_path = $1 WHERE id = 'default'", [root]);
+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(engine), transaction: fn => engine.transaction(tx => fn(sqlQueryForEngine(tx))) });
+ const reg = await provider.registerClientManual('agent-example', ['client_credentials'], 'read write admin', [], 'default');
+ await engine.executeRaw("UPDATE oauth_clients SET scope = 'read write admin agent', bound_tools = $2, bound_source_id = source_id, federated_read = ARRAY[source_id], delegated_namespace = 'job', delegated_slug_prefixes = NULL, bound_max_concurrent = 50 WHERE client_id = $1", [reg.clientId, ['get_page', 'search']]);
+ auth = await provider.verifyAccessToken((await provider.exchangeClientCredentials(reg.clientId, reg.clientSecret!)).access_token) as unknown as AuthInfo;
+}), 120_000);
+
+afterAll(async () => {
+ await engine.disconnect();
+ rmSync(sandbox, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ await engine.executeRaw('DELETE FROM minion_jobs');
+ rmSync(join(home, '.gbrain', 'notices'), { recursive: true, force: true });
+});
+
+describe('wakeshift_report_back coaching notice', () => {
+ test('is a registered, muteable coaching code', () => {
+ expect(NOTICE_CODES.wakeshift_report_back).toMatchObject({ kind: 'coaching' });
+ });
+
+ test('off: the first long submit carries the enable hint once, then never again in the session', () => isolated(async () => {
+ writeConfig(false);
+ const ledger = new NoticeLedger();
+ const first = await dispatchToolCall(engine, 'submit_job', { name: 'lint', data: {} }, http(ledger));
+ expect(first.isError).toBeFalsy();
+ expect(noticeCodes(first)).toContain('wakeshift_report_back');
+ expect(reportBack(first)).toHaveLength(1);
+ expect(reportBack(first)[0]).toContain(OFF_TEXT);
+ expect(first.content.map(b => b.text).join('\n')).not.toContain('watch_job');
+ for (const [op, params] of [['submit_job', { name: 'lint', data: {} }], ['submit_agent', { prompt: 'Summarize the notes' }], ['submit_job', { name: 'lint-fix', data: {} }]] as const) {
+ const again = await dispatchToolCall(engine, op, params, http(ledger));
+ expect(again.isError).toBeFalsy();
+ expect(noticeCodes(again)).not.toContain('wakeshift_report_back');
+ expect(reportBack(again)).toEqual([]);
+ }
+ }));
+
+ test('on: submit_agent offers watch_job with its own job id, once', () => isolated(async () => {
+ writeConfig(true);
+ const ledger = new NoticeLedger();
+ const first = await dispatchToolCall(engine, 'submit_agent', { prompt: 'Summarize the notes' }, http(ledger));
+ expect(first.isError).toBeFalsy();
+ expect(reportBack(first)).toHaveLength(1);
+ expect(reportBack(first)[0]).toContain(`Want this conversation woken when it's done? Call watch_job with id ${jobId(first)}.`);
+ const second = await dispatchToolCall(engine, 'submit_job', { name: 'lint', data: {} }, http(ledger));
+ expect(reportBack(second)).toEqual([]);
+ }));
+
+ test('never after mute_notice, in this session or a later one', () => isolated(async () => {
+ writeConfig(false);
+ const muted = await dispatchToolCall(engine, 'mute_notice', { code: 'wakeshift_report_back' }, http(new NoticeLedger()));
+ expect(muted.isError).toBeFalsy();
+ for (const ledger of [new NoticeLedger(), new NoticeLedger()]) {
+ const r = await dispatchToolCall(engine, 'submit_job', { name: 'lint', data: {} }, http(ledger));
+ expect(r.isError).toBeFalsy();
+ expect(noticeCodes(r)).not.toContain('wakeshift_report_back');
+ expect(reportBack(r)).toEqual([]);
+ }
+ }));
+
+ test('a trusted local CLI submit gets no hint (it has no conversation to wake)', () => isolated(async () => {
+ writeConfig(true);
+ const notices: Notice[] = [];
+ const ctx = { engine, config: {}, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, emitNotice: (n: Notice) => { notices.push(n); } } as unknown as OperationContext;
+ await operationsByName.submit_job!.handler(ctx, { name: 'lint', data: {} });
+ expect(notices.map(n => n.code)).not.toContain('wakeshift_report_back');
+ }));
+});
+
+describe('MCP instructions and tools/list', () => {
+ const callable = () => true;
+ const watchless = (name: string) => !name.startsWith('watch_') && name !== 'list_watches' && name !== 'unwatch';
+
+ test('off: instructions are byte-identical to the rendering without Wakeshift, and every watch tool is hidden', () => isolated(async () => {
+ writeConfig(false);
+ const content = await readInstructionContent(engine);
+ const served = buildMcpInstructions({ tools: { callable }, ...content });
+ const { references, governingRule } = content;
+ expect(served).toBe(buildMcpInstructions({ tools: { callable }, references, governingRule }));
+ expect(served).not.toContain('watch_job');
+ const gated = OPERATION_MANIFEST.filter(op => op.publishGateKey === 'mcp.publish_wakeshift').map(op => op.name);
+ expect(gated).toContain('watch_job');
+ const disabled = await disabledOpsForPublishGates(engine, null, { transport: 'http' });
+ for (const name of gated) expect(disabled.has(name)).toBe(true);
+ }));
+
+ test('on: exactly one added sentence, and only where watch_job is callable', () => isolated(async () => {
+ writeConfig(true);
+ const content = await readInstructionContent(engine);
+ const { references, governingRule } = content;
+ const base = buildMcpInstructions({ tools: { callable }, references, governingRule });
+ const served = buildMcpInstructions({ tools: { callable }, ...content });
+ expect(served).not.toBe(base);
+ expect(served.split('\n').filter(l => !base.split('\n').includes(l))).toHaveLength(1);
+ expect(served.match(/watch_job/g)).toHaveLength(1);
+ expect(buildMcpInstructions({ tools: { callable: watchless }, ...content })).toBe(buildMcpInstructions({ tools: { callable: watchless }, references, governingRule }));
+ }));
+});
diff --git a/test/wakeshift-watch.serial.test.ts b/test/wakeshift-watch.serial.test.ts
new file mode 100644
index 0000000000..df01947036
--- /dev/null
+++ b/test/wakeshift-watch.serial.test.ts
@@ -0,0 +1,72 @@
+/**
+ * \`gbrain wakeshift watch\` on a brain host (Wakeshift plan D8), on a repo-less PGLite brain: the local CLI has no
+ * conversation to wake, so watch_job's refusal prints with its fix (gbrain jobs wait <id>) and a non-zero exit, and a
+ * session_key passed on the command line is never written anywhere under GBRAIN_HOME nor echoed. The thin-client
+ * route is pinned in test/thin-client-routing.test.ts and the refusal matrix golden.
+ */
+import { describe, test, expect, beforeAll, afterAll, beforeEach, afterEach } from 'bun:test';
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runWakeshift } from '../src/commands/wakeshift.ts';
+import { parseWatchArgs } from '../src/commands/wakeshift-watch.ts';
+import { currentExitCode, _resetCliExitVerdictForTests } from '../src/core/cli-force-exit.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-wakeshift-watch-'));
+const SECRET = 'sk-never-persist-example';
+let engine: PGLiteEngine;
+let out = '';
+let err = '';
+const orig = { log: console.log, error: console.error, write: process.stderr.write.bind(process.stderr), exitCode: process.exitCode };
+
+function walk(dir: string): string[] {
+ return readdirSync(dir).flatMap(n => { const p = join(dir, n); return statSync(p).isDirectory() ? walk(p) : [p]; });
+}
+
+beforeAll(async () => {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+afterAll(async () => { await engine.disconnect(); rmSync(home, { recursive: true, force: true }); });
+beforeEach(() => {
+ out = ''; err = '';
+ _resetCliExitVerdictForTests();
+ console.log = (...a: unknown[]) => { out += a.map(String).join(' ') + '\n'; };
+ console.error = (...a: unknown[]) => { err += a.map(String).join(' ') + '\n'; };
+ process.stderr.write = ((c: string | Uint8Array) => { err += String(c); return true; }) as typeof process.stderr.write;
+});
+afterEach(() => {
+ console.log = orig.log; console.error = orig.error; process.stderr.write = orig.write;
+ _resetCliExitVerdictForTests();
+ process.exitCode = orig.exitCode ?? 0;
+});
+
+describe('gbrain wakeshift watch on the brain host', () => {
+ test('watch job prints watch_job\'s refusal with the local wait as its fix, exits non-zero, and never stores or echoes the session key', () =>
+ withEnv({ GBRAIN_HOME: home, WAKESHIFT_API_KEY: undefined }, async () => {
+ await runWakeshift(engine, ['watch', 'job', '5', '--session-key', SECRET, '--harness', 'claude-code']);
+ expect(err).toContain('wakeshift_needs_conversation');
+ expect(err).toContain('gbrain jobs wait 5');
+ expect(currentExitCode()).not.toBe(0);
+ expect(out).toBe('');
+ expect(err).not.toContain(SECRET);
+ for (const file of walk(home)) expect(readFileSync(file, 'utf8')).not.toContain(SECRET);
+ }));
+
+ test('watch --help prints the watch usage', async () => {
+ await runWakeshift(engine, ['watch', '--help']);
+ expect(out).toContain('gbrain wakeshift watch job <id>');
+ expect(out).toContain('--session-key');
+ });
+
+ test('parse: params pass through as given, nothing defaulted', () => {
+ expect(parseWatchArgs(['job', '7'])).toEqual({ tool: 'watch_job', params: { id: 7 }, json: false });
+ expect(parseWatchArgs(['cron', 'nightly-digest', '--harness', 'openclaw', '--json'])).toEqual({ tool: 'watch_cron', params: { name: 'nightly-digest', harness: 'openclaw' }, json: true });
+ expect(parseWatchArgs(['write', 'req-1', '--conversation-id', 'c-1'])).toEqual({ tool: 'watch_write_request', params: { request_id: 'req-1', conversation_id: 'c-1' }, json: false });
+ expect(typeof parseWatchArgs(['job', '0'])).toBe('string');
+ });
+});