@speculoai/baton 0.4.0 → 0.5.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/dist/worktree.js CHANGED
@@ -2,6 +2,8 @@ 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 { hasRulesyncSource, resolveRulesync, RULE_ENTRIES } from "./rules.js";
6
+ import { redact } from "./redact.js";
5
7
  const META_NAME = ".baton-worktree.json";
6
8
  function git(cwd, args) {
7
9
  const ran = spawnSync("git", args, { cwd, encoding: "utf8" });
@@ -19,7 +21,7 @@ export function loadWorktreeConfig(repo) {
19
21
  raw = JSON.parse(fs.readFileSync(file, "utf8"));
20
22
  }
21
23
  catch (error) {
22
- throw new Error(`.baton.json 无效:${error.message}`);
24
+ throw new Error(`.baton.json is invalid: ${error.message}`);
23
25
  }
24
26
  const section = raw && typeof raw === "object" && "worktree" in raw
25
27
  ? raw.worktree
@@ -32,6 +34,7 @@ export function loadWorktreeConfig(repo) {
32
34
  copy: strings(section.copy),
33
35
  symlink: strings(section.symlink),
34
36
  post_create: strings(section.post_create),
37
+ rulesync: typeof section.rulesync === "boolean" ? section.rulesync : undefined,
35
38
  };
36
39
  }
37
40
  export function resolveWorktreeRoot(repo, cfg) {
@@ -48,7 +51,7 @@ export function resolveWorktreeRoot(repo, cfg) {
48
51
  export function ensureIgnored(repo, worktreeRoot) {
49
52
  const rel = path.relative(repo, worktreeRoot) || ".";
50
53
  if (rel.startsWith("..") || path.isAbsolute(rel)) {
51
- throw new Error("worktree 根目录必须在仓库内。");
54
+ throw new Error("worktree root must be inside the repository.");
52
55
  }
53
56
  const check = git(repo, ["check-ignore", "-q", rel]);
54
57
  if (check.status === 0)
@@ -64,22 +67,51 @@ export function assertNotNestedWorktree(cwd) {
64
67
  const dir = git(cwd, ["rev-parse", "--git-dir"]);
65
68
  const common = git(cwd, ["rev-parse", "--git-common-dir"]);
66
69
  if (dir.status !== 0 || common.status !== 0)
67
- throw new Error("当前目录不是 git 仓库。");
68
- const gitDir = path.resolve(cwd, dir.stdout.trim());
69
- const gitCommon = path.resolve(cwd, common.stdout.trim());
70
+ throw new Error("Current directory is not a git repository.");
71
+ // realpath: on macOS /var vs /private/var must not look like a linked worktree.
72
+ const gitDir = fs.realpathSync(path.resolve(cwd, dir.stdout.trim()));
73
+ const gitCommon = fs.realpathSync(path.resolve(cwd, common.stdout.trim()));
70
74
  if (gitDir === gitCommon)
71
75
  return;
72
76
  const superproject = git(cwd, ["rev-parse", "--show-superproject-working-tree"]);
73
77
  if (superproject.status === 0 && superproject.stdout.trim())
74
78
  return;
75
- throw new Error("已在 linked worktree 中,请回到主仓再 add(禁止嵌套)。");
79
+ throw new Error("Already in a linked worktree; return to the main repository before add (nesting is not allowed).");
76
80
  }
77
81
  export function resolveRepoRoot(cwd) {
78
82
  const ran = git(cwd, ["rev-parse", "--show-toplevel"]);
79
83
  if (ran.status !== 0)
80
- throw new Error("当前目录不是 git 仓库。");
84
+ throw new Error("Current directory is not a git repository.");
81
85
  return ran.stdout.trim();
82
86
  }
87
+ /**
88
+ * Paths the dirty-tree guard should ignore when `cwd` is inside a Baton-managed
89
+ * linked worktree (has `.baton-worktree.json` and git-dir ≠ common-dir).
90
+ * Empty when not in such a worktree — so a stray `.baton-worktree.json` in the
91
+ * main checkout still counts as dirty.
92
+ */
93
+ export function batonWorktreeExemptPaths(cwd) {
94
+ const dir = git(cwd, ["rev-parse", "--git-dir"]);
95
+ const common = git(cwd, ["rev-parse", "--git-common-dir"]);
96
+ if (dir.status !== 0 || common.status !== 0)
97
+ return new Set();
98
+ const gitDir = fs.realpathSync(path.resolve(cwd, dir.stdout.trim()));
99
+ const gitCommon = fs.realpathSync(path.resolve(cwd, common.stdout.trim()));
100
+ if (gitDir === gitCommon)
101
+ return new Set(); // main checkout
102
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]);
103
+ if (top.status !== 0)
104
+ return new Set();
105
+ const worktreeRoot = top.stdout.trim();
106
+ if (!fs.existsSync(path.join(worktreeRoot, META_NAME)))
107
+ return new Set();
108
+ const exempt = new Set([META_NAME]);
109
+ const mainRepo = path.dirname(gitCommon);
110
+ const cfg = loadWorktreeConfig(mainRepo);
111
+ for (const entry of [...cfg.copy, ...cfg.symlink])
112
+ exempt.add(entry);
113
+ return exempt;
114
+ }
83
115
  function defaultBase(repo, configured) {
84
116
  if (configured)
85
117
  return configured;
@@ -91,7 +123,7 @@ function defaultBase(repo, configured) {
91
123
  const head = git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]);
92
124
  if (head.status === 0 && head.stdout.trim() && head.stdout.trim() !== "HEAD")
93
125
  return head.stdout.trim();
94
- throw new Error("无法探测 base 分支,请在 .baton.json 或 --base 指定。");
126
+ throw new Error("Cannot detect the base branch; set it in .baton.json or with --base.");
95
127
  }
96
128
  function writeMeta(worktreePath, meta) {
97
129
  fs.writeFileSync(path.join(worktreePath, META_NAME), `${JSON.stringify(meta, null, 2)}\n`);
@@ -116,15 +148,15 @@ export function addWorktree(cwd, options = {}) {
116
148
  fs.mkdirSync(root, { recursive: true });
117
149
  const name = options.name || randomBytes(4).toString("hex");
118
150
  if (!/^[A-Za-z0-9._-]+$/.test(name))
119
- throw new Error("worktree name 含非法字符。");
151
+ throw new Error("worktree name contains invalid characters.");
120
152
  const worktreePath = path.join(root, name);
121
153
  if (fs.existsSync(worktreePath))
122
- throw new Error(`worktree 已存在:${worktreePath}`);
154
+ throw new Error(`worktree already exists: ${worktreePath}`);
123
155
  const branch = options.branch || `baton/${name}`;
124
156
  const base = defaultBase(repo, options.base ?? cfg.base);
125
157
  const created = git(repo, ["worktree", "add", "-b", branch, worktreePath, base]);
126
158
  if (created.status !== 0) {
127
- throw new Error(`git worktree add 失败:${(created.stderr || created.stdout).trim()}`);
159
+ throw new Error(`git worktree add failed: ${(created.stderr || created.stdout).trim()}`);
128
160
  }
129
161
  const meta = { name, branch, base, created_at: new Date().toISOString() };
130
162
  writeMeta(worktreePath, meta);
@@ -135,7 +167,60 @@ export function addWorktree(cwd, options = {}) {
135
167
  cleanupWorktree(repo, worktreePath, branch);
136
168
  throw error;
137
169
  }
138
- return { status: "ok", path: worktreePath, branch, base, name, gitignore_updated };
170
+ const rules = applyWorktreeRulesync(repo, worktreePath, cfg);
171
+ return { status: "ok", path: worktreePath, branch, base, name, gitignore_updated, rules };
172
+ }
173
+ function rootRuleEntries(dir) {
174
+ const found = [];
175
+ for (const entry of RULE_ENTRIES) {
176
+ const full = path.join(dir, entry);
177
+ try {
178
+ const st = fs.statSync(full);
179
+ if (st.isDirectory()) {
180
+ if (fs.readdirSync(full).length)
181
+ found.push(entry);
182
+ }
183
+ else if (st.isFile()) {
184
+ found.push(entry);
185
+ }
186
+ }
187
+ catch {
188
+ // absent
189
+ }
190
+ }
191
+ return found.sort();
192
+ }
193
+ function applyWorktreeRulesync(repo, worktreePath, cfg) {
194
+ const missing = rootRuleEntries(repo).filter((entry) => !fs.existsSync(path.join(worktreePath, entry)));
195
+ if (cfg.rulesync === false) {
196
+ return { rulesync: "skipped", detail: "disabled in .baton.json", missing, dirtied: [] };
197
+ }
198
+ if (!hasRulesyncSource(worktreePath)) {
199
+ return { rulesync: "skipped", detail: "no .rulesync/ in worktree", missing, dirtied: [] };
200
+ }
201
+ const bin = resolveRulesync(worktreePath, repo);
202
+ if (!bin) {
203
+ return { rulesync: "skipped", detail: "rulesync not found in node_modules/.bin or PATH", missing, dirtied: [] };
204
+ }
205
+ const ran = spawnSync(bin, ["generate"], {
206
+ cwd: worktreePath,
207
+ encoding: "utf8",
208
+ env: { ...process.env, BATON_DELEGATION: "1" },
209
+ timeout: 60_000,
210
+ });
211
+ if ((ran.status ?? 1) !== 0) {
212
+ const detail = redact((ran.stderr || ran.stdout || `rulesync exited ${ran.status}`).trim()).slice(0, 200);
213
+ return { rulesync: "error", detail, missing: rootRuleEntries(repo).filter((entry) => !fs.existsSync(path.join(worktreePath, entry))), dirtied: [] };
214
+ }
215
+ const porcelain = git(worktreePath, ["status", "--porcelain", "--untracked-files=no"]);
216
+ const dirtied = porcelain.status === 0
217
+ ? porcelain.stdout.split("\n").map((line) => line.slice(3).trim()).filter(Boolean)
218
+ : [];
219
+ return {
220
+ rulesync: "generated",
221
+ missing: rootRuleEntries(repo).filter((entry) => !fs.existsSync(path.join(worktreePath, entry))),
222
+ dirtied,
223
+ };
139
224
  }
140
225
  export function listWorktrees(cwd) {
141
226
  const repo = resolveRepoRoot(cwd);
@@ -198,7 +283,7 @@ function prepareWorktree(repo, worktreePath, cfg) {
198
283
  });
199
284
  if (ran.status !== 0) {
200
285
  const detail = (ran.stderr || ran.stdout || "").trim() || `exit ${ran.status}`;
201
- throw new Error(`post_create 失败(${command}):${detail}`);
286
+ throw new Error(`post_create failed (${command}): ${detail}`);
202
287
  }
203
288
  }
204
289
  }
@@ -220,11 +305,11 @@ function resolveManagedPath(cwd, nameOrPath) {
220
305
  : candidate;
221
306
  const rel = path.relative(root, worktreePath);
222
307
  if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) {
223
- throw new Error("只能删除 worktree 根目录下由 baton 管理的树。");
308
+ throw new Error("Can only remove baton-managed trees under the worktree root.");
224
309
  }
225
310
  const meta = readMeta(worktreePath);
226
311
  if (!meta)
227
- throw new Error(`不是 baton 管理的 worktree:${worktreePath}`);
312
+ throw new Error(`Not a baton-managed worktree: ${worktreePath}`);
228
313
  return { repo, root, worktreePath, meta };
229
314
  }
230
315
  function isDirty(worktreePath) {
@@ -241,19 +326,19 @@ function hasUnmergedCommits(repo, branch, base) {
241
326
  export function removeWorktree(cwd, nameOrPath) {
242
327
  const { repo, worktreePath, meta } = resolveManagedPath(cwd, nameOrPath);
243
328
  if (isDirty(worktreePath)) {
244
- throw new Error(`worktree 有未提交改动,拒绝删除:${worktreePath}`);
329
+ throw new Error(`worktree has uncommitted changes; refusing to remove: ${worktreePath}`);
245
330
  }
246
331
  if (hasUnmergedCommits(repo, meta.branch, meta.base)) {
247
- throw new Error(`分支 ${meta.branch} 相对 ${meta.base} 仍有未合并提交,拒绝删除。`);
332
+ throw new Error(`Branch ${meta.branch} has commits not merged into ${meta.base}; refusing to remove.`);
248
333
  }
249
334
  // ponytail: --force after our tracked-dirty + unmerged checks; untracked copy/meta are expected
250
335
  const removed = git(repo, ["worktree", "remove", "--force", worktreePath]);
251
336
  if (removed.status !== 0) {
252
- throw new Error(`git worktree remove 失败:${(removed.stderr || removed.stdout).trim()}`);
337
+ throw new Error(`git worktree remove failed: ${(removed.stderr || removed.stdout).trim()}`);
253
338
  }
254
339
  const deleted = git(repo, ["branch", "-d", meta.branch]);
255
340
  if (deleted.status !== 0) {
256
- throw new Error(`删除分支失败:${(deleted.stderr || deleted.stdout).trim()}`);
341
+ throw new Error(`Failed to delete branch: ${(deleted.stderr || deleted.stdout).trim()}`);
257
342
  }
258
343
  git(repo, ["worktree", "prune"]);
259
344
  return { status: "ok", path: worktreePath, branch: meta.branch, name: meta.name };
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.4.0",
4
- "description": "把一块有边界的工作下放到另一家本地 Agent CLI,需要决定时用同一会话继续。",
3
+ "version": "0.5.0",
4
+ "description": "Hand a bounded coding task to another local agent CLI, then continue the same session when it needs a decision.",
5
+ "license": "MIT",
5
6
  "type": "module",
6
7
  "repository": {
7
8
  "type": "git",
@@ -21,6 +22,7 @@
21
22
  "typecheck": "tsc --noEmit"
22
23
  },
23
24
  "dependencies": {
25
+ "@clack/prompts": "^1.9.0",
24
26
  "@modelcontextprotocol/sdk": "^1.20.2"
25
27
  },
26
28
  "engines": {
@@ -30,7 +32,7 @@
30
32
  "access": "public"
31
33
  },
32
34
  "devDependencies": {
33
- "@types/node": "^24.19.2",
35
+ "@types/node": "^26.6.6",
34
36
  "typescript": "^7.0.2"
35
37
  }
36
38
  }