Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(windows): stop cmd.exe from eating the hive protocol prompt

Chaitanya Giri00abd5a34c74
diff --git a/package.json b/package.json
index 42f7ff4a..12e17e22 100644
--- a/package.json
+++ b/package.json
@@ -19,7 +19,7 @@
"typecheck:node": "tsc --noEmit -p tsconfig.node.json",
"typecheck:web": "tsc --noEmit -p tsconfig.web.json",
"typecheck": "npm run typecheck:node && npm run typecheck:web",
- "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs",
+ "test:focused": "node --test test/codex-remote.test.cjs test/control.test.cjs test/provider-automation.test.cjs test/provider-config.test.cjs test/queue-delivery.test.cjs test/terminal-automation.test.cjs test/terminal-recovery.test.cjs test/terminal-selection.test.cjs test/roster.test.cjs test/proc-kill.test.cjs test/expand-tilde.test.cjs test/hive-cwd.test.cjs test/hive-task-mutation.test.cjs test/hive-hook-node.test.cjs test/hive-roster-injection.test.cjs test/hive-runtime-path.test.cjs test/cli-install-ladder.test.cjs test/node-install.test.cjs test/office-gl-recovery.test.cjs test/update-state.test.cjs test/transcript-project-dir.test.cjs test/commit-graph.test.cjs test/win-cmd-shim.test.cjs test/hive-windows-prompt.test.cjs",
"check:links": "node tools/check-release-links.cjs",
"dist": "npm run build && electron-builder",
"dist:mac": "npm run build && electron-builder --mac",
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 2994b9e7..ce5cd937 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -376,6 +376,19 @@ export class HiveManager {
return p && existsSync(p) ? p : null;
}
+ /** The ABSOLUTE bundled-node command to BAKE into any text an agent is expected
+ * to run (`<launcher> <script> …`), falling back to bare `node`.
+ *
+ * Exactly the value of the agent's `HIVE_NODE` env var — but agent-facing text
+ * must never spell it as `$HIVE_NODE`: that is POSIX shell syntax. A Windows
+ * agent runs its commands through cmd.exe/PowerShell, where `$HIVE_NODE`
+ * expands to NOTHING (cmd) or to an undefined variable (PowerShell), so every
+ * such instruction is dead on arrival there. The absolute path is correct on
+ * every platform and needs no expansion at all. */
+ nodeCommand(): string {
+ return this.nodeLauncher() ?? 'node';
+ }
+
/**
* `<root>/bin/runtime` — the same bundled-node trick as `hive-node`, but the
* wrapper is NAMED `node`, so anything that resolves `node` off PATH finds one.
@@ -531,6 +544,12 @@ export class HiveManager {
opts: {
semanticMemory?: boolean;
knowledgeGraph?: boolean;
+ /** ABSOLUTE path to the Knowledge-Graph CLI (`knowledge.env().KG_CLI`), baked
+ * into the agent's prompt instead of a `$KG_CLI` shell reference — `$VAR` is
+ * POSIX-only and expands to nothing under cmd.exe/PowerShell, so the KG
+ * instructions were unusable on Windows. Optional: undefined degrades to the
+ * old env-var spelling. */
+ kgCliPath?: string;
theme?: 'light' | 'dark';
/** Consent state for the default-MCP bundle (W3). Threaded from the live
* HarnessConfig by the caller; undefined → catalog defaults apply. */
@@ -607,13 +626,16 @@ export class HiveManager {
AGENT_DIR: dir
};
// The bundled-node launcher, so an agent can run the hive's .cjs helpers (KG
- // CLI, Slack reply helper) even when `node` is not on its PATH. The agent's
- // system prompt tells it to use `"$HIVE_NODE" <script>`; invoking the Electron
- // binary directly would open a second app window, so this must stay the
- // wrapper path and never process.execPath.
- // Always set (falls back to plain `node`) so agent-facing commands can be
- // written as `"$HIVE_NODE" <script>` unconditionally and never expand to "".
- env.HIVE_NODE = this.nodeLauncher() ?? 'node';
+ // CLI, Slack reply helper) even when `node` is not on its PATH. Invoking the
+ // Electron binary directly would open a second app window, so this must stay
+ // the wrapper path and never process.execPath.
+ //
+ // Kept as an env var for agent CONVENIENCE and for anything that reads it
+ // programmatically — but agent-facing TEXT no longer references it by name:
+ // `$HIVE_NODE` is POSIX-only syntax and expands to nothing under cmd.exe /
+ // PowerShell, so every such instruction was dead on a Windows floor. Commands
+ // we write for an agent to run bake `nodeCommand()`'s absolute path instead.
+ env.HIVE_NODE = this.nodeCommand();
const claudeProvider = isClaudeProvider(meta.provider ?? 'claude');
@@ -635,7 +657,7 @@ export class HiveManager {
if (!isHiveAwareProvider(meta.provider)) {
const preset = providerPreset(meta.provider ?? 'claude');
const flag = preset.initialPromptFlag;
- const prompt = this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false, opts.knowledgeGraph ?? false);
+ const prompt = this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false, opts.knowledgeGraph ?? false, opts.kgCliPath);
// agy, codex, and grok expose a Claude-style lifecycle-hook surface, so each
// gets the SAME live status + Stop→inbox-drain Claude does — selected by the
// preset's `hookBridge`. agy needs a translating shim (its hook stdin/stdout
@@ -756,7 +778,7 @@ export class HiveManager {
const args: string[] = [];
if (!claudeProvider) return { args, env };
- args.push('--append-system-prompt', this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false, opts.knowledgeGraph ?? false));
+ args.push('--append-system-prompt', this.injectedPrompt(meta, dir, root, opts.semanticMemory ?? false, opts.knowledgeGraph ?? false, opts.kgCliPath));
// Phase 1 — autonomy: attach lifecycle hooks via --settings (no edits to the
// user's repo) so the agent reports activity and drains its inbox on Stop.
@@ -1022,7 +1044,9 @@ export class HiveManager {
const reason = [
`You have ${fresh.length} new hive message(s) in your inbox. Address them before finishing:`,
lines,
- `Open the files in ${dir}/inbox/ for full detail, act on each, then move handled ones to inbox/.done/. Reply via your outbox if a message requires it.`
+ // Native separators (join, not string-concatenated `/`) so a Windows agent is
+ // handed a path its own shell/tools accept, not `C:\…\agents\god/inbox/`.
+ `Open the files in ${join(dir, 'inbox')} for full detail, act on each, then move handled ones to ${join(dir, 'inbox', '.done')}. Reply via your outbox if a message requires it.`
].join('\n');
return { block: true, reason };
}
@@ -1053,35 +1077,62 @@ export class HiveManager {
* Anthropic's prompt cache (re-priming the whole system prompt every turn).
* Volatile context belongs on the live channels — the inbox (hive messages) and
* the PTY — never baked into this prefix. (Lane A #6.1.)
+ *
+ * 🪟 NO SHELL SYNTAX. Every path and command here is written the way the AGENT
+ * will actually type it, on the platform it is running on. That rules out two
+ * habits that were silently Windows-only breakage:
+ * - `$VAR` — POSIX-only. Under cmd.exe `$HIVE_NODE`/`$KG_CLI` expand to nothing
+ * and under PowerShell to an undefined variable, so those instructions were
+ * dead on every Windows floor. Bake the ABSOLUTE resolved path instead: it is
+ * platform-independent, needs no expansion, and stays prompt-cache-stable.
+ * - `'…' + '/inbox/'` — string-concatenating separators told a Windows agent to
+ * read `C:\Users\x\hive\agents\god/inbox/`. Use join() so the agent's own
+ * tooling gets a path it can pass straight to its shell.
*/
- private injectedPrompt(meta: AgentMeta, dir: string, root: string, semanticMemory: boolean, knowledgeGraph: boolean): string {
+ private injectedPrompt(
+ meta: AgentMeta,
+ dir: string,
+ root: string,
+ semanticMemory: boolean,
+ knowledgeGraph: boolean,
+ kgCliPath?: string
+ ): string {
+ // Native-separator path helpers — see the 🪟 note above.
+ const inDir = (...parts: string[]): string => join(dir, ...parts);
+ const inRoot = (...parts: string[]): string => join(root, ...parts);
const memoryLine = semanticMemory
- ? 'Semantic memory: the whole hive shares a searchable MemPalace at $MEMPALACE_PALACE_PATH. To recall relevant past knowledge across the team, run `mempalace search "<query>"`; run `mempalace wake-up` at the start of a task for a memory digest. Your notes in memory.md are mined into the palace automatically — write durable facts there.'
+ // The palace location is named, not spelled as `$MEMPALACE_PALACE_PATH`:
+ // `mempalace` reads that env var itself, and the POSIX `$` form was noise
+ // (or an empty expansion) for a Windows agent that tried to use it literally.
+ ? 'Semantic memory: the whole hive shares a searchable MemPalace at the path in your MEMPALACE_PALACE_PATH environment variable. To recall relevant past knowledge across the team, run `mempalace search "<query>"`; run `mempalace wake-up` at the start of a task for a memory digest. Your notes in memory.md are mined into the palace automatically — write durable facts there.'
: '';
- // Enterprise Knowledge Graph (opt-in). Volatile-free: references only the
- // stable $KG_CLI / $KG_ROOT env vars injected at spawn — no paths/counts that
- // would change per spawn and bust the prompt cache.
+ // Enterprise Knowledge Graph (opt-in). Volatile-free: the bundled-node launcher
+ // and the KG CLI are both fixed absolute paths for an install, so baking them
+ // keeps the prefix prompt-cache-stable while making the command runnable in
+ // cmd.exe/PowerShell as well as a POSIX shell.
+ const hiveNode = this.nodeCommand();
+ const kgCli = kgCliPath || (process.platform === 'win32' ? '%KG_CLI%' : '$KG_CLI');
const knowledgeLine = knowledgeGraph
- ? 'Enterprise knowledge: this organisation has a private Knowledge Graph of its own documents, policies, and business context. When a task needs that context — company-specific facts, house style, internal processes — query it instead of guessing: run `"$HIVE_NODE" "$KG_CLI" search "<query>"` for ranked passages, `"$HIVE_NODE" "$KG_CLI" list` to see what is available, and `"$HIVE_NODE" "$KG_CLI" get <id>` for a full document. ($HIVE_NODE is the harness\'s bundled Node — use it instead of bare `node`, which may not be on your PATH.)'
+ ? `Enterprise knowledge: this organisation has a private Knowledge Graph of its own documents, policies, and business context. When a task needs that context — company-specific facts, house style, internal processes — query it instead of guessing: run \`"${hiveNode}" "${kgCli}" search "<query>"\` for ranked passages, \`"${hiveNode}" "${kgCli}" list\` to see what is available, and \`"${hiveNode}" "${kgCli}" get <id>\` for a full document. (That first path is the harness's bundled Node — use it instead of bare \`node\`, which may not be on your PATH.)`
: '';
const godLine = meta.isGod
? 'You are the GOD / ORCHESTRATOR of this hive — your job is to ORCHESTRATE, not to implement: maintain live situational awareness and delegate the work. (1) AWARENESS — always know what is going on: keep an accurate picture of every agent (active vs archived/idle), the task board, and all in-flight work; drain your inbox continually and triage every other agent\'s requests, answering clarifications so the team runs autonomously. (2) DELEGATE — decompose work and fan it out to the hive agents via their inboxes (route messages and assign owners; do not do their jobs); do NOT take on grunt implementation yourself. Stay aware of who is already on the floor and delegate OPPORTUNISTICALLY: BEFORE you spawn anything, CHECK THE LIVE ROSTER (active agents in registry.json + their state in fleet.json) and prefer routing to an EXISTING agent that fits — above all when the request names one ("ask Pam to…", "have Jim…"), route to that agent instead of reflexively creating a new one. Reuse an idle or already-running agent whose role matches; only spawn a fresh agent when no existing one is a sensible fit, and say that you checked. One capable owner beats a duplicate. (3) OWN ONLY THE IMPORTANT, high-leverage things — task decomposition, dispatch decisions, sign-offs, conflict resolution, branch integration, and final QA — and remain the sole scribe of board.md. You are otherwise fully autonomous — there is NO separate approval queue. For the genuinely critical (destructive actions, spending real money, scope changes, unresolvable conflicts), ask the human directly in your own session and let the tool-permission prompt gate the action; the human approves natively, including remotely from their phone via /remote-control. Keep the team unblocked. When you DISPATCH a task, write it as a 4-part contract so the agent can run autonomously: (1) OBJECTIVE — the concrete goal; (2) OUTPUT — the expected deliverable/format; (3) TOOLS — what to use or avoid, and any references to read instead of re-deriving; (4) BOUNDARIES — scope limits + the definition of done. Pass references (file paths, message ids, board sections), not pasted content — keep dispatches short.'
- + ` MONITOR the floor by reading ${root}/fleet.json (live per-agent tokens, cost, status, last tool, breaker level, inbox backlog) and ${root}/registry.json — note that running 'claude agents' will NOT list your hive's sibling agents. A full Claude Code command reference is at ${root}/COMMANDS.md (slash commands act ONLY on your own session; CLI commands run in your shell and can target the fleet). You periodically receive scheduler / "Heartbeat" standup requests — on each, review every agent via fleet.json, re-engage anyone stalled, over-budget, or breaker-armed, and keep board.md and tasks.json accurate. In tasks.json, ALWAYS set each task's "assignee" to the worker's agent id the moment you dispatch it, and NEVER clear it on status changes — a done card must still say who did the work (the human reads the board by who-did-what). HUMAN FEEDBACK is first-class in the ledger: when a task can only proceed with the human's input — a QUESTION to answer OR an ACTION only the human can perform (create an account, approve a purchase, provide credentials/screenshots, test on their device) — set its status to "blocked" and append the concrete ask to the card's "humanQA" array (push {"q":"...","askedAt":"<iso>"}; phrase actions as clear to-dos; keep every past entry — the history documents the card's decisions). The harness surfaces open questions on the office floor's ASK ME board; the human's answer lands in the same entry ("a") AND arrives as an inbox message to you — read it, act on it, and unblock the card so work continues. Do NOT park human questions in separate files (no HumanQuestion.md) and never sit waiting on the human in your own session. Steward the token budget.`
+ + ` MONITOR the floor by reading ${inRoot('fleet.json')} (live per-agent tokens, cost, status, last tool, breaker level, inbox backlog) and ${inRoot('registry.json')} — note that running 'claude agents' will NOT list your hive's sibling agents. A full Claude Code command reference is at ${inRoot('COMMANDS.md')} (slash commands act ONLY on your own session; CLI commands run in your shell and can target the fleet). You periodically receive scheduler / "Heartbeat" standup requests — on each, review every agent via fleet.json, re-engage anyone stalled, over-budget, or breaker-armed, and keep board.md and tasks.json accurate. In tasks.json, ALWAYS set each task's "assignee" to the worker's agent id the moment you dispatch it, and NEVER clear it on status changes — a done card must still say who did the work (the human reads the board by who-did-what). HUMAN FEEDBACK is first-class in the ledger: when a task can only proceed with the human's input — a QUESTION to answer OR an ACTION only the human can perform (create an account, approve a purchase, provide credentials/screenshots, test on their device) — set its status to "blocked" and append the concrete ask to the card's "humanQA" array (push {"q":"...","askedAt":"<iso>"}; phrase actions as clear to-dos; keep every past entry — the history documents the card's decisions). The harness surfaces open questions on the office floor's ASK ME board; the human's answer lands in the same entry ("a") AND arrives as an inbox message to you — read it, act on it, and unblock the card so work continues. Do NOT park human questions in separate files (no HumanQuestion.md) and never sit waiting on the human in your own session. Steward the token budget.`
: meta.isAssistant
? 'You are Michael\'s PREP ASSISTANT. You will be handed short, possibly vague instructions (each begins with "ENRICH TASK:"). For each one: (1) figure out which project it concerns and cd into the most relevant repo — you start in Michael\'s home directory; (2) gather concrete context READ-ONLY (exact file paths, current state, relevant code, conventions, active branch, gotchas) — NEVER modify, create, or delete files; (3) rewrite the instruction into ONE clear, self-contained prompt that Michael can execute autonomously, preserving the user\'s original intent without inventing scope. Then deliver it: write ONE message JSON into your outbox with "to":"god", "act":"request", a short subject, and the finished prompt as the body. Do NOT perform the task yourself — your only output is the improved prompt sent to Michael.'
: 'For anything ambiguous, cross-cutting, or needing sign-off, address a message to "god".';
const guardrailsLine = 'Guardrails: a circuit breaker watches the floor — a "Circuit breaker: steer/constrain" message means you are looping or overspending, so STOP repeating, summarize what you tried, and follow it. Be token-frugal (a floor-wide or per-agent token budget can pause you). The shared plan has two parts: board.md (freeform; god is the sole scribe) and tasks.json (structured kanban — todo/doing/blocked/done).';
const slackLine = meta.isGod
? 'SLACK REPLIES: When composing a Slack reply (or writing the `result` field of a Slack-origin kanban card), you MUST: (1) directly address what the user asked — never a bare "done"; (2) include the relevant specifics, outcome, and details; (3) format for Slack mrkdwn — open with a short *bold* headline, use bullet points for multiple items, wrap code/paths in `backtick` blocks, keep it concise (no walls of text). When finishing a Slack-origin task, always write a complete, user-facing, well-formatted `result` on the kanban card — the system posts it verbatim to Slack as the done reply.'
- : 'SLACK REPLIES: If god dispatches you a task that came from Slack, it will include an exact `"$HIVE_NODE" "<helper>" --channel … --thread … --text "…"` reply command — when you finish, run it VERBATIM to post your result back to that thread yourself. The reply must be SUBSTANTIVE Slack mrkdwn (a short *bold* headline + the actual outcome/specifics/links), NEVER a bare "done".';
+ : `SLACK REPLIES: If god dispatches you a task that came from Slack, it will include an exact \`"${hiveNode}" "<helper>" --channel … --thread … --text "…"\` reply command — when you finish, run it VERBATIM to post your result back to that thread yourself. The reply must be SUBSTANTIVE Slack mrkdwn (a short *bold* headline + the actual outcome/specifics/links), NEVER a bare "done".`;
return [
`You are "${meta.name}" (${meta.id}), an autonomous agent in a collaborating hive of Claude agents.`,
- `Your private workspace is ${dir}. The shared hive is ${root}. Full protocol: ${root}/PROTOCOL.md.`,
+ `Your private workspace is ${dir}. The shared hive is ${root}. Full protocol: ${inRoot('PROTOCOL.md')}.`,
'',
'HIVE PROTOCOL — follow it every task:',
- `1. At the START of a task, read ${dir}/memory.md and EVERY file in ${dir}/inbox/ (messages other agents sent you). After handling an inbox message, move its file into ${dir}/inbox/.done/.`,
- `2. Record durable facts, decisions, and context by appending to ${dir}/memory.md.`,
- `3. To ask another agent for something or share information, write ONE message JSON into ${dir}/outbox/ (schema in PROTOCOL.md). NEVER write into another agent's folder — the orchestrator delivers your outbox.`,
+ `1. At the START of a task, read ${inDir('memory.md')} and EVERY file in ${inDir('inbox')} (messages other agents sent you). After handling an inbox message, move its file into ${inDir('inbox', '.done')}.`,
+ `2. Record durable facts, decisions, and context by appending to ${inDir('memory.md')}.`,
+ `3. To ask another agent for something or share information, write ONE message JSON into ${inDir('outbox')} (schema in PROTOCOL.md). NEVER write into another agent's folder — the orchestrator delivers your outbox.`,
'4. At the END of a task, append what you learned to memory.md so future-you remembers.',
guardrailsLine,
memoryLine,
@@ -1646,9 +1697,19 @@ export class HiveManager {
private installOpenCodePlugin(dir: string): string {
const home = join(dir, '.opencode');
try {
- const pluginDir = join(home, 'plugin');
- mkdirSync(pluginDir, { recursive: true });
- writeFileSync(join(pluginDir, 'hive-bridge.js'), OPENCODE_PLUGIN, 'utf8');
+ // BOTH `plugin/` and `plugins/`. OpenCode's current docs specify `plugins/`
+ // (plural); older builds — and the shape this bridge was originally written
+ // against — auto-load from `plugin/` (singular). Since the whole bridge is
+ // LIVE-UNVERIFIED (no BYOK keys to prove which the installed version reads),
+ // guessing one of them is a coin flip whose losing side is silent: the plugin
+ // simply never loads and the agent's only inbox drain becomes the renderer
+ // nudge. Writing the same ~2KB file twice costs nothing, is idempotent, and
+ // is correct whichever directory the installed OpenCode actually scans.
+ for (const name of ['plugin', 'plugins']) {
+ const pluginDir = join(home, name);
+ mkdirSync(pluginDir, { recursive: true });
+ writeFileSync(join(pluginDir, 'hive-bridge.js'), OPENCODE_PLUGIN, 'utf8');
+ }
} catch (e) { console.error('[hive] installOpenCodePlugin failed:', e); }
return home;
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 78bfd88b..6f0056ff 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -436,9 +436,11 @@ function teardownPty(id: string): void {
function informGod(subject: string, body: string, slack?: { channel: string; thread_ts: string }): void {
try {
const slackLine = slack
- // `$HIVE_NODE` (injected into every agent's env) — NOT bare `node`, which is
- // absent from the PATH of any machine whose node comes from nvm.
- ? `\n\n[SLACK] Close the loop — post a reply to channel ${slack.channel} thread ${slack.thread_ts} via:\n "$HIVE_NODE" "${slackReplyScriptPath()}" --channel ${slack.channel} --thread ${slack.thread_ts} --text "<your message>"`
+ // The bundled-node launcher, spelled as an ABSOLUTE PATH — NOT bare `node`
+ // (absent from the PATH of any machine whose node comes from nvm) and NOT
+ // `$HIVE_NODE` (POSIX-only: cmd.exe/PowerShell expand it to nothing, so the
+ // whole reply command was dead on Windows).
+ ? `\n\n[SLACK] Close the loop — post a reply to channel ${slack.channel} thread ${slack.thread_ts} via:\n "${hive.nodeCommand()}" "${slackReplyScriptPath()}" --channel ${slack.channel} --thread ${slack.thread_ts} --text "<your message>"`
: '';
hive.send({ to: 'god', act: 'inform', subject, body: body + slackLine }, 'ephemeral-worker');
} catch (e) {
@@ -1203,7 +1205,7 @@ let lastSlackUrl: string | undefined;
function buildAutonomousRequestProtocol(channel: string, threadTs: string, helperPath: string): string {
return `[AUTONOMOUS REQUEST PROTOCOL — this request arrived via Slack; no interactive human is watching] Handle it under this protocol:
1. ROUTE FAST — triage and hand this to the single most-relevant agent right away. CHECK THE LIVE ROSTER FIRST (active agents in registry.json + their state in fleet.json) and prefer an EXISTING agent that fits — especially when the request names one ("ask Pam…", "have Jim…"): route to that agent and only spawn a new one if none is a sensible fit. Decompose only if it genuinely needs several. Don't sit on it.
-2. DELEGATE WITH THE REPLY HANDLE — tell that agent to do the work autonomously AND to post its result back to THIS Slack thread itself when done, using exactly: "$HIVE_NODE" "${helperPath}" --channel ${channel} --thread ${threadTs} --text "<substantive result>" ($HIVE_NODE is the harness's bundled Node, injected into every agent's env — bare "node" is not on the hook/agent PATH on many machines.)
+2. DELEGATE WITH THE REPLY HANDLE — tell that agent to do the work autonomously AND to post its result back to THIS Slack thread itself when done, using exactly: "${hive.nodeCommand()}" "${helperPath}" --channel ${channel} --thread ${threadTs} --text "<substantive result>" (that first path is the harness's bundled Node, already resolved for this machine — pass it verbatim; bare "node" is not on the hook/agent PATH on many machines.)
3. AUTONOMOUS EXECUTION — no interactive questions. PAUSE/ask ONLY for high-severity actions: pushing to main or any remote; buying or spawning infrastructure or paid services; deleting an existing repo, file, or folder it did not create. Stay READ-ONLY at critical infrastructure and git-push-type changes unless explicitly approved.
4. DIRECT, SUBSTANTIVE REPLY — the agent posts a real Slack-mrkdwn answer (short *bold* headline + the actual outcome/specifics/links), NEVER a bare "done"/":white_check_mark:".
5. REPORT TO GOD — the agent then tells you (Michael) what it did.
@@ -2528,6 +2530,11 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
{
semanticMemory: memory.active(),
knowledgeGraph: knowledge.active(),
+ // Bake the ABSOLUTE KG CLI path into the agent's prompt. The prompt used
+ // to spell it `$KG_CLI`, which is POSIX-only: under cmd.exe/PowerShell it
+ // expands to nothing, so every knowledge-graph instruction was dead on a
+ // Windows floor. Empty when the KG is off (the line isn't emitted then).
+ kgCliPath: knowledge.env().KG_CLI,
theme: readConfig().terminalTheme ?? 'light',
// W3 — default-MCP consent state + the bundled skills source dir.
mcpDefaults: readConfig().mcpDefaults,
diff --git a/src/main/pty.ts b/src/main/pty.ts
index 864981b6..75d5f1b5 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -1,7 +1,7 @@
import * as pty from 'node-pty';
import type { WebContents } from 'electron';
-import { existsSync } from 'node:fs';
-import { delimiter, join } from 'node:path';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { delimiter, join, win32 } from 'node:path';
import { spawnSync } from 'node:child_process';
import { ensureKilled } from './procKill';
import { expandTilde } from './fs';
@@ -82,8 +82,33 @@ export interface SpawnOptions {
*
* This is handed to `pty.spawn(file, args, ...)` as a STRING, which node-pty treats
* as a pre-escaped CommandLine and passes through VERBATIM (no per-arg re-escaping),
- * so the quoting here is never double-wrapped. Embedded `"` in a token is escaped as
- * `\"` (cmd's quote-escape) so a token like `a"b` round-trips.
+ * so the quoting here is never double-wrapped.
+ *
+ * ⚠️ LAST-RESORT PATH — DO NOT PUT AN AGENT PROMPT THROUGH IT. Two hard limits of
+ * cmd.exe's parser that no amount of escaping here can work around:
+ *
+ * 1. **cmd.exe has NO backslash escape.** An earlier version of this comment
+ * claimed `\"` was "cmd's quote-escape". It is not: to cmd, `\` is an ordinary
+ * character and every `"` TOGGLES quote state. So `\"` does not embed a quote —
+ * it closes (or opens) the quoted run and dumps everything after it back into
+ * bare, metacharacter-interpreting context. The `\"` produced below survives
+ * only because the CRT of the *final* program un-escapes it; the intermediate
+ * cmd.exe still mis-tracks quote state across it.
+ * 2. **A newline can never survive.** cmd.exe treats CR/LF as a statement
+ * separator before quoting is even considered, so a multi-line argument is
+ * TRUNCATED at its first newline and the remainder is executed as commands.
+ * That is exactly how the Windows hive protocol prompt (multi-line, full of
+ * `(`/`)` which cmd reads as block delimiters) was being destroyed: the agent
+ * booted looking healthy but never received the HIVE PROTOCOL block, so it
+ * never knew its inbox/outbox existed and no agent could message another.
+ *
+ * There is also cmd.exe's ~8191-character command-line ceiling, which the injected
+ * hive prompt (~6.1k chars) sits uncomfortably close to.
+ *
+ * Prompt-carrying spawns therefore go through `parseNpmCmdShim` instead (spawn the
+ * shim's real interpreter with an ARRAY of args, so node-pty's own CRT-correct
+ * `argsToCommandLine` runs and no shell parser is involved). This function remains
+ * the fallback for every target we cannot decode — strictly no worse than before.
*/
export function buildCmdCommandLine(resolved: string, args: string[]): string {
const quoteToken = (s: string): string => {
@@ -99,6 +124,160 @@ export function buildCmdCommandLine(resolved: string, args: string[]): string {
return `/d /s /c "${inner}"`;
}
+/** What an npm-style Windows `.cmd` shim actually runs, decoded from its text. */
+export interface NpmShimTarget {
+ /** BARE interpreter name — `node`, `bun` or `deno` — to be resolved off PATH by
+ * the caller (kept bare deliberately: see parseNpmCmdShim). */
+ interpreter: string;
+ /** Absolute, normalized win32 path to the script that interpreter should run. */
+ scriptPath: string;
+}
+
+/** Interpreters we are willing to spawn directly. Deliberately a tiny allowlist:
+ * anything else (a hand-written batch file, a python/ruby shim, a shape we have
+ * not seen) resolves to null and falls back to the cmd.exe path — never worse
+ * than today's behaviour. */
+const SHIM_INTERPRETERS = new Set(['node', 'bun', 'deno']);
+/** The shim's target must look like a JS entry point. A shim that points at
+ * something else is not a shape we understand → null. */
+const SHIM_SCRIPT_EXT = /\.(?:c|m)?js$/i;
+
+/**
+ * Decode an npm-generated Windows `.cmd` shim into the interpreter + script it
+ * would have run. PURE (no filesystem, no `process.platform`): it takes the shim's
+ * path and its CONTENT so it is unit-testable on macOS/Linux, where every Windows
+ * build is authored.
+ *
+ * WHY THIS EXISTS. On Windows a `.cmd`/`.bat` cannot be handed to CreateProcess,
+ * so the spawn path used to route it through `cmd.exe /d /s /c "<line>"`. That
+ * turns argv into a single string parsed by cmd.exe — which cannot carry a newline
+ * (statement separator), reads `(`/`)` as block delimiters, has no backslash escape,
+ * and caps out near 8191 chars. The hive protocol prompt is a ~6.1k-char, 11-line,
+ * 62-paren argument, so on Windows it was truncated at its first newline: every
+ * npm-installed CLI (OpenCode always; `claude.cmd` whenever there is no native
+ * `claude.exe`) started up looking perfectly healthy but never received the HIVE
+ * PROTOCOL block, never learned that `inbox/`/`outbox/` existed, and so no agent
+ * ever heard from another. Claude appeared to work only because its native
+ * `claude.exe` skipped cmd.exe entirely.
+ *
+ * Spawning the shim's own interpreter with an ARRAY of args removes cmd.exe from
+ * the picture: node-pty's `argsToCommandLine` applies MSDN/CRT escaping (backslash
+ * doubling before a quote, whole-arg quoting on whitespace) and hands the result
+ * straight to CreateProcess, which passes the raw command line to the child. A
+ * newline inside a quoted CRT argument is just a character there, and the limit
+ * becomes CreateProcess's 32767 rather than cmd's 8191.
+ *
+ * SHAPES HANDLED (npm's cmd-shim, across its historical revisions; pnpm/yarn emit
+ * the same families):
+ *
+ * modern (cmd-shim ≥4 / npm ≥7) — dp0 captured into a variable, program chosen
+ * into %_prog%, single trailing exec line:
+ * SET dp0=%~dp0
+ * IF EXIST "%dp0%\node.exe" ( SET "_prog=%dp0%\node.exe" ) ELSE ( SET "_prog=node" … )
+ * endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\node_modules\pkg\bin\cli.js" %*
+ *
+ * classic (cmd-shim 2/3, npm 5/6) — IF/ELSE with the exec inlined in both arms:
+ * @IF EXIST "%~dp0\node.exe" (
+ * "%~dp0\node.exe" "%~dp0\node_modules\pkg\bin\cli.js" %*
+ * ) ELSE ( … node "%~dp0\node_modules\pkg\bin\cli.js" %* )
+ *
+ * ancient single-line:
+ * @"%~dp0\node.exe" "%~dp0\node_modules\pkg\bin\cli.js" %*
+ *
+ * The interpreter is returned BARE (`node`), not as the shim's `%dp0%\node.exe`
+ * candidate, on purpose: that candidate only exists for an npm install that ships a
+ * colocated node, and that directory is on PATH by construction — so resolving the
+ * bare name finds the same binary while also going through the caller's existing
+ * PATH/candidate-dir resolution and cache.
+ *
+ * Returns null — meaning "fall back to the cmd.exe path" — for ANY shape that is
+ * not fully understood: unknown interpreter, unexpanded `%VAR%` left in the target,
+ * a relative target, extra interpreter flags we would otherwise silently drop, a
+ * non-JS target, a file too large to be a shim, or plain garbage.
+ */
+export function parseNpmCmdShim(shimPath: string, content: string): NpmShimTarget | null {
+ if (typeof shimPath !== 'string' || typeof content !== 'string') return null;
+ if (!shimPath || !content) return null;
+ // A cmd-shim is ~1KB. Anything larger is somebody's real batch script (or a
+ // binary someone named `.cmd`) and is not ours to reinterpret.
+ if (content.length > 8192 || content.includes('\0')) return null;
+
+ // win32.* explicitly — these paths are Windows paths regardless of the host we
+ // are running (or testing) on.
+ const dir = win32.dirname(shimPath);
+ if (!dir || dir === '.') return null;
+
+ /** Expand a shim token's `%~dp0` / `%dp0%` (the shim's OWN directory, which cmd
+ * expands WITH a trailing backslash) into an absolute, normalized path. Any
+ * other surviving `%` means a variable we did not model → refuse. */
+ const expand = (raw: string): string | null => {
+ let s = raw.replace(/%~dp0%?|%dp0%/gi, `${dir}\\`);
+ if (s.includes('%')) return null;
+ if (!s.trim()) return null;
+ // `<dir>\` + `\node_modules\…` produces a doubled separator that Windows
+ // tolerates; collapse it so the path we hand to existsSync is clean. A leading
+ // UNC `\\server\share` prefix must survive that collapse.
+ const unc = /^[\\/]{2}/.test(s);
+ s = s.replace(/[\\/]+/g, '\\');
+ if (unc) s = `\\${s}`;
+ if (!win32.isAbsolute(s)) return null;
+ return win32.normalize(s);
+ };
+
+ // Every `SET "_prog=…"` the shim performs (the IF-EXISTS arm and the PATH arm).
+ const progValues: string[] = [];
+ for (const m of content.matchAll(/^\s*@?SET\s+"?_prog=([^"\r\n]*)"?/gim)) progValues.push(m[1]);
+
+ // The exec line is the LAST line carrying `%*` (cmd's "forward all args"): in the
+ // modern shim that is the single `endLocal & … & "%_prog%" "<script>" %*` line;
+ // in the classic IF/ELSE shim it is the ELSE arm, which runs the same script.
+ const lines = content.split(/\r?\n/);
+ let execLine: string | null = null;
+ for (let i = lines.length - 1; i >= 0; i--) {
+ if (lines[i].includes('%*')) { execLine = lines[i]; break; }
+ }
+ if (!execLine) return null;
+
+ const head = execLine.slice(0, execLine.lastIndexOf('%*'));
+ const quoted = [...head.matchAll(/"([^"]*)"/g)].map((m) => ({
+ text: m[1],
+ start: m.index ?? 0,
+ end: (m.index ?? 0) + m[0].length
+ }));
+ if (quoted.length === 0) return null;
+
+ const scriptTok = quoted[quoted.length - 1];
+ // Locate the program token and PROVE nothing sits between it and the script.
+ // Interpreter flags baked into a shebang (`#!/usr/bin/env node --flag`) land
+ // there; dropping them silently would change how the CLI runs, so we bail out
+ // to the cmd.exe fallback instead.
+ let progRaw: string;
+ if (quoted.length >= 2) {
+ const progTok = quoted[quoted.length - 2];
+ if (head.slice(progTok.end, scriptTok.start).trim() !== '') return null;
+ progRaw = progTok.text;
+ } else {
+ // Classic ELSE arm: `node "<script>" %*` — the program is an unquoted word.
+ const before = head.slice(0, scriptTok.start).trim();
+ const word = before.split(/\s+/).filter(Boolean).pop();
+ if (!word || word !== before) return null; // anything else before it → unknown shape
+ progRaw = word;
+ }
+
+ // `"%_prog%"` → the value the shim SET. Prefer the bare-name arm (the PATH
+ // fallback); a `%dp0%\node.exe` value still reduces to the same basename below.
+ if (/^%_prog%$/i.test(progRaw)) {
+ if (progValues.length === 0) return null;
+ progRaw = progValues.find((v) => !/[%\\/]/.test(v)) ?? progValues[progValues.length - 1];
+ }
+ const interpreter = (progRaw.split(/[\\/]/).pop() ?? '').replace(/\.exe$/i, '').toLowerCase();
+ if (!SHIM_INTERPRETERS.has(interpreter)) return null;
+
+ const scriptPath = expand(scriptTok.text);
+ if (!scriptPath || !SHIM_SCRIPT_EXT.test(scriptPath)) return null;
+ return { interpreter, scriptPath };
+}
+
export class PtyManager {
private sessions = new Map<string, PtySession>();
private webContents: WebContents | null = null;
@@ -212,7 +391,8 @@ export class PtyManager {
// EXTENSIONLESS shim (bare `claude`). Skip extensionless hits and take
// the first PATHEXT-eligible one (.CMD/.BAT/.EXE/…). NOTE: even .CMD/.BAT
// files are not directly spawnable by node-pty's CreateProcess (error 193);
- // spawn() routes them through `cmd.exe /c` (see below).
+ // spawn() either decodes the shim to its real interpreter or, failing that,
+ // routes it through `cmd.exe /c` (see resolveWindowsShimSpawn below).
try {
const res = spawnSync('where', [command], { encoding: 'utf8', timeout: 3000, shell: true });
const lines = (res.stdout ?? '').trim().split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
@@ -262,6 +442,56 @@ export class PtyManager {
return { path: command, found: false };
}
+ /**
+ * WINDOWS ONLY. Decide whether `resolved` is an npm-style shim we can spawn
+ * DIRECTLY (its real interpreter + script, as an argv ARRAY) instead of routing
+ * it through `cmd.exe /d /s /c "<one big string>"`.
+ *
+ * The cmd.exe route destroys any multi-line argument (see buildCmdCommandLine),
+ * which is what silently stripped the HIVE PROTOCOL block out of every
+ * npm-installed agent CLI's system prompt on Windows — agents booted fine and
+ * then never messaged each other because they never learned inbox/outbox exist.
+ *
+ * Returns null for anything not fully understood, and EVERY failure mode here
+ * (not a shim, unreadable, unknown shape, script missing on disk, interpreter
+ * not installed or itself not a real .exe) degrades to exactly today's cmd.exe
+ * behaviour. Never throws.
+ */
+ private resolveWindowsShimSpawn(resolved: string): { file: string; script: string } | null {
+ if (process.platform !== 'win32') return null;
+ try {
+ const lower = resolved.toLowerCase();
+ // The `.cmd` IS the shim. An extensionless npm shim (`%APPDATA%\npm\claude`)
+ // is a POSIX **sh** script that cmd.exe cannot run at all; npm always writes a
+ // `.cmd` sibling naming the same target, so read that instead — strictly an
+ // improvement over handing sh syntax to cmd.exe.
+ const shimPath = lower.endsWith('.cmd') || lower.endsWith('.bat')
+ ? resolved
+ : (existsSync(`${resolved}.cmd`) ? `${resolved}.cmd` : null);
+ if (!shimPath) return null;
+ const st = statSync(shimPath);
+ if (!st.isFile() || st.size > 8192) return null;
+
+ const target = parseNpmCmdShim(shimPath, readFileSync(shimPath, 'utf8'));
+ if (!target) return null;
+ // The shim can outlive the package it points at (a half-removed global
+ // install). Falling back to cmd.exe then at least reproduces today's error.
+ if (!existsSync(target.scriptPath)) return null;
+
+ const interp = this.resolveCommand(target.interpreter);
+ if (!interp.found) return null;
+ // Must be a REAL executable: if `node` itself only resolves to a `.cmd`
+ // (e.g. our own bundled-runtime shim appended to PATH), spawning it directly
+ // would hit the very CreateProcess limitation we are routing around.
+ const il = interp.path.toLowerCase();
+ if (!il.endsWith('.exe') && !il.endsWith('.com')) return null;
+
+ return { file: interp.path, script: target.scriptPath };
+ } catch {
+ return null; // unreadable/racing shim — fall back, never break the spawn
+ }
+ }
+
spawn(opts: SpawnOptions, owner: WebContents | null = null): { ok: boolean; error?: string } {
if (this.sessions.has(opts.id)) {
return { ok: false, error: `pty already exists for id ${opts.id}` };
@@ -285,11 +515,22 @@ export class PtyManager {
);
// On Windows, .cmd/.bat files (and extensionless shims) cannot be executed
- // directly by CreateProcess — only .exe/.com can. Route them through cmd.exe.
+ // directly by CreateProcess — only .exe/.com can. Two ways out, in order of
+ // preference: (1) decode an npm shim to the interpreter + script it wraps and
+ // spawn THAT with an argv array (correct escaping, newlines survive); or
+ // (2) the legacy fallback, route the whole thing through cmd.exe as one
+ // pre-escaped string (loses newlines — see buildCmdCommandLine).
const isWin = process.platform === 'win32';
const lower = resolved.toLowerCase();
const directExe = lower.endsWith('.exe') || lower.endsWith('.com');
const needsCmd = isWin && !directExe;
+ // Prefer decoding an npm shim to its interpreter over the cmd.exe route (see
+ // resolveWindowsShimSpawn). win32-only and null-on-anything-unexpected, so
+ // macOS/Linux and every undecodable Windows target keep today's behaviour.
+ // Skipped entirely for a shellScript spawn, which never executes `resolved`.
+ const shimSpawn = needsCmd && typeof opts.shellScript !== 'string'
+ ? this.resolveWindowsShimSpawn(resolved)
+ : null;
let file: string;
let spawnArgs: string[] | string;
if (typeof opts.shellScript === 'string') {
@@ -310,6 +551,19 @@ export class PtyManager {
file = process.env.SHELL || '/bin/sh';
spawnArgs = ['-lc', opts.shellScript];
}
+ } else if (needsCmd && shimSpawn) {
+ // WINDOWS, npm-shim target: spawn the shim's own interpreter with an ARRAY
+ // of args. node-pty then runs its `argsToCommandLine` (MSDN/CRT escaping:
+ // backslash doubling before a quote, whole-arg quoting on whitespace) and
+ // hands the result straight to CreateProcess — no shell parser anywhere in
+ // the chain. That is what lets the hive protocol prompt through intact:
+ // its newlines, parentheses and embedded quotes are just characters inside
+ // one quoted CRT argument, and the ceiling becomes CreateProcess's 32767
+ // instead of cmd.exe's 8191. Routing the same prompt through cmd.exe
+ // truncated it at the first newline, which is why Windows agents never
+ // learned they had an inbox/outbox and could not message each other.
+ file = shimSpawn.file;
+ spawnArgs = [shimSpawn.script, ...(opts.args ?? [])];
} else {
file = needsCmd ? (process.env.ComSpec || 'cmd.exe') : resolved;
// #55: when routing through cmd.exe we must NOT pass `resolved` as a bare,
diff --git a/src/shared/agentProvider.ts b/src/shared/agentProvider.ts
index aa41c58f..5d748e1d 100644
--- a/src/shared/agentProvider.ts
+++ b/src/shared/agentProvider.ts
@@ -352,6 +352,23 @@ export const AGENT_PROVIDER_PRESETS: AgentProviderPreset[] = [
// (protocol re-injected as the initial prompt), matching codex.
resumeFlag: undefined,
installCommand: 'npm install -g opencode-ai@latest', // trusted, hardcoded
+ // Node-free installers, for the rung that runs when npm is absent AND no Node
+ // installer could be resolved (offline / unsupported platform) — until now
+ // OpenCode had none, so that rung printed a manual hint and installed nothing.
+ // Both are trusted, hardcoded constants and contain no double-quotes (the
+ // win32 form is wrapped verbatim in `cmd /d /s /c "…"`).
+ //
+ // Unlike Claude, OpenCode ships NO standalone Windows one-liner: opencode.ai
+ // serves the POSIX install script but has no `install.ps1` (verified 404), and
+ // its docs list Chocolatey/Scoop as the Windows-native routes. `-y` because the
+ // banner runs the command unattended in the agent terminal. Honest limitation:
+ // this rung needs Chocolatey already present; when it isn't, the user sees
+ // choco's own "not recognized" error plus the banner's existing "run the
+ // command above manually" fallback — no worse off than the manual-only text.
+ nativeInstallCommand: {
+ posix: 'curl -fsSL https://opencode.ai/install | bash',
+ win32: 'choco install opencode -y'
+ },
docsUrl: 'https://opencode.ai/docs'
},
{
diff --git a/test/hive-windows-prompt.test.cjs b/test/hive-windows-prompt.test.cjs
new file mode 100644
index 00000000..e5356855
--- /dev/null
+++ b/test/hive-windows-prompt.test.cjs
@@ -0,0 +1,148 @@
+'use strict';
+
+/**
+ * The agent-facing text the hive injects has to be runnable BY THE AGENT, on the
+ * platform the agent is running on. Two habits were silently Windows-only breakage:
+ *
+ * - POSIX `$VAR` references (`"$HIVE_NODE" "$KG_CLI" search …`, the Slack reply
+ * command). Under cmd.exe `$FOO` expands to nothing and under PowerShell to an
+ * undefined variable, so those instructions were dead on every Windows floor.
+ * - String-concatenated separators (`${dir}/inbox/`), which told a Windows agent
+ * to read `C:\Users\x\hive\agents\god-1/inbox/`.
+ *
+ * And the prompt itself must survive the spawn: it is passed on argv, is multi-line
+ * and paren/quote-heavy, and on Windows now rides node-pty's CRT escaping rather
+ * than cmd.exe's parser (see win-cmd-shim.test.cjs for that half).
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const loadTs = require('./load-ts.cjs');
+
+const { HiveManager } = loadTs('src/main/hive.ts');
+const { argsToCommandLine } = require('node-pty/lib/windowsPtyAgent.js');
+
+const KG_CLI = path.join('/Applications', 'Munder Difflin.app', 'Contents', 'Resources', 'kg.cjs');
+
+async function floor(t, opts = {}) {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'md-winprompt-'));
+ t.after(() => fs.rmSync(home, { recursive: true, force: true }));
+ const hive = new HiveManager(() => home);
+ const inj = await hive.ensureAgent(
+ { id: 'god-1', name: 'Michael', provider: opts.provider ?? 'claude', cwd: home, isGod: true },
+ { semanticMemory: true, knowledgeGraph: true, kgCliPath: KG_CLI, ...(opts.injectOpts ?? {}) }
+ );
+ return { home, hive, inj, dir: path.join(home, 'hive', 'agents', 'god-1'), root: path.join(home, 'hive') };
+}
+
+/** The injected system prompt, whichever flag this provider carries it on. */
+function promptOf(inj) {
+ const i = inj.args.findIndex((a) => a === '--append-system-prompt' || a === '--prompt');
+ assert.ok(i >= 0, 'the hive protocol must be on argv');
+ return inj.args[i + 1];
+}
+
+test('no POSIX shell variables survive into agent-facing text', async (t) => {
+ const { inj } = await floor(t);
+ const prompt = promptOf(inj);
+ for (const dead of ['$HIVE_NODE', '$KG_CLI', '$KG_ROOT', '$MEMPALACE_PALACE_PATH']) {
+ assert.ok(!prompt.includes(dead), `${dead} expands to nothing under cmd.exe/PowerShell`);
+ }
+});
+
+test('the knowledge-graph command carries absolute paths, not variables', async (t) => {
+ const { inj, hive } = await floor(t);
+ const prompt = promptOf(inj);
+ assert.ok(prompt.includes(`"${hive.nodeCommand()}" "${KG_CLI}" search`), 'runnable as written');
+ assert.ok(path.isAbsolute(hive.nodeCommand()), 'the bundled-node launcher is baked absolute');
+});
+
+test('the KG line degrades to the env-var spelling when no path is supplied', async (t) => {
+ // Never emit a broken command: with no resolved CLI path we fall back to the
+ // old spelling rather than interpolating `undefined` into the instruction.
+ const { inj } = await floor(t, { injectOpts: { kgCliPath: undefined } });
+ const prompt = promptOf(inj);
+ assert.ok(!prompt.includes('undefined'));
+ assert.ok(prompt.includes(process.platform === 'win32' ? '%KG_CLI%' : '$KG_CLI'));
+});
+
+test('protocol paths use native separators the agent can actually use', async (t) => {
+ const { inj, dir, root } = await floor(t);
+ const prompt = promptOf(inj);
+ for (const p of [
+ path.join(dir, 'memory.md'),
+ path.join(dir, 'inbox'),
+ path.join(dir, 'inbox', '.done'),
+ path.join(dir, 'outbox'),
+ path.join(root, 'PROTOCOL.md'),
+ path.join(root, 'fleet.json'),
+ path.join(root, 'registry.json')
+ ]) {
+ assert.ok(prompt.includes(p), `missing native-separator path: ${p}`);
+ }
+ // The old form concatenated literal `/` onto a native dir, which on win32 read
+ // `C:\…\god-1/inbox/`. Pin the exact old spellings so a regression fails HERE,
+ // on macOS, where this code is actually written — they differ from the new text
+ // on POSIX too (the trailing slash is gone).
+ for (const old of ['/inbox/ (messages', '/inbox/.done/.', '/outbox/ (schema']) {
+ assert.ok(!prompt.includes(old), `old mixed-separator form leaked back in: ${old}`);
+ }
+ if (path.sep === '\\') {
+ assert.ok(!prompt.includes(`${dir}/`), 'mixed-separator path leaked back in');
+ assert.ok(!prompt.includes(`${root}/`), 'mixed-separator path leaked back in');
+ }
+});
+
+test('the Stop-hook drain text uses native separators too', async (t) => {
+ const { hive, dir } = await floor(t);
+ hive.send({ to: 'god-1', act: 'request', subject: 'ping', body: 'hello' }, 'tester');
+ const { block, reason } = hive.drainForStop('god-1');
+ assert.equal(block, true);
+ assert.ok(reason.includes(path.join(dir, 'inbox')));
+ assert.ok(reason.includes(path.join(dir, 'inbox', '.done')));
+ assert.ok(!reason.includes('/inbox/ for full detail'), 'old mixed-separator form');
+ assert.ok(!reason.includes('inbox/.done/'), 'old mixed-separator form');
+});
+
+test('the injected prompt survives the Windows ARRAY argv path byte for byte', async (t) => {
+ const { inj } = await floor(t);
+ const prompt = promptOf(inj);
+ // Sanity: this really is the hostile shape (cmd.exe truncates at the first
+ // newline and reads the parens as block delimiters).
+ assert.ok(prompt.split('\n').length > 5, 'multi-line');
+ assert.ok(prompt.includes('(') && prompt.includes('"'), 'paren- and quote-bearing');
+
+ const node = 'C:\\Program Files\\nodejs\\node.exe';
+ const script = 'C:\\Users\\Tester\\AppData\\Roaming\\npm\\node_modules\\opencode-ai\\bin\\opencode.js';
+ const line = argsToCommandLine(node, [script, '--prompt', prompt]);
+ // Newlines ride through CreateProcess as literal characters inside one quoted
+ // CRT argument; nothing is truncated and nothing needs a shell.
+ assert.ok(line.includes('\n'));
+ assert.ok(line.includes('HIVE PROTOCOL'));
+ const quotedArg = line.slice(line.indexOf('--prompt') + '--prompt '.length);
+ assert.equal(
+ quotedArg.slice(1, -1).replace(/\\"/g, '"'),
+ prompt,
+ 'the child CRT un-escapes back to exactly the prompt we injected'
+ );
+});
+
+test('the OpenCode plugin lands in BOTH plugin/ and plugins/', async (t) => {
+ // Which directory the installed OpenCode scans is version-dependent and the
+ // bridge is LIVE-UNVERIFIED; writing both is cheap and removes the coin flip.
+ const { dir } = await floor(t, { provider: 'opencode' });
+ for (const name of ['plugin', 'plugins']) {
+ const p = path.join(dir, '.opencode', name, 'hive-bridge.js');
+ assert.ok(fs.existsSync(p), `missing ${p}`);
+ assert.ok(fs.readFileSync(p, 'utf8').includes('HIVE_SOCK'), 'must be the real bridge');
+ }
+});
+
+test('OpenCode carries the protocol on --prompt, so the argv fix is what delivers it', async (t) => {
+ const { inj } = await floor(t, { provider: 'opencode' });
+ assert.ok(inj.args.includes('--prompt'));
+ assert.ok(promptOf(inj).includes('HIVE PROTOCOL'));
+});
diff --git a/test/win-cmd-shim.test.cjs b/test/win-cmd-shim.test.cjs
new file mode 100644
index 00000000..c0f54bd0
--- /dev/null
+++ b/test/win-cmd-shim.test.cjs
@@ -0,0 +1,275 @@
+'use strict';
+
+/**
+ * WINDOWS AGENT-TO-AGENT MESSAGING — the argv path.
+ *
+ * On Windows a `.cmd` cannot be handed to CreateProcess, so every npm-installed
+ * engine CLI (OpenCode always; `claude.cmd` whenever there is no native
+ * `claude.exe`) used to be spawned as `cmd.exe /d /s /c "<one big string>"`. The
+ * hive protocol is injected on argv (`--append-system-prompt <prompt>` /
+ * `--prompt <prompt>`) and that prompt is MULTI-LINE, paren-heavy and quote-heavy.
+ * cmd.exe treats CR/LF as a statement separator before quoting is even considered,
+ * so the prompt was truncated at its first newline: the agent booted looking
+ * perfectly healthy, never received the HIVE PROTOCOL block, never learned that
+ * `inbox/`/`outbox/` existed — and therefore no agent ever messaged another.
+ *
+ * The fix decodes the npm shim to the interpreter + script it wraps and spawns
+ * THAT with an argv ARRAY, so node-pty's `argsToCommandLine` (MSDN/CRT escaping)
+ * runs and CreateProcess receives the command line directly — no shell parser
+ * anywhere. These tests pin both halves: what the shim parser accepts/refuses, and
+ * that the array path really does round-trip a hostile prompt.
+ *
+ * Everything here is host-independent on purpose (win32 path handling and pure
+ * string escaping), because the whole Windows build is authored on macOS.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const { parseNpmCmdShim, buildCmdCommandLine, PtyManager } = loadTs('src/main/pty.ts');
+// The REAL escaper node-pty applies to an argv array on Windows. Testing against a
+// copy would prove nothing, so we reach into node-pty's own module (the native
+// bindings it needs load lazily inside the agent constructor, not on require).
+const { argsToCommandLine } = require('node-pty/lib/windowsPtyAgent.js');
+
+const NPM_DIR = 'C:\\Users\\Tester\\AppData\\Roaming\\npm';
+const SHIM = `${NPM_DIR}\\opencode.cmd`;
+
+// ── real-world npm shim shapes ───────────────────────────────────────────────
+
+/** cmd-shim >= 4 (npm >= 7) — what a 2024+ `npm i -g opencode-ai` writes. */
+const MODERN = [
+ '@ECHO off',
+ 'GOTO start',
+ ':find_dp0',
+ 'SET dp0=%~dp0',
+ 'EXIT /b',
+ ':start',
+ 'SETLOCAL',
+ 'CALL :find_dp0',
+ '',
+ 'IF EXIST "%dp0%\\node.exe" (',
+ ' SET "_prog=%dp0%\\node.exe"',
+ ') ELSE (',
+ ' SET "_prog=node"',
+ ' SET PATHEXT=%PATHEXT:;.JS;=;%',
+ ')',
+ '',
+ 'endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\\node_modules\\opencode-ai\\bin\\opencode.js" %*'
+].join('\r\n');
+
+/** cmd-shim 2/3 (npm 5/6) — IF/ELSE with the exec inlined in both arms. */
+const CLASSIC = [
+ '@IF EXIST "%~dp0\\node.exe" (',
+ ' "%~dp0\\node.exe" "%~dp0\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
+ ') ELSE (',
+ ' @SETLOCAL',
+ ' @SET PATHEXT=%PATHEXT:;.JS;=;%',
+ ' node "%~dp0\\node_modules\\opencode-ai\\bin\\opencode.js" %*',
+ ')'
+].join('\r\n');
+
+/** The oldest single-line form. */
+const ANCIENT = '@"%~dp0\\node.exe" "%~dp0\\node_modules\\npm\\bin\\npm-cli.js" %*\r\n';
+
+/** pnpm/yarn write the same family but reach OUT of the bin dir with `..`. */
+const PNPM = [
+ '@IF EXIST "%~dp0\\node.exe" (',
+ ' "%~dp0\\node.exe" "%~dp0\\..\\opencode-ai\\bin\\opencode.js" %*',
+ ') ELSE (',
+ ' node "%~dp0\\..\\opencode-ai\\bin\\opencode.js" %*',
+ ')'
+].join('\n');
+
+test('modern npm shim → the interpreter and script it really runs', () => {
+ assert.deepEqual(parseNpmCmdShim(SHIM, MODERN), {
+ interpreter: 'node',
+ scriptPath: `${NPM_DIR}\\node_modules\\opencode-ai\\bin\\opencode.js`
+ });
+});
+
+test('classic npm 5/6 shim resolves through its ELSE arm', () => {
+ assert.deepEqual(parseNpmCmdShim(SHIM, CLASSIC), {
+ interpreter: 'node',
+ scriptPath: `${NPM_DIR}\\node_modules\\opencode-ai\\bin\\opencode.js`
+ });
+});
+
+test('ancient single-line shim resolves', () => {
+ assert.deepEqual(parseNpmCmdShim(`${NPM_DIR}\\npm.cmd`, ANCIENT), {
+ interpreter: 'node',
+ scriptPath: `${NPM_DIR}\\node_modules\\npm\\bin\\npm-cli.js`
+ });
+});
+
+test('a `..` in the shim target is normalized, not passed through', () => {
+ const shim = `${NPM_DIR}\\node_modules\\.bin\\opencode.cmd`;
+ assert.deepEqual(parseNpmCmdShim(shim, PNPM), {
+ interpreter: 'node',
+ scriptPath: `${NPM_DIR}\\node_modules\\opencode-ai\\bin\\opencode.js`
+ });
+});
+
+test('LF-only content parses the same as CRLF', () => {
+ assert.deepEqual(
+ parseNpmCmdShim(SHIM, MODERN.replace(/\r\n/g, '\n')),
+ parseNpmCmdShim(SHIM, MODERN)
+ );
+});
+
+test('bun and deno shims are accepted; other interpreters are not', () => {
+ const bun = MODERN.replace(/node\.exe/g, 'bun.exe').replace('_prog=node', '_prog=bun');
+ assert.equal(parseNpmCmdShim(SHIM, bun).interpreter, 'bun');
+
+ const python = MODERN.replace(/node\.exe/g, 'python.exe').replace('_prog=node', '_prog=python');
+ assert.equal(parseNpmCmdShim(SHIM, python), null, 'not an interpreter we are willing to spawn');
+});
+
+// ── everything we refuse to guess at falls back to the cmd.exe path ──────────
+
+test('unrecognised content returns null rather than a guess', () => {
+ const cases = {
+ 'empty': '',
+ 'not a shim at all': '@echo off\r\necho hello world\r\n',
+ 'a real batch script with %* but no quoted target': '@echo off\r\nmytool.exe %*\r\n',
+ 'no exec line': '@ECHO off\r\nSET dp0=%~dp0\r\n',
+ 'unmodelled variable in the target': '"%_prog%" "%SOMETHING%\\cli.js" %*',
+ '%_prog% never assigned': '"%_prog%" "%dp0%\\node_modules\\x\\cli.js" %*',
+ 'relative target': 'node "cli.js" %*',
+ 'non-JS target': '"%_prog%" "%dp0%\\node_modules\\x\\bin\\tool.ps1" %*',
+ 'NUL byte': `@ECHO off\0\r\n"%_prog%" "%dp0%\\a.js" %*`,
+ 'too large to be a shim': `@ECHO off\r\n${'REM padding\r\n'.repeat(900)}"%_prog%" "%dp0%\\a.js" %*`
+ };
+ for (const [label, content] of Object.entries(cases)) {
+ assert.equal(parseNpmCmdShim(SHIM, content), null, `should refuse: ${label}`);
+ }
+ assert.equal(parseNpmCmdShim('', MODERN), null, 'no shim path');
+ assert.equal(parseNpmCmdShim(SHIM, null), null, 'non-string content');
+});
+
+test('interpreter flags between program and script are refused, never dropped', () => {
+ // A shebang like `#!/usr/bin/env node --experimental-vm-modules` puts flags on
+ // the shim's exec line. Silently discarding them would change how the CLI runs,
+ // so this shape is handed back to the (unchanged) cmd.exe fallback instead.
+ const withFlags = MODERN.replace(
+ '"%_prog%" "%dp0%',
+ '"%_prog%" --experimental-vm-modules "%dp0%'
+ );
+ assert.equal(parseNpmCmdShim(SHIM, withFlags), null);
+});
+
+test('the win32 branch is genuinely platform-gated', () => {
+ // Proves the macOS/Linux spawn path is untouched: on any non-win32 host the shim
+ // probe short-circuits before it ever looks at the filesystem.
+ const mgr = new PtyManager();
+ const probe = mgr['resolveWindowsShimSpawn'].bind(mgr);
+ if (process.platform === 'win32') return; // the guard under test is the negative one
+ assert.equal(probe(SHIM), null);
+ assert.equal(probe(`${NPM_DIR}\\opencode`), null);
+});
+
+// ── the payload: does a hostile prompt actually survive? ─────────────────────
+
+/** Everything about the injected hive prompt that breaks cmd.exe, in miniature:
+ * newlines, parentheses, embedded double quotes, a backslash run, `&`/`|`. */
+const HOSTILE_PROMPT = [
+ 'You are "Michael" (god-1), an autonomous agent in a collaborating hive.',
+ 'Your private workspace is C:\\Users\\Tester\\.munder\\hive\\agents\\god-1.',
+ '',
+ 'HIVE PROTOCOL — follow it every task:',
+ '1. Read EVERY file in C:\\Users\\Tester\\.munder\\hive\\agents\\god-1\\inbox (messages',
+ ' other agents sent you) & move handled ones to inbox\\.done.',
+ '3. To ask another agent, write ONE message JSON into your outbox\\ (schema in',
+ ' PROTOCOL.md) | NEVER write into another agent\'s folder.',
+ 'Trailing backslash torture: C:\\dir\\'
+].join('\n');
+
+/**
+ * Parse a Windows command line back into argv the way CommandLineToArgvW / the
+ * MSVC CRT does — 2n backslashes before a quote collapse to n and toggle quote
+ * state, 2n+1 collapse to n plus a literal quote, and ONLY space/tab delimit.
+ * This is the parser every child process on Windows effectively runs.
+ */
+function parseWindowsCommandLine(line) {
+ const argv = [];
+ let cur = '';
+ let inQuotes = false;
+ let started = false;
+ let i = 0;
+ while (i < line.length) {
+ const c = line[i];
+ if (c === '\\') {
+ let n = 0;
+ while (line[i] === '\\') { n++; i++; }
+ if (line[i] === '"') {
+ cur += '\\'.repeat(n >> 1);
+ if (n % 2 === 1) { cur += '"'; i++; } else { inQuotes = !inQuotes; i++; }
+ } else {
+ cur += '\\'.repeat(n);
+ }
+ started = true;
+ continue;
+ }
+ if (c === '"') { inQuotes = !inQuotes; started = true; i++; continue; }
+ if (!inQuotes && (c === ' ' || c === '\t')) {
+ if (started) { argv.push(cur); cur = ''; started = false; }
+ i++;
+ continue;
+ }
+ cur += c;
+ started = true;
+ i++;
+ }
+ if (started) argv.push(cur);
+ return argv;
+}
+
+test('ARRAY args: the whole prompt reaches the child intact', () => {
+ const nodeExe = 'C:\\Program Files\\nodejs\\node.exe'; // spaces in argv[0] too
+ const script = `${NPM_DIR}\\node_modules\\opencode-ai\\bin\\opencode.js`;
+ const argv = [nodeExe, script, '--prompt', HOSTILE_PROMPT];
+
+ const line = argsToCommandLine(nodeExe, argv.slice(1));
+ assert.deepEqual(parseWindowsCommandLine(line), argv, 'CRT round-trip must be exact');
+ assert.ok(line.includes('\n'), 'the newlines ride through as literal characters');
+});
+
+test('cmd.exe: the same prompt is destroyed — which is the bug', () => {
+ const line = buildCmdCommandLine(`${NPM_DIR}\\opencode.cmd`, ['--prompt', HOSTILE_PROMPT]);
+
+ // cmd.exe ends a statement at CR/LF regardless of quote state, so only the text
+ // before the first newline is ever part of the command that runs.
+ const firstStatement = line.split('\n')[0];
+ assert.ok(line.includes('\n'), 'the argument really is multi-line');
+ assert.ok(
+ !firstStatement.includes('HIVE PROTOCOL'),
+ 'the protocol block never reaches the agent — this is why Windows agents could not message each other'
+ );
+ assert.ok(
+ !firstStatement.includes('inbox'),
+ 'the agent is never told its inbox exists'
+ );
+ // Second, independent defect: cmd.exe has NO backslash escape. `\"` does not
+ // embed a quote — the `\` is literal and the `"` TOGGLES quote state, so text
+ // meant to be inside the quoted argument is actually parsed bare (where `&`,
+ // `|`, `(`, `)` are live metacharacters). Model cmd's toggling directly: `/s`
+ // strips the outer pair, then every `"` flips state.
+ const inner = firstStatement.slice('/d /s /c "'.length);
+ const atName = inner.indexOf('Michael');
+ assert.ok(atName > 0);
+ const quotesBefore = (inner.slice(0, atName).match(/"/g) || []).length;
+ assert.equal(
+ quotesBefore % 2,
+ 0,
+ 'the \\" produced here left cmd OUTSIDE quote state — it is not an escape, whatever the old comment claimed'
+ );
+});
+
+test('single-line args still go through cmd.exe unchanged (fallback preserved)', () => {
+ // The legacy path is untouched for everything the shim parser cannot decode.
+ assert.equal(
+ buildCmdCommandLine('C:\\Program Files\\x\\tool.cmd', ['--model', 'gpt-5-codex']),
+ '/d /s /c ""C:\\Program Files\\x\\tool.cmd" --model gpt-5-codex"'
+ );
+});