@speculoai/baton 0.0.0-stage → 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.
@@ -0,0 +1,345 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { randomBytes } from "node:crypto";
4
+ import { spawnSync } from "node:child_process";
5
+ import { hasRulesyncSource, resolveRulesync, RULE_ENTRIES } from "./rules.js";
6
+ import { redact } from "./redact.js";
7
+ const META_NAME = ".baton-worktree.json";
8
+ function git(cwd, args) {
9
+ const ran = spawnSync("git", args, { cwd, encoding: "utf8" });
10
+ return { status: ran.status ?? 1, stdout: ran.stdout || "", stderr: ran.stderr || "" };
11
+ }
12
+ function strings(value) {
13
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
14
+ }
15
+ export function loadWorktreeConfig(repo) {
16
+ const file = path.join(repo, ".baton.json");
17
+ if (!fs.existsSync(file))
18
+ return { copy: [], symlink: [], post_create: [] };
19
+ let raw;
20
+ try {
21
+ raw = JSON.parse(fs.readFileSync(file, "utf8"));
22
+ }
23
+ catch (error) {
24
+ throw new Error(`.baton.json is invalid: ${error.message}`);
25
+ }
26
+ const section = raw && typeof raw === "object" && "worktree" in raw
27
+ ? raw.worktree
28
+ : undefined;
29
+ if (!section || typeof section !== "object")
30
+ return { copy: [], symlink: [], post_create: [] };
31
+ return {
32
+ dir: typeof section.dir === "string" ? section.dir : undefined,
33
+ base: typeof section.base === "string" ? section.base : undefined,
34
+ copy: strings(section.copy),
35
+ symlink: strings(section.symlink),
36
+ post_create: strings(section.post_create),
37
+ rulesync: typeof section.rulesync === "boolean" ? section.rulesync : undefined,
38
+ };
39
+ }
40
+ export function resolveWorktreeRoot(repo, cfg) {
41
+ if (cfg.dir)
42
+ return path.resolve(repo, cfg.dir);
43
+ const hidden = path.join(repo, ".worktrees");
44
+ const plain = path.join(repo, "worktrees");
45
+ if (fs.existsSync(hidden))
46
+ return hidden;
47
+ if (fs.existsSync(plain))
48
+ return plain;
49
+ return hidden;
50
+ }
51
+ export function ensureIgnored(repo, worktreeRoot) {
52
+ const rel = path.relative(repo, worktreeRoot) || ".";
53
+ if (rel.startsWith("..") || path.isAbsolute(rel)) {
54
+ throw new Error("worktree root must be inside the repository.");
55
+ }
56
+ const check = git(repo, ["check-ignore", "-q", rel]);
57
+ if (check.status === 0)
58
+ return false;
59
+ const ignorePath = path.join(repo, ".gitignore");
60
+ const entry = rel.endsWith("/") ? rel : `${rel}/`;
61
+ const existing = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, "utf8") : "";
62
+ const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
63
+ fs.writeFileSync(ignorePath, `${existing}${prefix}${entry}\n`);
64
+ return true;
65
+ }
66
+ export function assertNotNestedWorktree(cwd) {
67
+ const dir = git(cwd, ["rev-parse", "--git-dir"]);
68
+ const common = git(cwd, ["rev-parse", "--git-common-dir"]);
69
+ if (dir.status !== 0 || common.status !== 0)
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()));
74
+ if (gitDir === gitCommon)
75
+ return;
76
+ const superproject = git(cwd, ["rev-parse", "--show-superproject-working-tree"]);
77
+ if (superproject.status === 0 && superproject.stdout.trim())
78
+ return;
79
+ throw new Error("Already in a linked worktree; return to the main repository before add (nesting is not allowed).");
80
+ }
81
+ export function resolveRepoRoot(cwd) {
82
+ const ran = git(cwd, ["rev-parse", "--show-toplevel"]);
83
+ if (ran.status !== 0)
84
+ throw new Error("Current directory is not a git repository.");
85
+ return ran.stdout.trim();
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
+ }
115
+ function defaultBase(repo, configured) {
116
+ if (configured)
117
+ return configured;
118
+ for (const candidate of ["main", "master"]) {
119
+ const check = git(repo, ["rev-parse", "--verify", candidate]);
120
+ if (check.status === 0)
121
+ return candidate;
122
+ }
123
+ const head = git(repo, ["rev-parse", "--abbrev-ref", "HEAD"]);
124
+ if (head.status === 0 && head.stdout.trim() && head.stdout.trim() !== "HEAD")
125
+ return head.stdout.trim();
126
+ throw new Error("Cannot detect the base branch; set it in .baton.json or with --base.");
127
+ }
128
+ function writeMeta(worktreePath, meta) {
129
+ fs.writeFileSync(path.join(worktreePath, META_NAME), `${JSON.stringify(meta, null, 2)}\n`);
130
+ }
131
+ function readMeta(worktreePath) {
132
+ const file = path.join(worktreePath, META_NAME);
133
+ if (!fs.existsSync(file))
134
+ return null;
135
+ try {
136
+ return JSON.parse(fs.readFileSync(file, "utf8"));
137
+ }
138
+ catch {
139
+ return null;
140
+ }
141
+ }
142
+ export function addWorktree(cwd, options = {}) {
143
+ assertNotNestedWorktree(cwd);
144
+ const repo = resolveRepoRoot(cwd);
145
+ const cfg = loadWorktreeConfig(repo);
146
+ const root = resolveWorktreeRoot(repo, cfg);
147
+ const gitignore_updated = ensureIgnored(repo, root);
148
+ fs.mkdirSync(root, { recursive: true });
149
+ const name = options.name || randomBytes(4).toString("hex");
150
+ if (!/^[A-Za-z0-9._-]+$/.test(name))
151
+ throw new Error("worktree name contains invalid characters.");
152
+ const worktreePath = path.join(root, name);
153
+ if (fs.existsSync(worktreePath))
154
+ throw new Error(`worktree already exists: ${worktreePath}`);
155
+ const branch = options.branch || `baton/${name}`;
156
+ const base = defaultBase(repo, options.base ?? cfg.base);
157
+ const created = git(repo, ["worktree", "add", "-b", branch, worktreePath, base]);
158
+ if (created.status !== 0) {
159
+ throw new Error(`git worktree add failed: ${(created.stderr || created.stdout).trim()}`);
160
+ }
161
+ const meta = { name, branch, base, created_at: new Date().toISOString() };
162
+ writeMeta(worktreePath, meta);
163
+ try {
164
+ prepareWorktree(repo, worktreePath, cfg);
165
+ }
166
+ catch (error) {
167
+ cleanupWorktree(repo, worktreePath, branch);
168
+ throw error;
169
+ }
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
+ };
224
+ }
225
+ export function listWorktrees(cwd) {
226
+ const repo = resolveRepoRoot(cwd);
227
+ const cfg = loadWorktreeConfig(repo);
228
+ const root = resolveWorktreeRoot(repo, cfg);
229
+ if (!fs.existsSync(root))
230
+ return [];
231
+ const items = [];
232
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
233
+ if (!entry.isDirectory())
234
+ continue;
235
+ const worktreePath = path.join(root, entry.name);
236
+ const meta = readMeta(worktreePath);
237
+ if (!meta)
238
+ continue;
239
+ items.push({ name: meta.name, path: worktreePath, branch: meta.branch, base: meta.base });
240
+ }
241
+ return items.sort((a, b) => a.name.localeCompare(b.name));
242
+ }
243
+ /** Minimal gitignore-style match for basename patterns (`*` / `?`). */
244
+ export function matchBasename(name, pattern) {
245
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
246
+ return new RegExp(`^${escaped}$`).test(name);
247
+ }
248
+ function prepareWorktree(repo, worktreePath, cfg) {
249
+ const names = fs.readdirSync(repo);
250
+ for (const pattern of cfg.copy) {
251
+ for (const name of names) {
252
+ if (!matchBasename(name, pattern))
253
+ continue;
254
+ const src = path.join(repo, name);
255
+ const dest = path.join(worktreePath, name);
256
+ const stat = fs.lstatSync(src);
257
+ if (stat.isDirectory())
258
+ fs.cpSync(src, dest, { recursive: true });
259
+ else
260
+ fs.copyFileSync(src, dest);
261
+ }
262
+ }
263
+ for (const pattern of cfg.symlink) {
264
+ for (const name of names) {
265
+ if (!matchBasename(name, pattern))
266
+ continue;
267
+ const src = path.join(repo, name);
268
+ const dest = path.join(worktreePath, name);
269
+ if (!fs.existsSync(src))
270
+ continue;
271
+ if (fs.existsSync(dest))
272
+ fs.rmSync(dest, { recursive: true, force: true });
273
+ fs.symlinkSync(src, dest);
274
+ }
275
+ }
276
+ for (const command of cfg.post_create) {
277
+ const ran = spawnSync(command, {
278
+ cwd: worktreePath,
279
+ shell: true,
280
+ encoding: "utf8",
281
+ env: { ...process.env, BATON_MAIN_REPO: repo, BATON_WORKTREE: worktreePath },
282
+ timeout: 600_000,
283
+ });
284
+ if (ran.status !== 0) {
285
+ const detail = (ran.stderr || ran.stdout || "").trim() || `exit ${ran.status}`;
286
+ throw new Error(`post_create failed (${command}): ${detail}`);
287
+ }
288
+ }
289
+ }
290
+ function cleanupWorktree(repo, worktreePath, branch) {
291
+ git(repo, ["worktree", "remove", "--force", worktreePath]);
292
+ git(repo, ["branch", "-D", branch]);
293
+ git(repo, ["worktree", "prune"]);
294
+ }
295
+ function resolveManagedPath(cwd, nameOrPath) {
296
+ const repo = resolveRepoRoot(cwd);
297
+ const cfg = loadWorktreeConfig(repo);
298
+ const root = resolveWorktreeRoot(repo, cfg);
299
+ const candidate = path.isAbsolute(nameOrPath) ? path.resolve(nameOrPath) : path.resolve(cwd, nameOrPath);
300
+ const byName = path.join(root, nameOrPath);
301
+ const worktreePath = fs.existsSync(path.join(candidate, META_NAME))
302
+ ? candidate
303
+ : fs.existsSync(path.join(byName, META_NAME))
304
+ ? byName
305
+ : candidate;
306
+ const rel = path.relative(root, worktreePath);
307
+ if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) {
308
+ throw new Error("Can only remove baton-managed trees under the worktree root.");
309
+ }
310
+ const meta = readMeta(worktreePath);
311
+ if (!meta)
312
+ throw new Error(`Not a baton-managed worktree: ${worktreePath}`);
313
+ return { repo, root, worktreePath, meta };
314
+ }
315
+ function isDirty(worktreePath) {
316
+ // Ignore untracked (copy/.baton-worktree.json); only block on tracked edits.
317
+ const status = git(worktreePath, ["status", "--porcelain", "--untracked-files=no"]);
318
+ return status.status === 0 && status.stdout.trim().length > 0;
319
+ }
320
+ function hasUnmergedCommits(repo, branch, base) {
321
+ const ran = git(repo, ["rev-list", "--count", `${base}..${branch}`]);
322
+ if (ran.status !== 0)
323
+ return true;
324
+ return Number(ran.stdout.trim()) > 0;
325
+ }
326
+ export function removeWorktree(cwd, nameOrPath) {
327
+ const { repo, worktreePath, meta } = resolveManagedPath(cwd, nameOrPath);
328
+ if (isDirty(worktreePath)) {
329
+ throw new Error(`worktree has uncommitted changes; refusing to remove: ${worktreePath}`);
330
+ }
331
+ if (hasUnmergedCommits(repo, meta.branch, meta.base)) {
332
+ throw new Error(`Branch ${meta.branch} has commits not merged into ${meta.base}; refusing to remove.`);
333
+ }
334
+ // ponytail: --force after our tracked-dirty + unmerged checks; untracked copy/meta are expected
335
+ const removed = git(repo, ["worktree", "remove", "--force", worktreePath]);
336
+ if (removed.status !== 0) {
337
+ throw new Error(`git worktree remove failed: ${(removed.stderr || removed.stdout).trim()}`);
338
+ }
339
+ const deleted = git(repo, ["branch", "-d", meta.branch]);
340
+ if (deleted.status !== 0) {
341
+ throw new Error(`Failed to delete branch: ${(deleted.stderr || deleted.stdout).trim()}`);
342
+ }
343
+ git(repo, ["worktree", "prune"]);
344
+ return { status: "ok", path: worktreePath, branch: meta.branch, name: meta.name };
345
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
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",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/SpeculoAI/baton.git"
10
+ },
11
+ "bin": {
12
+ "baton": "dist/cli.js"
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "scripts": {
18
+ "start": "node src/cli.ts",
19
+ "build": "tsc -p tsconfig.build.json",
20
+ "prepack": "npm run build",
21
+ "test": "tsc --noEmit && node --test \"test/**/*.test.ts\"",
22
+ "typecheck": "tsc --noEmit"
23
+ },
24
+ "dependencies": {
25
+ "@clack/prompts": "^1.9.0",
26
+ "@modelcontextprotocol/sdk": "^1.20.2"
27
+ },
28
+ "engines": {
29
+ "node": ">=20.17"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "^26.6.6",
36
+ "typescript": "^7.0.2"
37
+ }
38
+ }