The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(muse): bind the session the user typed in, and only one agent per directory
0xken1581996fee523f
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 441b14856..340ddc95a 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -27,6 +27,7 @@ import { registry, projectDisplayName, type RegisteredSession } from './lib/regiimport { installCodexHooks, installCommandCodeHooks, installCursorHooks, installDevinHooks, installHermesHooks, installOpencodePlugin, installPiExtension, installSessionHooks } from './lib/hooks.js'import { PID_FILE, TOKEN_FILE, daemonPort, isAlive, readPid } from './lib/daemonState.js'import { ENGINES, aliasesFor, engineBin, engineCommand, resolveEngine } from './lib/engineBin.js'+import { refuseDuplicateAgent } from './lib/duplicateAgent.js'import { launcherSessions } from './lib/launcherSessions.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'import { terminateDeletedAgent } from './lib/deleteAgentFallback.js'@@ -130,6 +131,12 @@ const ENGINE_SPAWN_GRACE_MS = 2_500/** Between repair attempts for the same launcher. Scanning an engine's store on every 5s tick, for a* launcher whose session cannot be resolved at all, is pure noise. */const REPAIR_RETRY_MS = 60_000+/** …but a NEW agent is a different case: it is waiting for something that is about to happen. Muse makes+ * this concrete — its session is only claimable once the user has typed, because a file with no turn in+ * it cannot be told apart from the ones muse opens for itself. Backing off a full minute there costs the+ * FIRST message: the pane answers while web and device show nothing. So keep sweeping for a while first,+ * then settle into the slow rhythm for launchers that will never resolve. */+const REPAIR_EAGER_ATTEMPTS = 24 // ≈2 min at the 5s sweepfunction usage(): never {console.log(`harness v${VERSION} — connect this computer to your machine@@ -906,6 +913,7 @@ async function runForeground(token: string): Promise<void> {*/const agentIdFor = (sessionId: string): string => registry.bySession(sessionId)?.agentId ?? sessionId+backend.runtimeModelsProvider = (sessionId) => {if (!sessionId) return runtimeProfiles.modelsForSessions(registry.list())const session = registry.resolve(sessionId)@@ -1144,6 +1152,8 @@ async function runForeground(token: string): Promise<void> {* worst case is staying invisible one more turn — never binding an agent to someone else's transcript.*/const lastRepairAttempt = new Map<string, number>()+ /** Attempts so far per agent — the first few run on every sweep, see REPAIR_EAGER_ATTEMPTS. */+ const repairAttempts = new Map<string, number>()/*** Bind the agents that have no engine session yet.*@@ -1158,8 +1168,10 @@ async function runForeground(token: string): Promise<void> {if (!launcher) continue// An engine we cannot resolve (or one still starting) would otherwise be re-scanned every tick.const attemptedAt = lastRepairAttempt.get(agent.agentId) ?? 0- if (Date.now() - attemptedAt < REPAIR_RETRY_MS) continue+ const attempts = repairAttempts.get(agent.agentId) ?? 0+ if (attempts >= REPAIR_EAGER_ATTEMPTS && Date.now() - attemptedAt < REPAIR_RETRY_MS) continuelastRepairAttempt.set(agent.agentId, Date.now())+ repairAttempts.set(agent.agentId, attempts + 1)const cwd = agent.cwd ?? launcher.cwdif (!cwd) continueconst identity = await resolvePaneEngineProcess(agent.tmuxPane, agent.engine)@@ -1234,6 +1246,14 @@ async function runForeground(token: string): Promise<void> {// record the LAUNCHER's pid as the session's process identity, and the reaper compares pid + start// time — the moment the engine appeared it would read as "process changed under pane" and evict a// live session. The periodic scan remains the backstop if this one is early anyway.+ // Turned away at the door, before hooks are installed or an engine is spawned — see the module for+ // why muse alone cannot host two agents in one directory.+ // Two filters, both learned the hard way: the registry is PERSISTED, so after a daemon restart it is+ // full of agents that may no longer exist, and a launcher reconnecting arrives under the agent id it+ // already owns. Without either guard the rule refused the very launchers it was meant to protect —+ // measured: a restart killed both live muse panes, because each was turned away by its own saved entry.+ refuseLauncher: ({ engine, cwd, launcherId, isLive }) =>+ refuseDuplicateAgent(registry.list(), engine, cwd, { selfId: launcherId, isLive }),onLauncherOpened: (launcher) => {// The agent IS the launcher: it exists from the moment `harness <engine>` runs, before the engine// has picked a session. Binding that session comes later (onRegistered / the reconcile sweep) —diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex 102b51304..2733d9a46 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -42,6 +42,16 @@ export interface HookServerHandlers {* this to go look (see adoptResumedSessions). Without it, a resumed agent stays invisible.*/onLauncherOpened?: (session: { launcherId: string; engine: RegisteredSession['engine']; tmuxPane: string; cwd?: string | null }) => void+ /** Turn a launcher away before it spawns anything; the string returned is shown to the person in the+ * pane. Used for engines that cannot have two agents in one directory (see `refuseDuplicateAgent`). */+ refuseLauncher?: (session: {+ engine: RegisteredSession['engine']+ cwd?: string | null+ /** This launcher's own agent id — it RECONNECTS under the same one, so it must never block itself. */+ launcherId: string+ /** Whether an agent id still has a launcher on the socket; a persisted entry alone proves nothing. */+ isLive: (agentId: string) => boolean+ }) => string | null/** A turn is now running (Command Code's PreToolUse — its only live turn-open signal). Idempotent:* it fires once per tool call, and every call after the first in a turn must be a no-op. */onTurnStart?: (body: { sessionId: string }) => void@@ -441,6 +451,24 @@ function handleLauncherSocket(ws: WebSocket, handlers: HookServerHandlers, port:// engine; the binary for an engine can be renamed — `commandcode` → `cmd` already happened). A// long-lived launcher from an older build would otherwise install stale hooks and spawn a stale// binary name, so the daemon — always the newest build — owns both.+ // Before anything is installed or spawned: some engines cannot have two agents in one directory,+ // because nothing in what they write says which of the two a session belongs to. `exit` — not+ // `error` — is what carries this: a launcher that predates this rule ignores an unknown `error`+ // reason and runs on regardless, while `exit` has always meant "stop this agent", so the rule holds+ // on old builds too. A new launcher acts on it before it spawns the engine at all.+ const refusal = handlers.refuseLauncher?.({+ engine: opened.engine,+ cwd: opened.cwd ?? null,+ launcherId: opened.launcherId,+ isLive: (agentId) => launcherSessions.has(agentId),+ })+ if (refusal) {+ console.warn(`[machine] refused ${sid(opened.launcherId)} · engine=${opened.engine} · ${refusal}`)+ send({ t: 'exit', reason: refusal })+ try { ws.close() } catch { /* ignore */ }+ return+ }+let hooksReady = falseif (!env.DISABLE_HOOK_INSTALL) {try { installHooksFor(opened.engine, port); hooksReady = true } catch { /* launcher falls back */ }diff --git a/cli/src/lib/duplicateAgent.spec.ts b/cli/src/lib/duplicateAgent.spec.tsnew file mode 100644index 000000000..f1daf9312--- /dev/null+++ b/cli/src/lib/duplicateAgent.spec.ts@@ -0,0 +1,72 @@+import { describe, expect, it } from 'vitest'+import { mkdtempSync, rmSync, symlinkSync } from 'fs'+import { tmpdir } from 'os'+import { join } from 'path'+import { refuseDuplicateAgent, sameDirSync } from './duplicateAgent.js'++/**+ * The rule exists because muse gives repair nothing to tell two agents in one directory apart, so the+ * second one could never stream. Refusing a launch is a heavy hammer — the daemon answers `exit`, and a+ * launcher acting on that ends the engine — so most of these tests are about what it must NOT block.+ */+describe('one agent per directory', () => {+ const CWD = '/Users/demo/work/project'+ const SELF = 'agent-self'+ const all = { selfId: SELF, isLive: () => true }+ const agent = (agentId: string, engine: string, cwd: string | null = CWD) => ({ agentId, engine, cwd })++ it('turns away a second muse agent in the same directory', () => {+ const reason = refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', CWD, all)+ expect(reason).toContain(CWD)+ expect(reason).toMatch(/one muse agent per directory/)+ })++ it('lets the FIRST muse agent in — a directory is only taken once someone is there', () => {+ expect(refuseDuplicateAgent([], 'muse', CWD, all)).toBeNull()+ expect(refuseDuplicateAgent([agent('agent-1', 'claude')], 'muse', CWD, all)).toBeNull()+ })++ it('lets muse run in a different directory', () => {+ expect(refuseDuplicateAgent([agent('agent-1', 'muse', '/Users/demo/other')], 'muse', CWD, all)).toBeNull()+ })++ it('never lets a launcher block itself', () => {+ // A reconnect arrives under the agent id it already owns — the registry entry it is about to reclaim.+ expect(refuseDuplicateAgent([agent(SELF, 'muse')], 'muse', CWD, all)).toBeNull()+ })++ it('ignores an agent whose launcher is gone', () => {+ // MEASURED failure: the registry is persisted, so a restarted daemon starts out holding agents that+ // may no longer exist. Treating those as occupancy killed two live muse panes — each refused by its+ // own saved entry. Only an agent still on the socket counts.+ const dead = { selfId: SELF, isLive: () => false }+ expect(refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', CWD, dead)).toBeNull()+ })++ it('applies to muse ONLY — every other engine may share a directory', () => {+ // The other eight report their session id, so two of them in one folder are still told apart.+ for (const engine of ['claude', 'codex', 'cursor', 'opencode', 'pi', 'hermes', 'commandcode', 'devin']) {+ expect(refuseDuplicateAgent([agent('agent-1', engine)], engine, CWD, all)).toBeNull()+ }+ })++ it('does not refuse on an unknown directory', () => {+ // A launcher that reports no cwd must never be blocked by a rule about directories.+ expect(refuseDuplicateAgent([agent('agent-1', 'muse')], 'muse', null, all)).toBeNull()+ expect(refuseDuplicateAgent([agent('agent-1', 'muse', null)], 'muse', CWD, all)).toBeNull()+ })++ it('sees through a symlink, so one directory under two names is still one directory', () => {+ // `/tmp` is itself a symlink to `/private/tmp` on macOS, which is why string equality is not enough.+ const real = mkdtempSync(join(tmpdir(), 'dup-'))+ const link = `${real}-link`+ try {+ symlinkSync(real, link)+ expect(sameDirSync(real, link)).toBe(true)+ expect(refuseDuplicateAgent([agent('agent-1', 'muse', real)], 'muse', link, all)).not.toBeNull()+ } finally {+ rmSync(link, { force: true })+ rmSync(real, { recursive: true, force: true })+ }+ })+})diff --git a/cli/src/lib/duplicateAgent.ts b/cli/src/lib/duplicateAgent.tsnew file mode 100644index 000000000..9ce25514c--- /dev/null+++ b/cli/src/lib/duplicateAgent.ts@@ -0,0 +1,63 @@+/**+ * One muse agent per directory.+ *+ * Muse is the only engine that hands back NO identity for the session it opens. Measured, and every other+ * channel ruled out: no hook fires (in `exec` or the TUI); `MUSE_CURRENT_SESSION_LOG` is something muse+ * sets for its own children, not something it reads from us; `MUSE_SESSIONS` moves nothing; `--workspace`+ * is realpath'd before it is recorded, so handing each agent its own symlink collapses to one string.+ *+ * So binding rests entirely on `workspace_root`, and two muse agents in one directory make it ambiguous+ * forever: `fileEngineSession` sees two equally valid candidates and — correctly — refuses both, leaving+ * NEITHER agent able to stream. The alternative was a per-agent `XDG_DATA_HOME`, the one thing that does+ * isolate muse; it was rejected because an agent id is minted fresh on every launch, so each relaunch+ * would open an empty history and strand the previous one's sessions, memory and cron.+ *+ * Turning the second agent away is the honest trade: nothing that worked stops working, and the user gets+ * a sentence instead of an agent that silently never streams.+ */++import { realpathSync } from 'fs'+import type { AgentEngine } from '../engines/types.js'++/** Engines that cannot tell two agents in one directory apart. Deliberately a list of one. */+const ONE_PER_DIRECTORY: ReadonlySet<string> = new Set<AgentEngine>(['muse'])++/** `sameDir` from sessionRepair without the await — the launcher handshake is synchronous, and this runs+ * once per launch. `/tmp` vs `/private/tmp` is the case raw string equality misses. */+export function sameDirSync(a: string, b: string): boolean {+ if (a === b) return true+ const real = (p: string): string => { try { return realpathSync(p) } catch { return p } }+ return real(a) === real(b)+}++export interface AgentLocation { agentId: string; engine: string; cwd?: string | null }++export interface DuplicateCheck {+ /** The asking launcher's own agent id. It RECONNECTS under the same one, so it must never block itself. */+ selfId: string+ /** Whether an agent id still has a launcher on the socket. */+ isLive: (agentId: string) => boolean+}++/**+ * The message to turn a launcher away with, or null to let it through.+ *+ * `known` is the registry as-is. Both filters below are load-bearing, and were learned by breaking it:+ * the registry is PERSISTED, so a restarted daemon starts out holding agents that may be long gone, and a+ * launcher reconnects under the id it already owns. Reading that list literally refused the very+ * launchers the rule exists to protect — measured: a daemon restart killed two live muse panes, each+ * turned away by its own saved entry, because `exit` means exactly what it says.+ */+export function refuseDuplicateAgent(+ known: readonly AgentLocation[],+ engine: string,+ cwd: string | null | undefined,+ { selfId, isLive }: DuplicateCheck,+): string | null {+ if (!ONE_PER_DIRECTORY.has(engine) || !cwd) return null+ const taken = known.some((agent) => agent.engine === engine+ && agent.agentId !== selfId+ && isLive(agent.agentId)+ && agent.cwd && sameDirSync(agent.cwd, cwd))+ return taken ? `a ${engine} agent is already running in ${cwd} — one ${engine} agent per directory` : null+}diff --git a/cli/src/lib/launch.ts b/cli/src/lib/launch.tsindex c93889095..1af89c297 100644--- a/cli/src/lib/launch.ts+++ b/cli/src/lib/launch.ts@@ -411,6 +411,15 @@ export async function launchEngine(engine: AgentEngine, argv: string[]): Promise// spawn a stale binary name and install stale hook definitions. Bounded wait — a wedged daemon must// never stop the agent from starting, so on timeout we fall back to this build's own answers.const ack = await link.waitForAck(ACK_WAIT_MS)+ // The daemon can turn a launch away outright — today only "one muse agent per directory", where a+ // second agent could never be told apart from the first. It arrives as `exit` in place of the ack, so+ // there is no `opened` and `waitForAck` simply times out. Bail HERE, in the gap before the spawn: the+ // engine has not started, so the pane returns to the shell instead of flashing a CLI that something+ // else kills a moment later (which is what an older launcher, acting on this only after spawning, does).+ if (link.exitRequested !== false) {+ console.error(`harness: ${link.exitRequested || 'this agent was refused by the machine'}`)+ process.exit(1)+ }const bin = ack?.bin || engineBin(engine)if (!ack?.hooksReady && !env.DISABLE_HOOK_INSTALL) {// Fallback only. The installers narrate to stdout, which here is the user's pane — a straydiff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex d6b8e28fc..2f3f510ac 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -169,3 +169,84 @@ describe('session repair', () => {await expect(findLiveSession('cursor', CWD, STARTED_AT)).resolves.toBeNull()})})++/**+ * Muse opens sessions of its OWN under the user's workspace — memory reminders are the ones seen live.+ * They share the workspace_root, sit at the same depth, and are BORN LATER, so they beat the real session+ * on every signal repair used to look at. Measured on a live machine: the daemon tailed an 11-line+ * reminder session while the conversation ran on in another file, and web and device received nothing.+ */+describe('session repair — muse', () => {+ /** `<MUSE_HOME>/sessions/YYYY/MM/DD/<uuid>/session.jsonl`, with the workspace on line one. */+ function writeMuseSession(+ home: string,+ id: string,+ workspace: string,+ events: ReadonlyArray<{ scope: string; event: Record<string, unknown> }>,+ mtimeMs: number,+ ): void {+ const dir = join(home, 'sessions', '2026', '08', '06', id)+ mkdirSync(dir, { recursive: true })+ const file = join(dir, 'session.jsonl')+ const lines = [JSON.stringify({ payload: { record: { workspace_root: workspace } } })]+ for (const { scope, event } of events) lines.push(JSON.stringify({ payload: { kind: scope, event } }))+ writeFileSync(file, `${lines.join('\n')}\n`)+ utimesSync(file, new Date(mtimeMs), new Date(mtimeMs))+ }++ // `payload.kind` is the discriminator: a RUN is a conversation turn, a TASK is scheduler bookkeeping.+ // Note the run is asserted WITHOUT a prompt — a scheduled run is a real turn nobody typed.+ const runTurn = { scope: 'run', event: { kind: 'started', prompt: 'xin chao' } }+ const scheduledRun = { scope: 'run', event: { kind: 'started', prompt: '' } }+ const taskOnly = [+ { scope: 'task', event: { kind: 'started', task_id: 't-1' } },+ { scope: 'task', event: { kind: 'status', message: 'opening' } },+ ]++ async function loadMuse(museHome: string) {+ vi.resetModules()+ process.env.MUSE_HOME = museHome+ return import('./sessionRepair.js')+ }++ it('ignores a session nobody typed into, and binds the one they did', async () => {+ const home = tempRoot()+ writeMuseSession(home, 'real-session', CWD, [runTurn], STARTED_AT + 5_000)+ writeMuseSession(home, 'reminder-session', CWD, taskOnly, STARTED_AT + 9_000) // younger: used to win+ const { findLiveSession } = await loadMuse(home)++ await expect(findLiveSession('muse', CWD, STARTED_AT))+ .resolves.toMatchObject({ sessionId: 'real-session' })+ })++ it('binds a SCHEDULED run, whose prompt is empty because nobody typed it', async () => {+ // The filter must key on the run lifecycle, not on the presence of a prompt: a scheduled run is a+ // real turn the scheduler triggered. Requiring a prompt would leave those sessions unbindable.+ const home = tempRoot()+ writeMuseSession(home, 'scheduled-session', CWD, [scheduledRun], STARTED_AT + 5_000)+ const { findLiveSession } = await loadMuse(home)++ await expect(findLiveSession('muse', CWD, STARTED_AT))+ .resolves.toMatchObject({ sessionId: 'scheduled-session' })+ })++ it('binds nothing at all when the only candidate has no user turn', async () => {+ const home = tempRoot()+ writeMuseSession(home, 'reminder-session', CWD, taskOnly, STARTED_AT + 5_000)+ const { findLiveSession } = await loadMuse(home)++ await expect(findLiveSession('muse', CWD, STARTED_AT)).resolves.toBeNull()+ })++ it('still refuses when two real sessions share a directory', async () => {+ // The filter narrows the field; it must not resolve a genuine tie. Two sessions someone typed into+ // is the case the "one muse agent per directory" rule prevents upstream — repair stays fail-closed,+ // because guessing here wires one agent's tile to the other's transcript.+ const home = tempRoot()+ writeMuseSession(home, 'session-a', CWD, [runTurn], STARTED_AT + 5_000)+ writeMuseSession(home, 'session-b', CWD, [runTurn], STARTED_AT + 6_000)+ const { findLiveSession } = await loadMuse(home)++ await expect(findLiveSession('muse', CWD, STARTED_AT)).resolves.toBeNull()+ })+})diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 4e1aec053..bccc8a2ab 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -26,7 +26,7 @@ import { readdir, readFile, realpath, stat } from 'fs/promises'import { basename, dirname, join, sep } from 'path'import { promisify } from 'util'import { env } from '../config/env.js'-import { museWorkspaceRoot } from '../engines/muse/normalizer.js'+import { museEvent, museWorkspaceRoot } from '../engines/muse/normalizer.js'import type { AgentEngine } from '../engines/types.js'import { readCodexRolloutMeta } from '../engines/codex/rollout.js'@@ -109,7 +109,7 @@ function idFromFile(path: string): string {* other describe the SAME directory and would never match textually — measured: a repair that resolved* correctly for `/private/tmp/synctest` returned null for `/tmp/synctest`.*/-async function sameDir(a: string, b: string): Promise<boolean> {+export async function sameDir(a: string, b: string): Promise<boolean> {if (a === b) return trueconst [ra, rb] = await Promise.all([realpath(a).catch(() => a),@@ -130,6 +130,23 @@ async function sameDir(a: string, b: string): Promise<boolean> {*/interface TranscriptMeta { cwd: string | null; sessionId?: string }+const str = (v: unknown): string => (typeof v === 'string' ? v : '')++/**+ * True once a muse session has opened a RUN — the lifecycle a conversation is made of.+ *+ * Not "has a prompt": a scheduled run is a real turn whose prompt is empty, because the scheduler+ * triggered it rather than a person. `payload.kind` is what separates the two lifecycles that share the+ * name `started`; a `task` one is scheduler bookkeeping and several fire inside a single run.+ */+function hasRun(lines: string[]): boolean {+ for (const line of lines) {+ const record = museEvent(line)+ if (record?.scope === 'run' && str(record.event.kind) === 'started') return true+ }+ return false+}+async function fileEngineSession(root: string,cwd: string,@@ -226,8 +243,17 @@ export async function findLiveSession(// files live one level deeper under `subagent/`, and must never be adopted as agents of their own.return fileEngineSession(join(env.MUSE_HOME, 'sessions'), cwd, startedAtMs, async (path) => {if (path.includes(`${sep}subagent${sep}`)) return null- const root = museWorkspaceRoot((await readFile(path, 'utf-8').catch(() => '')).split('\n', 1)[0] ?? '')- return root ? { cwd: root, sessionId: basename(dirname(path)) } : null+ const lines = (await readFile(path, 'utf-8').catch(() => '')).split('\n')+ const root = museWorkspaceRoot(lines[0] ?? '')+ if (!root) return null+ // Muse opens sessions of its OWN under the same workspace_root — memory reminders+ // (`memory_reminder_child_session_linked`) are the ones seen live. They are indistinguishable from+ // the user's session by path, workspace or birth time, and being younger they WIN the `born` tier:+ // measured, the daemon tailed an 11-line reminder session while the real conversation ran on in+ // another file, so web and device received nothing at all. What separates them is that a session+ // being conversed in has opened a RUN.+ if (!hasRun(lines)) return null+ return { cwd: root, sessionId: basename(dirname(path)) }}, opts)case 'opencode':// time_created is epoch MILLISECONDS here.