@speculoai/baton 0.5.1 → 0.6.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
@@ -62,7 +62,7 @@ The host starts the job, checks on it in short steps, passes Codex's "A or B?" t
62
62
  npx @speculoai/baton install
63
63
  ```
64
64
 
65
- It finds the agent CLIs on your machine, asks which ones should get the plugin, and installs the global `baton` command. Requires Node ≥ 20.17 and at least one supported agent CLI that is already logged in.
65
+ It finds the agent CLIs on your machine, asks which ones should get the plugin, and installs the global `baton` command. It then offers to set up [rulesync](https://github.com/dyoshikawa/rulesync) for the current project (optional; rerun any time with `baton rules init`). Requires Node ≥ 20.17 and at least one supported agent CLI that is already logged in.
66
66
 
67
67
  Check which workers Baton can see:
68
68
 
@@ -113,6 +113,7 @@ If no target is named, the task goes to `codex`, or to `claude` when you are alr
113
113
  | `baton reply` | Continues the same conversation when the worker asks a question or you want a follow-up. |
114
114
  | `baton cancel` / `ls` / `prune` | Stops a job, lists jobs, or deletes old ones. |
115
115
  | `baton worktree add/ls/rm` | Gives a job its own git worktree so it doesn't touch your checkout. |
116
+ | `baton rules init` | Installs and initializes rulesync for the current project, previewing changes before writing. |
116
117
  | `baton mcp` | Runs the same operations as an MCP server for hosts that can't run shell commands. |
117
118
 
118
119
  Every command prints exactly one JSON object, so the host agent can read it reliably. See the [full flag list and statuses](docs/reference.md#command-line).
package/README.zh-CN.md CHANGED
@@ -62,7 +62,7 @@
62
62
  npx @speculoai/baton install
63
63
  ```
64
64
 
65
- 它会找出本机装了哪些 Agent CLI,问你要给哪些装插件,并安装全局 `baton` 命令。需要 Node ≥ 20.17,以及至少一个已登录的受支持 Agent CLI。
65
+ 它会找出本机装了哪些 Agent CLI,问你要给哪些装插件,并安装全局 `baton` 命令。之后会推荐为当前项目配置 [rulesync](https://github.com/dyoshikawa/rulesync)(可选,以后可随时用 `baton rules init` 重跑)。需要 Node ≥ 20.17,以及至少一个已登录的受支持 Agent CLI。
66
66
 
67
67
  看看 Baton 能找到哪些执行者:
68
68
 
@@ -113,6 +113,7 @@ baton tail -f <task_id>
113
113
  | `baton reply` | 执行者提问、或者你想追加要求时,在同一个会话里接着说。 |
114
114
  | `baton cancel` / `ls` / `prune` | 停止任务、列出任务、清理旧任务。 |
115
115
  | `baton worktree add/ls/rm` | 给任务单独开一个 git worktree,不碰你的工作目录。 |
116
+ | `baton rules init` | 为当前项目安装并初始化 rulesync,写入前先预览改动。 |
116
117
  | `baton mcp` | 以 MCP 服务器的形式提供同样的操作,给不能跑 shell 的宿主用。 |
117
118
 
118
119
  每个命令都只输出一个 JSON 对象,主控 Agent 读起来不会出错。全部参数和状态见[完整手册](docs/reference.zh-CN.md#命令行)。
package/dist/cli.js CHANGED
@@ -4,7 +4,15 @@ import { parseArgs } from "node:util";
4
4
  import { agents, start, status, cancel, wait, reply, ls, prune } from "./tasks.js";
5
5
  import { addWorktree, listWorktrees, removeWorktree } from "./worktree.js";
6
6
  import { redact } from "./redact.js";
7
- import { runInstall } from "./install.js";
7
+ import { detectedHosts, runInstall } from "./install.js";
8
+ import { mappedAgents, rulesInit } from "./rulesync-setup.js";
9
+ function installChoice(value, flag) {
10
+ if (value === undefined)
11
+ return undefined;
12
+ if (value === "project" || value === "global" || value === "skip")
13
+ return value;
14
+ throw new Error(`${flag} must be project, global or skip.`);
15
+ }
8
16
  async function main() {
9
17
  const [command, ...args] = process.argv.slice(2);
10
18
  let result;
@@ -119,12 +127,52 @@ async function main() {
119
127
  throw new Error("Usage: baton worktree add|ls|rm");
120
128
  }
121
129
  }
130
+ else if (command === "rules") {
131
+ const [action, ...rest] = args;
132
+ if (action !== "init")
133
+ throw new Error("Usage: baton rules init");
134
+ const { values, positionals } = parseArgs({
135
+ args: rest, allowPositionals: true,
136
+ options: {
137
+ install: { type: "string" }, source: { type: "string" }, template: { type: "boolean" },
138
+ targets: { type: "string", multiple: true }, yes: { type: "boolean" }, "dry-run": { type: "boolean" },
139
+ },
140
+ });
141
+ if (positionals.length)
142
+ throw new Error("rules init takes no positional arguments.");
143
+ if (values.source && values.template)
144
+ throw new Error("--source and --template cannot be used together.");
145
+ const install = installChoice(values.install, "--install");
146
+ const known = mappedAgents();
147
+ const requested = (values.targets ?? []).flatMap((item) => item.split(",")).map((item) => item.trim()).filter(Boolean);
148
+ for (const id of requested)
149
+ if (!known.includes(id))
150
+ throw new Error(`Unknown agent: ${id} (expected ${known.join(", ")})`);
151
+ const agentIds = requested.length ? requested : detectedHosts().map((host) => host.id).filter((id) => known.includes(id));
152
+ const dryRun = Boolean(values["dry-run"]);
153
+ const ui = process.stdin.isTTY ? await import("./install-ui.js") : null;
154
+ ui?.beginAction("rules init");
155
+ const res = await rulesInit({
156
+ cwd: process.cwd(), agents: agentIds, install, dryRun, yes: values.yes,
157
+ source: values.template ? { kind: "template" } : values.source ? { kind: "import", target: values.source } : undefined,
158
+ prompt: ui && !dryRun ? ui.rulesPrompter() : undefined,
159
+ });
160
+ if (res.status === "failed" || res.status === "needs_input")
161
+ process.exitCode = 1;
162
+ if (ui) {
163
+ ui.showRulesResult(res);
164
+ ui.endAction(process.exitCode ? "Finished with errors" : "Done");
165
+ return;
166
+ }
167
+ result = res;
168
+ }
122
169
  else if (command === "install" || command === "update" || command === "uninstall") {
123
170
  const { values, positionals } = parseArgs({
124
171
  args, allowPositionals: true,
125
172
  options: {
126
173
  only: { type: "string", multiple: true }, force: { type: "boolean" },
127
174
  "dry-run": { type: "boolean" }, "skip-global": { type: "boolean" },
175
+ rulesync: { type: "string" },
128
176
  },
129
177
  });
130
178
  if (positionals.length)
@@ -133,6 +181,9 @@ async function main() {
133
181
  throw new Error(`${command} does not accept --force.`);
134
182
  if (command === "uninstall" && values["skip-global"])
135
183
  throw new Error("uninstall does not accept --skip-global.");
184
+ if (command !== "install" && values.rulesync !== undefined)
185
+ throw new Error(`${command} does not accept --rulesync.`);
186
+ const rulesyncChoice = installChoice(values.rulesync, "--rulesync");
136
187
  const action = command;
137
188
  const pretty = Boolean(process.stdin.isTTY);
138
189
  const interactive = action === "install" && !values.only?.length && pretty;
@@ -196,6 +247,20 @@ async function main() {
196
247
  });
197
248
  if (spinning)
198
249
  spin.stop(ran.exitCode ? "Finished with errors" : "Done");
250
+ let rulesync;
251
+ const installedAgents = ran.result.hosts.filter((host) => host.ok).map((host) => host.id);
252
+ if (action === "install" && !dryRun && !cancelled && installedAgents.length && (rulesyncChoice || interactive)) {
253
+ try {
254
+ rulesync = await rulesInit({
255
+ cwd: process.cwd(), agents: installedAgents, install: rulesyncChoice,
256
+ prompt: interactive && ui ? ui.rulesPrompter() : undefined,
257
+ });
258
+ }
259
+ catch (error) {
260
+ rulesync = { status: "failed", detail: redact(error.message) };
261
+ }
262
+ ui?.showRulesResult(rulesync);
263
+ }
199
264
  if (ui && !cancelled) {
200
265
  if (dryRun) {
201
266
  const lines = [];
@@ -215,7 +280,7 @@ async function main() {
215
280
  }
216
281
  ui.endAction(ui.summarizeResult(ran.result));
217
282
  }
218
- result = ran.result;
283
+ result = rulesync ? { ...ran.result, rulesync } : ran.result;
219
284
  if (ran.exitCode)
220
285
  process.exitCode = ran.exitCode;
221
286
  // TTY already showed the human summary; dumping JSON on top is noise. Scripts (non-TTY) still get JSON.
@@ -224,7 +289,7 @@ async function main() {
224
289
  return;
225
290
  }
226
291
  else
227
- throw new Error("Usage: baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | install | update | uninstall | mcp");
292
+ throw new Error("Usage: baton version | agents | start | status | cancel | wait | tail | reply | ls | prune | worktree | rules | install | update | uninstall | mcp");
228
293
  process.stdout.write(`${JSON.stringify(result)}\n`);
229
294
  }
230
295
  try {
@@ -57,6 +57,102 @@ export function logInfo(message) {
57
57
  export function createSpinner() {
58
58
  return p.spinner(opts);
59
59
  }
60
+ const INSTALL_LABELS = {
61
+ project: "Install into this project (npm i -D rulesync)",
62
+ global: "Install globally (npm i -g rulesync)",
63
+ skip: "Skip",
64
+ };
65
+ const GROUP_LABELS = {
66
+ overwrite: "Overwrite",
67
+ delete: "Delete",
68
+ setting: "Change settings",
69
+ create: "Create",
70
+ };
71
+ export function formatPreview(preview) {
72
+ const lines = [];
73
+ for (const group of ["overwrite", "delete", "setting", "create"]) {
74
+ const items = preview.items.filter((item) => item.group === group);
75
+ if (!items.length)
76
+ continue;
77
+ lines.push(`${GROUP_LABELS[group]}:`);
78
+ for (const item of items) {
79
+ const keys = item.keys?.length ? ` (${item.keys.join(", ")})` : "";
80
+ const unsaved = item.unsaved === "untracked" ? " — not in git" : item.unsaved === "modified" ? " — uncommitted changes" : "";
81
+ const warn = item.warn ? " ⚠ changes how this CLI runs hooks/approvals" : "";
82
+ lines.push(` ${item.path}${keys}${unsaved}${warn}`);
83
+ }
84
+ }
85
+ for (const warning of preview.warnings)
86
+ lines.push(`⚠ ${warning}`);
87
+ return lines;
88
+ }
89
+ export function rulesPrompter() {
90
+ const spin = p.spinner(opts);
91
+ return {
92
+ async install({ choices, projectUnavailable }) {
93
+ if (projectUnavailable)
94
+ p.log.info(`Project install unavailable: ${projectUnavailable}.`, opts);
95
+ const picked = await p.select({
96
+ message: "Recommended: rulesync keeps rules, MCP, skills and hooks in sync across your agents. Install it?",
97
+ options: choices.map((value) => ({ value, label: INSTALL_LABELS[value] })),
98
+ initialValue: choices[0],
99
+ ...opts,
100
+ });
101
+ if (p.isCancel(picked))
102
+ return null;
103
+ return picked;
104
+ },
105
+ async source(sources) {
106
+ const picked = await p.select({
107
+ message: "Existing rule files found. How should rulesync start?",
108
+ options: [
109
+ ...sources.map((source) => ({ value: source.target, label: `Import from ${source.label}`, hint: source.target })),
110
+ { value: "", label: "Start from an empty template", hint: "existing files stay as they are" },
111
+ ],
112
+ ...opts,
113
+ });
114
+ if (p.isCancel(picked))
115
+ return null;
116
+ return (picked ? { kind: "import", target: picked } : { kind: "template" });
117
+ },
118
+ async confirm(preview) {
119
+ p.note(formatPreview(preview).join("\n"), "rulesync generate will", opts);
120
+ const ok = await p.confirm({ message: "Apply these changes?", initialValue: false, ...opts });
121
+ return ok === true;
122
+ },
123
+ step(message) {
124
+ spin.start(message);
125
+ },
126
+ stepDone(message, ok) {
127
+ if (ok)
128
+ spin.stop(message);
129
+ else
130
+ spin.error(message);
131
+ },
132
+ };
133
+ }
134
+ export function showRulesResult(result) {
135
+ for (const note of result.notes ?? [])
136
+ p.log.info(note, opts);
137
+ const detail = result.detail ? `: ${result.detail}` : "";
138
+ switch (result.status) {
139
+ case "generated":
140
+ p.log.success(`rulesync set up${detail}`, opts);
141
+ break;
142
+ case "already_initialized":
143
+ p.log.info("rulesync is already initialized in this project (.rulesync/ exists).", opts);
144
+ break;
145
+ case "no_changes":
146
+ p.log.info("rulesync is set up; generated files are already up to date.", opts);
147
+ break;
148
+ case "failed":
149
+ p.log.error(`rulesync${detail}`, opts);
150
+ break;
151
+ default:
152
+ if (result.detail)
153
+ p.log.info(result.detail, opts);
154
+ }
155
+ }
60
156
  export function summarizeResult(input) {
61
157
  if (input.dry_run) {
62
158
  const n = input.hosts.length + (input.global ? 1 : 0);
@@ -0,0 +1,307 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { adapters } from "./adapters/index.js";
5
+ import { which } from "./adapters/common.js";
6
+ import { redact } from "./redact.js";
7
+ import { hasRulesyncSource, resolveRulesync, rulesGitRoot, stripJsonc } from "./rules.js";
8
+ /** Without permissions: rulesync rewrites Codex approval settings whenever that feature is on, even with an empty source. */
9
+ export const SETUP_FEATURES = ["rules", "mcp", "subagents", "skills", "hooks"];
10
+ const SCHEMA = "https://github.com/dyoshikawa/rulesync/releases/latest/download/config-schema.json";
11
+ /** Baton agent id → rulesync target id. Agents without a rulesync target are not mapped. */
12
+ export function rulesyncTargets(agentIds) {
13
+ const out = [];
14
+ for (const id of agentIds) {
15
+ const target = Object.hasOwn(adapters, id) ? adapters[id].rules?.rulesyncTarget : undefined;
16
+ if (target && !out.includes(target))
17
+ out.push(target);
18
+ }
19
+ return out;
20
+ }
21
+ export function mappedAgents() {
22
+ return Object.keys(adapters).filter((id) => adapters[id].rules?.rulesyncTarget);
23
+ }
24
+ const SOURCES = [
25
+ { target: "claudecode", label: "CLAUDE.md", files: ["CLAUDE.md", ".claude/CLAUDE.md"] },
26
+ { target: "codexcli", label: "AGENTS.md", files: ["AGENTS.md"] },
27
+ { target: "cursor", label: ".cursor/rules", files: [".cursor/rules", ".cursorrules"] },
28
+ ];
29
+ function nonEmpty(full) {
30
+ try {
31
+ const st = fs.statSync(full);
32
+ return st.isDirectory() ? fs.readdirSync(full).length > 0 : st.isFile();
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ /** Rule files at the repo root that `rulesync import` can read, one entry per importable tool. */
39
+ export function detectSources(root) {
40
+ return SOURCES
41
+ .filter((source) => source.files.some((file) => nonEmpty(path.join(root, file))))
42
+ .map(({ target, label }) => ({ target, label }));
43
+ }
44
+ function defaultRun(env) {
45
+ return (command, args, cwd) => new Promise((resolve) => {
46
+ let stdout = "";
47
+ let stderr = "";
48
+ let settled = false;
49
+ const finish = (result) => { if (!settled) {
50
+ settled = true;
51
+ resolve(result);
52
+ } };
53
+ let child;
54
+ try {
55
+ child = spawn(command, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
56
+ }
57
+ catch (error) {
58
+ finish({ status: 1, stdout, stderr: error.message });
59
+ return;
60
+ }
61
+ child.stdout?.on("data", (chunk) => { stdout += chunk; });
62
+ child.stderr?.on("data", (chunk) => { stderr += chunk; });
63
+ child.on("error", (error) => finish({ status: 1, stdout, stderr: error.message }));
64
+ child.on("close", (status) => finish({ status, stdout, stderr }));
65
+ });
66
+ }
67
+ function failText(ran) {
68
+ return redact(`${ran.stderr || ran.stdout || ""}`.trim().slice(-300)) || `exit code ${ran.status}`;
69
+ }
70
+ function parseJsonOutput(text) {
71
+ const start = text.indexOf("{");
72
+ if (start < 0)
73
+ return null;
74
+ try {
75
+ return JSON.parse(text.slice(start));
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ function gitUnsaved(root) {
82
+ const map = new Map();
83
+ const ran = spawnSync("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--ignored"], { cwd: root, encoding: "utf8", timeout: 5000 });
84
+ if (ran.status !== 0)
85
+ return map;
86
+ for (const entry of ran.stdout.split("\0")) {
87
+ if (entry.length < 4)
88
+ continue;
89
+ const code = entry.slice(0, 2);
90
+ const file = entry.slice(3);
91
+ map.set(file, code === "??" || code === "!!" ? "untracked" : "modified");
92
+ }
93
+ return map;
94
+ }
95
+ /** Turn `rulesync generate --dry-run --json` operations into a grouped, user-facing preview. */
96
+ export function classifyPlan(root, operations, unsaved = gitUnsaved(root)) {
97
+ const keyed = new Map();
98
+ for (const op of operations) {
99
+ if (op.kind !== "key" || op.action !== "write" || typeof op.path !== "string")
100
+ continue;
101
+ const entry = keyed.get(op.path) ?? { feature: String(op.feature ?? ""), keys: [] };
102
+ if (typeof op.key === "string" && !entry.keys.includes(op.key))
103
+ entry.keys.push(op.key);
104
+ keyed.set(op.path, entry);
105
+ }
106
+ const items = [];
107
+ const seen = new Set();
108
+ for (const op of operations) {
109
+ if (typeof op.path !== "string")
110
+ continue;
111
+ const rel = op.path;
112
+ const feature = String(op.feature ?? "");
113
+ const exists = fs.existsSync(path.join(root, rel));
114
+ const mark = exists && unsaved.has(rel) ? { unsaved: unsaved.get(rel) } : {};
115
+ if (op.action === "delete") {
116
+ items.push({ group: "delete", path: rel, feature, ...mark });
117
+ continue;
118
+ }
119
+ if (op.action !== "write" || seen.has(rel))
120
+ continue;
121
+ const keys = keyed.get(rel);
122
+ if (keys && exists) {
123
+ seen.add(rel);
124
+ const features = operations.filter((o) => o.path === rel).map((o) => String(o.feature ?? ""));
125
+ items.push({
126
+ group: "setting", path: rel, feature: keys.feature, keys: keys.keys, ...mark,
127
+ ...(features.some((f) => f === "hooks" || f === "permissions") ? { warn: true } : {}),
128
+ });
129
+ continue;
130
+ }
131
+ if (op.kind !== "file")
132
+ continue;
133
+ seen.add(rel);
134
+ items.push({ group: exists ? "overwrite" : "create", path: rel, feature, ...(exists ? mark : {}) });
135
+ }
136
+ const order = { overwrite: 0, delete: 1, setting: 2, create: 3 };
137
+ return items.sort((a, b) => order[a.group] - order[b.group] || a.path.localeCompare(b.path));
138
+ }
139
+ const TEMPLATE_RULE = `---
140
+ root: true
141
+ targets: ["*"]
142
+ description: "Project rules"
143
+ globs: ["**/*"]
144
+ ---
145
+
146
+ # Project rules
147
+ `;
148
+ /** `rulesync init` ships samples (Codex danger-full-access, demo MCP servers, a hook to a missing script). */
149
+ function cleanTemplate(root) {
150
+ const dir = path.join(root, ".rulesync");
151
+ for (const rel of ["mcp.jsonc", "hooks.jsonc", "permissions.jsonc", "subagents/planner.md", "skills/project-context"]) {
152
+ fs.rmSync(path.join(dir, rel), { recursive: true, force: true });
153
+ }
154
+ const rules = path.join(dir, "rules");
155
+ fs.mkdirSync(rules, { recursive: true });
156
+ fs.rmSync(path.join(rules, "overview.md"), { force: true });
157
+ fs.writeFileSync(path.join(rules, "project.md"), TEMPLATE_RULE);
158
+ }
159
+ /** An imported tool with no MCP servers or hooks still yields empty sources, which would blank those files for every target. */
160
+ function pruneEmptySources(root) {
161
+ for (const [file, field] of [["mcp.jsonc", "mcpServers"], ["hooks.jsonc", "hooks"]]) {
162
+ const full = path.join(root, ".rulesync", file);
163
+ try {
164
+ const value = JSON.parse(stripJsonc(fs.readFileSync(full, "utf8")))[field];
165
+ if (!value || (typeof value === "object" && !Object.keys(value).length))
166
+ fs.rmSync(full);
167
+ }
168
+ catch {
169
+ // missing or unreadable: leave it for rulesync to report
170
+ }
171
+ }
172
+ }
173
+ function writeConfig(root, targets) {
174
+ const config = { $schema: SCHEMA, targets, features: [...SETUP_FEATURES], delete: false };
175
+ fs.writeFileSync(path.join(root, "rulesync.jsonc"), `${JSON.stringify(config, null, 2)}\n`);
176
+ }
177
+ export async function rulesInit(input) {
178
+ const env = input.env ?? process.env;
179
+ const run = input.run ?? defaultRun(env);
180
+ const prompt = input.prompt;
181
+ const root = rulesGitRoot(input.cwd);
182
+ const locate = () => (root ? resolveRulesync(root, undefined, env) : which(["rulesync"], env));
183
+ const base = root ? { root } : {};
184
+ let bin = locate();
185
+ let install;
186
+ if (!bin) {
187
+ const projectUnavailable = !root
188
+ ? "not inside a git repository"
189
+ : !fs.existsSync(path.join(root, "package.json")) ? "no package.json at the repository root" : undefined;
190
+ const choices = projectUnavailable ? ["global", "skip"] : ["project", "global", "skip"];
191
+ const choice = input.install ?? (prompt ? await prompt.install({ choices, ...(projectUnavailable ? { projectUnavailable } : {}) }) : null);
192
+ if (!choice) {
193
+ return prompt
194
+ ? { ...base, status: "cancelled" }
195
+ : { ...base, status: "needs_input", detail: "rulesync is not installed; pass --install project|global|skip" };
196
+ }
197
+ if (choice === "skip")
198
+ return { ...base, status: "skipped", detail: "Run `baton rules init` later to set up rulesync." };
199
+ if (choice === "project" && projectUnavailable) {
200
+ return { ...base, status: "failed", detail: `Cannot install rulesync into the project: ${projectUnavailable}` };
201
+ }
202
+ const npm = process.platform === "win32" ? "npm.cmd" : "npm";
203
+ const command = choice === "project" ? [npm, "install", "-D", "rulesync"] : [npm, "install", "-g", "rulesync"];
204
+ if (input.dryRun)
205
+ return { ...base, status: "planned", install: { choice, ok: false, command } };
206
+ prompt?.step?.(`Installing rulesync (${command.slice(1).join(" ")})…`);
207
+ const ran = await run(command[0], command.slice(1), root ?? input.cwd);
208
+ if (ran.status !== 0) {
209
+ prompt?.stepDone?.("rulesync install failed", false);
210
+ return { ...base, status: "failed", install: { choice, ok: false, command }, detail: failText(ran) };
211
+ }
212
+ bin = locate();
213
+ if (!bin) {
214
+ prompt?.stepDone?.("rulesync installed but not found", false);
215
+ return {
216
+ ...base, status: "failed", install: { choice, ok: false, command },
217
+ detail: choice === "global"
218
+ ? "npm finished but rulesync is not on PATH; add the npm global bin directory (`npm prefix -g`) to PATH"
219
+ : "npm finished but node_modules/.bin/rulesync is missing",
220
+ };
221
+ }
222
+ prompt?.stepDone?.(`rulesync installed (${choice})`, true);
223
+ install = { choice, ok: true, command };
224
+ }
225
+ const withInstall = install ? { ...base, install } : base;
226
+ if (!root) {
227
+ return { ...withInstall, status: install ? "installed" : "skipped", detail: "Not inside a git repository; run `baton rules init` inside a project to set it up." };
228
+ }
229
+ if (hasRulesyncSource(root))
230
+ return { ...withInstall, status: "already_initialized" };
231
+ const targets = rulesyncTargets(input.agents);
232
+ if (!targets.length) {
233
+ return { ...withInstall, status: "needs_input", detail: `No agent maps to a rulesync target; choose from: ${mappedAgents().join(", ")}` };
234
+ }
235
+ const sources = detectSources(root);
236
+ let source = input.source ?? null;
237
+ if (!source) {
238
+ if (!sources.length)
239
+ source = { kind: "template" };
240
+ else if (prompt)
241
+ source = await prompt.source(sources);
242
+ else {
243
+ return {
244
+ ...withInstall, status: "needs_input", targets,
245
+ detail: `Existing rule files found (${sources.map((s) => s.label).join(", ")}); pass --source <${sources.map((s) => s.target).join("|")}> or --template`,
246
+ };
247
+ }
248
+ if (!source)
249
+ return { ...withInstall, status: "cancelled", targets };
250
+ }
251
+ const sourceLabel = source.kind === "template" ? "template" : source.target;
252
+ if (input.dryRun)
253
+ return { ...withInstall, status: "planned", source: sourceLabel, targets };
254
+ const hadConfig = fs.existsSync(path.join(root, "rulesync.jsonc"));
255
+ const notes = [];
256
+ prompt?.step?.(source.kind === "template" ? "Creating .rulesync/ from template…" : `Importing from ${source.target}…`);
257
+ const created = source.kind === "template"
258
+ ? await run(bin, ["init", "--silent"], root)
259
+ : await run(bin, ["import", "--targets", source.target, "--features", SETUP_FEATURES.join(","), "--silent"], root);
260
+ if (created.status !== 0 || !hasRulesyncSource(root)) {
261
+ prompt?.stepDone?.("rulesync setup failed", false);
262
+ return { ...withInstall, status: "failed", source: sourceLabel, targets, detail: failText(created) };
263
+ }
264
+ if (source.kind === "template")
265
+ cleanTemplate(root);
266
+ else
267
+ pruneEmptySources(root);
268
+ const local = path.join(root, ".rulesync", "rules", "CLAUDE.local.md");
269
+ if (fs.existsSync(local)) {
270
+ fs.rmSync(local);
271
+ notes.push("CLAUDE.local.md is personal; it was not imported into .rulesync/.");
272
+ }
273
+ if (!hadConfig)
274
+ writeConfig(root, targets);
275
+ else
276
+ notes.push("Kept the existing rulesync.jsonc; its targets and features were not changed.");
277
+ prompt?.stepDone?.(source.kind === "template" ? "Created .rulesync/" : `Imported from ${source.target}`, true);
278
+ const dry = await run(bin, ["generate", "--dry-run", "--json"], root);
279
+ const parsed = parseJsonOutput(dry.stdout);
280
+ const data = parsed?.data;
281
+ if (dry.status !== 0 || !parsed || parsed.success === false || !data?.plan) {
282
+ const error = parsed?.error?.message;
283
+ return { ...withInstall, status: "failed", source: sourceLabel, targets, notes, detail: error ? redact(error).slice(0, 300) : failText(dry) };
284
+ }
285
+ const preview = {
286
+ items: classifyPlan(root, data.plan.operations ?? []),
287
+ warnings: Array.isArray(parsed.warnings) ? parsed.warnings.filter((w) => typeof w === "string") : [],
288
+ };
289
+ const common = { ...withInstall, source: sourceLabel, targets, preview, ...(notes.length ? { notes } : {}) };
290
+ if (!preview.items.length)
291
+ return { ...common, status: "no_changes" };
292
+ const confirmed = input.yes || (prompt ? await prompt.confirm(preview) : false);
293
+ if (!confirmed) {
294
+ return {
295
+ ...common, status: prompt ? "cancelled" : "previewed",
296
+ detail: "Kept .rulesync/ and rulesync.jsonc; review them, then run `npx rulesync generate`.",
297
+ };
298
+ }
299
+ prompt?.step?.("Generating agent files…");
300
+ const gen = await run(bin, ["generate", "--silent"], root);
301
+ if (gen.status !== 0) {
302
+ prompt?.stepDone?.("rulesync generate failed", false);
303
+ return { ...common, status: "failed", detail: failText(gen) };
304
+ }
305
+ prompt?.stepDone?.("Generated agent files", true);
306
+ return { ...common, status: "generated", detail: "Review the changes, then commit .rulesync/, rulesync.jsonc and the generated files." };
307
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@speculoai/baton",
3
- "version": "0.5.1",
3
+ "version": "0.6.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",