@speculoai/baton 0.6.2 → 0.7.0

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.
package/README.md CHANGED
@@ -110,6 +110,7 @@ If no target is named, the task goes to `codex`, or to `claude` when you are alr
110
110
  | `baton start` | Starts a job. Options include `--effort`, `--mode readonly`, `--scope <glob>`, `--rules check\|pointer\|off`, and `--cwd <worktree>`. |
111
111
  | `baton wait` / `status` | Waits for the job to stop, or takes one look at it. |
112
112
  | `baton result` | Prints the worker's full final answer, without the transcript. |
113
+ | `baton diff` / `apply` | Shows what an `--isolate` job changed, then brings it back as one local commit on your current branch (never pushes). |
113
114
  | `baton tail [-f]` | Shows the live event stream as readable text. |
114
115
  | `baton reply` | Continues the same conversation when the worker asks a question or you want a follow-up. |
115
116
  | `baton cancel` / `ls` / `prune` | Stops a job, lists jobs, or deletes old ones. |
package/README.zh-CN.md CHANGED
@@ -110,6 +110,7 @@ baton tail -f <task_id>
110
110
  | `baton start` | 启动任务。可选参数包括 `--effort`、`--mode readonly`、`--scope <glob>`、`--rules check\|pointer\|off`、`--cwd <worktree>`。 |
111
111
  | `baton wait` / `status` | 等任务停下,或者看一眼当前状态。 |
112
112
  | `baton result` | 只打印 worker 的完整最终回答,不含过程记录。 |
113
+ | `baton diff` / `apply` | 查看 `--isolate` 任务改了什么,再把改动作为一个本地 commit 收回到当前分支(不 push)。 |
113
114
  | `baton tail [-f]` | 以可读文本显示实时事件流。 |
114
115
  | `baton reply` | 执行者提问、或者你想追加要求时,在同一个会话里接着说。 |
115
116
  | `baton cancel` / `ls` / `prune` | 停止任务、列出任务、清理旧任务。 |
@@ -32,16 +32,20 @@ export const claude = {
32
32
  resolve(env) {
33
33
  return which(["claude"], env);
34
34
  },
35
- build({ bin, prompt, sessionId, reasoningEffort, mode }) {
35
+ build({ bin, prompt, sessionId, reasoningEffort, model, mode }) {
36
36
  // stream-json requires --verbose with -p.
37
37
  const permission = mode === "readonly" ? "plan" : "acceptEdits";
38
38
  const args = ["-p", "--output-format", "stream-json", "--verbose", "--permission-mode", permission, "--permission-prompts", "none"];
39
39
  if (reasoningEffort)
40
40
  args.push("--effort", reasoningEffort === "ultra" ? "max" : reasoningEffort);
41
+ // Verified 2026-11-24 (Claude Code 2.1.332): --resume without --model falls back to the default model, so pass it every turn.
42
+ const modelArg = model?.trim() || undefined;
43
+ if (modelArg)
44
+ args.push("--model", modelArg);
41
45
  if (sessionId)
42
46
  args.push("--resume", sessionId);
43
47
  args.push(prompt);
44
- return { command: bin, args, stdin: null };
48
+ return { command: bin, args, stdin: null, modelArg };
45
49
  },
46
50
  sessionIdFrom(line) {
47
51
  const obj = parse(line);
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import fs from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
- import { agents, start, status, cancel, wait, reply, ls, prune, result as turnResult } from "./tasks.js";
4
+ import { agents, start, status, cancel, wait, reply, ls, prune, diff, apply, result as turnResult } from "./tasks.js";
5
5
  import { addWorktree, listWorktrees, removeWorktree } from "./worktree.js";
6
6
  import { redact } from "./redact.js";
7
7
  import { detectedHosts, runInstall } from "./install.js";
@@ -40,7 +40,7 @@ async function main() {
40
40
  scope: { type: "string", multiple: true }, "scope-on-violation": { type: "string" },
41
41
  mode: { type: "string" }, "allow-weak": { type: "boolean" },
42
42
  isolate: { type: "boolean" }, "allow-dirty": { type: "boolean" },
43
- rules: { type: "string" },
43
+ rules: { type: "string" }, check: { type: "string" },
44
44
  } });
45
45
  if (positionals.length)
46
46
  throw new Error("start takes no positional arguments.");
@@ -51,7 +51,7 @@ async function main() {
51
51
  mode: values.mode, allowWeak: values["allow-weak"],
52
52
  isolate: values.isolate, allowDirty: values["allow-dirty"],
53
53
  rules: values.rules,
54
- });
54
+ check: values.check, });
55
55
  if (result.status !== "running")
56
56
  process.exitCode = 1;
57
57
  }
@@ -85,6 +85,14 @@ async function main() {
85
85
  process.stdout.write(`${turnResult(positionals[0], values.turn === undefined ? undefined : Number(values.turn)).final_message}\n`);
86
86
  return;
87
87
  }
88
+ else if (command === "diff") {
89
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { stat: { type: "boolean" } } });
90
+ if (positionals.length !== 1)
91
+ throw new Error("diff requires one task_id.");
92
+ // Plain text, like result: a patch is read, not parsed.
93
+ process.stdout.write(diff(positionals[0], { stat: values.stat }));
94
+ return;
95
+ }
88
96
  else if (command === "tail") {
89
97
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { follow: { type: "boolean", short: "f" }, raw: { type: "boolean" } } });
90
98
  if (positionals.length !== 1)
@@ -104,6 +112,12 @@ async function main() {
104
112
  throw new Error("prune requires --older days.");
105
113
  result = { deleted: prune(Number(values.older)) };
106
114
  }
115
+ else if (command === "apply") {
116
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { remove: { type: "boolean" } } });
117
+ if (positionals.length !== 1)
118
+ throw new Error("apply requires one task_id.");
119
+ result = apply(positionals[0], { remove: values.remove });
120
+ }
107
121
  else if (command === "cancel") {
108
122
  if (args.length !== 1)
109
123
  throw new Error("cancel requires one task_id.");
@@ -297,7 +311,7 @@ async function main() {
297
311
  return;
298
312
  }
299
313
  else
300
- throw new Error("Usage: baton version | agents | start | status | cancel | wait | result | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
314
+ throw new Error("Usage: baton version | agents | start | status | cancel | wait | result | diff | apply | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
301
315
  process.stdout.write(`${JSON.stringify(result)}\n`);
302
316
  }
303
317
  try {
package/dist/mcp.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { z } from "zod";
4
- import { agents, cancel, ls, reply, result, start, status, wait } from "./tasks.js";
4
+ import { agents, apply, cancel, diff, ls, reply, result, start, status, wait } from "./tasks.js";
5
5
  import { redact } from "./redact.js";
6
6
  const MAX_WAIT_SECONDS = 55;
7
7
  const PROGRESS_MS = 15_000;
@@ -26,7 +26,7 @@ export function createServer() {
26
26
  prompt: z.string(),
27
27
  files: z.array(z.string()).optional(),
28
28
  reasoning_effort: z.enum(["low", "medium", "high", "ultra"]).optional(),
29
- model: z.string().optional().describe("Per-task model (cursor and codex; stored in meta and carried over by reply)."),
29
+ model: z.string().optional().describe("Per-task model (cursor, codex and claude; stored in meta and carried over by reply)."),
30
30
  idle_timeout_seconds: z.number().optional().describe("Stop after this long with no output at all; default 600."),
31
31
  max_duration_seconds: z.number().optional().describe("Maximum total duration per turn; default unlimited."),
32
32
  cwd: z.string().optional(),
@@ -37,6 +37,7 @@ export function createServer() {
37
37
  isolate: z.boolean().optional().describe("Create a git worktree and run the write job there (default false)."),
38
38
  allow_dirty: z.boolean().optional().describe("Allow in-place write on a dirty working tree (default false)."),
39
39
  rules: z.enum(["check", "pointer", "off"]).optional().describe("Project rules discovery; default check. pointer injects unread rule paths into the first-turn prompt."),
40
+ check: z.string().optional().describe("Shell command Baton runs in the task cwd after each successful turn; a non-zero exit ends the turn as check_failed."),
40
41
  },
41
42
  }, (args) => respond(() => start({
42
43
  target: args.target_agent, prompt: args.prompt, files: args.files, cwd: args.cwd,
@@ -46,6 +47,7 @@ export function createServer() {
46
47
  mode: args.mode, allowWeak: args.allow_weak,
47
48
  isolate: args.isolate, allowDirty: args.allow_dirty,
48
49
  rules: args.rules,
50
+ check: args.check,
49
51
  })));
50
52
  server.registerTool("task_status", {
51
53
  description: "Get a task's current status. While running, includes liveness (active/quiet/orphaned) and quiet_for_s.",
@@ -80,8 +82,16 @@ export function createServer() {
80
82
  description: "Get the agent's full final message of a finished turn (default: the latest), without the tool-call transcript. task_status/task_wait only carry the one-line summary.",
81
83
  inputSchema: { task_id: z.string(), turn: z.number().int().optional() },
82
84
  }, (args) => respond(() => result(args.task_id, args.turn)));
85
+ server.registerTool("task_diff", {
86
+ description: "Net change of an --isolate task since its worktree was created (worker commits, edits and new files; Baton's own worktree files excluded). stat=true returns a diffstat instead of the patch.",
87
+ inputSchema: { task_id: z.string(), stat: z.boolean().optional() },
88
+ }, (args) => respond(() => ({ task_id: args.task_id, diff: diff(args.task_id, { stat: args.stat }) })));
89
+ server.registerTool("task_apply", {
90
+ description: "Bring an --isolate task's net change onto the source repo's current branch as one local commit (three-way cherry-pick; never pushes). Refuses, changing nothing, on staged changes, overlapping dirty or untracked files, an operation in progress, or a conflict. remove=true then deletes the worktree and branch. Only with the user's consent.",
91
+ inputSchema: { task_id: z.string(), remove: z.boolean().optional() },
92
+ }, (args) => respond(() => apply(args.task_id, { remove: args.remove })));
83
93
  server.registerTool("task_reply", {
84
- description: "After a task stops at needs_input, success, scope_violation or readonly_violation, start the next turn in the same session. as=human means a human said it; default host. Returns busy while running.",
94
+ description: "After a task stops at needs_input, success, scope_violation, readonly_violation or check_failed, start the next turn in the same session. as=human means a human said it; default host. Returns busy while running.",
85
95
  inputSchema: { task_id: z.string(), prompt: z.string(), as: z.enum(["host", "human"]).optional() },
86
96
  }, (args) => respond(() => reply(args.task_id, args.prompt, (args.as ?? "host"))));
87
97
  server.registerTool("task_cancel", {
@@ -10,6 +10,7 @@ import { resolveRulesync, rulesGitRoot, rulesyncCheck } from "./rules.js";
10
10
  import { appendEvent, hasTurnEnded, readMeta, writeMeta, readTurn, writeTurn, taskDir, lockTask } from "./store.js";
11
11
  import { redact } from "./redact.js";
12
12
  import { killGroup } from "./process.js";
13
+ const CHECK_TAIL = 4000;
13
14
  const QUOTA_PHRASES = ["usage limit", "quota exceeded", "rate limit"];
14
15
  function withoutHtml(text) {
15
16
  return String(text || "")
@@ -110,6 +111,55 @@ export async function supervise(id) {
110
111
  };
111
112
  emit({ type: "turn_started", author: turn.author, prompt_preview: redact(turn.prompt).slice(0, 200) });
112
113
  const heartbeat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
114
+ // Run the --check command in its own process group. Cancel reaches it through childPid; the idle limit only kills the check.
115
+ const runCheck = async (command) => {
116
+ const startedCheck = Date.now();
117
+ const file = path.join(taskDir(id), "raw", `${meta.turn}.check.log`);
118
+ fs.writeFileSync(file, "", { mode: 0o600 });
119
+ let output = "";
120
+ let lastOutput = startedCheck;
121
+ let idle = false;
122
+ let code = null;
123
+ // The worker's heartbeat has already stopped; without this a check longer than 30s looks orphaned and gets killed.
124
+ const beat = setInterval(() => { meta.heartbeat_at = new Date().toISOString(); save(); }, 10_000);
125
+ let idleTimer;
126
+ try {
127
+ const child = spawn("/bin/sh", ["-c", command], { cwd: meta.cwd, env: { ...process.env, BATON_DELEGATION: "1" }, detached: true, stdio: ["ignore", "pipe", "pipe"] });
128
+ childPid = child.pid ?? null;
129
+ meta.child_pid = childPid;
130
+ save();
131
+ if (stopped)
132
+ killGroup(childPid);
133
+ const onData = (chunk) => {
134
+ lastOutput = Date.now();
135
+ fs.appendFileSync(file, chunk);
136
+ output = (output + chunk.toString()).slice(-200_000);
137
+ };
138
+ child.stdout.on("data", onData);
139
+ child.stderr.on("data", onData);
140
+ idleTimer = setInterval(() => {
141
+ if (Date.now() - lastOutput < meta.idle_timeout_s * 1000)
142
+ return;
143
+ idle = true;
144
+ try {
145
+ killGroup(childPid);
146
+ }
147
+ catch { /* already gone */ }
148
+ }, 50);
149
+ code = await new Promise((resolve) => {
150
+ child.once("error", (error) => { output += `\n${error.message}`; resolve(null); });
151
+ child.once("close", resolve);
152
+ });
153
+ }
154
+ finally {
155
+ clearInterval(beat);
156
+ clearInterval(idleTimer);
157
+ }
158
+ const result = { command, exit_code: code, duration_ms: Date.now() - startedCheck, output_tail: redact(output).slice(-CHECK_TAIL) };
159
+ if (!stopped)
160
+ result.status = idle ? "timed_out" : code === 0 ? "passed" : "failed";
161
+ return result;
162
+ };
113
163
  // rulesync --check before the idle timer so its duration does not count against the worker.
114
164
  if (meta.turn === 1 && meta.rules?.rulesync?.status === "pending") {
115
165
  const repoRoot = rulesGitRoot(meta.cwd) ?? meta.cwd;
@@ -327,6 +377,24 @@ export async function supervise(id) {
327
377
  }
328
378
  }
329
379
  }
380
+ if (final === "success" && meta.check_command && !stopped) {
381
+ // Keep waiters blocked: the turn is not decided until the check ends.
382
+ meta.status = "running";
383
+ emit({ type: "check_started", command: redact(meta.check_command).slice(0, 200) });
384
+ const check = await runCheck(meta.check_command);
385
+ emit({ type: "check_ended", status: check.status ?? "cancelled", exit_code: check.exit_code });
386
+ turn.check = check;
387
+ meta.check = check;
388
+ if (stopped === "cancelled") {
389
+ final = "cancelled";
390
+ meta.summary = "Cancelled.";
391
+ }
392
+ else if (check.status !== "passed") {
393
+ final = "check_failed";
394
+ meta.summary = `check_failed: ${check.status === "timed_out" ? "timed out" : `exit ${check.exit_code}`}\n${check.output_tail}`.slice(0, 8192);
395
+ }
396
+ meta.status = final;
397
+ }
330
398
  delete meta.stop_reason;
331
399
  turn.status = final;
332
400
  turn.summary = meta.summary;
package/dist/tail.js CHANGED
@@ -13,6 +13,8 @@ export function formatEvent(event) {
13
13
  case "tool_result": return `${prefix} ${event.name} ${event.ok ? "ok" : "failed"}: ${event.detail}`;
14
14
  case "error": return `${prefix} error: ${event.text}`;
15
15
  case "raw": return `${prefix} ${event.stream}: ${event.line}`;
16
+ case "check_started": return `${prefix} check: ${event.command}`;
17
+ case "check_ended": return `${prefix} check ${event.status} (exit ${event.exit_code})`;
16
18
  case "turn_ended": return `${prefix} ended: ${event.status} (exit ${event.exit_code})`;
17
19
  }
18
20
  }
package/dist/tasks.js CHANGED
@@ -12,7 +12,7 @@ import { isAlive, killGroup } from "./process.js";
12
12
  import { dirtyPaths, gitRepoRoot, gitSnapshot, snapshotToBaseline } from "./git.js";
13
13
  import { normalizeScopeInput, scopePromptPrefix } from "./scope.js";
14
14
  import { buildRulesyncReport, discoverRules, hasRulesyncSource, readRulesyncConfig, resolveRulesync, rulesGitRoot, rulesPointer, unseenRules, } from "./rules.js";
15
- import { addWorktree, assertNotNestedWorktree, batonWorktreeExemptPaths, resolveRepoRoot } from "./worktree.js";
15
+ import { addWorktree, applyTree, assertNotNestedWorktree, batonWorktreeExemptPaths, diffTrees, forkPoint, headSha, netTree, removeTaskWorktree, resolveRepoRoot } from "./worktree.js";
16
16
  const DIRTY_PATHS_CAP = 50;
17
17
  /** Validate --isolate / --allow-dirty against mode. Throws on invalid combos. */
18
18
  export function resolveWriteSafety(mode, isolate, allowDirty) {
@@ -80,9 +80,9 @@ export async function start(input) {
80
80
  if (input.reasoningEffort && !["low", "medium", "high", "ultra"].includes(input.reasoningEffort))
81
81
  throw new Error("Unknown effort.");
82
82
  const model = input.model?.trim() || undefined;
83
- if (model && adapter.id !== "cursor" && adapter.id !== "codex")
84
- throw new Error(`${adapter.id} does not support --model yet (cursor and codex only).`);
85
- let model_argv = adapter.id === "codex" ? model : 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;
86
86
  if (adapter.id === "cursor") {
87
87
  const resolved = resolveCursorModelArg(model, input.reasoningEffort ?? null);
88
88
  if (resolved)
@@ -150,6 +150,7 @@ export async function start(input) {
150
150
  branch: added.branch,
151
151
  source_cwd,
152
152
  gitignore_updated: added.gitignore_updated,
153
+ base_sha: headSha(added.path),
153
154
  };
154
155
  }
155
156
  let scope_baseline;
@@ -200,6 +201,7 @@ export async function start(input) {
200
201
  scope_baseline,
201
202
  rules,
202
203
  ...(input.allowDirty ? { allow_dirty: true } : {}),
204
+ ...(input.check?.trim() ? { check_command: input.check.trim() } : {}),
203
205
  ...(worktree ? { worktree } : {}),
204
206
  };
205
207
  writeMeta(meta);
@@ -324,6 +326,55 @@ export function result(id, turnNo) {
324
326
  throw new Error(`Turn ${n} has no recorded final message (older baton, or the agent sent none); use baton tail.`);
325
327
  return { task_id: id, turn: n, status: turn.status, final_message: turn.final_message };
326
328
  }
329
+ function isolatedWorktree(meta) {
330
+ if (!meta.worktree)
331
+ throw new Error(`Task ${meta.task_id} was not started with --isolate.`);
332
+ return meta.worktree;
333
+ }
334
+ /** Fork point and net tree of an --isolate task; the temp index lives in the task dir, never in the worktree. */
335
+ function netChange(meta) {
336
+ const worktree = isolatedWorktree(meta);
337
+ if (!fs.existsSync(worktree.path))
338
+ throw new Error(`Worktree ${worktree.path} no longer exists (applied with --remove, or removed by hand).`);
339
+ const base = forkPoint(resolveRepoRoot(worktree.source_cwd), worktree.branch, worktree.base_sha);
340
+ const tree = netTree(worktree.path, path.join(taskDir(meta.task_id), `net.${randomUUID()}.index`));
341
+ return { worktree, base, tree };
342
+ }
343
+ export function diff(id, options = {}) {
344
+ const { worktree, base, tree } = netChange(status(id));
345
+ return diffTrees(worktree.path, base, tree, options.stat);
346
+ }
347
+ /** One squash commit of the task's net change, cherry-picked onto the source repo's current branch. Never pushes. */
348
+ export function apply(id, options = {}) {
349
+ const running = new Error("Task is running; wait for it to finish.");
350
+ if (status(id).status === "running")
351
+ throw running;
352
+ const release = lockTask(id);
353
+ if (!release)
354
+ throw running;
355
+ try {
356
+ const meta = readMeta(id);
357
+ if (meta.status === "running")
358
+ throw running;
359
+ const { worktree, base, tree } = netChange(meta);
360
+ const repo = resolveRepoRoot(worktree.source_cwd);
361
+ const subject = redact(meta.summary?.split("\n")[0]?.trim() || `apply task ${id.slice(0, 8)}`).slice(0, 72);
362
+ const message = `baton(${meta.target}): ${subject}\n\nBaton-Task: ${id}\nBaton-Target: ${meta.target}\n`;
363
+ const applied = applyTree(repo, base, tree, message);
364
+ const result = applied
365
+ ? { task_id: id, status: "applied", repo, commit: applied.commit, files: applied.files, removed: false }
366
+ : { task_id: id, status: "nothing_to_apply", repo, removed: false };
367
+ 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}.`;
371
+ }
372
+ return result;
373
+ }
374
+ finally {
375
+ release();
376
+ }
377
+ }
327
378
  export async function wait(ids, seconds = 50) {
328
379
  if (!ids.length)
329
380
  throw new Error("task_ids is missing.");
@@ -361,7 +412,7 @@ export async function reply(id, prompt, author = "host") {
361
412
  const meta = readMeta(id);
362
413
  if (meta.status === "running")
363
414
  return busy;
364
- if (!["success", "needs_input", "scope_violation", "readonly_violation"].includes(meta.status))
415
+ if (!["success", "needs_input", "scope_violation", "readonly_violation", "check_failed"].includes(meta.status))
365
416
  throw new Error(`Cannot continue a task in status ${meta.status}.`);
366
417
  if (!meta.session_id)
367
418
  throw new Error("No session_id; cannot resume the session.");
@@ -372,6 +423,7 @@ export async function reply(id, prompt, author = "host") {
372
423
  delete next.summary;
373
424
  delete next.warning;
374
425
  delete next.scope_violations;
426
+ delete next.check;
375
427
  writeTurn(id, { turn: next.turn, author, prompt, status: "running" });
376
428
  writeMeta(next);
377
429
  }
package/dist/worktree.js CHANGED
@@ -5,10 +5,105 @@ import { spawnSync } from "node:child_process";
5
5
  import { hasRulesyncSource, resolveRulesync, RULE_ENTRIES } from "./rules.js";
6
6
  import { redact } from "./redact.js";
7
7
  const META_NAME = ".baton-worktree.json";
8
- function git(cwd, args) {
9
- const ran = spawnSync("git", args, { cwd, encoding: "utf8" });
8
+ function git(cwd, args, options = {}) {
9
+ const ran = spawnSync("git", args, {
10
+ cwd, encoding: "utf8", input: options.input, maxBuffer: 256 * 1024 * 1024,
11
+ env: options.env ? { ...process.env, ...options.env } : process.env,
12
+ });
10
13
  return { status: ran.status ?? 1, stdout: ran.stdout || "", stderr: ran.stderr || "" };
11
14
  }
15
+ function mustGit(cwd, args, options = {}) {
16
+ const ran = git(cwd, args, options);
17
+ if (ran.status !== 0)
18
+ throw new Error(`git ${args[0]} failed: ${(ran.stderr || ran.stdout).trim()}`);
19
+ return ran.stdout;
20
+ }
21
+ export function headSha(cwd) {
22
+ return mustGit(cwd, ["rev-parse", "HEAD"]).trim();
23
+ }
24
+ /** Commit the task worktree forked from: the recorded sha, or (older tasks) the merge-base with the source HEAD. */
25
+ export function forkPoint(sourceRepo, branch, recorded) {
26
+ if (recorded)
27
+ return recorded;
28
+ const ran = git(sourceRepo, ["merge-base", branch, "HEAD"]);
29
+ if (ran.status !== 0 || !ran.stdout.trim())
30
+ throw new Error(`Cannot find where ${branch} forked from; no base_sha recorded and merge-base failed.`);
31
+ return ran.stdout.trim();
32
+ }
33
+ /**
34
+ * The worktree's net state as a tree object: HEAD plus every non-ignored working-tree change,
35
+ * minus Baton's own files (.baton-worktree.json, copy / symlink entries). Built in a throwaway
36
+ * index so the worktree's own index, branch and files stay untouched.
37
+ */
38
+ export function netTree(worktreePath, indexFile) {
39
+ const env = { GIT_INDEX_FILE: indexFile };
40
+ try {
41
+ mustGit(worktreePath, ["read-tree", "HEAD"], { env });
42
+ const exclude = [...batonWorktreeExemptPaths(worktreePath)].map((entry) => `:(exclude,glob)${entry}`);
43
+ mustGit(worktreePath, ["add", "-A", "--", ".", ...exclude], { env });
44
+ return mustGit(worktreePath, ["write-tree"], { env }).trim();
45
+ }
46
+ finally {
47
+ fs.rmSync(indexFile, { force: true });
48
+ }
49
+ }
50
+ export function diffTrees(cwd, base, tree, stat = false) {
51
+ return mustGit(cwd, ["diff", stat ? "--stat" : "--binary", base, tree]);
52
+ }
53
+ /** Paths touched between two trees; --no-renames so a rename lists both its old and new path. */
54
+ export function changedPaths(cwd, base, tree) {
55
+ return mustGit(cwd, ["diff", "--name-only", "--no-renames", "-z", base, tree]).split("\0").filter(Boolean);
56
+ }
57
+ const IN_PROGRESS = ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD", "rebase-merge", "rebase-apply"];
58
+ /** Why bringing `files` into `repo` is unsafe right now, or null. Checked before anything is written. */
59
+ function applyBlocker(repo, files) {
60
+ for (const name of IN_PROGRESS) {
61
+ if (fs.existsSync(path.resolve(repo, mustGit(repo, ["rev-parse", "--git-path", name]).trim()))) {
62
+ return `${repo} is in the middle of a merge, rebase, cherry-pick or revert (${name}); finish or abort it first.`;
63
+ }
64
+ }
65
+ if (git(repo, ["diff", "--cached", "--quiet"]).status !== 0)
66
+ return `Staged changes in ${repo}; commit or unstage them first.`;
67
+ // porcelain v1 -z: "XY path\0", and a rename / copy adds its source path as the next field.
68
+ const fields = mustGit(repo, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]).split("\0");
69
+ const dirty = new Set();
70
+ for (let i = 0; i < fields.length; i++) {
71
+ const entry = fields[i];
72
+ if (entry.length < 4)
73
+ continue;
74
+ dirty.add(entry.slice(3));
75
+ if (entry[0] === "R" || entry[0] === "C")
76
+ dirty.add(fields[++i]);
77
+ }
78
+ const overlap = files.filter((file) => dirty.has(file));
79
+ return overlap.length ? `Uncommitted or untracked files in ${repo} overlap the task's changes: ${overlap.join(", ")}. Commit, stash or move them first.` : null;
80
+ }
81
+ /**
82
+ * Bring `tree` (forked at `base`) onto the current branch of `repo` as one commit: commit-tree, then cherry-pick
83
+ * for a three-way merge. Any refusal or conflict leaves HEAD, index and working tree as they were.
84
+ */
85
+ export function applyTree(repo, base, tree, message) {
86
+ const files = changedPaths(repo, base, tree);
87
+ if (!files.length)
88
+ return null;
89
+ const blocker = applyBlocker(repo, files);
90
+ if (blocker)
91
+ throw new Error(blocker);
92
+ const squash = mustGit(repo, ["commit-tree", tree, "-p", base, "-F", "-"], { input: message }).trim();
93
+ const picked = git(repo, ["cherry-pick", squash]);
94
+ if (picked.status !== 0) {
95
+ const conflicts = git(repo, ["diff", "--name-only", "--diff-filter=U", "-z"]).stdout.split("\0").filter(Boolean);
96
+ git(repo, ["cherry-pick", "--abort"]);
97
+ const detail = (picked.stderr || picked.stdout).trim();
98
+ throw new Error(`cherry-pick failed and was aborted; ${repo} is unchanged.${conflicts.length ? ` Conflicts: ${conflicts.join(", ")}.` : ""} ${detail}`.trim());
99
+ }
100
+ return { commit: headSha(repo), files };
101
+ }
102
+ /** Delete a task's worktree and branch regardless of their state; true when both are gone. */
103
+ 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
+ }
12
107
  function strings(value) {
13
108
  return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
14
109
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
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",