Skip to content

amElnagdy/delegate-skills / skills/muse-delegate

muse-delegate

Verified

Delegate a coding task to Muse Code (`muse`) as a background implementer, then review its diff and land it yourself. Use this whenever the user wants to hand implementation work to Muse — phrasings like "have Muse do X", "delegate this to Muse", "run it through Muse", or "use Muse to implement/fix/refactor" — or wants to run a queue of coding tasks through Muse while staying the reviewer. Prefer it when the user will review the diff and commit it themselves. It applies only when the user wants that separate `muse exec` implementer run: if you are Muse yourself and the user simply asks you to write the code, do it directly. DO NOT USE for tasks small enough to do inline.

FileKindSize
SKILL.mdskill md9.3 KB
references/dispatch-and-poll.mdmarkdown9.3 KB
references/multi-task-queues.mdmarkdown3.9 KB
references/review-and-land.mdmarkdown7.7 KB
references/writing-the-brief.mdmarkdown6.5 KB
scripts/relay.mjsexecutablescript26.5 KB

scripts/relay.mjs

View on GitHub
#!/usr/bin/env node
/**
 * delegate-skills · muse-delegate · relay.mjs
 *
 * Dispatch a self-contained brief to Muse Code (`muse exec`), capture the run,
 * and write a structured result the orchestrating agent can review. The
 * orchestrator runs this one command and reads the result JSON — every
 * Muse-specific mechanic lives in here.
 *
 * Trust posture: relay.mjs itself makes no network calls, reads or writes no
 * credentials, and sends no telemetry; it has no dependencies (Node built-ins
 * only). It shells out only to `muse` and `git`. The `muse` process it launches
 * does authenticate — exactly as you do at the terminal. Read this file before
 * you run it.
 *
 * It deliberately does NOT commit. Committing is always the orchestrator's job —
 * after it reviews the diff and re-runs the project gates.
 *
 * Headless Muse is `muse exec` only. `muse resume` is the interactive TUI and is
 * never invoked. Write runs keep Muse's sandbox on and pass `--disable-approval`
 * so a headless run cannot hang on a tool-approval prompt. `--read-only` adds
 * `--disable-write` (non-shell filesystem writes) and `--disable-shell`.
 * `--yolo` is not the default and is not exposed.
 *
 * Usage:
 *   node relay.mjs --brief <file> [options]
 *   cat brief.txt | node relay.mjs [options]
 *
 * Options:
 *   --brief <file>          Path to the brief. If omitted, the brief is read from stdin.
 *   --cd <dir>              Working root for Muse (default: current directory).
 *   --lane <name>           Fleet lane from delegate-setup config (dials apply; explicit flags win).
 *   --model <name>          Muse model id (optional; Muse's own default applies).
 *   --effort <level>        Passed as --reasoning-effort: none|minimal|low|medium|high|xhigh|max|ultra.
 *   --provider <mode>       Relay-only: echo | meta. Omit to use Muse's default (meta). Not a fleet dial.
 *   --read-only             Add --disable-write and --disable-shell (keep --disable-approval).
 *   --session <id>          Continue a specific session via --session-id; send only the delta brief.
 *   --resume-last           Rejected: muse resume --last is TUI-only. Use --session <id>.
 *   --timeout <dur>         Relay-side watchdog (default: off). Durations use h/m/s strings.
 *   --out-dir <dir>         Where to write run artifacts (default: a fresh dir under system temp).
 *   -h, --help              Show this help.
 *
 * Result: written to <out-dir>/result.json and summarized on stdout —
 *   status, exitCode, signal, museVersion, sessionId, finalMessage (from
 *   run.terminal.completed), touchedFiles, stderrTail on a run that did not
 *   succeed, and paths to events.jsonl, final.txt and stderr.txt. stderr.txt
 *   holds the complete stderr stream; stderrTail is up to 20 nonblank lines
 *   from its final 64 KiB, with a partial first line marked as truncated.
 *
 * Exit codes: a pre-run usage error exits 2 before any run and writes no result
 * file; a missing `muse` binary exits 127; otherwise the exit code mirrors Muse's
 * own except a zero child exit without run.terminal.completed is reported failed.
 * Once the brief validates, result.json is written on every outcome —
 * completed, failed, timeout, aborted, or muse_unavailable.
 */

import {spawn, execFile, execFileSync, spawnSync } from "node:child_process";
import { mkdirSync, writeFileSync, renameSync, readFileSync, existsSync, appendFileSync, rmSync, openSync, fstatSync, readSync, closeSync } from "node:fs";
import {join, resolve, basename, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { constants, tmpdir } from "node:os";
import { StringDecoder } from "node:string_decoder";
const MAX_BUFFERED_CHARS = 1_048_576;

const VERSION_PROBE_TIMEOUT_MS = 10_000;
const MAX_TIMER_MS = 2_147_483_647;
const MAX_STDERR_TAIL_BYTES = 64 * 1024;
const SAFE_MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;
const SAFE_SESSION = /^[A-Za-z0-9][A-Za-z0-9._:-]*$/;
const MUSE_EFFORT = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);
const MUSE_PROVIDER = new Set(["echo", "meta"]);

const IMPLEMENTER_KEY = "muse";
function makeLineScanner(onObject) {
  let buf = "";
  return (chunk) => {
    if (!chunk) return;
    let start = 0;
    for (;;) {
      const end = chunk.indexOf("\n", start);
      if (end === -1) break;
      const line = buf + chunk.slice(start, end);
      buf = "";
      const trimmed = line.trim();
      if (trimmed) {
        try { onObject(JSON.parse(trimmed)); } catch { /* skip non-JSON lines */ }
      }
      start = end + 1;
    }
    buf += chunk.slice(start);
    if (buf.length > MAX_BUFFERED_CHARS) buf = "";
  };
}

function applyFleetLane(opts, flagged) {
  if (!opts.lane) return;
  const script = join(dirname(fileURLToPath(import.meta.url)), "../../delegate-setup/scripts/lane.mjs");
  if (!existsSync(script)) {
    fail("--lane requires the delegate-setup skill installed beside this relay");
  }
  const r = spawnSync(
    process.execPath,
    [script, "resolve", "--cwd", opts.cd, "--lane", opts.lane, "--implementer", IMPLEMENTER_KEY],
    { encoding: "utf8", env: process.env },
  );
  if (r.error) fail(`lane resolve failed: ${r.error.message}`);
  if (r.status !== 0) {
    fail((r.stderr || "lane resolve failed").trim().replace(/^lane\.mjs:\s*/, ""));
  }
  let resolved;
  try {
    const lines = (r.stdout || "").trim().split("\n").filter(Boolean);
    resolved = JSON.parse(lines[lines.length - 1]);
  } catch {
    fail("lane resolve returned invalid JSON");
  }
  opts.laneSource = resolved.source;
  for (const [field, value] of Object.entries(resolved.dials || {})) {
    if (flagged.has(field)) continue;
    if (field === "autonomy" && (flagged.has("autonomy") || flagged.has("sandbox") || flagged.has("readOnly"))) continue;
    if (field === "agent" && (flagged.has("agent") || flagged.has("readOnly"))) continue;
    if (field === "sandbox" && (flagged.has("sandbox") || flagged.has("readOnly"))) continue;
    if (field === "permissionMode" && (flagged.has("permissionMode") || flagged.has("readOnly"))) continue;
    if (field === "planOnly" && (flagged.has("planOnly") || flagged.has("readOnly"))) continue;
    if (field === "readOnly" && flagged.has("readOnly")) continue;
    if (field === "force" && flagged.has("force")) continue;
    opts[field] = value;
  }
}
function parseDuration(duration) {
  const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(duration);
  if (!match || (!match[1] && !match[2] && !match[3])) return null;
  try {
    const seconds =
      BigInt(match[1] || 0) * 3600n +
      BigInt(match[2] || 0) * 60n +
      BigInt(match[3] || 0);
    const milliseconds = seconds * 1000n;
    if (milliseconds <= 0n || milliseconds > BigInt(MAX_TIMER_MS)) return null;
    return Number(milliseconds);
  } catch {
    return null;
  }
}

function killChild(child, signal = "SIGTERM") {
  if (!child || !child.pid) return;
  if (process.platform === "win32") {
    if (signal !== "SIGTERM") return;
    try {
      execFileSync("taskkill", ["/pid", String(child.pid), "/t", "/f"], {
        stdio: ["ignore", "ignore", "inherit"],
      });
    } catch {
      // The process tree already exited.
    }
    return;
  }
  try {
    process.kill(-child.pid, signal);
  } catch {
    try {
      child.kill(signal);
    } catch {
      // The process group already exited.
    }
  }
}

function gitTouchedFiles(cwd) {
  try {
    const output = execFileSync("git", ["status", "--porcelain"], {
      cwd,
      encoding: "utf8",
      timeout: 10_000,
      killSignal: "SIGKILL",
      stdio: ["ignore", "pipe", "ignore"],
      maxBuffer: 64 * 1024 * 1024,
    });
    return output.split("\n").map((line) => line.trimEnd()).filter(Boolean);
  } catch {
    return null;
  }
}

function fail(message, code = 2) {
  process.stderr.write(`relay: ${message}\n`);
  process.exit(code);
}

function parseArgs(argv) {
  const flagged = new Set();
  const opts = {
    lane: null,
    laneSource: null,
    brief: null,
    cd: process.cwd(),
    model: null,
    effort: null,
    provider: null,
    readOnly: false,
    resumeLast: false,
    session: null,
    timeout: null,
    outDir: null,
  };
  for (let i = 0; i < argv.length; i += 1) {
    const arg = argv[i];
    const next = () => {
      const value = argv[i + 1];
      if (value === undefined) fail(`${arg} requires a value`);
      i += 1;
      return value;
    };
    switch (arg) {
      case "-h":
      case "--help":
        process.stdout.write(headerComment());
        process.exit(0);
        break;
      case "--brief": opts.brief = next(); break;
      case "--cd": opts.cd = resolve(next()); break;
      case "--lane": opts.lane = next(); break;
      case "--model": opts.model = next(); flagged.add("model"); break;
      case "--effort": opts.effort = next(); flagged.add("effort"); break;
      case "--provider": opts.provider = next(); flagged.add("provider"); break;
      case "--read-only": opts.readOnly = true; flagged.add("readOnly"); break;
      case "--resume-last": opts.resumeLast = true; break;
      case "--session": opts.session = next(); break;
      case "--timeout": opts.timeout = next(); flagged.add("timeout"); break;
      case "--out-dir": opts.outDir = resolve(next()); break;
      default:
        fail(`unknown option: ${arg}`);
    }
  }
  applyFleetLane(opts, flagged);
  if (opts.resumeLast) {
    fail("muse resume --last is TUI-only; headless resume is --session <id>");
  }
  if (opts.model !== null && !SAFE_MODEL.test(opts.model)) {
    fail("--model contains unsupported characters (allowed: letters, digits, . _ : / -)");
  }
  if (opts.effort !== null && !MUSE_EFFORT.has(opts.effort)) {
    fail(`invalid --effort "${opts.effort}" (expected: ${[...MUSE_EFFORT].join(", ")})`);
  }
  if (opts.provider !== null && !MUSE_PROVIDER.has(opts.provider)) {
    fail(`invalid --provider "${opts.provider}" (expected: echo or meta)`);
  }
  if (opts.timeout !== null && parseDuration(opts.timeout) === null) {
    fail(`--timeout "${opts.timeout}" is invalid or too long; use a positive h/m/s duration no longer than about 24 days`);
  }
  if (opts.session !== null && !SAFE_SESSION.test(opts.session)) {
    fail("--session must be a shell-safe session id (letters, digits, . _ : -)");
  }
  return opts;
}

function headerComment() {
  const src = readFileSync(new URL(import.meta.url), "utf8");
  const match = src.match(/\/\*\*([\s\S]*?)\*\//);
  if (!match) return "relay.mjs — dispatch a brief to muse exec\n";
  return match[1].replace(/^\s*\* ?/gm, "").trim() + "\n";
}

function readBrief(opts) {
  if (opts.brief) {
    if (!existsSync(opts.brief)) fail(`brief file not found: ${opts.brief}`);
    return readFileSync(opts.brief, "utf8");
  }
  if (process.stdin.isTTY) {
    fail("no --brief given and stdin is a TTY; pass --brief <file> or pipe the brief on stdin");
  }
  let stdin = "";
  try {
    stdin = readFileSync(0, "utf8");
  } catch {
    stdin = "";
  }
  return stdin;
}

function versionProbeTimeout(opts) {
  const timeoutMs = opts.timeout === null ? null : parseDuration(opts.timeout);
  return timeoutMs === null ? VERSION_PROBE_TIMEOUT_MS : Math.min(timeoutMs, VERSION_PROBE_TIMEOUT_MS);
}

function museVersion(opts, run, probeTimeoutMs) {
  return new Promise((resolveProbe) => {
    let child;
    let aborted = false;
    const writeResult = makeResultWriter(opts, null, run);
    const handlers = new Map(["SIGTERM", "SIGINT", "SIGHUP"].map((signal) => [signal, () => {
      if (aborted) return;
      aborted = true;
      const result = writeResult({
        status: "aborted",
        exitCode: 128 + constants.signals[signal],
        signal,
        sessionId: null,
        finalMessage: "",
        touchedFiles: gitTouchedFiles(opts.cd),
        stderrTail: [],
        error: `the relay was killed by ${signal} during muse --version preflight; Muse was not dispatched`,
      });
      printSummary(result, run.resultPath);
      killChild(child);
      setTimeout(() => {
        killChild(child, "SIGKILL");
        process.exit(result.exitCode);
      }, 2000);
    }]));
    for (const [signal, handler] of handlers) process.on(signal, handler);
    child = execFile("muse", ["--version"], {
      encoding: "utf8",
      timeout: probeTimeoutMs,
      killSignal: "SIGKILL",
      detached: process.platform !== "win32",
    }, (error, stdout, stderr) => {
      if (aborted) return;
      for (const [signal, handler] of handlers) process.removeListener(signal, handler);
      killChild(child, "SIGKILL");
      if (error?.code === "ENOENT") return resolveProbe({ version: null, error: null });
      if (error) {
        const timedOut = error.killed && error.signal === "SIGKILL";
        return resolveProbe({ version: null, error: {
          code: timedOut ? "ETIMEDOUT" : error.code,
          status: Number.isInteger(error.code) ? error.code : null,
          stderr,
        } });
      }
      resolveProbe({ version: stdout.trim() || "unknown", error: null });
    });
    // Version probes can inherit pipes into descendants, just like a dispatch.
    child.once("exit", () => {
      const drain = setTimeout(() => {
        child.stdout.destroy();
        child.stderr.destroy();
      }, 500);
      drain.unref();
    });
  });
}

function timestamp() {
  return new Date().toISOString().replace(/[:.]/g, "-");
}

function buildArgv(opts, briefPath) {
  const argv = [
    "exec",
    "--json",
    "--prompt-file", briefPath,
    "--disable-approval",
    "--trust-workspace",
    "--workspace", opts.cd,
    "--user-input-auto-resolve",
  ];
  if (opts.readOnly) {
    argv.push("--disable-write", "--disable-shell");
  }
  if (opts.session) argv.push("--session-id", opts.session);
  if (opts.provider) argv.push("--provider", opts.provider);
  if (opts.model) argv.push("--model", opts.model);
  if (opts.effort) argv.push("--reasoning-effort", opts.effort);
  return argv;
}

function consumeMuseEvent(event, state) {
  if (!event || typeof event !== "object") return;
  const stream = event.stream;
  if (stream && stream.kind === "session" && typeof stream.id === "string" && stream.id) {
    state.sessionId = stream.id;
  }
  const payload = event.payload && typeof event.payload === "object" ? event.payload : {};
  const payloadType = event.payload_type;
  const isTerminal = payloadType === "run.terminal.completed" || payload.kind === "run_terminal";
  if (!isTerminal) return;
  state.sawTerminal = true;
  if (typeof payload.text === "string") state.finalMessage = payload.text;
  state.terminalOk = payload.terminal == null || payload.terminal === "completed";
}

function prepareRunDir(opts, brief) {
  const startedAt = new Date().toISOString();
  const outDir = opts.outDir || join(tmpdir(), "delegate-relay", `${basename(opts.cd) || "repo"}-${timestamp()}`);
  mkdirSync(outDir, { recursive: true });
  const run = {
    startedAt,
    eventsPath: join(outDir, "events.jsonl"),
    finalPath: join(outDir, "final.txt"),
    briefPath: join(outDir, "brief.txt"),
    stderrPath: join(outDir, "stderr.txt"),
    resultPath: join(outDir, "result.json"),
  };
  rmSync(run.finalPath, { force: true });
  rmSync(run.resultPath, { force: true });
  writeFileSync(run.briefPath, brief, "utf8");
  writeFileSync(run.eventsPath, "", "utf8");
  writeFileSync(run.stderrPath, "", "utf8");
  return run;
}

function makeResultWriter(opts, version, run) {
  return (extra) => {
    const result = {
      schema: "delegate-relay.result.v1",
      lane: opts.lane,
      laneSource: opts.laneSource,
      tool: "muse",
      workdir: opts.cd,
      model: opts.model,
      effort: opts.effort,
      provider: opts.provider,
      readOnly: opts.readOnly,
      resumed: Boolean(opts.session),
      museVersion: version,
      startedAt: run.startedAt,
      finishedAt: new Date().toISOString(),
      briefPath: run.briefPath,
      eventsPath: run.eventsPath,
      finalPath: existsSync(run.finalPath) ? run.finalPath : null,
      stderrPath: run.stderrPath,
      ...extra,
    };
    const temporary = `${run.resultPath}.${process.pid}.tmp`;
    writeFileSync(temporary, `${JSON.stringify(result, null, 2)}\n`, "utf8");
    renameSync(temporary, run.resultPath);
    return result;
  };
}

function reportUnavailable(writeResult, resultPath) {
  const result = writeResult({ status: "muse_unavailable", exitCode: 127, signal: null, sessionId: null, finalMessage: "", touchedFiles: null });
  printSummary(result, resultPath);
  process.stderr.write("relay: `muse` not found on PATH. Install Muse Code and run `muse login`.\n");
  process.exit(127);
}

// ponytail: bound the summary to the final 64 KiB; read stderrPath for longer diagnostics.
// Reading the whole log here can exhaust memory before publishing a failure or forwarding an abort.
function stderrTail(stderrPath) {
  let fd;
  try {
    fd = openSync(stderrPath, "r");
    const size = fstatSync(fd).size;
    const start = Math.max(0, size - MAX_STDERR_TAIL_BYTES);
    const readStart = Math.max(0, start - 1);
    const buffer = Buffer.alloc(size - readStart);
    let bytesRead = 0;
    while (bytesRead < buffer.length) {
      const count = readSync(fd, buffer, bytesRead, buffer.length - bytesRead, readStart + bytesRead);
      if (count === 0) break;
      bytesRead += count;
    }
    let offset = start - readStart;
    // The preceding byte distinguishes a cut line from a line starting at the window boundary.
    const partialLine = offset > 0 && buffer[0] !== 0x0a;
    while (partialLine && offset < bytesRead && (buffer[offset] & 0xc0) === 0x80) offset += 1;
    const lines = buffer.subarray(offset, bytesRead).toString("utf8")
      .split(/\r?\n/)
      .map((line) => line.trimEnd());
    if (partialLine && lines[0]?.trim()) lines[0] = `[truncated; read stderrPath] ${lines[0]}`;
    return lines.filter((line) => line.trim()).slice(-20);
  } catch {
    // A missing or unreadable diagnostic must not prevent the run result from being published.
    return [];
  } finally {
    if (fd !== undefined) closeSync(fd);
  }
}

function reportVersionFailure(opts, writeResult, run, error, probeTimeoutMs) {
  const timedOut = error?.code === "ETIMEDOUT";
  const stderr = String(error?.stderr || "").trim();
  if (stderr) writeFileSync(run.stderrPath, `${stderr}\n`, "utf8");
  const message = timedOut
    ? `muse --version preflight timed out after ${probeTimeoutMs}ms; Muse was not dispatched`
    : `muse --version preflight failed${Number.isInteger(error?.status) ? ` with exit ${error.status}` : ""}; Muse was not dispatched`;
  const result = writeResult({
    status: timedOut ? "timeout" : "failed",
    exitCode: timedOut ? 124 : Number.isInteger(error?.status) ? error.status : 1,
    signal: null,
    sessionId: null,
    finalMessage: "",
    touchedFiles: gitTouchedFiles(opts.cd),
    stderrTail: stderrTail(run.stderrPath),
    error: message,
  });
  printSummary(result, run.resultPath);
  process.stderr.write(`relay: ${message}\n`);
  process.exit(result.exitCode);
}

function dispatchToMuse(opts, run, writeResult) {
  const argv = buildArgv(opts, run.briefPath);
  const child = spawn("muse", argv, {
    cwd: opts.cd,
    env: { ...process.env, PWD: opts.cd },
    stdio: ["ignore", "pipe", "pipe"],
    detached: process.platform !== "win32",
  });

  const state = {
    sessionId: opts.session || null,
    finalMessage: "",
    sawTerminal: false,
    terminalOk: false,
  };
  const stdoutDecoder = new StringDecoder("utf8");
  const scan = makeLineScanner((event) => consumeMuseEvent(event, state));

  child.stdout.on("data", (chunk) => {
    appendFileSync(run.eventsPath, chunk);
    scan(stdoutDecoder.write(chunk));
  });

  child.stderr.on("data", (chunk) => {
    process.stderr.write(chunk); // surface Muse progress live for the orchestrator
    appendFileSync(run.stderrPath, chunk);
  });

  const assembleFinal = () => {
    const message = (state.finalMessage || "").trim();
    if (message) writeFileSync(run.finalPath, message, "utf8");
    return message;
  };

  let settled = false;
  let watchdogFired = false;
  let watchdogTimer = null;
  let sigkillTimer = null;
  const timeoutMs = opts.timeout === null ? null : parseDuration(opts.timeout);
  if (timeoutMs !== null) {
    watchdogTimer = setTimeout(() => {
      watchdogFired = true;
      child.once("exit", () => {
        child.stdout.destroy();
        child.stderr.destroy();
      });
      killChild(child);
      sigkillTimer = setTimeout(() => {
        if (!settled) killChild(child, "SIGKILL");
      }, 10_000);
    }, timeoutMs);
  }

  const clearWatchdog = () => {
    if (watchdogTimer) clearTimeout(watchdogTimer);
    if (sigkillTimer) clearTimeout(sigkillTimer);
  };

  for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"]) {
    process.on(sig, () => {
      if (settled) return;
      settled = true;
      clearWatchdog();
      const abortedFields = {
        status: "aborted",
        exitCode: 128 + (constants.signals[sig] || 15),
        signal: sig,
        sessionId: state.sessionId,
        finalMessage: assembleFinal(),
        touchedFiles: gitTouchedFiles(opts.cd),
        stderrTail: stderrTail(run.stderrPath),
        error: `the relay was killed by ${sig}; muse was terminated with it — inspect the working tree before re-dispatching`,
      };
      const result = writeResult(abortedFields);
      printSummary(result, run.resultPath);
      killChild(child);
      setTimeout(() => {
        killChild(child, "SIGKILL");
        writeResult({ ...abortedFields, touchedFiles: gitTouchedFiles(opts.cd) });
        process.exit(result.exitCode);
      }, 2000);
    });
  }

  // A grandchild that outlives muse and inherited the pipes keeps stdout/stderr open, so
  // "close" never fires and the relay waits forever, writing no result. Once muse itself is
  // gone the pipes hold nothing we still need — events are scanned synchronously as they
  // arrive, and the stderr log is appended synchronously too — so drop them after a short
  // drain grace and let "close" run. This is the normal-exit twin of the stream teardown
  // the watchdog already does on the timeout path.
  child.once("exit", () => {
    // The implementer already exited. Leaving the watchdog armed lets a drain that
    // overlaps the remaining budget fire, set watchdogFired, and report timeout.
    if (!watchdogFired) clearWatchdog();
    const drain = setTimeout(() => {
      if (settled) return;
      child.stdout.destroy();
      child.stderr.destroy();
    }, 500);
    if (typeof drain.unref === "function") drain.unref();
  });

  child.on("error", (err) => {
    if (settled) return;
    settled = true;
    clearWatchdog();
    const result = writeResult({
      status: "failed",
      exitCode: 1,
      signal: null,
      sessionId: state.sessionId,
      finalMessage: assembleFinal(),
      touchedFiles: gitTouchedFiles(opts.cd),
      error: String(err && err.message ? err.message : err),
    });
    printSummary(result, run.resultPath);
    process.exit(1);
  });

  child.on("close", (code, signal) => {
    if (settled) return;
    settled = true;
    clearWatchdog();
    if (watchdogFired) killChild(child, "SIGKILL");
    scan(`${stdoutDecoder.end()}\n`);
    const finalMessage = assembleFinal();
    const mapped = code ?? (constants.signals[signal] ? 128 + constants.signals[signal] : 1);
    const terminalOk = state.sawTerminal && state.terminalOk;
    const succeeded = code === 0 && !watchdogFired && terminalOk;
    const result = writeResult({
      status: succeeded ? "completed" : watchdogFired ? "timeout" : "failed",
      exitCode: succeeded ? 0 : mapped === 0 ? 1 : mapped,
      signal: signal ?? null,
      sessionId: state.sessionId,
      finalMessage,
      touchedFiles: gitTouchedFiles(opts.cd),
      ...(succeeded ? {} : { stderrTail: stderrTail(run.stderrPath) }),
      ...(watchdogFired ? { error: `muse did not finish within --timeout ${opts.timeout}; killed by the relay watchdog` } : {}),
      ...(!succeeded && !watchdogFired && code === 0 && !state.sawTerminal
        ? { error: "muse exited 0 without a run.terminal.completed event" }
        : {}),
    });
    printSummary(result, run.resultPath);
    process.exit(result.exitCode);
  });
}

async function main() {
  const opts = parseArgs(process.argv.slice(2));
  const brief = readBrief(opts);
  if (!brief.trim()) fail("empty brief (pass --brief <file> or pipe the brief on stdin)");
  if (opts.session && opts.resumeLast) {
    fail("--session and --resume-last are mutually exclusive; pass only one");
  }

  const run = prepareRunDir(opts, brief);
  const probeTimeoutMs = versionProbeTimeout(opts);
  const probe = await museVersion(opts, run, probeTimeoutMs);
  const writeResult = makeResultWriter(opts, probe.version, run);

  if (!probe.version && !probe.error) {
    reportUnavailable(writeResult, run.resultPath);
    return;
  }
  if (probe.error) {
    reportVersionFailure(opts, writeResult, run, probe.error, probeTimeoutMs);
    return;
  }

  dispatchToMuse(opts, run, writeResult);
}

function printSummary(result, resultPath) {
  const lines = [];
  lines.push("");
  lines.push(`relay: ${result.status} (exit ${result.exitCode}${result.signal ? `, killed by ${result.signal}` : ""})  ·  muse ${result.museVersion ?? "?"}`);
  if (result.signal === "SIGKILL" && result.status === "failed") lines.push("hint: the host killed the process (commonly the OOM killer or a supervisor timeout) — this is not a muse error; check host memory and re-dispatch, or split the task into smaller briefs.");
  if (result.signal === "SIGTERM" && result.status === "failed") lines.push("hint: something outside the relay terminated muse (a supervisor, the session ending, or a manual kill) — when the relay itself does the killing it reports status \"timeout\" or \"aborted\" instead; inspect the working tree before re-dispatching.");
  if (result.resumed) lines.push("mode: resumed existing session");
  if (result.sessionId) lines.push(`session id (resume with: --session ${result.sessionId}): ${result.sessionId}`);
  const touched = result.touchedFiles;
  if (touched === null) {
    lines.push("touched files: git unavailable — inspect the working tree directly");
  } else {
    lines.push(`touched files: ${touched.length}`);
    for (const file of touched.slice(0, 40)) lines.push(`  ${file}`);
    if (touched.length > 40) lines.push(`  … and ${touched.length - 40} more`);
  }
  if (result.stderrTail && result.stderrTail.length) {
    lines.push("last stderr:");
    for (const line of result.stderrTail.slice(-8)) lines.push(`  ${line}`);
  }
  lines.push("");
  lines.push("--- muse final report ---");
  lines.push(result.finalMessage || "(no final message captured)");
  lines.push("--- end report ---");
  lines.push("");
  lines.push(`result: ${resultPath}`);
  lines.push("relay does not commit. Review the diff, re-run the project gates yourself, then commit from the orchestrator.");
  process.stdout.write(`${lines.join("\n")}\n`);
}

main();
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall