benignswarm 0.12.152 → 0.12.154

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/ux-jobs.js CHANGED
@@ -1,6 +1,6 @@
1
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";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { basename, dirname, join } from "node:path";
6
6
  import { Client } from "./client.js";
@@ -16,10 +16,145 @@ const SHA_RE = /^[0-9a-f]{7,64}$/i;
16
16
  const MAX_UX_JOB_LOG_TAIL = 2000;
17
17
  export const UX_JOBS_MAX_CONCURRENT = 3;
18
18
  const UX_JOB_COMPLETION_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000];
19
+ const UX_JOB_KEEP_MS = 6 * 60 * 60 * 1000;
20
+ const UX_JOB_CHECKOUT_RETENTION_FILE = ".b9s-ux-job-retention.json";
21
+ const DEFAULT_UX_JOB_DISK_FLOOR_PCT = 15;
22
+ const JOB_SECRET_TEXT_RE = /(bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|AKIA[0-9A-Z]{16}|sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]+)/g;
23
+ const JOB_SECRET_KEYS = "AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY";
24
+ const JOB_SECRET_ASSIGNMENT_RE = new RegExp(`\\b(${JOB_SECRET_KEYS})\\b(\\s*[:=]\\s*)(?:\"[^\"\\r\\n]*\"|'[^'\\r\\n]*'|[^\\s,;}\\]]+)`, "gi");
25
+ export function redactUxJobDiagnosticText(value) {
26
+ return value.replace(JOB_SECRET_ASSIGNMENT_RE, "$1$2[REDACTED]").replace(JOB_SECRET_TEXT_RE, "[REDACTED]");
27
+ }
28
+ function lastOutputLines(value, count = 200) {
29
+ const lines = redactUxJobDiagnosticText(value).split(/\r?\n/);
30
+ return lines.slice(-count).join("\n");
31
+ }
32
+ function defaultJobDiskSpace(path) {
33
+ try {
34
+ const stat = statfsSync(path);
35
+ return { freeBytes: Number(stat.bavail) * Number(stat.bsize), totalBytes: Number(stat.blocks) * Number(stat.bsize) };
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ /** Remove only expired job worktrees whose signed-in local manifest matches their UUID directory. */
42
+ export async function sweepExpiredUxJobWorktrees(workRoot, projects, runner = spawnAsyncCommand, env = process.env, log = () => { }, nowMs = Date.now(), markRemoved) {
43
+ let removed = 0;
44
+ for (const project of projects) {
45
+ if (!/^[a-zA-Z0-9._-]+$/.test(project.name) || project.name === "." || project.name === "..")
46
+ continue;
47
+ const projectRoot = join(workRoot, project.name);
48
+ const jobRoot = join(projectRoot, ".ux-jobs");
49
+ const baseDir = join(projectRoot, "main");
50
+ if (!existsSync(join(baseDir, ".git")) || !existsSync(jobRoot))
51
+ continue;
52
+ try {
53
+ const jobRootStat = lstatSync(jobRoot);
54
+ if (!jobRootStat.isDirectory() || jobRootStat.isSymbolicLink())
55
+ continue;
56
+ }
57
+ catch {
58
+ continue;
59
+ }
60
+ let entries;
61
+ try {
62
+ entries = readdirSync(jobRoot);
63
+ }
64
+ catch (error) {
65
+ log(`UX job retention sweep could not read ${jobRoot}: ${error.message}`);
66
+ continue;
67
+ }
68
+ if (markRemoved) {
69
+ for (const name of entries.filter((entry) => /^[0-9a-f-]{36}\.removed\.json$/i.test(entry))) {
70
+ const markerPath = join(jobRoot, name);
71
+ let marker;
72
+ try {
73
+ marker = JSON.parse(readFileSync(markerPath, "utf8"));
74
+ }
75
+ catch {
76
+ continue;
77
+ }
78
+ if (marker.version !== 1 || marker.job_id !== name.slice(0, -".removed.json".length) || !Number.isFinite(Date.parse(marker.removed_at)))
79
+ continue;
80
+ try {
81
+ await markRemoved(marker.job_id);
82
+ unlinkSync(markerPath);
83
+ }
84
+ catch (error) {
85
+ log(`expired failed UX job checkout ${marker.job_id} was removed locally, but its API record was not updated: ${error.message}`);
86
+ }
87
+ }
88
+ }
89
+ for (const id of entries) {
90
+ if (!/^[0-9a-f-]{36}$/i.test(id))
91
+ continue;
92
+ const checkout = join(jobRoot, id);
93
+ try {
94
+ const checkoutStat = lstatSync(checkout);
95
+ if (!checkoutStat.isDirectory() || checkoutStat.isSymbolicLink())
96
+ continue;
97
+ }
98
+ catch {
99
+ continue;
100
+ }
101
+ const manifestPath = join(checkout, UX_JOB_CHECKOUT_RETENTION_FILE);
102
+ let record;
103
+ try {
104
+ record = JSON.parse(readFileSync(manifestPath, "utf8"));
105
+ }
106
+ catch {
107
+ continue;
108
+ }
109
+ const expiry = Date.parse(record.expires_at);
110
+ if (record.version !== 1 || record.job_id !== id || !Number.isFinite(expiry) || expiry > nowMs)
111
+ continue;
112
+ const remove = await runner("git", ["-C", baseDir, "worktree", "remove", "--force", checkout], {
113
+ cwd: baseDir,
114
+ env,
115
+ timeoutMs: 60_000,
116
+ }).catch((error) => ({ status: null, stdout: "", stderr: error.message }));
117
+ if (remove.status !== 0) {
118
+ log(`expired failed UX job checkout could not be removed: ${id}; git worktree remove exited ${remove.status ?? "without a status"}: ${(remove.stderr || remove.stdout).trim().slice(0, 300)}`);
119
+ continue;
120
+ }
121
+ if (!existsSync(checkout)) {
122
+ const markerPath = join(jobRoot, `${id}.removed.json`);
123
+ if (markRemoved) {
124
+ const marker = { version: 1, job_id: id, removed_at: new Date(nowMs).toISOString() };
125
+ writeFileSync(markerPath, `${JSON.stringify(marker)}\n`, { mode: 0o600 });
126
+ }
127
+ const prune = await runner("git", ["-C", baseDir, "worktree", "prune"], { cwd: baseDir, env, timeoutMs: 30_000 });
128
+ if (prune.status !== 0) {
129
+ log(`expired failed UX job checkout ${id} was removed but git worktree prune failed (${prune.status ?? "no status"}): ${(prune.stderr || prune.stdout).trim().slice(0, 300)}`);
130
+ }
131
+ removed++;
132
+ log(`expired failed UX job checkout removed: ${id}`);
133
+ if (markRemoved) {
134
+ try {
135
+ await markRemoved(id);
136
+ unlinkSync(markerPath);
137
+ }
138
+ catch (error) {
139
+ log(`expired failed UX job checkout ${id} was removed locally, but its API record was not updated: ${error.message}`);
140
+ }
141
+ }
142
+ }
143
+ else {
144
+ log(`expired failed UX job checkout could not be removed: ${id}`);
145
+ }
146
+ }
147
+ }
148
+ return removed;
149
+ }
19
150
  function completionStatePath(jobId, deps) {
20
151
  const name = createHash("sha256").update(jobId).digest("hex");
21
152
  return join(deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions"), `${name}.json`);
22
153
  }
154
+ function diagnosticLogPathForJob(jobId, deps) {
155
+ const name = createHash("sha256").update(jobId).digest("hex");
156
+ return join(deps.diagnosticLogRoot ?? join(configRoot(), "state", "ux-job-logs"), `${name}.log`);
157
+ }
23
158
  function completionErrorCode(error) {
24
159
  const code = error && typeof error === "object" && "code" in error ? String(error.code) : null;
25
160
  return code;
@@ -37,8 +172,14 @@ function defaultCompletionSleep(ms) {
37
172
  * Completion is the durable result of expensive work. Save it before sending so a daemon restart
38
173
  * can resend it, and never reinterpret a reporting failure as a failed UX or gate run.
39
174
  */
40
- export async function reportUxJobCompletion(machineClient, jobId, body, log, deps = {}) {
41
- const record = { version: 1, job_id: jobId, body };
175
+ export async function reportUxJobCompletion(machineClient, jobId, body, log, deps = {}, logState, sessions = []) {
176
+ const record = {
177
+ version: 1,
178
+ job_id: jobId,
179
+ body,
180
+ ...(logState ? { diagnostic_log_path: logState.path } : {}),
181
+ ...(logState?.pendingUpload && !body.full_log_evidence_id ? { pending_full_log: logState.pendingUpload } : {}),
182
+ };
42
183
  const path = completionStatePath(jobId, deps);
43
184
  try {
44
185
  writeFileAtomic(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
@@ -47,9 +188,43 @@ export async function reportUxJobCompletion(machineClient, jobId, body, log, dep
47
188
  log(`UX job ${jobId}: could not persist completion before reporting: ${error.message}`);
48
189
  return "pending";
49
190
  }
50
- return sendStoredUxJobCompletion(machineClient, record, path, log, deps);
191
+ return sendStoredUxJobCompletion(machineClient, record, path, log, deps, sessions);
51
192
  }
52
- async function sendStoredUxJobCompletion(machineClient, record, path, log, deps) {
193
+ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps, sessions = []) {
194
+ if (record.refused_error) {
195
+ log(`UX job ${record.job_id}: completion remains refused; diagnostic log retained at ${record.diagnostic_log_path ?? "unknown path"}: ${record.refused_error}`);
196
+ return "refused";
197
+ }
198
+ if (record.pending_full_log && !record.body.full_log_evidence_id) {
199
+ const logPath = record.diagnostic_log_path;
200
+ if (!logPath || !existsSync(logPath)) {
201
+ log(`UX job ${record.job_id}: full-log upload remains pending because its redacted local log is unavailable`);
202
+ return "pending";
203
+ }
204
+ try {
205
+ const credentials = await resolveProjectAgentForUxJob(record.pending_full_log, sessions, deps);
206
+ const uploadEvidence = deps.uploadEvidence ?? defaultUploadEvidence;
207
+ const evidenceId = await uploadEvidence(credentials, record.pending_full_log.project, {
208
+ path: logPath,
209
+ filename: record.pending_full_log.filename,
210
+ kind: "log",
211
+ contentType: "text/plain",
212
+ label: record.pending_full_log.label,
213
+ claim: record.pending_full_log.claim,
214
+ });
215
+ record.body = {
216
+ ...record.body,
217
+ evidence_ids: [...new Set([...(record.body.evidence_ids ?? []), evidenceId])],
218
+ full_log_evidence_id: evidenceId,
219
+ };
220
+ delete record.pending_full_log;
221
+ writeFileAtomic(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
222
+ }
223
+ catch (error) {
224
+ log(`UX job ${record.job_id}: full-log evidence upload remains pending for daemon retry: ${error.message || String(error)}`);
225
+ return "pending";
226
+ }
227
+ }
53
228
  const delays = deps.completionRetryDelaysMs ?? UX_JOB_COMPLETION_RETRY_DELAYS_MS;
54
229
  const sleep = deps.sleep ?? defaultCompletionSleep;
55
230
  const route = `/machines/me/ux-jobs/${encodeURIComponent(record.job_id)}/complete`;
@@ -65,6 +240,14 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps)
65
240
  catch (error) {
66
241
  log(`UX job ${record.job_id}: completion was accepted, but its local retry record could not be removed: ${error.message}`);
67
242
  }
243
+ if (record.diagnostic_log_path) {
244
+ try {
245
+ rmSync(record.diagnostic_log_path, { force: true });
246
+ }
247
+ catch (error) {
248
+ log(`UX job ${record.job_id}: completion was accepted, but its redacted full log could not be removed: ${error.message}`);
249
+ }
250
+ }
68
251
  return "accepted";
69
252
  }
70
253
  catch (error) {
@@ -74,13 +257,25 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps)
74
257
  continue;
75
258
  }
76
259
  if (!retryableCompletionError(error)) {
77
- try {
78
- rmSync(path, { force: true });
260
+ if (record.diagnostic_log_path) {
261
+ record.refused_error = message;
262
+ try {
263
+ writeFileAtomic(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
264
+ }
265
+ catch (writeError) {
266
+ log(`UX job ${record.job_id}: refused completion could not be retained: ${writeError.message}`);
267
+ }
268
+ log(`UX job ${record.job_id}: completion report refused; diagnostic log retained at ${record.diagnostic_log_path}: ${message}`);
79
269
  }
80
- catch (removeError) {
81
- log(`UX job ${record.job_id}: server refused completion and its local retry record could not be removed: ${removeError.message}`);
270
+ else {
271
+ try {
272
+ rmSync(path, { force: true });
273
+ }
274
+ catch (removeError) {
275
+ log(`UX job ${record.job_id}: server refused completion and its local retry record could not be removed: ${removeError.message}`);
276
+ }
277
+ log(`UX job ${record.job_id}: completion report refused; saved result discarded: ${message}`);
82
278
  }
83
- log(`UX job ${record.job_id}: completion report refused; saved result discarded: ${message}`);
84
279
  return "refused";
85
280
  }
86
281
  log(`UX job ${record.job_id}: completion report remains pending after ${attempts} attempts: ${message}`);
@@ -90,7 +285,7 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps)
90
285
  return "pending";
91
286
  }
92
287
  /** Retry durable completion reports on each daemon reconciliation, including after a restart. */
93
- export async function retryPendingUxJobCompletions(machineClient, log, deps = {}) {
288
+ export async function retryPendingUxJobCompletions(machineClient, log, deps = {}, sessions = []) {
94
289
  const dir = deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions");
95
290
  if (!existsSync(dir))
96
291
  return;
@@ -117,7 +312,7 @@ export async function retryPendingUxJobCompletions(machineClient, log, deps = {}
117
312
  log(`UX job completion state ${name} was retained because it cannot be read: ${error.message}`);
118
313
  continue;
119
314
  }
120
- await sendStoredUxJobCompletion(machineClient, record, path, log, deps);
315
+ await sendStoredUxJobCompletion(machineClient, record, path, log, deps, sessions);
121
316
  }
122
317
  }
123
318
  /** The machine report identifies jobs that are still executing or have a durable result to resend. */
@@ -431,6 +626,8 @@ export function collectUxJobArtifacts(artifactsRoot) {
431
626
  }
432
627
  if (!entry.isFile())
433
628
  continue;
629
+ if (entry.name === UX_JOB_CHECKOUT_RETENTION_FILE)
630
+ continue;
434
631
  const contentType = guessType(entry.name);
435
632
  const kind = contentType.startsWith("image/")
436
633
  ? "screenshot"
@@ -479,21 +676,17 @@ async function defaultUploadEvidence(agentCreds, project, file) {
479
676
  return json.evidence.id;
480
677
  }
481
678
  function forwardLockedChunks(onOutput, onLine) {
482
- let tail = "";
679
+ let pending = "";
483
680
  return (text, final = false) => {
484
- const lines = (tail + text).split(/\r?\n/);
485
- const incomplete = lines.pop() ?? "";
486
- if (final) {
487
- tail = "";
488
- if (incomplete)
489
- lines.push(incomplete);
490
- }
491
- else {
492
- tail = incomplete.slice(-32_768);
493
- if (tail.trim())
494
- onOutput?.(tail);
495
- }
496
- for (const line of lines) {
681
+ pending += text;
682
+ const lines = pending.split(/\r?\n/);
683
+ pending = lines.pop() ?? "";
684
+ if (final && pending) {
685
+ lines.push(pending);
686
+ pending = "";
687
+ }
688
+ for (const rawLine of lines) {
689
+ const line = redactUxJobDiagnosticText(rawLine);
497
690
  if (line.trim())
498
691
  onOutput?.(line);
499
692
  onLine?.(line);
@@ -526,6 +719,7 @@ async function defaultRunWithLock(opts, agentClient, log) {
526
719
  }
527
720
  export async function executeUxJob(machineClient, job, ctx, deps = {}) {
528
721
  const runner = deps.runCommand ?? spawnAsyncCommand;
722
+ const nowMs = deps.now ?? Date.now;
529
723
  const runWithLock = deps.runWithLock ?? defaultRunWithLock;
530
724
  const uploadEvidence = deps.uploadEvidence ?? defaultUploadEvidence;
531
725
  const jobKind = job.job_kind ?? "ux";
@@ -575,15 +769,211 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
575
769
  let worktreeCreated = false;
576
770
  let resolvedHead = job.head;
577
771
  let logTail = "";
578
- const appendLog = (chunk) => {
579
- if (!chunk)
772
+ const uploadedIds = [];
773
+ const jobArtifactDir = join(jobWorktreeDir, "artifacts", "remote-jobs", job.id);
774
+ const diagnosticLogPath = diagnosticLogPathForJob(job.id, deps);
775
+ const diagnosticLogDir = dirname(diagnosticLogPath);
776
+ const stepTimeline = [];
777
+ let activeStep = null;
778
+ let fullLogBytes = 0;
779
+ let logPending = "";
780
+ const writeRedactedLog = (rawLine) => {
781
+ const redacted = redactUxJobDiagnosticText(rawLine);
782
+ if (!redacted)
580
783
  return;
581
- logTail = `${logTail}\n${chunk}`.trim();
784
+ const bytes = Buffer.byteLength(redacted, "utf8");
785
+ writeFileSync(diagnosticLogPath, redacted, { flag: "a", mode: 0o600 });
786
+ fullLogBytes += bytes;
787
+ if (activeStep)
788
+ activeStep.output += redacted;
789
+ logTail = `${logTail}${redacted}`;
582
790
  if (logTail.length > MAX_UX_JOB_LOG_TAIL)
583
791
  logTail = logTail.slice(-MAX_UX_JOB_LOG_TAIL);
792
+ ctx.log(redacted.trimEnd());
793
+ };
794
+ const appendLog = (chunk) => {
795
+ if (!chunk)
796
+ return;
797
+ logPending += chunk;
798
+ const lines = logPending.split(/\r?\n/);
799
+ logPending = lines.pop() ?? "";
800
+ for (const line of lines)
801
+ writeRedactedLog(`${line}\n`);
802
+ };
803
+ const flushLogPending = () => {
804
+ if (!logPending)
805
+ return;
806
+ writeRedactedLog(logPending);
807
+ logPending = "";
808
+ };
809
+ mkdirSync(diagnosticLogDir, { recursive: true, mode: 0o700 });
810
+ writeFileSync(diagnosticLogPath, "", { mode: 0o600 });
811
+ const diagnosticRunner = async (cmd, args, opts) => {
812
+ appendLog(`\n$ ${cmd} ${args.join(" ")}\n`);
813
+ let sawOut = false;
814
+ let sawErr = false;
815
+ const result = await runner(cmd, args, {
816
+ ...opts,
817
+ onStdoutChunk: (chunk) => { sawOut = true; appendLog(chunk); opts.onStdoutChunk?.(chunk); },
818
+ onStderrChunk: (chunk) => { sawErr = true; appendLog(chunk); opts.onStderrChunk?.(chunk); },
819
+ });
820
+ if (!sawOut && result.stdout)
821
+ appendLog(result.stdout);
822
+ if (!sawErr && result.stderr)
823
+ appendLog(result.stderr);
824
+ flushLogPending();
825
+ if (activeStep && result.status !== null)
826
+ activeStep.entry.exit_code = result.status;
827
+ return result;
828
+ };
829
+ const runStep = async (name, run, exitCode) => {
830
+ const entry = { name, started_at: new Date(nowMs()).toISOString(), duration_ms: 0, exit_code: null, output_tail: "" };
831
+ const active = { entry, output: "" };
832
+ stepTimeline.push(entry);
833
+ activeStep = active;
834
+ const started = nowMs();
835
+ try {
836
+ const result = await run();
837
+ const reported = exitCode?.(result);
838
+ if (reported !== undefined)
839
+ entry.exit_code = reported;
840
+ else if (entry.exit_code === null)
841
+ entry.exit_code = 0;
842
+ return result;
843
+ }
844
+ catch (error) {
845
+ flushLogPending();
846
+ const message = redactUxJobDiagnosticText(error.message || String(error));
847
+ appendLog(`${message}\n`);
848
+ if (entry.exit_code === null)
849
+ entry.exit_code = 1;
850
+ throw error;
851
+ }
852
+ finally {
853
+ entry.duration_ms = Math.max(0, nowMs() - started);
854
+ entry.output_tail = lastOutputLines(active.output);
855
+ activeStep = null;
856
+ }
857
+ };
858
+ const environmentFingerprint = async (lockedEnv, lockContext) => {
859
+ const executable = (command) => {
860
+ if (command.includes("/"))
861
+ return command.startsWith("/") ? command : null;
862
+ const result = spawnSync("which", [command], { cwd: baseDir ?? workRoot, env: lockedEnv, encoding: "utf8", timeout: 10_000 });
863
+ return result.status === 0 ? result.stdout.trim().split(/\r?\n/)[0] || null : null;
864
+ };
865
+ const version = (command) => {
866
+ const result = spawnSync(command, ["--version"], { cwd: baseDir ?? workRoot, env: lockedEnv, encoding: "utf8", timeout: 10_000 });
867
+ return result.status === 0 ? redactUxJobDiagnosticText(String(result.stdout ?? "").trim()).slice(0, 100) : null;
868
+ };
869
+ const npmVersion = version(npmBin);
870
+ const b9sCommand = b9sBin ?? "b9s";
871
+ const b9sVersion = version(b9sCommand);
872
+ const ports = {};
873
+ for (const key of ["PORT", "API_PORT", "VITE_PORT", "UX_PORT", "BSCHAT_API_PORT"]) {
874
+ const value = lockedEnv[key];
875
+ if (value && /^\\d{1,5}$/.test(value) && Number(value) >= 1 && Number(value) <= 65535)
876
+ ports[key] = Number(value);
877
+ }
878
+ return {
879
+ node: { version: process.version, path: process.execPath },
880
+ npm: { version: npmVersion, path: executable(npmBin) },
881
+ b9s: { version: b9sVersion, path: executable(b9sCommand) },
882
+ PATH: redactUxJobDiagnosticText(lockedEnv.PATH ?? ""),
883
+ slot: lockContext?.slot ?? null,
884
+ lock_job_id: lockContext?.jobId ?? null,
885
+ ports,
886
+ head: resolvedHead,
887
+ machine: ctx.machineName,
888
+ };
889
+ };
890
+ let fingerprint;
891
+ let checkoutPath = null;
892
+ let checkoutExpiresAt = null;
893
+ let checkoutRetentionNote = null;
894
+ let preserveCheckout = false;
895
+ const uploadedArtifacts = new Map();
896
+ let fullLogEvidenceId;
897
+ const fullLogUploadMetadata = (status) => {
898
+ const head = (resolvedHead ?? job.head ?? "unknown").slice(0, 9);
899
+ const taskTag = jobKind === "gate"
900
+ ? `gate ${status === "succeeded" ? "PASSED" : "FAILED"}`
901
+ : [job.task, job.compare_screen ? `compare-${job.compare_screen}` : null].filter(Boolean).join(" ");
902
+ const claim = jobKind === "gate"
903
+ ? `Complete-suite gate run (${status === "succeeded" ? "PASSED" : "FAILED"}) on ${ctx.machineName} at ${head} for WU #${job.work_unit_number}`
904
+ : `Seeded UX run (${jobTaskLabel}) on ${ctx.machineName} at ${head} for WU #${job.work_unit_number}`;
905
+ return {
906
+ project: job.project,
907
+ project_id: job.project_id,
908
+ filename: `remote-job-${job.id}.log`,
909
+ label: `WU #${job.work_unit_number} ${head} ${taskTag} remote-job-${job.id}.log`,
910
+ claim,
911
+ };
912
+ };
913
+ const determineCheckoutRetention = () => {
914
+ if (!worktreeCreated) {
915
+ checkoutRetentionNote = "No job checkout was created, so there is no checkout to retain.";
916
+ return;
917
+ }
918
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(job.id)) {
919
+ checkoutRetentionNote = "Failed checkout removed because the job ID is not a UUID safe for the retention manifest.";
920
+ return;
921
+ }
922
+ const disk = deps.diskSpace ? deps.diskSpace(jobWorktreeDir) : defaultJobDiskSpace(jobWorktreeDir);
923
+ const floorPct = Number.isInteger(ctx.diskFloorPct) && ctx.diskFloorPct >= 1 && ctx.diskFloorPct <= 90
924
+ ? ctx.diskFloorPct
925
+ : DEFAULT_UX_JOB_DISK_FLOOR_PCT;
926
+ if (!disk || disk.totalBytes <= 0) {
927
+ checkoutRetentionNote = `Failed checkout removed because free space could not be measured against the ${floorPct}% machine cache floor.`;
928
+ return;
929
+ }
930
+ const freePct = disk.freeBytes / disk.totalBytes * 100;
931
+ if (freePct < floorPct) {
932
+ checkoutRetentionNote = `Failed checkout removed because its volume had ${freePct.toFixed(1)}% free, below the ${floorPct}% machine cache floor.`;
933
+ return;
934
+ }
935
+ checkoutPath = jobWorktreeDir;
936
+ checkoutExpiresAt = new Date(nowMs() + UX_JOB_KEEP_MS).toISOString();
937
+ checkoutRetentionNote = `Failed checkout retained until ${checkoutExpiresAt}; its volume had ${freePct.toFixed(1)}% free against the ${floorPct}% machine cache floor.`;
938
+ const manifest = { version: 1, job_id: job.id, expires_at: checkoutExpiresAt };
939
+ writeFileSync(join(jobWorktreeDir, UX_JOB_CHECKOUT_RETENTION_FILE), `${JSON.stringify(manifest)}\n`, { mode: 0o600 });
940
+ preserveCheckout = true;
941
+ };
942
+ const uploadJobArtifacts = async (status) => {
943
+ flushLogPending();
944
+ if (fullLogBytes === 0)
945
+ appendLog("No child-process output was produced.\n");
946
+ flushLogPending();
947
+ // Upload the complete diagnostic log first. If a screenshot or task artifact upload
948
+ // later fails, the job still has its primary troubleshooting record attached.
949
+ const artifacts = [
950
+ { path: diagnosticLogPath, filename: `remote-job-${job.id}.log`, kind: "log", contentType: "text/plain" },
951
+ ...(worktreeCreated ? collectUxJobArtifacts(jobArtifactDir) : []),
952
+ ];
953
+ const taskTag = jobKind === "gate"
954
+ ? `gate ${status === "succeeded" ? "PASSED" : "FAILED"}`
955
+ : [job.task, job.compare_screen ? `compare-${job.compare_screen}` : null].filter(Boolean).join(" ");
956
+ const claim = jobKind === "gate"
957
+ ? `Complete-suite gate run (${status === "succeeded" ? "PASSED" : "FAILED"}) on ${ctx.machineName} at ${(resolvedHead ?? job.head ?? "unknown").slice(0, 9)} for WU #${job.work_unit_number}`
958
+ : `Seeded UX run (${jobTaskLabel}) on ${ctx.machineName} at ${(resolvedHead ?? job.head ?? "unknown").slice(0, 9)} for WU #${job.work_unit_number}`;
959
+ for (const artifact of artifacts) {
960
+ const alreadyUploaded = uploadedArtifacts.get(artifact.path);
961
+ if (alreadyUploaded) {
962
+ if (!uploadedIds.includes(alreadyUploaded))
963
+ uploadedIds.push(alreadyUploaded);
964
+ if (artifact.path === diagnosticLogPath)
965
+ fullLogEvidenceId = alreadyUploaded;
966
+ continue;
967
+ }
968
+ const label = `WU #${job.work_unit_number} ${(resolvedHead ?? job.head ?? "unknown").slice(0, 9)} ${taskTag} ${artifact.filename}`;
969
+ const evidenceId = await uploadEvidence(agentCreds, job.project, { ...artifact, label, claim });
970
+ uploadedArtifacts.set(artifact.path, evidenceId);
971
+ if (!uploadedIds.includes(evidenceId))
972
+ uploadedIds.push(evidenceId);
973
+ if (artifact.path === diagnosticLogPath)
974
+ fullLogEvidenceId = evidenceId;
975
+ }
584
976
  };
585
- const uploadedIds = [];
586
- const jobArtifactDir = join(jobWorktreeDir, "artifacts", "remote-jobs", job.id);
587
977
  try {
588
978
  if (jobKind === "ux") {
589
979
  if (job.task && !SLUG_RE.test(job.task))
@@ -594,13 +984,19 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
594
984
  else if (!job.head || !SHA_RE.test(job.head)) {
595
985
  throw new Error("gate job requires a candidate commit SHA");
596
986
  }
597
- baseDir = await resolveProjectRepoDir(job, ctx, runner, childEnv);
598
- resolvedHead = await prepareUxJobWorktree(baseDir, jobWorktreeDir, job.branch, job.head, runner, childEnv, {
599
- requireBranchAncestry: jobKind === "ux",
600
- fetchOrigin: jobKind === "gate",
601
- });
602
- worktreeCreated = true;
987
+ await runStep("worktree", async () => {
988
+ baseDir = await resolveProjectRepoDir(job, ctx, diagnosticRunner, childEnv);
989
+ resolvedHead = await prepareUxJobWorktree(baseDir, jobWorktreeDir, job.branch, job.head, diagnosticRunner, childEnv, {
990
+ requireBranchAncestry: jobKind === "ux",
991
+ fetchOrigin: jobKind === "gate",
992
+ });
993
+ worktreeCreated = true;
994
+ return resolvedHead;
995
+ }, () => 0);
996
+ if (!resolvedHead)
997
+ throw new Error("job worktree setup returned no resolved head");
603
998
  const shortHead = resolvedHead.slice(0, 9);
999
+ fingerprint = await environmentFingerprint(childEnv);
604
1000
  const agentClient = Client.forAgent(agentCreds, undefined, { presence: false });
605
1001
  const commandLabel = jobKind === "gate"
606
1002
  ? ["scripts/gate.sh", resolvedHead]
@@ -630,6 +1026,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
630
1026
  else
631
1027
  delete lockedEnv.B9S_LOCK_SLOT;
632
1028
  lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = jobArtifactDir;
1029
+ fingerprint = await environmentFingerprint(lockedEnv, lockContext);
633
1030
  const heartbeatController = new AbortController();
634
1031
  let heartbeatTimer;
635
1032
  let heartbeatInFlight;
@@ -654,45 +1051,35 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
654
1051
  return;
655
1052
  throw new CliError("lock_heartbeat_failed", `job ${lockContext?.jobId ?? job.id} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
656
1053
  };
657
- const runLockedStep = async (cmd, args, stepOpts) => {
1054
+ const runLockedStep = async (stepName, cmd, args, stepOpts) => {
658
1055
  throwIfHeartbeatFailed();
659
- let combined = "";
660
- let sawStdoutChunk = false;
661
- let sawStderrChunk = false;
662
- const pushStdout = forwardLockedChunks(stepOpts.omitOutput ? undefined : lockContext?.onOutput, stepOpts.onStdoutLine);
663
- const pushStderr = forwardLockedChunks(stepOpts.omitOutput ? undefined : lockContext?.onOutput);
664
- const res = await runner(cmd, args, {
665
- cwd: jobWorktreeDir,
666
- env: lockedEnv,
667
- timeoutMs: stepOpts.timeoutMs,
668
- signal: heartbeatController.signal,
669
- onStdoutChunk: (chunk) => {
670
- sawStdoutChunk = true;
671
- if (stepOpts.captureCombined)
672
- combined += chunk;
673
- pushStdout(chunk);
674
- },
675
- onStderrChunk: (chunk) => {
676
- sawStderrChunk = true;
677
- if (stepOpts.captureCombined)
678
- combined += chunk;
679
- pushStderr(chunk);
680
- },
681
- });
682
- if (!sawStdoutChunk && res.stdout) {
683
- if (stepOpts.captureCombined)
684
- combined += res.stdout;
685
- pushStdout(res.stdout);
686
- }
687
- if (!sawStderrChunk && res.stderr) {
688
- if (stepOpts.captureCombined)
689
- combined += res.stderr;
690
- pushStderr(res.stderr);
691
- }
692
- pushStdout("", true);
693
- pushStderr("", true);
694
- throwIfHeartbeatFailed();
695
- return { res, combined };
1056
+ return runStep(stepName, async () => {
1057
+ let combined = "";
1058
+ const pushStdout = forwardLockedChunks(stepOpts.omitOutput ? undefined : lockContext?.onOutput, stepOpts.onStdoutLine);
1059
+ const pushStderr = forwardLockedChunks(stepOpts.omitOutput ? undefined : lockContext?.onOutput);
1060
+ const res = await diagnosticRunner(cmd, args, {
1061
+ cwd: jobWorktreeDir,
1062
+ env: lockedEnv,
1063
+ timeoutMs: stepOpts.timeoutMs,
1064
+ signal: heartbeatController.signal,
1065
+ onStdoutChunk: (chunk) => {
1066
+ if (stepOpts.captureCombined)
1067
+ combined += chunk;
1068
+ pushStdout(chunk);
1069
+ },
1070
+ onStderrChunk: (chunk) => {
1071
+ if (stepOpts.captureCombined)
1072
+ combined += chunk;
1073
+ pushStderr(chunk);
1074
+ },
1075
+ });
1076
+ if (!res.stdout && !res.stderr && res.error)
1077
+ combined += `${res.error.message}\n`;
1078
+ pushStdout("", true);
1079
+ pushStderr("", true);
1080
+ throwIfHeartbeatFailed();
1081
+ return { res, combined };
1082
+ }, (result) => result.res.status);
696
1083
  };
697
1084
  const stepFailure = (label, result) => {
698
1085
  const cause = (result.stderr || result.error?.message || result.stdout || "no stderr or stdout").trim().slice(0, 320);
@@ -706,13 +1093,12 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
706
1093
  throw new Error(`scripts/gate.sh is missing at commit ${shortHead}`);
707
1094
  }
708
1095
  const scanner = createGateMarkerScanner();
709
- const { res: gateRes, combined: fullOutput } = await runLockedStep("/bin/sh", ["scripts/gate.sh", resolvedHead], {
1096
+ const { res: gateRes, combined: fullOutput } = await runLockedStep("gate", "/bin/sh", ["scripts/gate.sh", resolvedHead], {
710
1097
  timeoutMs: 1_800_000,
711
1098
  captureCombined: true,
712
1099
  onStdoutLine: (line) => scanner.push(`${line}\n`),
713
1100
  });
714
1101
  scanner.push("", true);
715
- appendLog(fullOutput || gateRes.stdout || gateRes.stderr);
716
1102
  const logDir = join(jobArtifactDir, "gate");
717
1103
  mkdirSync(logDir, { recursive: true });
718
1104
  gateLogFile = join(logDir, `gate-wu${job.work_unit_number}-${shortHead}.log`);
@@ -720,34 +1106,32 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
720
1106
  return { exit_code: gateRes.status ?? 1, ...scanner.result() };
721
1107
  }
722
1108
  if (job.compare_screen) {
723
- const registryFile = join(jobWorktreeDir, "docs/ux/screens/mocks/compare.json");
724
- if (!existsSync(registryFile)) {
725
- throw new Error(`compare registry docs/ux/screens/mocks/compare.json is missing at checkout ${shortHead}`);
726
- }
727
- const registry = JSON.parse(readFileSync(registryFile, "utf8"));
728
- const screenIds = new Set((registry.screens ?? []).map((item) => item.id).filter(Boolean));
729
- if (!screenIds.has(job.compare_screen)) {
730
- throw new Error(`compare screen ${job.compare_screen} is not registered in compare.json at ${shortHead}`);
731
- }
1109
+ const compareScreen = job.compare_screen;
1110
+ await runStep("compare registry", async () => {
1111
+ const registryFile = join(jobWorktreeDir, "docs/ux/screens/mocks/compare.json");
1112
+ if (!existsSync(registryFile)) {
1113
+ throw new Error(`compare registry docs/ux/screens/mocks/compare.json is missing at checkout ${shortHead}`);
1114
+ }
1115
+ const registry = JSON.parse(readFileSync(registryFile, "utf8"));
1116
+ const screenIds = new Set((registry.screens ?? []).map((item) => item.id).filter(Boolean));
1117
+ if (!screenIds.has(compareScreen)) {
1118
+ throw new Error(`compare screen ${compareScreen} is not registered in compare.json at ${shortHead}`);
1119
+ }
1120
+ return 0;
1121
+ }, () => 0);
732
1122
  }
733
- const { res: installRes } = await runLockedStep(npmBin, ["ci"], { timeoutMs: 600_000 });
734
- appendLog(installRes.stdout);
735
- appendLog(installRes.stderr);
1123
+ const { res: installRes } = await runLockedStep("npm ci", npmBin, ["ci"], { timeoutMs: 600_000 });
736
1124
  if (installRes.status !== 0)
737
1125
  throw stepFailure("npm ci", installRes);
738
1126
  if (jobKind === "ux") {
739
- const { res: cliBuildRes } = await runLockedStep(npmBin, ["run", "build", "-w", "packages/cli"], { timeoutMs: 300_000 });
740
- appendLog(cliBuildRes.stdout);
741
- appendLog(cliBuildRes.stderr);
1127
+ const { res: cliBuildRes } = await runLockedStep("CLI build", npmBin, ["run", "build", "-w", "packages/cli"], { timeoutMs: 300_000 });
742
1128
  if (cliBuildRes.status !== 0)
743
1129
  throw stepFailure("npm run build -w packages/cli", cliBuildRes);
744
1130
  if (job.task) {
745
- const { res: listed } = await runLockedStep("node", ["scripts/ux-console.mjs", "tasks"], {
1131
+ const { res: listed } = await runLockedStep("task listing", "node", ["scripts/ux-console.mjs", "tasks"], {
746
1132
  timeoutMs: 30_000,
747
1133
  omitOutput: true,
748
1134
  });
749
- appendLog(listed.stdout);
750
- appendLog(listed.stderr);
751
1135
  if (listed.status !== 0) {
752
1136
  throw stepFailure(`could not enumerate registered ux:task names in ${jobWorktreeDir}`, listed);
753
1137
  }
@@ -757,22 +1141,16 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
757
1141
  }
758
1142
  }
759
1143
  }
760
- const { res: seedRes } = await runLockedStep(npmBin, ["run", "ux:seed"], { timeoutMs: 300_000 });
761
- appendLog(seedRes.stdout);
762
- appendLog(seedRes.stderr);
1144
+ const { res: seedRes } = await runLockedStep("seed", npmBin, ["run", "ux:seed"], { timeoutMs: 300_000 });
763
1145
  if (seedRes.status !== 0)
764
1146
  return seedRes.status ?? 1;
765
1147
  if (job.task) {
766
- const { res: taskRes } = await runLockedStep(npmBin, ["run", "ux:task", "--", job.task], { timeoutMs: 600_000 });
767
- appendLog(taskRes.stdout);
768
- appendLog(taskRes.stderr);
1148
+ const { res: taskRes } = await runLockedStep("task", npmBin, ["run", "ux:task", "--", job.task], { timeoutMs: 600_000 });
769
1149
  if (taskRes.status !== 0)
770
1150
  return taskRes.status ?? 1;
771
1151
  }
772
1152
  if (job.compare_screen) {
773
- const { res: compareRes } = await runLockedStep(npmBin, ["run", "ux:compare", "--", job.compare_screen, "--unit", String(job.work_unit_number), "--widths", "1440,375"], { timeoutMs: 600_000 });
774
- appendLog(compareRes.stdout);
775
- appendLog(compareRes.stderr);
1153
+ const { res: compareRes } = await runLockedStep("compare", npmBin, ["run", "ux:compare", "--", job.compare_screen, "--unit", String(job.work_unit_number), "--widths", "1440,375"], { timeoutMs: 600_000 });
776
1154
  if (compareRes.status !== 0)
777
1155
  return compareRes.status ?? 1;
778
1156
  }
@@ -786,56 +1164,84 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
786
1164
  }
787
1165
  },
788
1166
  }, agentClient, ctx.log);
789
- const artifacts = collectUxJobArtifacts(jobArtifactDir);
790
- const taskTag = jobKind === "gate"
791
- ? `gate ${exitCode === 0 ? "PASSED" : "FAILED"}`
792
- : [job.task, job.compare_screen ? `compare-${job.compare_screen}` : null].filter(Boolean).join(" ");
793
- for (const artifact of artifacts) {
794
- const label = `WU #${job.work_unit_number} ${shortHead} ${taskTag} ${artifact.filename}`;
795
- const claim = jobKind === "gate"
796
- ? `Complete-suite gate run (${exitCode === 0 ? "PASSED" : "FAILED"}) on ${ctx.machineName} at ${shortHead} for WU #${job.work_unit_number}`
797
- : `Seeded UX run (${jobTaskLabel}) on ${ctx.machineName} at ${shortHead} for WU #${job.work_unit_number}`;
798
- const evidenceId = await uploadEvidence(agentCreds, job.project, {
799
- ...artifact,
800
- label,
801
- claim,
802
- });
803
- uploadedIds.push(evidenceId);
804
- }
805
1167
  if (exitCode !== 0) {
806
1168
  const errMsg = `${jobKind} job exited with code ${exitCode}${logTail ? `: ${logTail.slice(-280)}` : ""}`.slice(0, 500);
1169
+ determineCheckoutRetention();
1170
+ appendLog(`${errMsg}\n`);
1171
+ await uploadJobArtifacts("failed");
807
1172
  await reportUxJobCompletion(machineClient, job.id, {
808
1173
  status: "failed",
809
1174
  resolved_head: resolvedHead,
810
1175
  evidence_ids: uploadedIds,
811
- error: errMsg,
1176
+ full_log_evidence_id: fullLogEvidenceId,
1177
+ step_timeline: stepTimeline,
1178
+ environment_fingerprint: fingerprint,
1179
+ checkout_path: checkoutPath,
1180
+ checkout_expires_at: checkoutExpiresAt,
1181
+ checkout_retention_note: checkoutRetentionNote,
1182
+ error: redactUxJobDiagnosticText(errMsg),
812
1183
  log_excerpt: logTail || undefined,
813
- }, ctx.log, deps);
1184
+ }, ctx.log, deps, {
1185
+ path: diagnosticLogPath,
1186
+ pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("failed"),
1187
+ }, ctx.sessions);
814
1188
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
815
1189
  }
1190
+ await uploadJobArtifacts("succeeded");
816
1191
  await reportUxJobCompletion(machineClient, job.id, {
817
1192
  status: "succeeded",
818
1193
  resolved_head: resolvedHead,
819
1194
  evidence_ids: uploadedIds,
1195
+ full_log_evidence_id: fullLogEvidenceId,
1196
+ step_timeline: stepTimeline,
1197
+ environment_fingerprint: fingerprint,
1198
+ checkout_path: null,
1199
+ checkout_expires_at: null,
1200
+ checkout_retention_note: "Successful job checkout removed after artifact collection.",
820
1201
  log_excerpt: logTail || undefined,
821
- }, ctx.log, deps);
1202
+ }, ctx.log, deps, {
1203
+ path: diagnosticLogPath,
1204
+ pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("succeeded"),
1205
+ }, ctx.sessions);
822
1206
  ctx.log(`${jobKind} job ${job.id}: completed (${uploadedIds.length} artifact(s) posted for WU #${job.work_unit_number} at ${shortHead})`);
823
1207
  return { id: job.id, status: "succeeded", evidence_ids: uploadedIds, resolved_head: resolvedHead };
824
1208
  }
825
1209
  catch (error) {
826
- const message = (error.message || `${jobKind} job failed`).slice(0, 500);
1210
+ const message = redactUxJobDiagnosticText((error.message || `${jobKind} job failed`).slice(0, 500));
1211
+ // Once the complete log has been uploaded, later artifact-posting errors belong
1212
+ // in daemon output; mutating the local log would make its evidence stale.
1213
+ if (!fullLogEvidenceId)
1214
+ appendLog(`${message}\n`);
1215
+ else
1216
+ ctx.log(`UX job ${job.id}: ${message}`);
1217
+ determineCheckoutRetention();
1218
+ try {
1219
+ await uploadJobArtifacts("failed");
1220
+ }
1221
+ catch (uploadError) {
1222
+ appendLog(`full diagnostics evidence upload failed: ${redactUxJobDiagnosticText(uploadError.message || String(uploadError))}\n`);
1223
+ }
827
1224
  await reportUxJobCompletion(machineClient, job.id, {
828
1225
  status: "failed",
829
1226
  resolved_head: resolvedHead ?? undefined,
830
1227
  evidence_ids: uploadedIds,
1228
+ full_log_evidence_id: fullLogEvidenceId,
1229
+ step_timeline: stepTimeline,
1230
+ environment_fingerprint: fingerprint ?? await environmentFingerprint(childEnv),
1231
+ checkout_path: checkoutPath,
1232
+ checkout_expires_at: checkoutExpiresAt,
1233
+ checkout_retention_note: checkoutRetentionNote,
831
1234
  error: message,
832
1235
  log_excerpt: logTail || undefined,
833
- }, ctx.log, deps);
1236
+ }, ctx.log, deps, {
1237
+ path: diagnosticLogPath,
1238
+ pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("failed"),
1239
+ }, ctx.sessions);
834
1240
  ctx.log(`${jobKind} job ${job.id}: failed (${message})`);
835
1241
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: message };
836
1242
  }
837
1243
  finally {
838
- if (worktreeCreated && baseDir) {
1244
+ if (worktreeCreated && baseDir && !preserveCheckout) {
839
1245
  await cleanupUxJobWorktree(baseDir, jobWorktreeDir, runner, childEnv);
840
1246
  }
841
1247
  }