@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.
- package/LICENSE +21 -0
- package/README.md +171 -2
- package/README.zh-CN.md +172 -0
- package/dist/adapters/agy.js +67 -0
- package/dist/adapters/claude.js +86 -0
- package/dist/adapters/codex.js +114 -0
- package/dist/adapters/common.js +25 -0
- package/dist/adapters/cursor.js +104 -0
- package/dist/adapters/index.js +6 -0
- package/dist/cli.js +224 -0
- package/dist/contract.js +42 -0
- package/dist/git.js +220 -0
- package/dist/install-ui.js +74 -0
- package/dist/install.js +221 -0
- package/dist/mcp.js +95 -0
- package/dist/process.js +23 -0
- package/dist/redact.js +9 -0
- package/dist/rules.js +394 -0
- package/dist/scope.js +108 -0
- package/dist/store.js +105 -0
- package/dist/supervisor.js +320 -0
- package/dist/tail.js +64 -0
- package/dist/tasks.js +417 -0
- package/dist/types.js +1 -0
- package/dist/worktree.js +345 -0
- package/package.json +36 -4
package/dist/rules.js
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
4
|
+
import { which } from "./adapters/common.js";
|
|
5
|
+
import { redact } from "./redact.js";
|
|
6
|
+
const ALL_FEATURES = ["rules", "mcp", "subagents", "skills", "hooks", "permissions", "checks"];
|
|
7
|
+
const GATE_FEATURES = ["mcp", "hooks"];
|
|
8
|
+
/** Rule entries scanned at each directory level (union across adapters). */
|
|
9
|
+
export const RULE_ENTRIES = [
|
|
10
|
+
"CLAUDE.md",
|
|
11
|
+
".claude/CLAUDE.md",
|
|
12
|
+
"CLAUDE.local.md",
|
|
13
|
+
"AGENTS.md",
|
|
14
|
+
"AGENTS.override.md",
|
|
15
|
+
"GEMINI.md",
|
|
16
|
+
".agents/AGENTS.md",
|
|
17
|
+
".agents/GEMINI.md",
|
|
18
|
+
".agents/rules",
|
|
19
|
+
".agent/rules",
|
|
20
|
+
".cursor/rules",
|
|
21
|
+
".cursorrules",
|
|
22
|
+
];
|
|
23
|
+
const DIR_ENTRIES = new Set([".agents/rules", ".agent/rules", ".cursor/rules"]);
|
|
24
|
+
/** Nearest git toplevel, or null when cwd is not inside a repo. */
|
|
25
|
+
export function rulesGitRoot(cwd) {
|
|
26
|
+
const result = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", timeout: 5000 });
|
|
27
|
+
if (result.status !== 0)
|
|
28
|
+
return null;
|
|
29
|
+
const root = result.stdout.trim();
|
|
30
|
+
return root || null;
|
|
31
|
+
}
|
|
32
|
+
function existsEntry(dir, entry) {
|
|
33
|
+
const full = path.join(dir, entry);
|
|
34
|
+
try {
|
|
35
|
+
const st = fs.statSync(full);
|
|
36
|
+
if (DIR_ENTRIES.has(entry)) {
|
|
37
|
+
if (!st.isDirectory())
|
|
38
|
+
return false;
|
|
39
|
+
return fs.readdirSync(full).length > 0;
|
|
40
|
+
}
|
|
41
|
+
return st.isFile();
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
function toPosix(p) {
|
|
48
|
+
return p.split(path.sep).join("/");
|
|
49
|
+
}
|
|
50
|
+
function isDirEntry(rel) {
|
|
51
|
+
const n = toPosix(rel);
|
|
52
|
+
return [...DIR_ENTRIES].some((d) => n === d || n.endsWith(`/${d}`));
|
|
53
|
+
}
|
|
54
|
+
/** Discover rule files from cwd up to the git root (or cwd only when not a repo). Paths are cwd-relative, sorted. */
|
|
55
|
+
export function discoverRules(cwd) {
|
|
56
|
+
const start = path.resolve(cwd);
|
|
57
|
+
const root = rulesGitRoot(start) ?? start;
|
|
58
|
+
const found = new Set();
|
|
59
|
+
let cur = start;
|
|
60
|
+
for (;;) {
|
|
61
|
+
for (const entry of RULE_ENTRIES) {
|
|
62
|
+
if (!existsEntry(cur, entry))
|
|
63
|
+
continue;
|
|
64
|
+
found.add(toPosix(path.relative(start, path.join(cur, entry)) || entry));
|
|
65
|
+
}
|
|
66
|
+
if (path.resolve(cur) === path.resolve(root))
|
|
67
|
+
break;
|
|
68
|
+
const parent = path.dirname(cur);
|
|
69
|
+
if (parent === cur)
|
|
70
|
+
break;
|
|
71
|
+
cur = parent;
|
|
72
|
+
}
|
|
73
|
+
return [...found].sort();
|
|
74
|
+
}
|
|
75
|
+
function basenameMatch(foundRel, entry) {
|
|
76
|
+
const n = toPosix(foundRel);
|
|
77
|
+
return n === entry || n.endsWith(`/${entry}`);
|
|
78
|
+
}
|
|
79
|
+
function levelHasAny(found, foundRel, names) {
|
|
80
|
+
const dir = path.posix.dirname(toPosix(foundRel));
|
|
81
|
+
const prefix = dir === "." ? "" : `${dir}/`;
|
|
82
|
+
return names.some((name) => {
|
|
83
|
+
const candidate = `${prefix}${name}`;
|
|
84
|
+
return found.some((f) => toPosix(f) === candidate);
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
function readsNatively(foundRel, found, support) {
|
|
88
|
+
const n = toPosix(foundRel);
|
|
89
|
+
for (const entry of support.files) {
|
|
90
|
+
if (basenameMatch(n, entry))
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
for (const cond of support.conditional ?? []) {
|
|
94
|
+
if (!basenameMatch(n, cond.file))
|
|
95
|
+
continue;
|
|
96
|
+
if (!levelHasAny(found, n, cond.unless))
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
/** Rule files the target will not load natively; paths are cwd-relative, sorted. */
|
|
102
|
+
export function unseenRules(found, support) {
|
|
103
|
+
const list = [...found].map(toPosix).sort();
|
|
104
|
+
if (!support)
|
|
105
|
+
return list;
|
|
106
|
+
return list.filter((rel) => !readsNatively(rel, list, support));
|
|
107
|
+
}
|
|
108
|
+
/** English pointer block for `--rules pointer`. Empty when nothing to inject. */
|
|
109
|
+
export function rulesPointer(unseen) {
|
|
110
|
+
if (!unseen.length)
|
|
111
|
+
return "";
|
|
112
|
+
const lines = unseen.map((rel) => {
|
|
113
|
+
const n = toPosix(rel);
|
|
114
|
+
return isDirEntry(n)
|
|
115
|
+
? `- ${n}/ (read the rule files that apply to the files you change)`
|
|
116
|
+
: `- ${n}`;
|
|
117
|
+
});
|
|
118
|
+
return (`This repository has project rules your CLI does not load automatically:\n` +
|
|
119
|
+
`${lines.join("\n")}\n` +
|
|
120
|
+
`Before editing, read each file above (and any files they reference with @path) and follow those rules.\n\n`);
|
|
121
|
+
}
|
|
122
|
+
/** Strip line/block comments and trailing commas outside strings. */
|
|
123
|
+
export function stripJsonc(text) {
|
|
124
|
+
let out = "";
|
|
125
|
+
let i = 0;
|
|
126
|
+
let inString = false;
|
|
127
|
+
let escape = false;
|
|
128
|
+
while (i < text.length) {
|
|
129
|
+
const ch = text[i];
|
|
130
|
+
if (inString) {
|
|
131
|
+
out += ch;
|
|
132
|
+
if (escape)
|
|
133
|
+
escape = false;
|
|
134
|
+
else if (ch === "\\")
|
|
135
|
+
escape = true;
|
|
136
|
+
else if (ch === "\"")
|
|
137
|
+
inString = false;
|
|
138
|
+
i += 1;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (ch === "\"") {
|
|
142
|
+
inString = true;
|
|
143
|
+
out += ch;
|
|
144
|
+
i += 1;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (ch === "/" && text[i + 1] === "/") {
|
|
148
|
+
i += 2;
|
|
149
|
+
while (i < text.length && text[i] !== "\n")
|
|
150
|
+
i += 1;
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
if (ch === "/" && text[i + 1] === "*") {
|
|
154
|
+
i += 2;
|
|
155
|
+
while (i + 1 < text.length && !(text[i] === "*" && text[i + 1] === "/"))
|
|
156
|
+
i += 1;
|
|
157
|
+
i += 2;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (ch === ",") {
|
|
161
|
+
let j = i + 1;
|
|
162
|
+
while (j < text.length && /[\s\r\n]/.test(text[j]))
|
|
163
|
+
j += 1;
|
|
164
|
+
if (text[j] === "}" || text[j] === "]") {
|
|
165
|
+
i += 1;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
out += ch;
|
|
170
|
+
i += 1;
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
function asStringList(value) {
|
|
175
|
+
if (value === "*")
|
|
176
|
+
return "*";
|
|
177
|
+
if (!Array.isArray(value))
|
|
178
|
+
return null;
|
|
179
|
+
const list = value.filter((item) => typeof item === "string");
|
|
180
|
+
return list.length === value.length ? list : null;
|
|
181
|
+
}
|
|
182
|
+
function loadJsoncObject(file) {
|
|
183
|
+
if (!fs.existsSync(file))
|
|
184
|
+
return "missing";
|
|
185
|
+
try {
|
|
186
|
+
const parsed = JSON.parse(stripJsonc(fs.readFileSync(file, "utf8")));
|
|
187
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
188
|
+
return "error";
|
|
189
|
+
return parsed;
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
return "error";
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/** Read rulesync.jsonc (+ local overlay). Returns null when missing or unreadable. */
|
|
196
|
+
export function readRulesyncConfig(repoRoot) {
|
|
197
|
+
const base = loadJsoncObject(path.join(repoRoot, "rulesync.jsonc"));
|
|
198
|
+
const local = loadJsoncObject(path.join(repoRoot, "rulesync.local.jsonc"));
|
|
199
|
+
if (base === "missing" && local === "missing")
|
|
200
|
+
return null;
|
|
201
|
+
if (base === "error" || local === "error")
|
|
202
|
+
return null;
|
|
203
|
+
const raw = { ...(base === "missing" ? {} : base), ...(local === "missing" ? {} : local) };
|
|
204
|
+
const features = asStringList(raw.features) ?? ["rules"];
|
|
205
|
+
const targetsRaw = raw.targets;
|
|
206
|
+
let targets = ["claudecode", "codexcli", "opencode"];
|
|
207
|
+
if (targetsRaw === "*")
|
|
208
|
+
targets = "*";
|
|
209
|
+
else if (Array.isArray(targetsRaw)) {
|
|
210
|
+
const list = asStringList(targetsRaw);
|
|
211
|
+
if (!list || list === "*")
|
|
212
|
+
return null;
|
|
213
|
+
targets = list;
|
|
214
|
+
}
|
|
215
|
+
else if (targetsRaw && typeof targetsRaw === "object") {
|
|
216
|
+
const obj = {};
|
|
217
|
+
for (const [key, value] of Object.entries(targetsRaw)) {
|
|
218
|
+
const feats = value === "*" ? "*" : asStringList(value);
|
|
219
|
+
if (feats == null)
|
|
220
|
+
return null;
|
|
221
|
+
obj[key] = feats;
|
|
222
|
+
}
|
|
223
|
+
targets = obj;
|
|
224
|
+
}
|
|
225
|
+
else if (targetsRaw !== undefined) {
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
return { targets, features: features === "*" ? "*" : features };
|
|
229
|
+
}
|
|
230
|
+
function expandFeatures(value) {
|
|
231
|
+
return value === "*" ? [...ALL_FEATURES] : value;
|
|
232
|
+
}
|
|
233
|
+
/** Locate rulesync: project node_modules → main repo node_modules → PATH. Never uses npx. */
|
|
234
|
+
export function resolveRulesync(repoRoot, mainRepoRoot, env = process.env) {
|
|
235
|
+
for (const root of [repoRoot, mainRepoRoot].filter(Boolean)) {
|
|
236
|
+
const local = path.join(root, "node_modules", ".bin", "rulesync");
|
|
237
|
+
try {
|
|
238
|
+
fs.accessSync(local, fs.constants.X_OK);
|
|
239
|
+
return local;
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
// try next
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return which(["rulesync"], env);
|
|
246
|
+
}
|
|
247
|
+
/** Build the rulesync slice of RulesReport from config + adapter support. */
|
|
248
|
+
export function buildRulesyncReport(config, support, bin) {
|
|
249
|
+
const target = support?.rulesyncTarget;
|
|
250
|
+
let target_configured = null;
|
|
251
|
+
let features = [];
|
|
252
|
+
if (config && target) {
|
|
253
|
+
if (config.targets === "*") {
|
|
254
|
+
target_configured = true;
|
|
255
|
+
features = expandFeatures(config.features);
|
|
256
|
+
}
|
|
257
|
+
else if (Array.isArray(config.targets)) {
|
|
258
|
+
target_configured = config.targets.includes("*") || config.targets.includes(target);
|
|
259
|
+
features = target_configured ? expandFeatures(config.features) : [];
|
|
260
|
+
}
|
|
261
|
+
else {
|
|
262
|
+
target_configured = Object.hasOwn(config.targets, target) || Object.hasOwn(config.targets, "*");
|
|
263
|
+
if (target_configured) {
|
|
264
|
+
const per = config.targets[target] ?? config.targets["*"];
|
|
265
|
+
features = per ? expandFeatures(per) : expandFeatures(config.features);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
else if (config) {
|
|
270
|
+
target_configured = false;
|
|
271
|
+
}
|
|
272
|
+
const gates = [];
|
|
273
|
+
if (support?.gates && target_configured) {
|
|
274
|
+
for (const feat of GATE_FEATURES) {
|
|
275
|
+
if (features.includes(feat) && support.gates[feat])
|
|
276
|
+
gates.push(support.gates[feat]);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (!bin) {
|
|
280
|
+
return {
|
|
281
|
+
status: "skipped",
|
|
282
|
+
detail: "rulesync not found in node_modules/.bin or PATH",
|
|
283
|
+
target_configured,
|
|
284
|
+
features,
|
|
285
|
+
gates,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
return { status: "pending", target_configured, features, gates };
|
|
289
|
+
}
|
|
290
|
+
/** True when `<repo>/.rulesync` exists as a directory. */
|
|
291
|
+
export function hasRulesyncSource(repoRoot) {
|
|
292
|
+
try {
|
|
293
|
+
return fs.statSync(path.join(repoRoot, ".rulesync")).isDirectory();
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/** Run `rulesync generate --check` asynchronously. Never throws. */
|
|
300
|
+
export function rulesyncCheck(bin, repoRoot, timeoutMs) {
|
|
301
|
+
const ms = timeoutMs
|
|
302
|
+
?? (Number(process.env.BATON_RULESYNC_CHECK_MS) > 0 ? Number(process.env.BATON_RULESYNC_CHECK_MS) : 15_000);
|
|
303
|
+
return new Promise((resolve) => {
|
|
304
|
+
let settled = false;
|
|
305
|
+
const finish = (result) => {
|
|
306
|
+
if (settled)
|
|
307
|
+
return;
|
|
308
|
+
settled = true;
|
|
309
|
+
resolve(result);
|
|
310
|
+
};
|
|
311
|
+
let stderr = "";
|
|
312
|
+
let child;
|
|
313
|
+
try {
|
|
314
|
+
child = spawn(bin, ["generate", "--check"], {
|
|
315
|
+
cwd: repoRoot,
|
|
316
|
+
env: { ...process.env, BATON_DELEGATION: "1" },
|
|
317
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
finish({ status: "error", detail: redact(error.message).slice(0, 200) });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const timer = setTimeout(() => {
|
|
325
|
+
try {
|
|
326
|
+
child.kill("SIGKILL");
|
|
327
|
+
}
|
|
328
|
+
catch { /* already gone */ }
|
|
329
|
+
finish({ status: "error", detail: `rulesync generate --check timed out after ${ms}ms` });
|
|
330
|
+
}, ms);
|
|
331
|
+
child.stderr?.on("data", (chunk) => {
|
|
332
|
+
stderr = (stderr + chunk.toString()).slice(-4_000);
|
|
333
|
+
});
|
|
334
|
+
child.on("error", (error) => {
|
|
335
|
+
clearTimeout(timer);
|
|
336
|
+
finish({ status: "error", detail: redact(error.message).slice(0, 200) });
|
|
337
|
+
});
|
|
338
|
+
child.on("close", (code) => {
|
|
339
|
+
clearTimeout(timer);
|
|
340
|
+
if (code === 0)
|
|
341
|
+
finish({ status: "in_sync" });
|
|
342
|
+
else if (code === 1)
|
|
343
|
+
finish({ status: "stale" });
|
|
344
|
+
else
|
|
345
|
+
finish({ status: "error", detail: redact(stderr || `rulesync exited ${code}`).slice(0, 200) });
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/** Run `rulesync generate` (writes files). Never throws; returns ok/error. */
|
|
350
|
+
export function rulesyncGenerate(bin, worktreeRoot, timeoutMs = 60_000) {
|
|
351
|
+
return new Promise((resolve) => {
|
|
352
|
+
let settled = false;
|
|
353
|
+
const finish = (result) => {
|
|
354
|
+
if (settled)
|
|
355
|
+
return;
|
|
356
|
+
settled = true;
|
|
357
|
+
resolve(result);
|
|
358
|
+
};
|
|
359
|
+
let stderr = "";
|
|
360
|
+
let child;
|
|
361
|
+
try {
|
|
362
|
+
child = spawn(bin, ["generate"], {
|
|
363
|
+
cwd: worktreeRoot,
|
|
364
|
+
env: { ...process.env, BATON_DELEGATION: "1" },
|
|
365
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
finish({ ok: false, detail: redact(error.message).slice(0, 200) });
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const timer = setTimeout(() => {
|
|
373
|
+
try {
|
|
374
|
+
child.kill("SIGKILL");
|
|
375
|
+
}
|
|
376
|
+
catch { /* already gone */ }
|
|
377
|
+
finish({ ok: false, detail: `rulesync generate timed out after ${timeoutMs}ms` });
|
|
378
|
+
}, timeoutMs);
|
|
379
|
+
child.stderr?.on("data", (chunk) => {
|
|
380
|
+
stderr = (stderr + chunk.toString()).slice(-4_000);
|
|
381
|
+
});
|
|
382
|
+
child.on("error", (error) => {
|
|
383
|
+
clearTimeout(timer);
|
|
384
|
+
finish({ ok: false, detail: redact(error.message).slice(0, 200) });
|
|
385
|
+
});
|
|
386
|
+
child.on("close", (code) => {
|
|
387
|
+
clearTimeout(timer);
|
|
388
|
+
if (code === 0)
|
|
389
|
+
finish({ ok: true });
|
|
390
|
+
else
|
|
391
|
+
finish({ ok: false, detail: redact(stderr || `rulesync exited ${code}`).slice(0, 200) });
|
|
392
|
+
});
|
|
393
|
+
});
|
|
394
|
+
}
|
package/dist/scope.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
const HAS_WILDCARD = /[*?[\]]/;
|
|
4
|
+
export function validateScopeGlob(glob) {
|
|
5
|
+
if (!glob || !glob.trim())
|
|
6
|
+
throw new Error("scope must not be empty.");
|
|
7
|
+
if (glob.trimStart().startsWith("!"))
|
|
8
|
+
throw new Error("scope does not support ! negation patterns.");
|
|
9
|
+
}
|
|
10
|
+
/** Normalize CLI/MCP scope list; throws if policy set without scopes. */
|
|
11
|
+
export function normalizeScopeInput(scopes, policy) {
|
|
12
|
+
const cleaned = (scopes ?? []).map((s) => s.trim()).filter(Boolean);
|
|
13
|
+
if (policy && !cleaned.length)
|
|
14
|
+
throw new Error("--scope-on-violation cannot be used without --scope.");
|
|
15
|
+
if (!cleaned.length)
|
|
16
|
+
return {};
|
|
17
|
+
for (const g of cleaned)
|
|
18
|
+
validateScopeGlob(g);
|
|
19
|
+
const scope_on_violation = policy ?? "warn";
|
|
20
|
+
if (scope_on_violation !== "warn" && scope_on_violation !== "fail") {
|
|
21
|
+
throw new Error("scope-on-violation must be warn or fail.");
|
|
22
|
+
}
|
|
23
|
+
return { scope: cleaned, scope_on_violation };
|
|
24
|
+
}
|
|
25
|
+
export function scopePromptPrefix(scopes) {
|
|
26
|
+
return `[Baton scope] Only modify these paths (post-check enforced): ${scopes.join(", ")}\n\n`;
|
|
27
|
+
}
|
|
28
|
+
function normalizeRel(p) {
|
|
29
|
+
return p.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
30
|
+
}
|
|
31
|
+
function hasWildcard(glob) {
|
|
32
|
+
return HAS_WILDCARD.test(glob);
|
|
33
|
+
}
|
|
34
|
+
export function pathInScope(filePath, globs, opts = {}) {
|
|
35
|
+
const file = normalizeRel(filePath);
|
|
36
|
+
if (file.startsWith("../") || file === "..")
|
|
37
|
+
return false;
|
|
38
|
+
for (const raw of globs) {
|
|
39
|
+
const glob = normalizeRel(raw);
|
|
40
|
+
if (!glob)
|
|
41
|
+
continue;
|
|
42
|
+
if (hasWildcard(glob)) {
|
|
43
|
+
if (path.matchesGlob(file, glob))
|
|
44
|
+
return true;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (file === glob)
|
|
48
|
+
return true;
|
|
49
|
+
const isDir = opts.isDir?.(glob) ?? false;
|
|
50
|
+
if (isDir && (file === glob || file.startsWith(`${glob}/`)))
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
export function findScopeViolations(paths, globs, opts = {}) {
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const p of paths) {
|
|
58
|
+
const file = normalizeRel(p);
|
|
59
|
+
if (file.startsWith("../") || file === ".." || !pathInScope(file, globs, opts)) {
|
|
60
|
+
out.push(file);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
/** Map repo-root-relative git paths into task-cwd-relative paths; cwd escapes → `../…`. */
|
|
66
|
+
export function relativizeToTaskCwd(repoRelativePaths, repoRoot, cwd) {
|
|
67
|
+
const root = path.resolve(repoRoot);
|
|
68
|
+
const base = path.resolve(cwd);
|
|
69
|
+
return repoRelativePaths.map((rel) => {
|
|
70
|
+
const abs = path.resolve(root, rel);
|
|
71
|
+
return normalizeRel(path.relative(base, abs));
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
export function isDirUnderCwd(cwd, pattern) {
|
|
75
|
+
try {
|
|
76
|
+
return fs.statSync(path.resolve(cwd, pattern)).isDirectory();
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
/** Apply warn/fail after transport final status is known. */
|
|
83
|
+
export function applyScopePolicy(input) {
|
|
84
|
+
const violations = [...input.violations];
|
|
85
|
+
if (!violations.length) {
|
|
86
|
+
return {
|
|
87
|
+
status: input.final,
|
|
88
|
+
summary: input.summary,
|
|
89
|
+
warning: input.warning,
|
|
90
|
+
scope_violations: [],
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const note = `scope_violation: ${violations.length} file(s)`;
|
|
94
|
+
const warning = input.warning ? `${input.warning}; ${note}` : note;
|
|
95
|
+
if (input.policy === "fail" && input.final === "success") {
|
|
96
|
+
const body = input.summary ?? "";
|
|
97
|
+
const summary = body.startsWith("scope_violation:")
|
|
98
|
+
? body
|
|
99
|
+
: `scope_violation: see scope_violations${body ? `\n${body}` : ""}`;
|
|
100
|
+
return { status: "scope_violation", summary, warning, scope_violations: violations };
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
status: input.final,
|
|
104
|
+
summary: input.summary,
|
|
105
|
+
warning,
|
|
106
|
+
scope_violations: violations,
|
|
107
|
+
};
|
|
108
|
+
}
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { redact } from "./redact.js";
|
|
6
|
+
import { isAlive } from "./process.js";
|
|
7
|
+
export function batonHome() {
|
|
8
|
+
return path.resolve(process.env.BATON_HOME || path.join(os.homedir(), ".baton"));
|
|
9
|
+
}
|
|
10
|
+
export function taskDir(id) {
|
|
11
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))
|
|
12
|
+
throw new Error("task_id must be a UUID.");
|
|
13
|
+
return path.join(batonHome(), "tasks", id);
|
|
14
|
+
}
|
|
15
|
+
export function ensureTask(id) {
|
|
16
|
+
const dir = taskDir(id);
|
|
17
|
+
for (const name of [batonHome(), path.dirname(dir), dir, path.join(dir, "turns"), path.join(dir, "raw")]) {
|
|
18
|
+
fs.mkdirSync(name, { recursive: true, mode: 0o700 });
|
|
19
|
+
fs.chmodSync(name, 0o700);
|
|
20
|
+
}
|
|
21
|
+
return dir;
|
|
22
|
+
}
|
|
23
|
+
function writeJson(file, value) {
|
|
24
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
25
|
+
try {
|
|
26
|
+
fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600, flag: "wx" });
|
|
27
|
+
fs.renameSync(tmp, file);
|
|
28
|
+
}
|
|
29
|
+
finally {
|
|
30
|
+
fs.rmSync(tmp, { force: true });
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export function writeMeta(meta) {
|
|
34
|
+
writeJson(path.join(ensureTask(meta.task_id), "meta.json"), meta);
|
|
35
|
+
}
|
|
36
|
+
export function readMeta(id) {
|
|
37
|
+
const dir = taskDir(id);
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8"));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function appendEvent(id, event) {
|
|
46
|
+
const safe = Object.fromEntries(Object.entries(event).map(([key, value]) => [key, typeof value === "string" ? redact(value) : value]));
|
|
47
|
+
fs.appendFileSync(path.join(ensureTask(id), "events.jsonl"), `${JSON.stringify(safe)}\n`, { mode: 0o600 });
|
|
48
|
+
}
|
|
49
|
+
export function writeTurn(id, turn) {
|
|
50
|
+
if (!Number.isSafeInteger(turn.turn) || turn.turn < 1)
|
|
51
|
+
throw new Error("turn must be a positive integer.");
|
|
52
|
+
writeJson(path.join(ensureTask(id), "turns", `${turn.turn}.json`), turn);
|
|
53
|
+
}
|
|
54
|
+
export function readTurn(id, turn) {
|
|
55
|
+
return JSON.parse(fs.readFileSync(path.join(taskDir(id), "turns", `${turn}.json`), "utf8"));
|
|
56
|
+
}
|
|
57
|
+
export function listTasks() {
|
|
58
|
+
let names;
|
|
59
|
+
try {
|
|
60
|
+
names = fs.readdirSync(path.join(batonHome(), "tasks"));
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (error.code === "ENOENT")
|
|
64
|
+
return [];
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
return names.filter((name) => /^[0-9a-f-]{36}$/i.test(name)).flatMap((name) => {
|
|
68
|
+
try {
|
|
69
|
+
return readMeta(name) ?? [];
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return [];
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function lockTask(id) {
|
|
77
|
+
const file = path.join(taskDir(id), ".control.lock");
|
|
78
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
79
|
+
fs.writeFileSync(temp, String(process.pid), { mode: 0o600, flag: "wx" });
|
|
80
|
+
try {
|
|
81
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
82
|
+
try {
|
|
83
|
+
fs.linkSync(temp, file);
|
|
84
|
+
return () => fs.rmSync(file, { force: true });
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error.code !== "EEXIST")
|
|
88
|
+
throw error;
|
|
89
|
+
try {
|
|
90
|
+
if (isAlive(Number(fs.readFileSync(file, "utf8"))))
|
|
91
|
+
return null;
|
|
92
|
+
fs.rmSync(file, { force: true });
|
|
93
|
+
}
|
|
94
|
+
catch (readError) {
|
|
95
|
+
if (readError.code !== "ENOENT")
|
|
96
|
+
throw readError;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
fs.rmSync(temp, { force: true });
|
|
104
|
+
}
|
|
105
|
+
}
|