benignswarm 0.12.151 → 0.12.153

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 CHANGED
@@ -42,7 +42,7 @@ export const STRING_FLAGS = [
42
42
  export const BOOL_FLAGS = [
43
43
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
44
44
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
- "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
45
+ "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
47
  "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor", "overdue",
48
48
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only", "continue",
@@ -44,7 +44,7 @@ import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
44
44
  import { publishHostedImage } from "../hosted-registry.js";
45
45
  import { assumeHostedBuilder } from "../hosted-registry-session.js";
46
46
  import { pushHostedImage } from "../hosted-registry-push.js";
47
- import { reconcilePendingUxJobs, retryPendingUxJobCompletions, uxJobIdsForMachineReport } from "../ux-jobs.js";
47
+ import { reconcilePendingUxJobs, retryPendingUxJobCompletions, sweepExpiredUxJobWorktrees, uxJobIdsForMachineReport } from "../ux-jobs.js";
48
48
  export const machineFile = () => join(configRoot(), "machine.json");
49
49
  export function loadMachine() {
50
50
  const f = machineFile();
@@ -2003,7 +2003,19 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2003
2003
  active_ux_job_ids: uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps),
2004
2004
  ...(imageProbes.length ? { image_probes: imageProbes } : {}),
2005
2005
  });
2006
- await retryPendingUxJobCompletions(client, log, deps?.uxJobDeps);
2006
+ const uxSessionHints = desired.map((session) => ({
2007
+ id: session.id,
2008
+ agent: session.agent,
2009
+ agent_name: session.agent_name,
2010
+ project: session.project,
2011
+ project_id: session.project_id ?? null,
2012
+ dir: session.dir,
2013
+ desired: session.desired,
2014
+ benched_at: session.benched_at ?? null,
2015
+ retired_at: null,
2016
+ }));
2017
+ await retryPendingUxJobCompletions(client, log, deps?.uxJobDeps, uxSessionHints);
2018
+ await sweepExpiredUxJobWorktrees(workdir ?? join(homedir(), "bschat"), projects, undefined, process.env, log, Date.now(), (jobId) => client.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(jobId)}/checkout-removed`, {}));
2007
2019
  for (const item of probedProjects) {
2008
2020
  lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
2009
2021
  }
@@ -2015,6 +2027,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2015
2027
  accountId,
2016
2028
  machineName: m.name,
2017
2029
  workdir,
2030
+ diskFloorPct: me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT,
2018
2031
  sessions: desired.map((s) => ({
2019
2032
  id: s.id,
2020
2033
  agent: s.agent,
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { bool, str } from "../args.js";
2
3
  import { Client } from "../client.js";
3
4
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
@@ -5,6 +6,35 @@ import { CliError } from "../errors.js";
5
6
  import { collectAuto } from "../git.js";
6
7
  import { table } from "../output.js";
7
8
  import { projectOf } from "./agent.js";
9
+ async function printJob(job, res, p, out, creds, client, project) {
10
+ if (!bool(p.flags, "log")) {
11
+ out.print(formatJob(job), res);
12
+ return;
13
+ }
14
+ const evidenceId = job.full_log_evidence_id;
15
+ if (typeof evidenceId !== "string" || !evidenceId) {
16
+ throw new CliError("log_unavailable", "this job has no uploaded full-log evidence");
17
+ }
18
+ const response = await fetch(`${creds.url}/projects/${encodeURIComponent(project)}/evidence/${encodeURIComponent(evidenceId)}/content`, {
19
+ headers: client.headers(),
20
+ });
21
+ if (!response.ok) {
22
+ let message = `full-log download failed (HTTP ${response.status})`;
23
+ try {
24
+ const body = await response.json();
25
+ if (typeof body.message === "string")
26
+ message = body.message;
27
+ }
28
+ catch { }
29
+ throw new CliError(`http_${response.status}`, message);
30
+ }
31
+ const bytes = Buffer.from(await response.arrayBuffer());
32
+ const expected = response.headers.get("x-bschat-sha256") ?? "";
33
+ const actual = createHash("sha256").update(bytes).digest("hex");
34
+ if (!expected || actual !== expected)
35
+ throw new CliError("checksum_mismatch", `full-log bytes hash to ${actual} but server says ${expected || "no checksum"}`);
36
+ process.stdout.write(bytes);
37
+ }
8
38
  function formatJob(job) {
9
39
  const isGate = job.job_kind === "gate";
10
40
  const what = isGate
@@ -16,7 +46,32 @@ function formatJob(job) {
16
46
  : "";
17
47
  const errorLine = job.error ? `\nError: ${job.error}` : "";
18
48
  const kindLabel = isGate ? "Gate" : "UX";
19
- return `${kindLabel} job ${job.id} [${job.status}] on ${job.machine} for WU #${job.work_unit_number}\nTask: ${what}\nBranch: ${job.branch} @ ${headText}${evidenceLine}${errorLine}`;
49
+ const fullLogLine = job.full_log_evidence_id ? `\nFull log: evidence:${job.full_log_evidence_id} (use --log to print)` : "\nFull log: unavailable";
50
+ const steps = Array.isArray(job.step_timeline) && job.step_timeline.length
51
+ ? `\nSteps:\n${table(job.step_timeline.map((step) => ({
52
+ step: step.name,
53
+ started: step.started_at,
54
+ duration_ms: step.duration_ms,
55
+ exit: step.exit_code ?? "unknown",
56
+ })), ["step", "started", "duration_ms", "exit"])}`
57
+ : "";
58
+ const failedStep = Array.isArray(job.step_timeline) ? [...job.step_timeline].reverse().find((step) => step.exit_code !== null && step.exit_code !== undefined && step.exit_code !== 0) : undefined;
59
+ const failedTail = failedStep?.output_tail ? `\nFailed step (${failedStep.name}) output tail:\n${failedStep.output_tail}` : "";
60
+ const fingerprint = job.environment_fingerprint && typeof job.environment_fingerprint === "object"
61
+ ? `\nEnvironment: node ${job.environment_fingerprint.node?.version ?? "unknown"} (${job.environment_fingerprint.node?.path ?? "path unknown"}); npm ${job.environment_fingerprint.npm?.version ?? "unknown"} (${job.environment_fingerprint.npm?.path ?? "path unknown"}); b9s ${job.environment_fingerprint.b9s?.version ?? "unknown"} (${job.environment_fingerprint.b9s?.path ?? "path unknown"}); slot ${job.environment_fingerprint.slot ?? "unknown"}; lock ${job.environment_fingerprint.lock_job_id ?? "unknown"}; ports ${JSON.stringify(job.environment_fingerprint.ports ?? {})}; PATH ${job.environment_fingerprint.PATH ?? "unknown"}`
62
+ : "";
63
+ let checkoutLine = "";
64
+ if (job.checkout_path) {
65
+ if (job.checkout_removed_at)
66
+ checkoutLine = `\nCheckout: removed at ${job.checkout_removed_at} (${job.checkout_path})`;
67
+ else if (job.checkout_expires_at && Date.parse(job.checkout_expires_at) <= Date.now())
68
+ checkoutLine = `\nCheckout: retention expired at ${job.checkout_expires_at}; daemon cleanup not yet reported (${job.checkout_path})`;
69
+ else
70
+ checkoutLine = `\nCheckout: retained at ${job.checkout_path}${job.checkout_expires_at ? ` until ${job.checkout_expires_at}` : ""}`;
71
+ }
72
+ else if (job.checkout_retention_note)
73
+ checkoutLine = `\nCheckout: ${job.checkout_retention_note}`;
74
+ return `${kindLabel} job ${job.id} [${job.status}] on ${job.machine} for WU #${job.work_unit_number}\nTask: ${what}\nBranch: ${job.branch} @ ${headText}${steps}${failedTail}${fingerprint}${checkoutLine}${evidenceLine}${fullLogLine}${errorLine}`;
20
75
  }
21
76
  export async function ux(p, out) {
22
77
  const sub = p.positionals[1];
@@ -65,9 +120,9 @@ export async function ux(p, out) {
65
120
  if (sub === "job") {
66
121
  const id = p.positionals[2]?.trim();
67
122
  if (!id)
68
- throw new CliError("usage", "b9s ux job <id>");
123
+ throw new CliError("usage", "b9s ux job <id> [--log]");
69
124
  const res = await client.call("GET", `/projects/${project}/ux-jobs/${encodeURIComponent(id)}`);
70
- out.print(formatJob(res.job), res);
125
+ await printJob(res.job, res, p, out, creds, client, project);
71
126
  return;
72
127
  }
73
128
  if (sub === "jobs") {
@@ -124,9 +179,9 @@ export async function gate(p, out) {
124
179
  if (sub === "job") {
125
180
  const id = p.positionals[2]?.trim();
126
181
  if (!id)
127
- throw new CliError("usage", "b9s gate job <id>");
182
+ throw new CliError("usage", "b9s gate job <id> [--log]");
128
183
  const res = await client.call("GET", `/projects/${project}/gate-jobs/${encodeURIComponent(id)}`);
129
- out.print(formatJob(res.job), res);
184
+ await printJob(res.job, res, p, out, creds, client, project);
130
185
  return;
131
186
  }
132
187
  if (sub === "jobs") {
@@ -1041,6 +1041,7 @@ export async function wu(p, out) {
1041
1041
  case "proceed":
1042
1042
  case "changes": {
1043
1043
  const note = str(p.flags, "note");
1044
+ const reviewedHead = str(p.flags, "head");
1044
1045
  const unmet = str(p.flags, "unmet");
1045
1046
  const plainSummary = str(p.flags, "plain-summary") ?? str(p.flags, "summary");
1046
1047
  if (!note)
@@ -1050,7 +1051,27 @@ export async function wu(p, out) {
1050
1051
  throw new CliError("usage", 'wu changes <n> --cause <scope_gap|missing_context|worker_error|reviewer_scope_growth|environment|stale_base> --unmet "<cited clause>" --note "what must change"');
1051
1052
  if (sub === "changes" && !plainSummary?.trim())
1052
1053
  throw new CliError("usage", 'wu changes <n> --summary "plain explanation of the revision" --cause <cause> --unmet "<cited clause>" --note "what must change"');
1053
- const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, usage: await reviewUsage(client, project, name), ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "changes" ? { plain_summary: plainSummary } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
1054
+ let reviewedHeadProof = {};
1055
+ if (sub === "approve" && reviewedHead === undefined) {
1056
+ const detail = await client.call("GET", `${base}/${num()}`);
1057
+ if (detail.unit?.head)
1058
+ throw new CliError("usage", 'wu approve <n> --head <exact-reviewed-full-sha> --note "what you checked" (code-backed work requires the SHA you reviewed; source-free work may omit --head)');
1059
+ }
1060
+ if (reviewedHead !== undefined) {
1061
+ if (sub !== "approve" || !/^[0-9a-f]{40}$/.test(reviewedHead))
1062
+ throw new CliError("usage", 'wu approve <n> --head <full-40-character-lowercase-sha> --note "what you checked"');
1063
+ const detail = await client.call("GET", `${base}/${num()}`);
1064
+ if (!detail.unit.branch)
1065
+ throw new CliError("no_branch", `WU #${num()} has no recorded branch to verify the reviewed head`);
1066
+ const repository = await client.call("GET", `${base}/${num()}/head-verification`);
1067
+ if (repository.branch !== detail.unit.branch || typeof repository.repository_identity !== "string" || typeof repository.repository_url !== "string")
1068
+ throw new CliError("origin_verification_failed", `WU #${num()} did not provide its recorded branch and project repository identity`);
1069
+ const proof = verifyUnitHeadOnOrigin(detail.unit.branch, reviewedHead, repository.repository_identity, repository.repository_url);
1070
+ if (detail.unit.head && isAncestor(detail.unit.head, reviewedHead) !== true)
1071
+ throw new CliError("stale_review_head", `reviewed head ${reviewedHead} does not contain the currently recorded head ${detail.unit.head}`);
1072
+ reviewedHeadProof = { head: reviewedHead, expected_head: detail.unit.head, remote_tip: proof.remote_tip, repository_identity: proof.repository_identity };
1073
+ }
1074
+ const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, usage: await reviewUsage(client, project, name), ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "changes" ? { plain_summary: plainSummary } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}), ...reviewedHeadProof });
1054
1075
  out.print(withRuleText(fmt(r.unit), r, sub === "approve" ? "merge" : "verdict"), r);
1055
1076
  return;
1056
1077
  }
@@ -1137,6 +1158,13 @@ export async function wu(p, out) {
1137
1158
  if (!checked.on)
1138
1159
  throw new CliError("not_merged", `${merged} is not on ${checked.ref}`, "Merge first, then pass the merge commit (or the branch head once it is on the target).");
1139
1160
  }
1161
+ if (unit.approved_head) {
1162
+ const containsApprovedHead = isAncestor(unit.approved_head, merged);
1163
+ if (containsApprovedHead === null)
1164
+ throw new CliError("unknown_commit", `cannot verify that merge commit ${merged} contains approved head ${unit.approved_head}`, "Fetch the approved head and merge commit, then retry.");
1165
+ if (!containsApprovedHead)
1166
+ throw new CliError("not_approved_head", `merge commit ${merged} does not contain approved head ${unit.approved_head}`, "Merge the approved head into the target branch before closing the unit.");
1167
+ }
1140
1168
  }
1141
1169
  else if (def.merge.require_merge_commit) {
1142
1170
  throw new CliError("usage", `this project's process requires the merge commit: b9s wu done ${num()} --merged <sha>`);
package/dist/git.js CHANGED
@@ -641,7 +641,22 @@ export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), re
641
641
  }
642
642
  // Check ancestry against the advertised object ID, not a mutable tracking ref. A concurrent
643
643
  // fetch can move that ref between checking its tip and asking Git about containment.
644
- const branches = [...advertisedTips].filter(([branch, tip]) => branch !== `${remote}/HEAD` && remoteTrackingRefContainsCommit(branch, tip, sha, cwd)).map(([branch]) => branch).sort();
644
+ // The unit's own branch first: it is nearly always the one, and checking it costs two git calls.
645
+ const ownTip = advertisedTips.get(checkedRef);
646
+ if (ownTip && remoteTrackingRefContainsCommit(checkedRef, ownTip, sha, cwd)) {
647
+ return { remoteBranch: checkedRef, advertisedTip: ownTip, checkedRef, checked: true, reason: null };
648
+ }
649
+ // Otherwise ask Git once which remote-tracking refs contain the commit, then verify only those
650
+ // against their advertised tips. Checking every advertised branch one by one ran 1,542 git
651
+ // processes for 771 branches (238 s on 2026-11-21), long enough for the API connection opened
652
+ // before it to go stale, so wu submit failed with "fetch failed".
653
+ const containing = spawnSync("git", ["for-each-ref", "--contains", sha, "--format=%(refname:short)", `refs/remotes/${remote}/`], { cwd, encoding: "utf8", timeout: 60_000 });
654
+ if (containing.status !== 0) {
655
+ const detail = (containing.stderr || containing.stdout || `git for-each-ref exited with status ${containing.status ?? "unknown"}`).trim();
656
+ return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git for-each-ref --contains ${sha} failed: ${detail}` };
657
+ }
658
+ const candidates = new Set(containing.stdout.split("\n").map((line) => line.trim()).filter(Boolean));
659
+ const branches = [...advertisedTips].filter(([branch, tip]) => branch !== `${remote}/HEAD` && candidates.has(branch) && remoteTrackingRefContainsCommit(branch, tip, sha, cwd)).map(([branch]) => branch).sort();
645
660
  const remoteBranch = branches.includes(checkedRef) ? checkedRef : branches[0] ?? null;
646
661
  return remoteBranch
647
662
  ? { remoteBranch, advertisedTip: advertisedTips.get(remoteBranch), checkedRef, checked: true, reason: null }
package/dist/help.js CHANGED
@@ -159,8 +159,9 @@ Machine placement enforces configured session slots and reports machine pressure
159
159
  b9s wu review <n> reviewer's checkout: fetch the submitted branch from origin and open
160
160
  ../<repo>-review-wu<n> detached at the submitted head (refused if origin differs)
161
161
  b9s wu reviewer <n> --replace <agent> [--with <agent>] --note "why" assigner or operator: replace an owing reviewer with an available qualified reviewer; audited and announced (console control WU #733)
162
- b9s wu approve <n> --note ".." [--confirm-causes cause,cause] approval covers tags your role reviews (escalated or away-takeover reviewers cover only their handed-over tags); complete approval confirms classified send-back causes in timeline order
163
- a planned reviewer still owing may approve after coverage; status stays approved until merge
162
+ b9s wu approve <n> --head <exact-reviewed-full-sha> --note ".." [--confirm-causes cause,cause]
163
+ code-backed approval records the reviewed head; source-free work may omit --head; escalated or away-takeover reviewers cover only their handed-over tags
164
+ complete approval confirms send-back causes in timeline order; a planned reviewer may approve after coverage; status stays approved until merge
164
165
  b9s wu changes <n> --unmet ".." --cause <cause> --note ".." [--summary "..." | --plain-summary "..."] send back with a cited clause, cause and stored explanation (scope_gap, missing_context, worker_error, reviewer_scope_growth, environment, stale_base)
165
166
  concerns outside those are notes (wu note) or questions (wu ask)
166
167
  b9s wu classify <n> --tags a,b classifier: confirm or change a new unit's tags before it routes for review
@@ -315,11 +316,11 @@ Machine placement enforces configured session slots and reports machine pressure
315
316
  b9s test-results show <run-id> show the stored run, outcome counts, and original report evidence
316
317
  b9s ux run [<task>] [--compare <screen>] --unit <n> [--on <machine>] [--head <sha>]
317
318
  queue a remote seeded browser task or ux:compare on an account machine labeled ux-host or browser
318
- b9s ux job <id> inspect a queued, running or finished remote browser job and its evidence
319
+ b9s ux job <id> [--log] inspect remote browser job diagnostics; --log prints its full log
319
320
  b9s ux jobs [--unit <n>] [--limit n] list remote browser jobs in this project
320
321
  b9s gate run <n> [--merge-candidate <sha>] --on <machine>
321
322
  queue a complete-suite gate run on a machine; records the receipt and posts the log as evidence
322
- b9s gate job <id> inspect a queued, running or finished remote gate job and its evidence
323
+ b9s gate job <id> [--log] inspect remote gate diagnostics; --log prints its full log
323
324
  b9s gate jobs [--unit <n>] [--limit n] list remote gate jobs in this project
324
325
  b9s retire --title t (--body b | --body-file f) [--handoff-to @x|@role:y] [--evidence id,id] --yes
325
326
  save a RESUME or HANDOFF note, revoke keys and remove machine sessions; revival does not restore sessions
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
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.151";
1
+ export const CLI_VERSION = "0.12.153";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.151",
3
+ "version": "0.12.153",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {