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(cwd+hooks): expand `~` at ingestion; run every hook shim under bundled Node

Chaitanya Giri913b8ad87f57
diff --git a/src/main/config.ts b/src/main/config.ts
index 4d91c01b..43116a8b 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -10,6 +10,7 @@ import {
type AgentProvider
} from '../shared/agentProvider';
import { defaultMcpDefaults } from '../shared/mcpCatalog';
+import { expandTilde } from './fs';
import type { IntegrationRecord } from '../shared/integrations';
/** A recurring auto-dispatched mission fired on an interval by the scheduler. */
@@ -419,6 +420,16 @@ export function readConfig(): HarnessConfig {
export function writeConfig(patch: Partial<HarnessConfig>): HarnessConfig {
const current = readConfig();
const next: HarnessConfig = { ...current, ...patch };
+ // Project INGESTION — a registered repo is typed by hand ("~/dev/foo") as often
+ // as it is picked from the folder dialog. Expand `~` here so the persisted list
+ // (and therefore every agent's default cwd) is ABSOLUTE; Node's fs/spawn treat
+ // `~` as a literal directory name and the spawn dies with `cwd does not exist`.
+ if (Array.isArray(patch.registeredRepos)) {
+ const seen = new Set<string>();
+ next.registeredRepos = patch.registeredRepos
+ .map((r) => expandTilde(r))
+ .filter((r) => r && !seen.has(r) && (seen.add(r), true));
+ }
// Track recently-opened hive homes so the launch picker can list them. Any write
// that SETS harnessHome (onboarding finish, changeHome) promotes it to the front,
// deduped and capped. Skips empty/null so a clear doesn't pollute the list.
diff --git a/src/main/fs.ts b/src/main/fs.ts
index 67f077bf..a868cd01 100644
--- a/src/main/fs.ts
+++ b/src/main/fs.ts
@@ -84,6 +84,34 @@ export async function writeFileText(root: string, rel: string, content: string):
}
}
+/**
+ * Expand a leading `~` to the user's home dir and return an absolute, normalized
+ * path. SYNC on purpose — every consumer (spawn guards, cwd validation, config
+ * writes) is synchronous.
+ *
+ * Only a SHELL expands `~`; Node's `fs`/`child_process` treat it as a literal
+ * directory name, so a user-typed `~/dev/foo` fails every existsSync/statSync and
+ * dies with `cwd does not exist`. This is applied at INGESTION (project add,
+ * `pty:spawn`) so the registry only ever stores an ABSOLUTE cwd, with
+ * defense-in-depth at the consumers.
+ *
+ * Non-tilde absolute paths are returned resolved/normalized. Anything that is
+ * still RELATIVE after expansion is returned untouched (trimmed) so callers keep
+ * their own "not-absolute" errors instead of it being silently resolved against
+ * the Electron process cwd. Empty input passes straight through. Windows paths
+ * (`C:\…`, UNC) are unaffected — they never start with `~`.
+ */
+export function expandTilde(p: string): string {
+ if (typeof p !== 'string') return p;
+ const t = p.trim();
+ if (!t) return p;
+ let out = t;
+ if (t === '~') out = homedir();
+ else if (t.startsWith('~/') || t.startsWith('~\\')) out = join(homedir(), t.slice(2));
+ if (!isAbsolute(out)) return t;
+ return resolve(out);
+}
+
/** Existence/metadata check for an ABSOLUTE path (v0.3.4 — backs the terminal
* ⌘-click markdown flow). `~/` is expanded here (the renderer doesn't know
* the home dir). Read-only metadata: returns whether a regular file exists and
diff --git a/src/main/hiddenClaude.ts b/src/main/hiddenClaude.ts
index 74a85734..528735f3 100644
--- a/src/main/hiddenClaude.ts
+++ b/src/main/hiddenClaude.ts
@@ -2,6 +2,7 @@ import * as pty from 'node-pty';
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
import { resolveCommand, userShellPath } from './shellEnv';
+import { expandTilde } from './fs';
import { projectDir } from './transcript';
import { ensureKilled } from './procKill';
@@ -98,10 +99,13 @@ function extractLastAssistantText(cwd: string, spawnedAt: number): string | null
export function runHiddenClaude(prompt: string, opts: HiddenClaudeOptions): Promise<HiddenClaudeResult> {
return new Promise((resolve) => {
if (!prompt.trim()) { resolve({ ok: false, error: 'empty prompt' }); return; }
- if (!opts.cwd || !existsSync(opts.cwd)) {
+ // Defense-in-depth: `~` is shell syntax, not a path Node understands.
+ const cwd = opts.cwd ? expandTilde(opts.cwd) : opts.cwd;
+ if (!cwd || !existsSync(cwd)) {
resolve({ ok: false, error: `cwd does not exist: ${opts.cwd}` });
return;
}
+ opts = { ...opts, cwd };
const binary = (opts.command || 'claude').trim().split(/\s+/)[0] || 'claude';
const exe = resolveCommand(binary);
diff --git a/src/main/hive.ts b/src/main/hive.ts
index 2140c9f8..9c529720 100644
--- a/src/main/hive.ts
+++ b/src/main/hive.ts
@@ -19,7 +19,7 @@
*/
import {
existsSync, mkdirSync, readFileSync, writeFileSync, renameSync,
- readdirSync, statSync, rmSync, appendFileSync, symlinkSync, copyFileSync
+ readdirSync, statSync, rmSync, appendFileSync, symlinkSync, copyFileSync, chmodSync
} from 'node:fs';
import { join, dirname, isAbsolute } from 'node:path';
import { homedir } from 'node:os';
@@ -36,6 +36,7 @@ import {
type AgentProvider
} from '../shared/agentProvider';
import { MCP_CATALOG } from '../shared/mcpCatalog';
+import { expandTilde } from './fs';
/** The subset of HarnessConfig the hive consumes for the default-MCP merge.
* Kept as a local shape so hive.ts never imports the foundation-owned config
@@ -324,6 +325,72 @@ export class HiveManager {
return root ? join(root, 'bin', 'hive-proxy.cjs') : null;
}
+ /**
+ * The BUNDLED-NODE launcher: `<root>/bin/hive-node` (POSIX) / `hive-node.cmd`
+ * (Windows). Every `.cjs` shim in the hive is executed through it.
+ *
+ * Why it exists: hooks are run by the agent CLI through a plain
+ * `/bin/sh -c` with a bare `PATH=/usr/bin:/bin:/usr/sbin:/sbin`. A user whose
+ * node comes from nvm (PATH set only by an interactive login shell) has NO node
+ * there, so a hook written as `node "<shim>"` exits **127 — command not found**
+ * and every payload is silently lost: no live status, no Stop→inbox drain, no
+ * session ids. Electron's own binary IS a full Node runtime under
+ * `ELECTRON_RUN_AS_NODE=1`, and it is guaranteed present (it is us).
+ *
+ * A wrapper SCRIPT rather than an inline `ELECTRON_RUN_AS_NODE=1 "<exe>" …`
+ * prefix because that prefix is POSIX-sh syntax — it is a hard error under
+ * cmd.exe, which is what runs hook commands on Windows. The wrapper also gives
+ * agents a `$HIVE_NODE` they can invoke directly (running the Electron binary
+ * WITHOUT the env var would launch a second app window, not a script).
+ *
+ * Rewritten on every bootstrap, so an app update/move re-bakes execPath.
+ */
+ private nodeLauncherPath(): string | null {
+ const root = this.root();
+ if (!root) return null;
+ return join(root, 'bin', process.platform === 'win32' ? 'hive-node.cmd' : 'hive-node');
+ }
+
+ /** Write the launcher described above. Best-effort: on failure callers fall
+ * back to bare `node`, i.e. exactly the pre-fix behavior. */
+ private writeNodeLauncher(): void {
+ const p = this.nodeLauncherPath();
+ if (!p) return;
+ try {
+ if (process.platform === 'win32') {
+ writeFileSync(p, `@echo off\r\nset ELECTRON_RUN_AS_NODE=1\r\n"${process.execPath}" %*\r\n`, 'utf8');
+ } else {
+ writeFileSync(p, `#!/bin/sh\nELECTRON_RUN_AS_NODE=1 exec "${process.execPath}" "$@"\n`, 'utf8');
+ chmodSync(p, 0o755);
+ }
+ } catch (e) {
+ console.error('[hive] writeNodeLauncher failed:', e);
+ }
+ }
+
+ /** The launcher path if it is actually on disk, else null (→ callers fall back
+ * to bare `node`, i.e. exactly the pre-fix behavior — never worse than before). */
+ private nodeLauncher(): string | null {
+ const p = this.nodeLauncherPath();
+ return p && existsSync(p) ? p : null;
+ }
+
+ /** Build a hook command string that runs `script` under the guaranteed node,
+ * DOUBLE-QUOTED (safe for paths with spaces). */
+ private nodeRun(script: string, ...args: string[]): string {
+ const launcher = this.nodeLauncher();
+ return [launcher ? `"${launcher}"` : 'node', `"${script}"`, ...args].join(' ');
+ }
+
+ /** Same, but UNQUOTED — for the CLIs whose hook config mangles embedded quotes
+ * (agy on cmd.exe) or stores the command in a quote-sensitive literal (codex's
+ * single-quoted TOML). Safe because both the hive root and the launcher inside
+ * it are space-free by construction; this only preserves each installer's
+ * existing quoting convention while swapping `node` for the bundled runtime. */
+ private nodeRunUnquoted(script: string, ...args: string[]): string {
+ return [this.nodeLauncher() ?? 'node', script, ...args].join(' ');
+ }
+
/** One proxy sidecar per live proxy-tier agent, keyed by agentId. Spawned in
* ensureAgent, killed on PTY exit / removeAgent / app quit (index.ts) — so a
* dead agent never leaks an orphan loopback listener. */
@@ -371,6 +438,9 @@ export class HiveManager {
writeFileSync(this.shimPath()!, HOOK_SHIM, 'utf8');
// The proxy-bridge sidecar for hookless CLIs (qwen). Same refresh policy.
writeFileSync(this.proxyShimPath()!, PROXY_BRIDGE_SHIM, 'utf8');
+ // The bundled-node launcher every shim above is invoked through — MUST be
+ // written before any hook installer runs (they probe for it).
+ this.writeNodeLauncher();
if (!existsSync(join(root, '.git'))) {
this.git(['init', '-q'], root);
@@ -384,6 +454,10 @@ export class HiveManager {
* Best-effort; never throws (a stat error degrades to invalid). */
private cwdValidity(cwd: string | undefined): { valid: boolean; issue: string | null } {
if (!cwd || typeof cwd !== 'string') return { valid: false, issue: 'missing' };
+ // Defense-in-depth: a `~/…` cwd from an older registry entry (written before
+ // ingestion-time expansion) would read as 'not-absolute' forever. Expand first
+ // so the roster reports the truth about the directory the spawn would use.
+ cwd = expandTilde(cwd);
if (!isAbsolute(cwd)) return { valid: false, issue: 'not-absolute' };
try {
return statSync(cwd).isDirectory()
@@ -447,6 +521,9 @@ export class HiveManager {
const prev = reg.agents[meta.id];
// Validate the working directory at the source so a bad value is visible on
// the roster (cwdValid) rather than silently spawning into a nonexistent dir.
+ // Store the EXPANDED cwd, never the raw `~/…` the user typed — the registry is
+ // read by hooks, the roster and the worker watcher, none of which run a shell.
+ if (meta.cwd) meta = { ...meta, cwd: expandTilde(meta.cwd) };
const cwd = this.cwdValidity(meta.cwd);
reg.agents[meta.id] = {
...prev,
@@ -475,6 +552,14 @@ export class HiveManager {
HIVE_ROOT: root,
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';
const claudeProvider = isClaudeProvider(meta.provider ?? 'claude');
@@ -686,7 +771,9 @@ export class HiveManager {
* scopes the filesystem/git servers; cfg (the consent map) gates which servers
* are written. Claude-only — this is invoked solely on the Claude spawn path. */
private hookSettings(shim: string, cwd: string, cfg: McpDefaultsMap, theme?: 'light' | 'dark'): unknown {
- const cmd = `node "${shim}"`;
+ // Bundled node, NOT bare `node` — see nodeLauncherPath(). Claude runs each of
+ // these through `sh -c` with a stripped PATH, where `node` is often absent.
+ const cmd = this.nodeRun(shim);
const entry = (matcher?: string) => ({
...(matcher ? { matcher } : {}),
hooks: [{ type: 'command', command: cmd }]
@@ -921,7 +1008,7 @@ export class HiveManager {
// stable $KG_CLI / $KG_ROOT env vars injected at spawn — no paths/counts that
// would change per spawn and bust the prompt cache.
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 `node "$KG_CLI" search "<query>"` for ranked passages, `node "$KG_CLI" list` to see what is available, and `node "$KG_CLI" get <id>` for a full document.'
+ ? '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.)'
: '';
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.'
@@ -932,7 +1019,7 @@ export class HiveManager {
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 `node "<helper>" --channel … --thread … --text "…"` reply command — when you finish, run it 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 `"$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".';
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.`,
@@ -1316,12 +1403,13 @@ export class HiveManager {
const shim = join(root, 'bin', 'agy-hook.cjs');
mkdirSync(join(root, 'bin'), { recursive: true });
writeFileSync(shim, AGY_HOOK_SHIM, 'utf8');
+ // Bundled node, not bare `node` — agy's hooks run with a stripped PATH too.
const tool = (event: string) => ({
matcher: '*',
- hooks: [{ type: 'command', command: `node ${shim} ${event}`, timeout: 0 }]
+ hooks: [{ type: 'command', command: this.nodeRunUnquoted(shim, event), timeout: 0 }]
});
const plain = (event: string) => ({
- hooks: [{ type: 'command', command: `node ${shim} ${event}`, timeout: 0 }]
+ hooks: [{ type: 'command', command: this.nodeRunUnquoted(shim, event), timeout: 0 }]
});
const group = {
PreToolUse: [tool('PreToolUse')],
@@ -1405,7 +1493,7 @@ export class HiveManager {
'SessionStart', 'UserPromptSubmit', 'PreCompact', 'PostCompact'];
config += '\n# --- munder-hive lifecycle hooks (auto-generated; do not edit) ---\n';
for (const ev of events) {
- config += `\n[[hooks.${ev}]]\n[[hooks.${ev}.hooks]]\ntype = "command"\ncommand = 'node ${shim}'\ntimeout = 0\n`;
+ config += `\n[[hooks.${ev}]]\n[[hooks.${ev}.hooks]]\ntype = "command"\ncommand = '${this.nodeRunUnquoted(shim)}'\ntimeout = 0\n`;
}
}
writeFileSync(join(home, 'config.toml'), config, 'utf8');
@@ -1521,7 +1609,9 @@ export class HiveManager {
const tool = (matcher?: string) => ({
...(matcher ? { matcher } : {}),
// Let Grok apply its event-aware defaults (5s normally, 600s for Stop).
- hooks: [{ type: 'command', command: `node ${shim}` }]
+ // Grok is a HOOK bridge (not a proxy sidecar), so it is hit by the same
+ // `node: command not found` 127 — bundled node here too.
+ hooks: [{ type: 'command', command: this.nodeRun(shim) }]
});
const hooks = {
PreToolUse: [tool('.*')],
diff --git a/src/main/index.ts b/src/main/index.ts
index 8bd9cca5..2ed8036e 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -16,7 +16,7 @@ import {
readConfig, writeConfig, resetConfig, ensureHarnessHome, ensureClaudePermissionsAccepted,
modelForRole, OPS_STANDUP_MISSION, HEARTBEAT_MISSION, COMPACT_MAINTENANCE_MISSION, type HarnessConfig, type ScheduledMission
} from './config';
-import { listDir, readFileText, writeFileText, statAbs } from './fs';
+import { listDir, readFileText, writeFileText, statAbs, expandTilde } from './fs';
import {
getBranch, getStatus, getLog, getBranches, getAheadBehind, isRepo, getDiff, mainRepoRoot,
addWorktree, removeWorktree, worktreeHasUnintegratedWork, worktreeIsGcSafe,
@@ -422,7 +422,9 @@ function teardownPty(id: string): void {
function informGod(subject: string, body: string, slack?: { channel: string; thread_ts: string }): void {
try {
const slackLine = slack
- ? `\n\n[SLACK] Close the loop — post a reply to channel ${slack.channel} thread ${slack.thread_ts} via:\n node "${slackReplyScriptPath()}" --channel ${slack.channel} --thread ${slack.thread_ts} --text "<your message>"`
+ // `$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>"`
: '';
hive.send({ to: 'god', act: 'inform', subject, body: body + slackLine }, 'ephemeral-worker');
} catch (e) {
@@ -1029,7 +1031,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: node "${helperPath}" --channel ${channel} --thread ${threadTs} --text "<substantive result>"
+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.)
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.
@@ -2010,7 +2012,17 @@ ipcMain.handle('pty:spawn', async (evt, opts: AgentSpawnOptions) => {
* it can ALSO be invoked by the god-triggered ephemeral-worker watcher (which has
* no renderer `evt`). `owner` is the window that should receive this PTY's output
* (null → the primary window). Behavior-identical to the prior inline handler. */
-async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebContents | null): Promise<{ ok: boolean; error?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean; seedPrompt?: string }> {
+async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebContents | null): Promise<{ ok: boolean; error?: string; cwd?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean; seedPrompt?: string }> {
+ // ── cwd INGESTION — expand `~` exactly once, here ───────────────────────────
+ // This is the single door every agent spawn comes through (`pty:spawn` IPC and
+ // the god-triggered ephemeral-worker watcher), so it is where a user-typed
+ // `~/dev/foo` becomes an absolute path. Only a shell expands `~`; Node treats it
+ // as a literal dir, so without this every downstream existsSync/statSync fails
+ // with `cwd does not exist`. Expanding BEFORE hive provisioning is what makes the
+ // registry store an ABSOLUTE cwd (and `cwdValid: true`). The resolved value is
+ // returned to the caller so the renderer records the same absolute path.
+ opts.cwd = expandTilde(opts.cwd);
+ if (opts.hive) opts.hive = { ...opts.hive, cwd: expandTilde(opts.hive.cwd) };
// Which CLI is this? Explicit wins; else inferred from the binary
// (claude/codex/grok/agy). Non-Claude providers skip every Claude-only spawn step
// below. Persist the resolved provider onto opts (+ hive meta) so the registry
@@ -2336,7 +2348,9 @@ async function spawnAgentCore(opts: AgentSpawnOptions, owner: Electron.WebConten
// The restore flow re-enters this exact worktree (cwd = worktreePath) so a
// restored isolated agent resumes in the CORRECT checkout, not the base repo.
const worktreePath = worktreePaths.get(opts.id);
- return { ...res, ...(worktreePath ? { worktreePath } : {}), ...(resumeNotFound ? { resumeNotFound: true } : {}), ...(didResume ? { resumed: true } : {}), ...(seedPrompt ? { seedPrompt } : {}) };
+ // `cwd` echoes back the TILDE-EXPANDED absolute path so the renderer's agent
+ // record matches what the registry and the PTY actually used.
+ return { ...res, cwd: opts.cwd, ...(worktreePath ? { worktreePath } : {}), ...(resumeNotFound ? { resumeNotFound: true } : {}), ...(didResume ? { resumed: true } : {}), ...(seedPrompt ? { seedPrompt } : {}) };
}
ipcMain.handle('pty:write', (_evt, id: string, data: string) => {
if (typeof id !== 'string' || typeof data !== 'string') return { ok: false, error: 'invalid args' };
@@ -3498,7 +3512,9 @@ async function processSpawnRequest(filePath: string): Promise<void> {
const workerId = `worker-${reqId}`;
if (liveWorkers.has(workerId)) { fail(`worker "${workerId}" already running`); return; }
- const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? raw.cwd.trim() : '';
+ // Worker request files are hand/LLM-authored, so `~/…` shows up here too — expand
+ // before the existence check (Node reads `~` literally).
+ const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? expandTilde(raw.cwd) : '';
if (!cwd || !existsSync(cwd)) { fail(`"cwd" missing or not found (${cwd || 'unset'})`); return; }
const command = typeof raw.command === 'string' && raw.command.trim() ? raw.command.trim() : (readConfig().defaultCommand ?? 'claude');
diff --git a/src/main/pty.ts b/src/main/pty.ts
index af033348..efc759d1 100644
--- a/src/main/pty.ts
+++ b/src/main/pty.ts
@@ -3,6 +3,7 @@ import type { WebContents } from 'electron';
import { existsSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { ensureKilled } from './procKill';
+import { expandTilde } from './fs';
import { captureFromLoginShell, userShellPath } from './shellEnv';
interface PtySession {
@@ -234,6 +235,10 @@ export class PtyManager {
if (this.sessions.has(opts.id)) {
return { ok: false, error: `pty already exists for id ${opts.id}` };
}
+ // Defense-in-depth: cwd is already tilde-expanded at ingestion (spawnAgentCore),
+ // but any other caller reaching the PTY directly gets the same treatment —
+ // `existsSync('~/dev/foo')` is always false, only a shell expands `~`.
+ opts = { ...opts, cwd: expandTilde(opts.cwd) };
if (!existsSync(opts.cwd)) {
return { ok: false, error: `cwd does not exist: ${opts.cwd}` };
}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index 064d7c30..4377567f 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -546,7 +546,9 @@ const api = {
version: __APP_VERSION__,
// ─── PTY ─────────────────────────────────────────────────────────────────
- spawnPty: (opts: SpawnPtyOptions): Promise<{ ok: boolean; error?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean; seedPrompt?: string }> =>
+ /** `cwd` in the result is the TILDE-EXPANDED absolute path main actually spawned
+ * into — the renderer stores that, not the raw `~/…` the user typed. */
+ spawnPty: (opts: SpawnPtyOptions): Promise<{ ok: boolean; error?: string; cwd?: string; worktreePath?: string; resumeNotFound?: boolean; resumed?: boolean; seedPrompt?: string }> =>
ipcRenderer.invoke('pty:spawn', opts),
writePty: (id: string, data: string): Promise<{ ok: boolean; error?: string }> =>
ipcRenderer.invoke('pty:write', id, data),
diff --git a/src/renderer/src/components/AddAgentModal.tsx b/src/renderer/src/components/AddAgentModal.tsx
index 24361545..c7467558 100644
--- a/src/renderer/src/components/AddAgentModal.tsx
+++ b/src/renderer/src/components/AddAgentModal.tsx
@@ -272,6 +272,12 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
setCwd(p);
try {
const updated = await window.cth.updateConfig({ registeredRepos: next });
+ // Main expands `~` when it persists registeredRepos, so adopt the stored
+ // (absolute) list — otherwise a typed "~/dev/foo" stays literal in this
+ // modal's state and rides along into the spawn.
+ const stored = updated.registeredRepos ?? next;
+ setRepos(stored);
+ if (stored[0]) setCwd(stored[0]);
onConfigChange?.(updated);
} catch { /* best-effort persist */ }
};
@@ -358,15 +364,19 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
console.warn(`[add-agent] resume session "${resumeSessionId.trim()}" not found — started a fresh session`);
}
+ // Main expands `~` at ingestion and echoes back the absolute path it actually
+ // spawned into — record THAT, so this agent's cwd matches the hive registry
+ // (and survives a restart, where nothing re-expands it).
+ const spawnedCwd = spawnRes.cwd || cwd;
const agent: Agent = {
id,
name: name.trim(),
character,
accent,
description: description.trim() || 'a fresh harness',
- project: basename(cwd),
+ project: basename(spawnedCwd),
tmuxTarget: '',
- cwd,
+ cwd: spawnedCwd,
goal: goal.trim() || undefined,
status: 'idle',
action: resuming && spawnRes.resumeNotFound ? 'session not found — fresh start' : 'starting up',
@@ -388,8 +398,8 @@ export function AddAgentModal({ onClose, config, onConfigChange }: AddAgentModal
// Remember the folder for the next hire: promote it to the front of the
// registeredRepos quick-picks (the modal's default cwd) so back-to-back
// hires land in the same project without re-picking.
- if (cwd && repos[0] !== cwd) {
- const nextRepos = [cwd, ...repos.filter((r) => r !== cwd)];
+ if (spawnedCwd && repos[0] !== spawnedCwd) {
+ const nextRepos = [spawnedCwd, ...repos.filter((r) => r !== spawnedCwd && r !== cwd)];
void window.cth.updateConfig({ registeredRepos: nextRepos })
.then((updated) => onConfigChange?.(updated))
.catch(() => { /* best-effort */ });