benignswarm 0.12.145 → 0.12.147
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/args.js +8 -4
- package/dist/build-caches.js +2 -1
- package/dist/claude-egress-proxy.js +1312 -0
- package/dist/command-flags.js +1 -1
- package/dist/commands/admin.js +3 -1
- package/dist/commands/agent.js +16 -3
- package/dist/commands/codex-start.js +133 -19
- package/dist/commands/evidence.js +5 -1
- package/dist/commands/hook.js +43 -4
- package/dist/commands/lock-run-supervisor.js +113 -0
- package/dist/commands/lock-run.js +180 -13
- package/dist/commands/machine-admin.js +3 -0
- package/dist/commands/machine.js +148 -17
- package/dist/commands/operator.js +90 -15
- package/dist/commands/ux.js +154 -0
- package/dist/commands/watch.js +170 -21
- package/dist/commands/worktrees.js +9 -2
- package/dist/commands/wu.js +52 -8
- package/dist/console-links.js +17 -0
- package/dist/harnesses.js +832 -10
- package/dist/help.js +22 -9
- package/dist/index.js +3 -0
- package/dist/machine-report.js +239 -0
- package/dist/session-secrets.js +214 -0
- package/dist/ux-jobs.js +728 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/ux-jobs.js
ADDED
|
@@ -0,0 +1,728 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { basename, dirname, join } from "node:path";
|
|
6
|
+
import { Client } from "./client.js";
|
|
7
|
+
import { agentRef, loadAgent, listSaved } from "./config.js";
|
|
8
|
+
import { guessType } from "./commands/evidence.js";
|
|
9
|
+
import { createGateMarkerScanner, runUnderLock } from "./commands/lock-run.js";
|
|
10
|
+
import { CliError } from "./errors.js";
|
|
11
|
+
import { composeMachinePath, requireInstall } from "./install.js";
|
|
12
|
+
import { isolatedSubprocessEnv } from "./container.js";
|
|
13
|
+
const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
14
|
+
const SHA_RE = /^[0-9a-f]{7,64}$/i;
|
|
15
|
+
const MAX_UX_JOB_LOG_TAIL = 2000;
|
|
16
|
+
export const UX_JOBS_MAX_CONCURRENT = 3;
|
|
17
|
+
const defaultUxJobsInFlight = new Set();
|
|
18
|
+
export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
|
|
19
|
+
if (opts.signal?.aborted) {
|
|
20
|
+
resolve({ status: null, stdout: "", stderr: "command aborted", error: new Error("command aborted") });
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
const child = spawn(cmd, args, {
|
|
24
|
+
cwd: opts.cwd,
|
|
25
|
+
env: opts.env,
|
|
26
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
27
|
+
shell: false,
|
|
28
|
+
});
|
|
29
|
+
let stdout = "";
|
|
30
|
+
let stderr = "";
|
|
31
|
+
const append = (cur, chunk) => {
|
|
32
|
+
const next = cur + chunk;
|
|
33
|
+
return next.length <= 128_000 ? next : next.slice(-128_000);
|
|
34
|
+
};
|
|
35
|
+
child.stdout?.on("data", (chunk) => {
|
|
36
|
+
const text = chunk.toString("utf8");
|
|
37
|
+
stdout = append(stdout, text);
|
|
38
|
+
opts.onStdoutChunk?.(text);
|
|
39
|
+
});
|
|
40
|
+
child.stderr?.on("data", (chunk) => {
|
|
41
|
+
const text = chunk.toString("utf8");
|
|
42
|
+
stderr = append(stderr, text);
|
|
43
|
+
opts.onStderrChunk?.(text);
|
|
44
|
+
});
|
|
45
|
+
let timedOut = false;
|
|
46
|
+
let aborted = false;
|
|
47
|
+
const stopChild = () => {
|
|
48
|
+
child.kill("SIGTERM");
|
|
49
|
+
setTimeout(() => child.kill("SIGKILL"), 5_000).unref();
|
|
50
|
+
};
|
|
51
|
+
const onAbort = () => {
|
|
52
|
+
aborted = true;
|
|
53
|
+
stopChild();
|
|
54
|
+
};
|
|
55
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
56
|
+
const timer = setTimeout(() => {
|
|
57
|
+
timedOut = true;
|
|
58
|
+
stopChild();
|
|
59
|
+
}, opts.timeoutMs);
|
|
60
|
+
const cleanup = () => {
|
|
61
|
+
clearTimeout(timer);
|
|
62
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
63
|
+
};
|
|
64
|
+
child.on("error", (error) => {
|
|
65
|
+
cleanup();
|
|
66
|
+
resolve({ status: null, stdout, stderr, error });
|
|
67
|
+
});
|
|
68
|
+
child.on("close", (code) => {
|
|
69
|
+
cleanup();
|
|
70
|
+
resolve({
|
|
71
|
+
status: code,
|
|
72
|
+
stdout,
|
|
73
|
+
stderr: aborted
|
|
74
|
+
? `${stderr}\ncommand aborted`
|
|
75
|
+
: timedOut
|
|
76
|
+
? `${stderr}\ncommand timed out after ${opts.timeoutMs}ms`
|
|
77
|
+
: stderr,
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
export function isValidBranchRef(branch) {
|
|
82
|
+
if (!branch || branch.length > 256 || branch.startsWith("-") || branch.endsWith("."))
|
|
83
|
+
return false;
|
|
84
|
+
if (/[\s\0~^:?*[\\\x00-\x1f\x7f]/.test(branch) || branch.includes("..") || branch.includes("@{") || branch.startsWith("/") || branch.endsWith("/") || branch.includes("//")) {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
export async function resolveProjectAgentForUxJob(job, sessions, deps = {}) {
|
|
90
|
+
const listFn = deps.listSavedAgents ?? (() => listSaved("agents"));
|
|
91
|
+
const loadFn = deps.loadAgentCreds ?? ((ref) => loadAgent(ref));
|
|
92
|
+
const projectSessions = sessions
|
|
93
|
+
.filter((s) => (s.project_id === job.project_id || s.project === job.project) && !s.benched_at && !s.retired_at)
|
|
94
|
+
.sort((a, b) => {
|
|
95
|
+
if ((a.desired === "running") !== (b.desired === "running"))
|
|
96
|
+
return a.desired === "running" ? -1 : 1;
|
|
97
|
+
return a.agent_name.localeCompare(b.agent_name);
|
|
98
|
+
});
|
|
99
|
+
for (const session of projectSessions) {
|
|
100
|
+
if (deps.ensureSessionKey) {
|
|
101
|
+
await deps.ensureSessionKey(session).catch(() => { });
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
const creds = loadFn(session.agent);
|
|
105
|
+
if (creds.key.startsWith("bs_agent_") && creds.project === job.project) {
|
|
106
|
+
return creds;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
// Try next session or saved project identity.
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
for (const ref of listFn()) {
|
|
114
|
+
if (!ref.startsWith(`${job.project}/`))
|
|
115
|
+
continue;
|
|
116
|
+
try {
|
|
117
|
+
const creds = loadFn(ref);
|
|
118
|
+
if (creds.key.startsWith("bs_agent_") && creds.project === job.project) {
|
|
119
|
+
return creds;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
// Ignore unreadable credentials file.
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
throw new Error(`no saved project agent identity for ${job.project} on this machine; configure a project session first`);
|
|
127
|
+
}
|
|
128
|
+
function buildIsolatedAgentEnv(agentCreds, b9sBin, npmBin) {
|
|
129
|
+
const basePath = b9sBin
|
|
130
|
+
? composeMachinePath({
|
|
131
|
+
platform: process.platform,
|
|
132
|
+
home: homedir(),
|
|
133
|
+
installBin: b9sBin,
|
|
134
|
+
npmBin: npmBin ?? "npm",
|
|
135
|
+
currentPath: process.env.PATH ?? "",
|
|
136
|
+
})
|
|
137
|
+
: (process.env.PATH ?? "");
|
|
138
|
+
return isolatedSubprocessEnv(process.env, {
|
|
139
|
+
CI: "true",
|
|
140
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
141
|
+
BSCHAT_AGENT: agentRef(agentCreds),
|
|
142
|
+
B9S_AGENT: agentRef(agentCreds),
|
|
143
|
+
PATH: basePath,
|
|
144
|
+
...(process.env.HOME ? { HOME: process.env.HOME } : {}),
|
|
145
|
+
...(process.env.XDG_CONFIG_HOME ? { XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME } : {}),
|
|
146
|
+
...(process.env.BSCHAT_CONFIG_DIR ? { BSCHAT_CONFIG_DIR: process.env.BSCHAT_CONFIG_DIR } : {}),
|
|
147
|
+
...(process.env.B9S_CONFIG_DIR ? { B9S_CONFIG_DIR: process.env.B9S_CONFIG_DIR } : {}),
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
async function resolveProjectRepoDir(job, ctx, runner, env) {
|
|
151
|
+
const workRoot = ctx.workdir ?? join(homedir(), "bschat");
|
|
152
|
+
const defaultMain = join(workRoot, job.project, "main");
|
|
153
|
+
if (existsSync(join(defaultMain, ".git")))
|
|
154
|
+
return defaultMain;
|
|
155
|
+
for (const session of ctx.sessions) {
|
|
156
|
+
if ((session.project_id !== job.project_id && session.project !== job.project) || !session.dir)
|
|
157
|
+
continue;
|
|
158
|
+
if (!existsSync(session.dir))
|
|
159
|
+
continue;
|
|
160
|
+
const probe = await runner("git", ["-C", session.dir, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
|
|
161
|
+
cwd: session.dir,
|
|
162
|
+
env,
|
|
163
|
+
timeoutMs: 15_000,
|
|
164
|
+
});
|
|
165
|
+
if (probe.status === 0) {
|
|
166
|
+
const commonDir = probe.stdout.trim();
|
|
167
|
+
const repoRoot = basename(commonDir) === ".git" ? dirname(commonDir) : commonDir;
|
|
168
|
+
if (existsSync(join(repoRoot, ".git")))
|
|
169
|
+
return repoRoot;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (job.repo_url) {
|
|
173
|
+
mkdirSync(dirname(defaultMain), { recursive: true });
|
|
174
|
+
const clone = await runner("git", ["clone", job.repo_url, defaultMain], {
|
|
175
|
+
cwd: dirname(defaultMain),
|
|
176
|
+
env,
|
|
177
|
+
timeoutMs: 300_000,
|
|
178
|
+
});
|
|
179
|
+
if (clone.status !== 0) {
|
|
180
|
+
throw new Error(`failed to clone ${job.project} repository into ${defaultMain}: ${(clone.stderr || clone.stdout).trim().slice(0, 300)}`);
|
|
181
|
+
}
|
|
182
|
+
return defaultMain;
|
|
183
|
+
}
|
|
184
|
+
throw new Error(`project ${job.project} has no local git checkout at ${defaultMain} and no repo_url`);
|
|
185
|
+
}
|
|
186
|
+
export async function prepareUxJobWorktree(baseDir, jobDir, branch, head, runner, env, options = {}) {
|
|
187
|
+
if (!isValidBranchRef(branch)) {
|
|
188
|
+
throw new Error(`invalid unit branch name: ${JSON.stringify(branch)}`);
|
|
189
|
+
}
|
|
190
|
+
if (head !== null && !SHA_RE.test(head)) {
|
|
191
|
+
throw new Error(`invalid recorded commit head: ${JSON.stringify(head)}`);
|
|
192
|
+
}
|
|
193
|
+
const requireAncestry = options.requireBranchAncestry !== false;
|
|
194
|
+
if (options.fetchOrigin) {
|
|
195
|
+
const fetchAll = await runner("git", ["-C", baseDir, "fetch", "--prune", "--no-tags", "origin"], {
|
|
196
|
+
cwd: baseDir,
|
|
197
|
+
env,
|
|
198
|
+
timeoutMs: 120_000,
|
|
199
|
+
});
|
|
200
|
+
if (fetchAll.status !== 0) {
|
|
201
|
+
throw new Error(`git fetch origin failed: ${(fetchAll.stderr || fetchAll.stdout).trim().slice(0, 300)}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const fetchBranch = await runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", branch], {
|
|
205
|
+
cwd: baseDir,
|
|
206
|
+
env,
|
|
207
|
+
timeoutMs: 120_000,
|
|
208
|
+
});
|
|
209
|
+
if (fetchBranch.status !== 0 && requireAncestry) {
|
|
210
|
+
throw new Error(`git fetch origin ${branch} failed: ${(fetchBranch.stderr || fetchBranch.stdout).trim().slice(0, 300)}`);
|
|
211
|
+
}
|
|
212
|
+
let branchHeadSha = null;
|
|
213
|
+
if (fetchBranch.status === 0) {
|
|
214
|
+
const remoteRef = `refs/remotes/origin/${branch}`;
|
|
215
|
+
const branchRev = await runner("git", ["-C", baseDir, "rev-parse", "--verify", `${remoteRef}^{commit}`], {
|
|
216
|
+
cwd: baseDir,
|
|
217
|
+
env,
|
|
218
|
+
timeoutMs: 15_000,
|
|
219
|
+
});
|
|
220
|
+
if (branchRev.status === 0) {
|
|
221
|
+
branchHeadSha = branchRev.stdout.trim().toLowerCase();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (requireAncestry && !branchHeadSha) {
|
|
225
|
+
throw new Error(`remote branch origin/${branch} could not be resolved`);
|
|
226
|
+
}
|
|
227
|
+
let targetSha = branchHeadSha ?? "";
|
|
228
|
+
if (head) {
|
|
229
|
+
let hasCommit = await runner("git", ["-C", baseDir, "cat-file", "-e", `${head}^{commit}`], {
|
|
230
|
+
cwd: baseDir,
|
|
231
|
+
env,
|
|
232
|
+
timeoutMs: 15_000,
|
|
233
|
+
});
|
|
234
|
+
if (hasCommit.status !== 0) {
|
|
235
|
+
await runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", head], { cwd: baseDir, env, timeoutMs: 120_000 });
|
|
236
|
+
hasCommit = await runner("git", ["-C", baseDir, "cat-file", "-e", `${head}^{commit}`], { cwd: baseDir, env, timeoutMs: 15_000 });
|
|
237
|
+
}
|
|
238
|
+
if (hasCommit.status !== 0) {
|
|
239
|
+
throw new Error(`recorded head ${head} is missing on origin/${branch}; push the branch commits first`);
|
|
240
|
+
}
|
|
241
|
+
const resolved = await runner("git", ["-C", baseDir, "rev-parse", "--verify", `${head}^{commit}`], {
|
|
242
|
+
cwd: baseDir,
|
|
243
|
+
env,
|
|
244
|
+
timeoutMs: 15_000,
|
|
245
|
+
});
|
|
246
|
+
if (resolved.status !== 0 || !resolved.stdout.trim().toLowerCase().startsWith(head.toLowerCase())) {
|
|
247
|
+
throw new Error(`recorded head ${head} did not resolve deterministically`);
|
|
248
|
+
}
|
|
249
|
+
targetSha = resolved.stdout.trim().toLowerCase();
|
|
250
|
+
if (requireAncestry && branchHeadSha) {
|
|
251
|
+
const ancestor = await runner("git", ["-C", baseDir, "merge-base", "--is-ancestor", targetSha, branchHeadSha], {
|
|
252
|
+
cwd: baseDir,
|
|
253
|
+
env,
|
|
254
|
+
timeoutMs: 15_000,
|
|
255
|
+
});
|
|
256
|
+
if (ancestor.status !== 0) {
|
|
257
|
+
throw new Error(`recorded head ${targetSha.slice(0, 9)} is not contained in origin/${branch}; push before running ux job`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (!targetSha) {
|
|
262
|
+
throw new Error(`could not resolve target commit for ${branch}`);
|
|
263
|
+
}
|
|
264
|
+
if (existsSync(jobDir)) {
|
|
265
|
+
await cleanupUxJobWorktree(baseDir, jobDir, runner, env);
|
|
266
|
+
}
|
|
267
|
+
mkdirSync(dirname(jobDir), { recursive: true });
|
|
268
|
+
const added = await runner("git", ["-C", baseDir, "worktree", "add", "--detach", jobDir, targetSha], {
|
|
269
|
+
cwd: baseDir,
|
|
270
|
+
env,
|
|
271
|
+
timeoutMs: 120_000,
|
|
272
|
+
});
|
|
273
|
+
if (added.status !== 0) {
|
|
274
|
+
throw new Error(`git worktree add failed for ${targetSha.slice(0, 9)}: ${(added.stderr || added.stdout).trim().slice(0, 300)}`);
|
|
275
|
+
}
|
|
276
|
+
return targetSha;
|
|
277
|
+
}
|
|
278
|
+
export async function cleanupUxJobWorktree(baseDir, jobDir, runner, env) {
|
|
279
|
+
await runner("git", ["-C", baseDir, "worktree", "remove", "--force", jobDir], {
|
|
280
|
+
cwd: baseDir,
|
|
281
|
+
env,
|
|
282
|
+
timeoutMs: 60_000,
|
|
283
|
+
}).catch(() => { });
|
|
284
|
+
try {
|
|
285
|
+
rmSync(jobDir, { recursive: true, force: true });
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// Best-effort removal after worktree detach.
|
|
289
|
+
}
|
|
290
|
+
await runner("git", ["-C", baseDir, "worktree", "prune"], {
|
|
291
|
+
cwd: baseDir,
|
|
292
|
+
env,
|
|
293
|
+
timeoutMs: 30_000,
|
|
294
|
+
}).catch(() => { });
|
|
295
|
+
}
|
|
296
|
+
export function collectUxJobArtifacts(worktreeDir) {
|
|
297
|
+
const artifactsRoot = join(worktreeDir, "artifacts");
|
|
298
|
+
if (!existsSync(artifactsRoot))
|
|
299
|
+
return [];
|
|
300
|
+
const results = [];
|
|
301
|
+
const walk = (dir) => {
|
|
302
|
+
const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
303
|
+
for (const entry of entries) {
|
|
304
|
+
const fullPath = join(dir, entry.name);
|
|
305
|
+
if (entry.isDirectory()) {
|
|
306
|
+
walk(fullPath);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
if (!entry.isFile())
|
|
310
|
+
continue;
|
|
311
|
+
const contentType = guessType(entry.name);
|
|
312
|
+
const kind = contentType.startsWith("image/")
|
|
313
|
+
? "screenshot"
|
|
314
|
+
: entry.name.endsWith(".json")
|
|
315
|
+
? "test"
|
|
316
|
+
: entry.name.endsWith(".log") || entry.name.endsWith(".txt")
|
|
317
|
+
? "log"
|
|
318
|
+
: "other";
|
|
319
|
+
results.push({ path: fullPath, filename: entry.name, kind, contentType });
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
walk(artifactsRoot);
|
|
323
|
+
return results;
|
|
324
|
+
}
|
|
325
|
+
async function defaultUploadEvidence(agentCreds, project, file) {
|
|
326
|
+
const bytes = readFileSync(file.path);
|
|
327
|
+
if (bytes.length === 0)
|
|
328
|
+
throw new Error(`artifact ${file.filename} is empty`);
|
|
329
|
+
const sha = createHash("sha256").update(bytes).digest("hex");
|
|
330
|
+
const client = Client.forAgent(agentCreds, undefined, { presence: false });
|
|
331
|
+
const headers = {
|
|
332
|
+
...client.headers(),
|
|
333
|
+
"content-type": file.contentType,
|
|
334
|
+
"x-bschat-sha256": sha,
|
|
335
|
+
"x-bschat-filename": file.filename,
|
|
336
|
+
"x-bschat-label": file.label.slice(0, 500),
|
|
337
|
+
"x-bschat-kind": file.kind,
|
|
338
|
+
"x-bschat-claim": file.claim.slice(0, 300),
|
|
339
|
+
};
|
|
340
|
+
const res = await fetch(`${agentCreds.url}/projects/${encodeURIComponent(project)}/evidence`, {
|
|
341
|
+
method: "POST",
|
|
342
|
+
headers,
|
|
343
|
+
body: new Uint8Array(bytes),
|
|
344
|
+
});
|
|
345
|
+
const text = await res.text();
|
|
346
|
+
let json;
|
|
347
|
+
try {
|
|
348
|
+
json = JSON.parse(text);
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
throw new Error(`evidence upload failed (${res.status}): ${text.slice(0, 200)}`);
|
|
352
|
+
}
|
|
353
|
+
if (!res.ok || typeof json?.evidence?.id !== "string") {
|
|
354
|
+
throw new Error(json?.message ?? `evidence upload failed (${res.status})`);
|
|
355
|
+
}
|
|
356
|
+
return json.evidence.id;
|
|
357
|
+
}
|
|
358
|
+
function forwardLockedChunks(onOutput, onLine) {
|
|
359
|
+
let tail = "";
|
|
360
|
+
return (text, final = false) => {
|
|
361
|
+
const lines = (tail + text).split(/\r?\n/);
|
|
362
|
+
const incomplete = lines.pop() ?? "";
|
|
363
|
+
if (final) {
|
|
364
|
+
tail = "";
|
|
365
|
+
if (incomplete)
|
|
366
|
+
lines.push(incomplete);
|
|
367
|
+
}
|
|
368
|
+
else {
|
|
369
|
+
tail = incomplete.slice(-32_768);
|
|
370
|
+
if (tail.trim())
|
|
371
|
+
onOutput?.(tail);
|
|
372
|
+
}
|
|
373
|
+
for (const line of lines) {
|
|
374
|
+
if (line.trim())
|
|
375
|
+
onOutput?.(line);
|
|
376
|
+
onLine?.(line);
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
async function defaultRunWithLock(opts, agentClient, log) {
|
|
381
|
+
const lockDeps = {
|
|
382
|
+
call: (method, path, body) => agentClient.call(method, path, body),
|
|
383
|
+
run: (_command, context) => opts.run(context),
|
|
384
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
385
|
+
interrupted: () => false,
|
|
386
|
+
log,
|
|
387
|
+
};
|
|
388
|
+
return runUnderLock({
|
|
389
|
+
project: opts.project,
|
|
390
|
+
identity: opts.identity,
|
|
391
|
+
lock: opts.lock,
|
|
392
|
+
shared: false,
|
|
393
|
+
machine: opts.machine,
|
|
394
|
+
unit: opts.unit,
|
|
395
|
+
note: opts.note,
|
|
396
|
+
command: opts.commandLabel,
|
|
397
|
+
token: `b9sjob_${randomBytes(16).toString("hex")}`,
|
|
398
|
+
jobId: randomBytes(6).toString("hex"),
|
|
399
|
+
jobsFile: join(homedir(), ".b9s", "ux-lock-jobs.json"),
|
|
400
|
+
jobsKey: `${opts.project}:${opts.lock}:${opts.machine}`,
|
|
401
|
+
...(opts.pollMs === undefined ? {} : { pollMs: opts.pollMs }),
|
|
402
|
+
}, lockDeps);
|
|
403
|
+
}
|
|
404
|
+
export async function executeUxJob(machineClient, job, ctx, deps = {}) {
|
|
405
|
+
const runner = deps.runCommand ?? spawnAsyncCommand;
|
|
406
|
+
const runWithLock = deps.runWithLock ?? defaultRunWithLock;
|
|
407
|
+
const uploadEvidence = deps.uploadEvidence ?? defaultUploadEvidence;
|
|
408
|
+
const jobKind = job.job_kind ?? "ux";
|
|
409
|
+
let b9sBin = deps.b9sBin;
|
|
410
|
+
let npmBin = deps.npmBin;
|
|
411
|
+
if (!b9sBin || !npmBin) {
|
|
412
|
+
try {
|
|
413
|
+
const inst = requireInstall();
|
|
414
|
+
b9sBin = b9sBin ?? inst.bin;
|
|
415
|
+
npmBin = npmBin ?? inst.npm;
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
npmBin = npmBin ?? "npm";
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
let agentCreds;
|
|
422
|
+
try {
|
|
423
|
+
agentCreds = await resolveProjectAgentForUxJob(job, ctx.sessions, deps);
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
const message = error.message;
|
|
427
|
+
try {
|
|
428
|
+
await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
|
|
429
|
+
await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
|
|
430
|
+
status: "failed",
|
|
431
|
+
error: message,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
catch {
|
|
435
|
+
// Ignore secondary report error if claim failed.
|
|
436
|
+
}
|
|
437
|
+
return { id: job.id, status: "failed", evidence_ids: [], error: message };
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
|
|
441
|
+
}
|
|
442
|
+
catch {
|
|
443
|
+
return { id: job.id, status: "skipped", evidence_ids: [] };
|
|
444
|
+
}
|
|
445
|
+
const jobTaskLabel = jobKind === "gate"
|
|
446
|
+
? "complete-suite gate"
|
|
447
|
+
: [job.task ? `ux:task ${job.task}` : null, job.compare_screen ? `ux:compare ${job.compare_screen}` : null].filter(Boolean).join(" + ");
|
|
448
|
+
const childEnv = buildIsolatedAgentEnv(agentCreds, b9sBin, npmBin);
|
|
449
|
+
const workRoot = ctx.workdir ?? join(homedir(), "bschat");
|
|
450
|
+
const jobWorktreeDir = join(workRoot, job.project, ".ux-jobs", job.id);
|
|
451
|
+
let baseDir = null;
|
|
452
|
+
let worktreeCreated = false;
|
|
453
|
+
let resolvedHead = job.head;
|
|
454
|
+
let logTail = "";
|
|
455
|
+
const appendLog = (chunk) => {
|
|
456
|
+
if (!chunk)
|
|
457
|
+
return;
|
|
458
|
+
logTail = `${logTail}\n${chunk}`.trim();
|
|
459
|
+
if (logTail.length > MAX_UX_JOB_LOG_TAIL)
|
|
460
|
+
logTail = logTail.slice(-MAX_UX_JOB_LOG_TAIL);
|
|
461
|
+
};
|
|
462
|
+
const uploadedIds = [];
|
|
463
|
+
try {
|
|
464
|
+
if (jobKind === "ux") {
|
|
465
|
+
if (job.task && !SLUG_RE.test(job.task))
|
|
466
|
+
throw new Error(`invalid ux task name ${job.task}`);
|
|
467
|
+
if (job.compare_screen && !SLUG_RE.test(job.compare_screen))
|
|
468
|
+
throw new Error(`invalid compare screen ${job.compare_screen}`);
|
|
469
|
+
}
|
|
470
|
+
else if (!job.head || !SHA_RE.test(job.head)) {
|
|
471
|
+
throw new Error("gate job requires a candidate commit SHA");
|
|
472
|
+
}
|
|
473
|
+
baseDir = await resolveProjectRepoDir(job, ctx, runner, childEnv);
|
|
474
|
+
resolvedHead = await prepareUxJobWorktree(baseDir, jobWorktreeDir, job.branch, job.head, runner, childEnv, {
|
|
475
|
+
requireBranchAncestry: jobKind === "ux",
|
|
476
|
+
fetchOrigin: jobKind === "gate",
|
|
477
|
+
});
|
|
478
|
+
worktreeCreated = true;
|
|
479
|
+
const shortHead = resolvedHead.slice(0, 9);
|
|
480
|
+
const agentClient = Client.forAgent(agentCreds, undefined, { presence: false });
|
|
481
|
+
const commandLabel = jobKind === "gate"
|
|
482
|
+
? ["scripts/gate.sh", resolvedHead]
|
|
483
|
+
: [
|
|
484
|
+
"ux-job",
|
|
485
|
+
job.id.slice(0, 8),
|
|
486
|
+
...(job.task ? ["ux:task", job.task] : []),
|
|
487
|
+
...(job.compare_screen ? ["ux:compare", job.compare_screen] : []),
|
|
488
|
+
];
|
|
489
|
+
const lockName = jobKind === "gate" ? "complete-suite" : "ux-browser";
|
|
490
|
+
let gateLogFile = null;
|
|
491
|
+
const exitCode = await runWithLock({
|
|
492
|
+
lock: lockName,
|
|
493
|
+
project: job.project,
|
|
494
|
+
identity: agentRef(agentCreds),
|
|
495
|
+
machine: agentCreds.machine,
|
|
496
|
+
unit: job.work_unit_number,
|
|
497
|
+
note: `${jobKind}-job ${job.id}: ${jobTaskLabel} @ ${shortHead}`,
|
|
498
|
+
commandLabel,
|
|
499
|
+
...(deps.lockPollMs === undefined ? {} : { pollMs: deps.lockPollMs }),
|
|
500
|
+
run: async (lockContext) => {
|
|
501
|
+
const lockedEnv = { ...childEnv };
|
|
502
|
+
if (lockContext?.jobId)
|
|
503
|
+
lockedEnv.B9S_LOCK_JOB_ID = lockContext.jobId;
|
|
504
|
+
if (lockContext?.slot !== undefined)
|
|
505
|
+
lockedEnv.B9S_LOCK_SLOT = String(lockContext.slot);
|
|
506
|
+
else
|
|
507
|
+
delete lockedEnv.B9S_LOCK_SLOT;
|
|
508
|
+
const heartbeatController = new AbortController();
|
|
509
|
+
let heartbeatTimer;
|
|
510
|
+
let heartbeatInFlight;
|
|
511
|
+
let heartbeatFailure;
|
|
512
|
+
if (lockContext?.heartbeat) {
|
|
513
|
+
const heartbeatMs = deps.lockHeartbeatMs ?? 15_000;
|
|
514
|
+
heartbeatTimer = setInterval(() => {
|
|
515
|
+
if (heartbeatInFlight)
|
|
516
|
+
return;
|
|
517
|
+
heartbeatInFlight = lockContext.heartbeat().then(() => undefined, (error) => {
|
|
518
|
+
heartbeatFailure = error;
|
|
519
|
+
ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
|
|
520
|
+
heartbeatController.abort();
|
|
521
|
+
}).finally(() => {
|
|
522
|
+
heartbeatInFlight = undefined;
|
|
523
|
+
});
|
|
524
|
+
}, heartbeatMs);
|
|
525
|
+
heartbeatTimer.unref?.();
|
|
526
|
+
}
|
|
527
|
+
const throwIfHeartbeatFailed = () => {
|
|
528
|
+
if (!heartbeatFailure)
|
|
529
|
+
return;
|
|
530
|
+
throw new CliError("lock_heartbeat_failed", `job ${lockContext?.jobId ?? job.id} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
|
|
531
|
+
};
|
|
532
|
+
const runLockedStep = async (cmd, args, stepOpts) => {
|
|
533
|
+
throwIfHeartbeatFailed();
|
|
534
|
+
let combined = "";
|
|
535
|
+
let sawStdoutChunk = false;
|
|
536
|
+
let sawStderrChunk = false;
|
|
537
|
+
const pushStdout = forwardLockedChunks(stepOpts.omitOutput ? undefined : lockContext?.onOutput, stepOpts.onStdoutLine);
|
|
538
|
+
const pushStderr = forwardLockedChunks(stepOpts.omitOutput ? undefined : lockContext?.onOutput);
|
|
539
|
+
const res = await runner(cmd, args, {
|
|
540
|
+
cwd: jobWorktreeDir,
|
|
541
|
+
env: lockedEnv,
|
|
542
|
+
timeoutMs: stepOpts.timeoutMs,
|
|
543
|
+
signal: heartbeatController.signal,
|
|
544
|
+
onStdoutChunk: (chunk) => {
|
|
545
|
+
sawStdoutChunk = true;
|
|
546
|
+
if (stepOpts.captureCombined)
|
|
547
|
+
combined += chunk;
|
|
548
|
+
pushStdout(chunk);
|
|
549
|
+
},
|
|
550
|
+
onStderrChunk: (chunk) => {
|
|
551
|
+
sawStderrChunk = true;
|
|
552
|
+
if (stepOpts.captureCombined)
|
|
553
|
+
combined += chunk;
|
|
554
|
+
pushStderr(chunk);
|
|
555
|
+
},
|
|
556
|
+
});
|
|
557
|
+
if (!sawStdoutChunk && res.stdout) {
|
|
558
|
+
if (stepOpts.captureCombined)
|
|
559
|
+
combined += res.stdout;
|
|
560
|
+
pushStdout(res.stdout);
|
|
561
|
+
}
|
|
562
|
+
if (!sawStderrChunk && res.stderr) {
|
|
563
|
+
if (stepOpts.captureCombined)
|
|
564
|
+
combined += res.stderr;
|
|
565
|
+
pushStderr(res.stderr);
|
|
566
|
+
}
|
|
567
|
+
pushStdout("", true);
|
|
568
|
+
pushStderr("", true);
|
|
569
|
+
throwIfHeartbeatFailed();
|
|
570
|
+
return { res, combined };
|
|
571
|
+
};
|
|
572
|
+
try {
|
|
573
|
+
if (jobKind === "gate") {
|
|
574
|
+
const scriptPath = join(jobWorktreeDir, "scripts", "gate.sh");
|
|
575
|
+
if (!existsSync(scriptPath)) {
|
|
576
|
+
throw new Error(`scripts/gate.sh is missing at commit ${shortHead}`);
|
|
577
|
+
}
|
|
578
|
+
const scanner = createGateMarkerScanner();
|
|
579
|
+
const { res: gateRes, combined: fullOutput } = await runLockedStep("/bin/sh", ["scripts/gate.sh", resolvedHead], {
|
|
580
|
+
timeoutMs: 1_800_000,
|
|
581
|
+
captureCombined: true,
|
|
582
|
+
onStdoutLine: (line) => scanner.push(`${line}\n`),
|
|
583
|
+
});
|
|
584
|
+
scanner.push("", true);
|
|
585
|
+
appendLog(fullOutput || gateRes.stdout || gateRes.stderr);
|
|
586
|
+
const logDir = join(jobWorktreeDir, "artifacts", "gate");
|
|
587
|
+
mkdirSync(logDir, { recursive: true });
|
|
588
|
+
gateLogFile = join(logDir, `gate-wu${job.work_unit_number}-${shortHead}.log`);
|
|
589
|
+
writeFileSync(gateLogFile, fullOutput || `${gateRes.stdout}\n${gateRes.stderr}` || `exit ${gateRes.status ?? 1}\n`);
|
|
590
|
+
return { exit_code: gateRes.status ?? 1, ...scanner.result() };
|
|
591
|
+
}
|
|
592
|
+
if (job.task) {
|
|
593
|
+
const { res: listed } = await runLockedStep("node", ["scripts/ux-console.mjs", "tasks"], {
|
|
594
|
+
timeoutMs: 30_000,
|
|
595
|
+
omitOutput: true,
|
|
596
|
+
});
|
|
597
|
+
if (listed.status !== 0) {
|
|
598
|
+
appendLog(listed.stderr || listed.stdout);
|
|
599
|
+
throw new Error(`could not enumerate registered ux:task names in ${jobWorktreeDir}`);
|
|
600
|
+
}
|
|
601
|
+
const registered = new Set(listed.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
|
|
602
|
+
if (!registered.has(job.task)) {
|
|
603
|
+
throw new Error(`ux:task ${job.task} is not registered in checkout ${shortHead}`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
if (job.compare_screen) {
|
|
607
|
+
const registryFile = join(jobWorktreeDir, "docs/ux/screens/mocks/compare.json");
|
|
608
|
+
if (!existsSync(registryFile)) {
|
|
609
|
+
throw new Error(`compare registry docs/ux/screens/mocks/compare.json is missing at checkout ${shortHead}`);
|
|
610
|
+
}
|
|
611
|
+
const registry = JSON.parse(readFileSync(registryFile, "utf8"));
|
|
612
|
+
const screenIds = new Set((registry.screens ?? []).map((item) => item.id).filter(Boolean));
|
|
613
|
+
if (!screenIds.has(job.compare_screen)) {
|
|
614
|
+
throw new Error(`compare screen ${job.compare_screen} is not registered in compare.json at ${shortHead}`);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
const { res: installRes } = await runLockedStep(npmBin, ["ci"], { timeoutMs: 600_000 });
|
|
618
|
+
appendLog(installRes.stdout);
|
|
619
|
+
appendLog(installRes.stderr);
|
|
620
|
+
if (installRes.status !== 0)
|
|
621
|
+
return installRes.status ?? 1;
|
|
622
|
+
const { res: seedRes } = await runLockedStep(npmBin, ["run", "ux:seed"], { timeoutMs: 300_000 });
|
|
623
|
+
appendLog(seedRes.stdout);
|
|
624
|
+
appendLog(seedRes.stderr);
|
|
625
|
+
if (seedRes.status !== 0)
|
|
626
|
+
return seedRes.status ?? 1;
|
|
627
|
+
if (job.task) {
|
|
628
|
+
const { res: taskRes } = await runLockedStep(npmBin, ["run", "ux:task", "--", job.task], { timeoutMs: 600_000 });
|
|
629
|
+
appendLog(taskRes.stdout);
|
|
630
|
+
appendLog(taskRes.stderr);
|
|
631
|
+
if (taskRes.status !== 0)
|
|
632
|
+
return taskRes.status ?? 1;
|
|
633
|
+
}
|
|
634
|
+
if (job.compare_screen) {
|
|
635
|
+
const { res: compareRes } = await runLockedStep(npmBin, ["run", "ux:compare", "--", job.compare_screen, "--unit", String(job.work_unit_number), "--widths", "1440,375"], { timeoutMs: 600_000 });
|
|
636
|
+
appendLog(compareRes.stdout);
|
|
637
|
+
appendLog(compareRes.stderr);
|
|
638
|
+
if (compareRes.status !== 0)
|
|
639
|
+
return compareRes.status ?? 1;
|
|
640
|
+
}
|
|
641
|
+
return 0;
|
|
642
|
+
}
|
|
643
|
+
finally {
|
|
644
|
+
if (heartbeatTimer)
|
|
645
|
+
clearInterval(heartbeatTimer);
|
|
646
|
+
await heartbeatInFlight;
|
|
647
|
+
throwIfHeartbeatFailed();
|
|
648
|
+
}
|
|
649
|
+
},
|
|
650
|
+
}, agentClient, ctx.log);
|
|
651
|
+
const artifacts = collectUxJobArtifacts(jobWorktreeDir);
|
|
652
|
+
const taskTag = jobKind === "gate"
|
|
653
|
+
? `gate ${exitCode === 0 ? "PASSED" : "FAILED"}`
|
|
654
|
+
: [job.task, job.compare_screen ? `compare-${job.compare_screen}` : null].filter(Boolean).join(" ");
|
|
655
|
+
for (const artifact of artifacts) {
|
|
656
|
+
const label = `WU #${job.work_unit_number} ${shortHead} ${taskTag} ${artifact.filename}`;
|
|
657
|
+
const claim = jobKind === "gate"
|
|
658
|
+
? `Complete-suite gate run (${exitCode === 0 ? "PASSED" : "FAILED"}) on ${ctx.machineName} at ${shortHead} for WU #${job.work_unit_number}`
|
|
659
|
+
: `Seeded UX run (${jobTaskLabel}) on ${ctx.machineName} at ${shortHead} for WU #${job.work_unit_number}`;
|
|
660
|
+
const evidenceId = await uploadEvidence(agentCreds, job.project, {
|
|
661
|
+
...artifact,
|
|
662
|
+
label,
|
|
663
|
+
claim,
|
|
664
|
+
});
|
|
665
|
+
uploadedIds.push(evidenceId);
|
|
666
|
+
}
|
|
667
|
+
if (exitCode !== 0) {
|
|
668
|
+
const errMsg = `${jobKind} job exited with code ${exitCode}${logTail ? `: ${logTail.slice(-280)}` : ""}`.slice(0, 500);
|
|
669
|
+
await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
|
|
670
|
+
status: "failed",
|
|
671
|
+
resolved_head: resolvedHead,
|
|
672
|
+
evidence_ids: uploadedIds,
|
|
673
|
+
error: errMsg,
|
|
674
|
+
log_excerpt: logTail || undefined,
|
|
675
|
+
});
|
|
676
|
+
return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
|
|
677
|
+
}
|
|
678
|
+
await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
|
|
679
|
+
status: "succeeded",
|
|
680
|
+
resolved_head: resolvedHead,
|
|
681
|
+
evidence_ids: uploadedIds,
|
|
682
|
+
log_excerpt: logTail || undefined,
|
|
683
|
+
});
|
|
684
|
+
ctx.log(`${jobKind} job ${job.id}: completed (${uploadedIds.length} artifact(s) posted for WU #${job.work_unit_number} at ${shortHead})`);
|
|
685
|
+
return { id: job.id, status: "succeeded", evidence_ids: uploadedIds, resolved_head: resolvedHead };
|
|
686
|
+
}
|
|
687
|
+
catch (error) {
|
|
688
|
+
const message = (error.message || `${jobKind} job failed`).slice(0, 500);
|
|
689
|
+
await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
|
|
690
|
+
status: "failed",
|
|
691
|
+
resolved_head: resolvedHead ?? undefined,
|
|
692
|
+
evidence_ids: uploadedIds,
|
|
693
|
+
error: message,
|
|
694
|
+
log_excerpt: logTail || undefined,
|
|
695
|
+
}).catch((completeError) => {
|
|
696
|
+
ctx.log(`${jobKind} job ${job.id}: completion report failed: ${completeError.message}`);
|
|
697
|
+
});
|
|
698
|
+
ctx.log(`${jobKind} job ${job.id}: failed (${message})`);
|
|
699
|
+
return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: message };
|
|
700
|
+
}
|
|
701
|
+
finally {
|
|
702
|
+
if (worktreeCreated && baseDir) {
|
|
703
|
+
await cleanupUxJobWorktree(baseDir, jobWorktreeDir, runner, childEnv);
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
export function reconcilePendingUxJobs(machineClient, jobs, ctx, opts = {}) {
|
|
708
|
+
const inFlight = opts.inFlight ?? defaultUxJobsInFlight;
|
|
709
|
+
const maxConcurrent = opts.maxConcurrent ?? UX_JOBS_MAX_CONCURRENT;
|
|
710
|
+
const started = [];
|
|
711
|
+
for (const job of jobs) {
|
|
712
|
+
if (job.status !== "queued")
|
|
713
|
+
continue;
|
|
714
|
+
if (inFlight.has(job.id))
|
|
715
|
+
continue;
|
|
716
|
+
if (inFlight.size >= maxConcurrent)
|
|
717
|
+
break;
|
|
718
|
+
inFlight.add(job.id);
|
|
719
|
+
const runPromise = executeUxJob(machineClient, job, ctx, opts.deps).finally(() => {
|
|
720
|
+
inFlight.delete(job.id);
|
|
721
|
+
});
|
|
722
|
+
started.push(runPromise);
|
|
723
|
+
if (!opts.awaitCompletion) {
|
|
724
|
+
void runPromise;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
return opts.awaitCompletion ? Promise.all(started) : Promise.resolve([]);
|
|
728
|
+
}
|