@speculoai/baton 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { spawn } from "node:child_process";
3
+ import spawn from "cross-spawn";
4
4
  import { createInterface } from "node:readline";
5
5
  import { getAdapter } from "./adapters/index.js";
6
6
  import { buildPrompt, interpret } from "./contract.js";
7
7
  import { baselineToSnapshot, gitChanges, gitRepoRoot, gitSnapshot, pathsSinceBaseline } from "./git.js";
8
8
  import { applyScopePolicy, findScopeViolations, isDirUnderCwd, relativizeToTaskCwd } from "./scope.js";
9
9
  import { resolveRulesync, rulesGitRoot, rulesyncCheck } from "./rules.js";
10
- import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, lockTask } from "./store.js";
10
+ import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, cancelRequestPath, lockTask } from "./store.js";
11
11
  import { redact } from "./redact.js";
12
12
  import { killGroup } from "./process.js";
13
13
  const CHECK_TAIL = 4000;
@@ -58,6 +58,8 @@ function failureSummary(stdout, stderr) {
58
58
  return reason.slice(-8192);
59
59
  return (withoutHtml(stderr) || withoutHtml(stdout)).slice(-8192);
60
60
  }
61
+ // Only POSIX needs a process group (killGroup). On Windows a detached child under a .cmd shim never produces output, and taskkill /T finds the tree through parent pids anyway.
62
+ const DETACHED = process.platform !== "win32";
61
63
  export async function supervise(id) {
62
64
  // Test hook: simulate a slow ("<ms>") or crashing ("exit") supervisor start.
63
65
  const hook = process.env.BATON_TEST_SUPERVISE_START;
@@ -91,6 +93,13 @@ export async function supervise(id) {
91
93
  };
92
94
  const cancel = () => stop("cancelled");
93
95
  process.on("SIGTERM", cancel);
96
+ // The request file is the portable path (Windows has no signal to send); SIGTERM only makes POSIX react sooner.
97
+ const cancelFile = cancelRequestPath(id, meta.turn);
98
+ const cancelWatch = setInterval(() => { if (fs.existsSync(cancelFile)) {
99
+ clearInterval(cancelWatch);
100
+ cancel();
101
+ } }, 250);
102
+ cancelWatch.unref();
94
103
  try {
95
104
  meta.supervisor_pid = process.pid;
96
105
  meta.heartbeat_at = new Date().toISOString();
@@ -124,7 +133,7 @@ export async function supervise(id) {
124
133
  const beat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
125
134
  let idleTimer;
126
135
  try {
127
- const child = spawn("/bin/sh", ["-c", command], { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: true, stdio: ["ignore", "pipe", "pipe"] });
136
+ const child = spawn(command, { shell: true, cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: DETACHED, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
128
137
  childPid = child.pid ?? null;
129
138
  meta.child_pid = childPid;
130
139
  save();
@@ -223,7 +232,7 @@ export async function supervise(id) {
223
232
  fs.writeFileSync(spec.lastMessagePath, "", { mode: 0o600, flag: "wx" });
224
233
  lastMessageCreated = true;
225
234
  }
226
- const child = spawn(spec.command, spec.args, { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: true, stdio: [spec.stdin == null ? "ignore" : "pipe", "pipe", "pipe"] });
235
+ const child = spawn(spec.command, spec.args, { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: DETACHED, windowsHide: true, stdio: [spec.stdin == null ? "ignore" : "pipe", "pipe", "pipe"] });
227
236
  childPid = child.pid ?? null;
228
237
  meta.child_pid = childPid;
229
238
  if (stopped)
@@ -406,4 +415,5 @@ export async function supervise(id) {
406
415
  else
407
416
  emit({ type: "turn_ended", status: final, exit_code: code });
408
417
  process.off("SIGTERM", cancel);
418
+ clearInterval(cancelWatch);
409
419
  }
package/dist/tasks.js CHANGED
@@ -2,10 +2,11 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { spawn, spawnSync } from "node:child_process";
5
+ import crossSpawn from "cross-spawn";
5
6
  import { once } from "node:events";
6
7
  import { adapters, getAdapter } from "./adapters/index.js";
7
8
  import { resolveCursorModelArg } from "./adapters/cursor.js";
8
- import { readMeta, writeMeta, writeTurn, readTurn, appendEvent, hasTurnEnded, taskDir, lockTask, listTasks } from "./store.js";
9
+ import { readMeta, writeMeta, writeTurn, readTurn, appendEvent, hasTurnEnded, taskDir, cancelRequestPath, lockTask, listTasks } from "./store.js";
9
10
  import { setTimeout as sleep } from "node:timers/promises";
10
11
  import { redact } from "./redact.js";
11
12
  import { isAlive, killGroup } from "./process.js";
@@ -48,7 +49,7 @@ function positive(value, name) {
48
49
  // Stay under the 30s no-supervisor orphan window in orphaned().
49
50
  const SUPERVISOR_READY_MS = 15_000;
50
51
  async function launch(id) {
51
- const child = spawn(process.execPath, [path.join(import.meta.dirname, `cli${path.extname(import.meta.filename)}`), "_supervise", id], { detached: true, stdio: "ignore", env: process.env });
52
+ const child = spawn(process.execPath, [path.join(import.meta.dirname, `cli${path.extname(import.meta.filename)}`), "_supervise", id], { detached: true, windowsHide: true, stdio: "ignore", env: process.env });
52
53
  await once(child, "spawn");
53
54
  let exited = false;
54
55
  child.once("exit", () => { exited = true; });
@@ -80,9 +81,9 @@ export async function start(input) {
80
81
  if (input.reasoningEffort && !["low", "medium", "high", "ultra"].includes(input.reasoningEffort))
81
82
  throw new Error("Unknown effort.");
82
83
  const model = input.model?.trim() || undefined;
83
- if (model && adapter.id !== "cursor" && adapter.id !== "codex" && adapter.id !== "claude")
84
- throw new Error(`${adapter.id} does not support --model yet (cursor, codex and claude only).`);
85
- let model_argv = adapter.id === "codex" || adapter.id === "claude" ? model : undefined;
84
+ if (model && adapter.id !== "cursor" && adapter.id !== "codex" && adapter.id !== "claude" && adapter.id !== "kimi")
85
+ throw new Error(`${adapter.id} does not support --model yet (cursor, codex, claude and kimi only).`);
86
+ let model_argv = adapter.id === "codex" || adapter.id === "claude" || adapter.id === "kimi" ? model : undefined;
86
87
  if (adapter.id === "cursor") {
87
88
  const resolved = resolveCursorModelArg(model, input.reasoningEffort ?? null);
88
89
  if (resolved)
@@ -135,8 +136,8 @@ export async function start(input) {
135
136
  const short = task_id.replace(/-/g, "").slice(0, 8);
136
137
  const name = `task-${short}`;
137
138
  const added = addWorktree(cwd, { name, branch: `baton/${name}`, base: "HEAD" });
138
- const realCwd = fs.realpathSync(cwd);
139
- const realRepo = fs.realpathSync(repo);
139
+ const realCwd = fs.realpathSync.native(cwd);
140
+ const realRepo = fs.realpathSync.native(repo);
140
141
  const rel = path.relative(realRepo, realCwd);
141
142
  if (rel.startsWith("..") || path.isAbsolute(rel)) {
142
143
  throw new Error("--isolate cwd must be inside the repository.");
@@ -264,7 +265,7 @@ export function status(id) {
264
265
  }
265
266
  }
266
267
  killGroup(meta.child_pid);
267
- const reason = meta.stop_reason;
268
+ const reason = meta.stop_reason ?? (fs.existsSync(cancelRequestPath(id, meta.turn)) ? "cancelled" : undefined);
268
269
  const decided = reason === "idle" || reason === "max_duration" || reason === "cancelled";
269
270
  meta.status = decided ? (reason === "cancelled" ? "cancelled" : "timed_out") : "failed";
270
271
  meta.summary = decided ? (reason === "cancelled" ? "Cancelled." : `Timed out: ${reason}.`) : "supervisor exited unexpectedly";
@@ -289,17 +290,22 @@ export function status(id) {
289
290
  release();
290
291
  }
291
292
  }
293
+ // The supervisor polls for the request every 250ms; past this it is treated as stuck and killed, and the orphan path records the cancel.
294
+ const CANCEL_FORCE_MS = 5000;
292
295
  export async function cancel(id) {
293
296
  let meta = status(id);
294
297
  if (meta.status !== "running")
295
298
  return meta;
296
- const end = Date.now() + 2000;
299
+ fs.writeFileSync(cancelRequestPath(id, meta.turn), "", { flag: "a", mode: 0o600 });
300
+ const start = Date.now();
297
301
  let signalled = null;
298
- while (Date.now() < end) {
302
+ let forced = false;
303
+ while (Date.now() - start < CANCEL_FORCE_MS + 2000) {
299
304
  meta = status(id);
300
305
  if (meta.status !== "running")
301
306
  return meta;
302
- if (meta.supervisor_pid !== signalled && isAlive(meta.supervisor_pid)) {
307
+ // POSIX also signals so the supervisor reacts at once; Windows has no signal that reaches its handler.
308
+ if (process.platform !== "win32" && meta.supervisor_pid !== signalled && isAlive(meta.supervisor_pid)) {
303
309
  try {
304
310
  process.kill(meta.supervisor_pid, "SIGTERM");
305
311
  signalled = meta.supervisor_pid;
@@ -309,6 +315,16 @@ export async function cancel(id) {
309
315
  throw error;
310
316
  }
311
317
  }
318
+ if (!forced && Date.now() - start > CANCEL_FORCE_MS && isAlive(meta.supervisor_pid)) {
319
+ forced = true;
320
+ try {
321
+ process.kill(meta.supervisor_pid, "SIGKILL");
322
+ }
323
+ catch (error) {
324
+ if (error.code !== "ESRCH")
325
+ throw error;
326
+ }
327
+ }
312
328
  await sleep(20);
313
329
  }
314
330
  throw new Error("Cancellation not yet confirmed; retry status.");
@@ -365,9 +381,10 @@ export function apply(id, options = {}) {
365
381
  ? { task_id: id, status: "applied", repo, commit: applied.commit, files: applied.files, removed: false }
366
382
  : { task_id: id, status: "nothing_to_apply", repo, removed: false };
367
383
  if (options.remove) {
368
- result.removed = removeTaskWorktree(repo, worktree.path, worktree.branch);
369
- if (!result.removed)
370
- result.warning = `Applied, but could not fully remove ${worktree.path} or branch ${worktree.branch}.`;
384
+ const problem = removeTaskWorktree(repo, worktree.path, worktree.branch);
385
+ result.removed = problem === null;
386
+ if (problem)
387
+ result.warning = `Applied, but could not fully remove ${worktree.path} or branch ${worktree.branch}: ${problem}`;
371
388
  }
372
389
  return result;
373
390
  }
@@ -436,7 +453,7 @@ export function ls(all = false, cwd = process.cwd()) {
436
453
  const here = path.resolve(cwd);
437
454
  let hereReal = here;
438
455
  try {
439
- hereReal = fs.realpathSync(here);
456
+ hereReal = fs.realpathSync.native(here);
440
457
  }
441
458
  catch { /* keep resolved */ }
442
459
  return listTasks().filter((meta) => {
@@ -445,9 +462,9 @@ export function ls(all = false, cwd = process.cwd()) {
445
462
  if (meta.cwd === here || meta.worktree?.source_cwd === here)
446
463
  return true;
447
464
  try {
448
- if (fs.realpathSync(meta.cwd) === hereReal)
465
+ if (fs.realpathSync.native(meta.cwd) === hereReal)
449
466
  return true;
450
- if (meta.worktree?.source_cwd && fs.realpathSync(meta.worktree.source_cwd) === hereReal)
467
+ if (meta.worktree?.source_cwd && fs.realpathSync.native(meta.worktree.source_cwd) === hereReal)
451
468
  return true;
452
469
  }
453
470
  catch { /* missing path */ }
@@ -492,7 +509,7 @@ export function agents(env = process.env) {
492
509
  const bin = adapter.resolve(env);
493
510
  if (!bin)
494
511
  return { id: adapter.id, installed: false, bin: null, version: null };
495
- const ran = spawnSync(bin, ["--version"], { encoding: "utf8", timeout: 5000, env });
512
+ const ran = crossSpawn.sync(bin, ["--version"], { encoding: "utf8", timeout: 5000, env });
496
513
  const version = `${ran.stdout || ""}\n${ran.stderr || ""}`.trim().split("\n").filter(Boolean)[0] || null;
497
514
  return { id: adapter.id, installed: true, bin, version };
498
515
  });
package/dist/usage.js ADDED
@@ -0,0 +1,212 @@
1
+ const INSTALL_OPTIONS = {
2
+ only: { type: "string", multiple: true, arg: "agent", desc: "Only this agent: claude, codex, cursor, agy or gemini (repeatable)" },
3
+ force: { type: "boolean", desc: "Reinstall even when already installed" },
4
+ "dry-run": { type: "boolean", desc: "Print the commands without running them" },
5
+ "skip-global": { type: "boolean", desc: "Do not install or update the global baton command" },
6
+ rulesync: { type: "string", arg: "project|global|skip", desc: "Answer the rulesync install question up front" },
7
+ };
8
+ const UPDATE_OPTIONS = { only: INSTALL_OPTIONS.only, "dry-run": INSTALL_OPTIONS["dry-run"], "skip-global": INSTALL_OPTIONS["skip-global"] };
9
+ const UNINSTALL_OPTIONS = { only: INSTALL_OPTIONS.only, "dry-run": INSTALL_OPTIONS["dry-run"] };
10
+ export const COMMANDS = {
11
+ version: { usage: "baton version", summary: "Print the installed baton version." },
12
+ agents: { usage: "baton agents", summary: "List the local agent CLIs baton can delegate to and whether each is installed." },
13
+ start: {
14
+ usage: "baton start --target <agent> [--prompt <text> | stdin] [options]",
15
+ summary: "Start a job in the background and return its task_id.",
16
+ options: {
17
+ target: { type: "string", arg: "agent", desc: "Agent CLI to run: codex, claude, cursor, agy or kimi (required)" },
18
+ prompt: { type: "string", arg: "text", desc: "Task prompt; read from stdin when omitted" },
19
+ cwd: { type: "string", arg: "dir", desc: "Working directory for the job (default: current directory)" },
20
+ file: { type: "string", multiple: true, arg: "path", desc: "File the agent should focus on (repeatable)" },
21
+ effort: { type: "string", arg: "low|medium|high|ultra", desc: "Reasoning effort, mapped to the CLI's native flag (not cursor)" },
22
+ model: { type: "string", arg: "id", desc: "Model id for cursor, codex, claude or kimi; kept across reply" },
23
+ "idle-timeout": { type: "string", arg: "s", desc: "Stop after this many seconds with no output (default 600)" },
24
+ "max-duration": { type: "string", arg: "s", desc: "Maximum seconds per turn (default unlimited)" },
25
+ scope: { type: "string", multiple: true, arg: "glob", desc: "Paths allowed to change, checked after each turn (repeatable)" },
26
+ "scope-on-violation": { type: "string", arg: "warn|fail", desc: "What an out-of-scope change does (default warn)" },
27
+ mode: { type: "string", arg: "readonly|write", desc: "Permission mode (default write)" },
28
+ "allow-weak": { type: "boolean", desc: "Allow --mode readonly on a target that cannot enforce it" },
29
+ isolate: { type: "boolean", desc: "Run in a new git worktree; bring the work back with baton apply" },
30
+ "allow-dirty": { type: "boolean", desc: "Allow an in-place write job on a dirty working tree" },
31
+ rules: { type: "string", arg: "check|pointer|off", desc: "Project rule file discovery (default check)" },
32
+ check: { type: "string", arg: "cmd", desc: "Shell command run after each successful turn; non-zero ends it as check_failed" },
33
+ },
34
+ examples: [
35
+ "baton start --target codex --isolate --prompt \"fix the failing test in test/a.test.ts\"",
36
+ "baton start --target claude --mode readonly --scope \"src/**\" < task.md",
37
+ ],
38
+ },
39
+ status: { usage: "baton status <task_id>", summary: "Print a job's current status; while running, includes liveness." },
40
+ cancel: { usage: "baton cancel <task_id>", summary: "Stop a running job and its whole process group." },
41
+ wait: {
42
+ usage: "baton wait <task_id>... [--for <s> | --until-done]",
43
+ summary: "Wait until any of the jobs leaves running, or until the time runs out.",
44
+ options: {
45
+ for: { type: "string", arg: "s", desc: "Seconds to wait (default 50)" },
46
+ "until-done": { type: "boolean", desc: "Block until a job leaves running" },
47
+ },
48
+ },
49
+ result: {
50
+ usage: "baton result <task_id> [--turn <n>]",
51
+ summary: "Print the agent's full final message of a finished turn as plain text.",
52
+ options: { turn: { type: "string", arg: "n", desc: "Turn number (default latest)" } },
53
+ },
54
+ diff: {
55
+ usage: "baton diff <task_id> [--stat]",
56
+ summary: "Print the net change of an --isolate job as a plain-text patch.",
57
+ options: { stat: { type: "boolean", desc: "Print a diffstat instead of the patch" } },
58
+ },
59
+ apply: {
60
+ usage: "baton apply <task_id> [--remove]",
61
+ summary: "Bring an --isolate job's net change onto the current branch as one local commit; never pushes.",
62
+ options: { remove: { type: "boolean", desc: "Delete the worktree and its branch after a successful apply" } },
63
+ },
64
+ tail: {
65
+ usage: "baton tail <task_id> [-f] [--raw]",
66
+ summary: "Print a job's events in readable form.",
67
+ options: {
68
+ follow: { type: "boolean", short: "f", desc: "Keep following until the job stops" },
69
+ raw: { type: "boolean", desc: "Print the raw events.jsonl lines" },
70
+ },
71
+ },
72
+ reply: {
73
+ usage: "baton reply <task_id> [--prompt <text> | stdin] [--as host|human]",
74
+ summary: "Start the next turn of a stopped job in the same session.",
75
+ options: {
76
+ prompt: { type: "string", arg: "text", desc: "Reply text; read from stdin when omitted" },
77
+ as: { type: "string", arg: "host|human", desc: "Who is speaking (default host)" },
78
+ },
79
+ },
80
+ ls: {
81
+ usage: "baton ls [--all]",
82
+ summary: "List jobs for the current directory, newest first.",
83
+ options: { all: { type: "boolean", desc: "List jobs from every directory" } },
84
+ },
85
+ prune: {
86
+ usage: "baton prune --older <days>",
87
+ summary: "Delete non-running task directories older than N days (worktrees are kept).",
88
+ options: { older: { type: "string", arg: "days", desc: "Age threshold in days (required)" } },
89
+ },
90
+ worktree: {
91
+ usage: "baton worktree add | ls | rm",
92
+ summary: "Manage baton worktrees under .worktrees/.",
93
+ subcommands: {
94
+ add: {
95
+ usage: "baton worktree add [--name <id>] [--branch <name>] [--base <ref>]",
96
+ summary: "Create a baton-managed worktree and local branch.",
97
+ options: {
98
+ name: { type: "string", arg: "id", desc: "Worktree name (default random hex)" },
99
+ branch: { type: "string", arg: "name", desc: "Branch to create (default baton/<name>)" },
100
+ base: { type: "string", arg: "ref", desc: "Ref to start from (default .baton.json base, main, master, or HEAD)" },
101
+ },
102
+ },
103
+ ls: {
104
+ usage: "baton worktree ls",
105
+ summary: "List baton-managed worktrees.",
106
+ },
107
+ rm: {
108
+ usage: "baton worktree rm <name-or-path> [-f | --force]",
109
+ summary: "Remove a baton-managed worktree and delete its local branch.",
110
+ options: {
111
+ force: { type: "boolean", short: "f", desc: "Remove even when dirty or unmerged (git branch -D)" },
112
+ },
113
+ notes: [
114
+ "Accepts a worktree name under .worktrees/ or its path; only baton-managed trees can be removed.",
115
+ "Without --force, refuses dirty trees or branches with commits unmerged into base; when clean, removes the tree and deletes the associated local branch (e.g. baton/*).",
116
+ ],
117
+ },
118
+ },
119
+ },
120
+ rules: {
121
+ usage: "baton rules init [options]",
122
+ summary: "Set up rulesync so your agents share one set of rules.",
123
+ options: {
124
+ install: { type: "string", arg: "project|global|skip", desc: "How to install rulesync when it is missing" },
125
+ source: { type: "string", arg: "agent", desc: "Import existing rules from claudecode, codexcli or cursor" },
126
+ template: { type: "boolean", desc: "Start from baton's template instead of importing" },
127
+ targets: { type: "string", multiple: true, arg: "agent[,agent]", desc: "Agents to generate for (default: detected hosts)" },
128
+ yes: { type: "boolean", desc: "Apply the generated changes without asking" },
129
+ "dry-run": { type: "boolean", desc: "Preview only" },
130
+ },
131
+ },
132
+ install: {
133
+ usage: "baton install [options]",
134
+ summary: "Install the global baton command and the plugin into your agent CLIs.",
135
+ options: INSTALL_OPTIONS,
136
+ },
137
+ update: {
138
+ usage: "baton update [--only <agent>]... [--dry-run] [--skip-global]",
139
+ summary: "Update the global baton command and the installed plugins.",
140
+ options: UPDATE_OPTIONS,
141
+ },
142
+ uninstall: {
143
+ usage: "baton uninstall [--only <agent>]... [--dry-run]",
144
+ summary: "Remove the baton plugin from your agent CLIs.",
145
+ options: UNINSTALL_OPTIONS,
146
+ },
147
+ mcp: { usage: "baton mcp", summary: "Start the MCP server on stdio." },
148
+ report: {
149
+ usage: "baton report [task_id] [--title <text>] [--body <text>] [--label <name>]... [--submit]",
150
+ summary: "Generate a redacted diagnostic report and GitHub issue link (optionally submit).",
151
+ options: {
152
+ title: { type: "string", arg: "text", desc: "Issue title override" },
153
+ body: { type: "string", arg: "text", desc: "What happened: expected vs. actual, repro (redacted like the rest)" },
154
+ label: { type: "string", multiple: true, arg: "name", desc: "Existing repo label to apply (repeatable; default: bug)" },
155
+ submit: { type: "boolean", desc: "Create the issue via gh if logged in, otherwise open the prefilled form in a browser" },
156
+ },
157
+ notes: ["Never includes prompts, raw logs, file names, or credentials; still review before posting."],
158
+ },
159
+ };
160
+ export function isCommand(name) {
161
+ return name !== undefined && Object.hasOwn(COMMANDS, name);
162
+ }
163
+ export function hasSubcommand(name, sub) {
164
+ const subs = COMMANDS[name].subcommands;
165
+ return sub !== undefined && subs !== undefined && Object.hasOwn(subs, sub);
166
+ }
167
+ /** `-h` / `--help` anywhere before `--`. */
168
+ export function wantsHelp(args) {
169
+ const end = args.indexOf("--");
170
+ return (end < 0 ? args : args.slice(0, end)).some((arg) => arg === "-h" || arg === "--help");
171
+ }
172
+ export const commandList = `Usage: baton ${Object.keys(COMMANDS).join(" | ")}`;
173
+ function columns(rows) {
174
+ const width = Math.max(...rows.map(([left]) => left.length)) + 2;
175
+ return rows.map(([left, right]) => ` ${left.padEnd(width)}${right}`);
176
+ }
177
+ export function renderHelp(name, sub) {
178
+ if (!name) {
179
+ return [
180
+ "Usage: baton <command> [options]",
181
+ "",
182
+ "Hand a bounded coding task to another local agent CLI, then continue the same session.",
183
+ "",
184
+ "Commands:",
185
+ ...columns(Object.entries(COMMANDS).map(([cmd, def]) => [cmd, def.summary])),
186
+ "",
187
+ "Run `baton <command> --help` for a command's options.",
188
+ "",
189
+ ].join("\n");
190
+ }
191
+ const top = COMMANDS[name];
192
+ const cmd = sub && top.subcommands && Object.hasOwn(top.subcommands, sub) ? top.subcommands[sub] : top;
193
+ const options = Object.entries(cmd.options ?? {}).map(([key, opt]) => [
194
+ `${opt.short ? `-${opt.short}, ` : ""}--${key}${opt.type === "string" ? ` <${opt.arg ?? "value"}>` : ""}`,
195
+ opt.desc,
196
+ ]);
197
+ options.push(["-h, --help", "Show this help"]);
198
+ const subs = cmd.subcommands ? Object.entries(cmd.subcommands) : [];
199
+ return [
200
+ `Usage: ${cmd.usage}`,
201
+ "",
202
+ cmd.summary,
203
+ ...(subs.length ? ["", "Subcommands:", ...columns(subs.map(([k, v]) => [k, v.summary]))] : []),
204
+ "",
205
+ "Options:",
206
+ ...columns(options),
207
+ ...(cmd.notes?.length ? ["", ...cmd.notes] : []),
208
+ ...(cmd.examples?.length ? ["", "Examples:", ...cmd.examples.map((line) => ` ${line}`)] : []),
209
+ ...(subs.length ? ["", `Run \`baton ${name} <subcommand> --help\` for a subcommand's options.`] : []),
210
+ "",
211
+ ].join("\n");
212
+ }
package/dist/worktree.js CHANGED
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { randomBytes } from "node:crypto";
4
4
  import { spawnSync } from "node:child_process";
5
+ import crossSpawn from "cross-spawn";
5
6
  import { hasRulesyncSource, resolveRulesync, RULE_ENTRIES } from "./rules.js";
6
7
  import { redact } from "./redact.js";
7
8
  const META_NAME = ".baton-worktree.json";
@@ -100,9 +101,22 @@ export function applyTree(repo, base, tree, message) {
100
101
  return { commit: headSha(repo), files };
101
102
  }
102
103
  /** Delete a task's worktree and branch regardless of their state; true when both are gone. */
104
+ /** Removes an --isolate worktree and its branch; null on success, otherwise what stayed behind and what git said. */
103
105
  export function removeTaskWorktree(repo, worktreePath, branch) {
104
- cleanupWorktree(repo, worktreePath, branch);
105
- return !fs.existsSync(worktreePath) && git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status !== 0;
106
+ const problems = cleanupWorktree(repo, worktreePath, branch);
107
+ // Windows keeps a deleted directory visible ("delete pending", or git leaves it) until the last handle on it closes, e.g. a worker that is still exiting.
108
+ for (let wait = 0; process.platform === "win32" && wait < 20 && fs.existsSync(worktreePath); wait++) {
109
+ try {
110
+ fs.rmSync(worktreePath, { recursive: true, force: true });
111
+ }
112
+ catch { /* still held */ }
113
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
114
+ }
115
+ if (fs.existsSync(worktreePath))
116
+ problems.push(`${worktreePath} still exists`);
117
+ if (git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status === 0)
118
+ problems.push(`branch ${branch} still exists`);
119
+ return problems.length ? problems.join("; ") : null;
106
120
  }
107
121
  function strings(value) {
108
122
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
@@ -148,11 +162,13 @@ export function ensureIgnored(repo, worktreeRoot) {
148
162
  if (rel.startsWith("..") || path.isAbsolute(rel)) {
149
163
  throw new Error("worktree root must be inside the repository.");
150
164
  }
151
- const check = git(repo, ["check-ignore", "-q", rel]);
165
+ const normalized = rel.replace(/\\/g, "/");
166
+ // Trailing slash tells git check-ignore this is a directory even before mkdirSync creates it.
167
+ const entry = normalized.endsWith("/") ? normalized : `${normalized}/`;
168
+ const check = git(repo, ["check-ignore", "-q", entry]);
152
169
  if (check.status === 0)
153
170
  return false;
154
171
  const ignorePath = path.join(repo, ".gitignore");
155
- const entry = rel.endsWith("/") ? rel : `${rel}/`;
156
172
  const existing = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, "utf8") : "";
157
173
  const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
158
174
  fs.writeFileSync(ignorePath, `${existing}${prefix}${entry}\n`);
@@ -164,8 +180,8 @@ export function assertNotNestedWorktree(cwd) {
164
180
  if (dir.status !== 0 || common.status !== 0)
165
181
  throw new Error("Current directory is not a git repository.");
166
182
  // realpath: on macOS /var vs /private/var must not look like a linked worktree.
167
- const gitDir = fs.realpathSync(path.resolve(cwd, dir.stdout.trim()));
168
- const gitCommon = fs.realpathSync(path.resolve(cwd, common.stdout.trim()));
183
+ const gitDir = fs.realpathSync.native(path.resolve(cwd, dir.stdout.trim()));
184
+ const gitCommon = fs.realpathSync.native(path.resolve(cwd, common.stdout.trim()));
169
185
  if (gitDir === gitCommon)
170
186
  return;
171
187
  const superproject = git(cwd, ["rev-parse", "--show-superproject-working-tree"]);
@@ -190,8 +206,8 @@ export function batonWorktreeExemptPaths(cwd) {
190
206
  const common = git(cwd, ["rev-parse", "--git-common-dir"]);
191
207
  if (dir.status !== 0 || common.status !== 0)
192
208
  return new Set();
193
- const gitDir = fs.realpathSync(path.resolve(cwd, dir.stdout.trim()));
194
- const gitCommon = fs.realpathSync(path.resolve(cwd, common.stdout.trim()));
209
+ const gitDir = fs.realpathSync.native(path.resolve(cwd, dir.stdout.trim()));
210
+ const gitCommon = fs.realpathSync.native(path.resolve(cwd, common.stdout.trim()));
195
211
  if (gitDir === gitCommon)
196
212
  return new Set(); // main checkout
197
213
  const top = git(cwd, ["rev-parse", "--show-toplevel"]);
@@ -297,7 +313,7 @@ function applyWorktreeRulesync(repo, worktreePath, cfg) {
297
313
  if (!bin) {
298
314
  return { rulesync: "skipped", detail: "rulesync not found in node_modules/.bin or PATH", missing, dirtied: [] };
299
315
  }
300
- const ran = spawnSync(bin, ["generate"], {
316
+ const ran = crossSpawn.sync(bin, ["generate"], {
301
317
  cwd: worktreePath,
302
318
  encoding: "utf8",
303
319
  env: { ...process.env, BATON_DELEGATION: "1" },
@@ -365,7 +381,15 @@ function prepareWorktree(repo, worktreePath, cfg) {
365
381
  continue;
366
382
  if (fs.existsSync(dest))
367
383
  fs.rmSync(dest, { recursive: true, force: true });
368
- fs.symlinkSync(src, dest);
384
+ try {
385
+ // junction: Windows lets any user link a directory this way; file links need Developer Mode or admin.
386
+ fs.symlinkSync(src, dest, fs.statSync(src).isDirectory() ? "junction" : "file");
387
+ }
388
+ catch (error) {
389
+ if (error.code !== "EPERM")
390
+ throw error;
391
+ throw new Error(`cannot symlink ${name}: Windows needs Developer Mode or admin rights for file links; list it under "copy" in .baton.json instead.`);
392
+ }
369
393
  }
370
394
  }
371
395
  for (const command of cfg.post_create) {
@@ -383,9 +407,13 @@ function prepareWorktree(repo, worktreePath, cfg) {
383
407
  }
384
408
  }
385
409
  function cleanupWorktree(repo, worktreePath, branch) {
386
- git(repo, ["worktree", "remove", "--force", worktreePath]);
387
- git(repo, ["branch", "-D", branch]);
388
- git(repo, ["worktree", "prune"]);
410
+ const errors = [];
411
+ for (const args of [["worktree", "remove", "--force", worktreePath], ["branch", "-D", branch], ["worktree", "prune"]]) {
412
+ const ran = git(repo, args);
413
+ if (ran.status !== 0)
414
+ errors.push(`git ${args.slice(0, 2).join(" ")}: ${(ran.stderr || ran.stdout).trim()}`);
415
+ }
416
+ return errors;
389
417
  }
390
418
  function resolveManagedPath(cwd, nameOrPath) {
391
419
  const repo = resolveRepoRoot(cwd);
@@ -408,9 +436,20 @@ function resolveManagedPath(cwd, nameOrPath) {
408
436
  return { repo, root, worktreePath, meta };
409
437
  }
410
438
  function isDirty(worktreePath) {
411
- // Ignore untracked (copy/.baton-worktree.json); only block on tracked edits.
412
- const status = git(worktreePath, ["status", "--porcelain", "--untracked-files=no"]);
413
- return status.status === 0 && status.stdout.trim().length > 0;
439
+ const status = git(worktreePath, ["status", "--porcelain=v1", "-z", "--untracked-files=normal"]);
440
+ if (status.status !== 0)
441
+ return true;
442
+ const exempt = [...batonWorktreeExemptPaths(worktreePath)];
443
+ for (const entry of status.stdout.split("\0")) {
444
+ if (entry.length < 4)
445
+ continue;
446
+ if (entry.slice(0, 2) !== "??")
447
+ return true;
448
+ const top = entry.slice(3).replace(/\/$/, "").split("/")[0];
449
+ if (!exempt.some((pattern) => matchBasename(top, pattern)))
450
+ return true;
451
+ }
452
+ return false;
414
453
  }
415
454
  function hasUnmergedCommits(repo, branch, base) {
416
455
  const ran = git(repo, ["rev-list", "--count", `${base}..${branch}`]);
@@ -418,23 +457,28 @@ function hasUnmergedCommits(repo, branch, base) {
418
457
  return true;
419
458
  return Number(ran.stdout.trim()) > 0;
420
459
  }
421
- export function removeWorktree(cwd, nameOrPath) {
460
+ export function removeWorktree(cwd, nameOrPath, options = {}) {
422
461
  const { repo, worktreePath, meta } = resolveManagedPath(cwd, nameOrPath);
423
- if (isDirty(worktreePath)) {
424
- throw new Error(`worktree has uncommitted changes; refusing to remove: ${worktreePath}`);
425
- }
426
- if (hasUnmergedCommits(repo, meta.branch, meta.base)) {
427
- throw new Error(`Branch ${meta.branch} has commits not merged into ${meta.base}; refusing to remove.`);
462
+ if (!options.force) {
463
+ if (isDirty(worktreePath)) {
464
+ throw new Error(`worktree has uncommitted changes; refusing to remove: ${worktreePath} (pass --force to remove anyway).`);
465
+ }
466
+ if (hasUnmergedCommits(repo, meta.branch, meta.base)) {
467
+ throw new Error(`Branch ${meta.branch} has commits not merged into ${meta.base}; refusing to remove (pass --force to remove anyway).`);
468
+ }
428
469
  }
429
- // ponytail: --force after our tracked-dirty + unmerged checks; untracked copy/meta are expected
470
+ // ponytail: --force after our dirty + unmerged checks (or user --force); untracked copy/meta are expected
430
471
  const removed = git(repo, ["worktree", "remove", "--force", worktreePath]);
431
472
  if (removed.status !== 0) {
432
473
  throw new Error(`git worktree remove failed: ${(removed.stderr || removed.stdout).trim()}`);
433
474
  }
434
- const deleted = git(repo, ["branch", "-d", meta.branch]);
435
- if (deleted.status !== 0) {
436
- throw new Error(`Failed to delete branch: ${(deleted.stderr || deleted.stdout).trim()}`);
437
- }
438
475
  git(repo, ["worktree", "prune"]);
476
+ const branchExists = git(repo, ["rev-parse", "--verify", "--quiet", `refs/heads/${meta.branch}`]).status === 0;
477
+ if (branchExists || !options.force) {
478
+ const deleted = git(repo, ["branch", options.force ? "-D" : "-d", meta.branch]);
479
+ if (deleted.status !== 0) {
480
+ throw new Error(`Failed to delete branch: ${(deleted.stderr || deleted.stdout).trim()}`);
481
+ }
482
+ }
439
483
  return { status: "ok", path: worktreePath, branch: meta.branch, name: meta.name };
440
484
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Hand a bounded coding task to another local agent CLI, then continue the same session when it needs a decision.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -23,7 +23,9 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@clack/prompts": "^1.9.0",
26
- "@modelcontextprotocol/sdk": "^1.20.2"
26
+ "@modelcontextprotocol/sdk": "^1.20.2",
27
+ "cross-spawn": "^7.0.6",
28
+ "picomatch": "^4.0.7"
27
29
  },
28
30
  "engines": {
29
31
  "node": ">=20.17"
@@ -32,7 +34,9 @@
32
34
  "access": "public"
33
35
  },
34
36
  "devDependencies": {
37
+ "@types/cross-spawn": "^6.0.6",
35
38
  "@types/node": "^26.6.6",
39
+ "@types/picomatch": "^4.0.3",
36
40
  "typescript": "^7.0.2"
37
41
  }
38
42
  }