benignswarm 0.12.164 → 0.12.166

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,9 +1,10 @@
1
1
  import { evidenceTextHeaders } from "./evidence-text.js";
2
- import { createHash, randomBytes } from "node:crypto";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
4
  import { spawn, spawnSync } from "node:child_process";
4
5
  import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
5
6
  import { homedir } from "node:os";
6
- import { basename, dirname, join } from "node:path";
7
+ import { basename, dirname, join, relative } from "node:path";
7
8
  import { Client } from "./client.js";
8
9
  import { agentRef, configRoot, loadAgent, listSaved } from "./config.js";
9
10
  import { guessType } from "./commands/evidence.js";
@@ -15,11 +16,12 @@ import { isolatedSubprocessEnv } from "./container.js";
15
16
  import { writeFileAtomic } from "./shared-file.js";
16
17
  import { runMergeTrainWorkflow } from "./merge-train.js";
17
18
  import { retryGitFetch } from "./git-fetch.js";
19
+ import { recordMachineNetworkRequest } from "./machine-network-health.js";
18
20
  const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
19
21
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
20
22
  const MAX_UX_JOB_LOG_TAIL = 2000;
21
23
  export const UX_JOBS_MAX_CONCURRENT = 3;
22
- const UX_JOB_COMPLETION_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000];
24
+ const UX_JOB_COMPLETION_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000, 60_000, 60_000, 60_000];
23
25
  const UX_JOB_KEEP_MS = 6 * 60 * 60 * 1000;
24
26
  const UX_JOB_CHECKOUT_RETENTION_FILE = ".b9s-ux-job-retention.json";
25
27
  const DEFAULT_UX_JOB_DISK_FLOOR_PCT = 15;
@@ -86,7 +88,23 @@ export async function sweepExpiredUxJobWorktrees(workRoot, projects, runner = sp
86
88
  unlinkSync(markerPath);
87
89
  }
88
90
  catch (error) {
89
- log(`expired failed UX job checkout ${marker.job_id} was removed locally, but its API record was not updated: ${error.message}`);
91
+ const msg = error.message ?? "";
92
+ // Terminal 404/403/409 (other than "not expired") means the server has no retained checkout
93
+ // left to clear; drop the stale local marker so the daemon stops retrying every heartbeat.
94
+ const isPermanent = (/\b(404|403)\b/.test(msg) ||
95
+ (/\b409\b/.test(msg) && !/not expired/i.test(msg)) ||
96
+ /only failed jobs with a retained checkout/i.test(msg) ||
97
+ /ux job not found/i.test(msg));
98
+ if (isPermanent) {
99
+ try {
100
+ unlinkSync(markerPath);
101
+ }
102
+ catch { /* ignore */ }
103
+ log(`cleared stale UX job checkout-removed marker ${marker.job_id} (${msg})`);
104
+ }
105
+ else {
106
+ log(`expired failed UX job checkout ${marker.job_id} was removed locally, but its API record was not updated: ${msg}`);
107
+ }
90
108
  }
91
109
  }
92
110
  }
@@ -159,6 +177,32 @@ function diagnosticLogPathForJob(jobId, deps) {
159
177
  const name = createHash("sha256").update(jobId).digest("hex");
160
178
  return join(deps.diagnosticLogRoot ?? join(configRoot(), "state", "ux-job-logs"), `${name}.log`);
161
179
  }
180
+ function passedTrainGateDir(deps) {
181
+ return join(deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions"), "passed-gates");
182
+ }
183
+ function passedTrainGatePath(jobId, deps) {
184
+ const name = createHash("sha256").update(jobId).digest("hex");
185
+ return join(passedTrainGateDir(deps), `${name}.json`);
186
+ }
187
+ function savePassedTrainGate(record, deps) {
188
+ writeFileAtomic(passedTrainGatePath(record.job.id, deps), `${JSON.stringify(record)}\n`, { mode: 0o600 });
189
+ }
190
+ function removePassedTrainGate(jobId, deps) {
191
+ rmSync(passedTrainGatePath(jobId, deps), { force: true });
192
+ }
193
+ function pendingClaimDir(deps) {
194
+ return join(deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions"), "claims");
195
+ }
196
+ function pendingClaimPath(jobId, deps) {
197
+ const name = createHash("sha256").update(jobId).digest("hex");
198
+ return join(pendingClaimDir(deps), `${name}.json`);
199
+ }
200
+ function savePendingClaim(record, deps) {
201
+ writeFileAtomic(pendingClaimPath(record.job.id, deps), `${JSON.stringify(record)}\n`, { mode: 0o600 });
202
+ }
203
+ function removePendingClaim(jobId, deps) {
204
+ rmSync(pendingClaimPath(jobId, deps), { force: true });
205
+ }
162
206
  function completionErrorCode(error) {
163
207
  const code = error && typeof error === "object" && "code" in error ? String(error.code) : null;
164
208
  return code;
@@ -169,10 +213,18 @@ function completionHttpStatus(error) {
169
213
  : null;
170
214
  }
171
215
  function retryableCompletionError(error) {
172
- const code = completionErrorCode(error);
173
- const status = error && typeof error === "object" && "httpStatus" in error ? Number(error.httpStatus) : null;
174
- return code === "network" || (status !== null && status >= 500 && status <= 599)
175
- || (code !== null && /^http_5\d\d$/.test(code));
216
+ const seen = new Set();
217
+ let current = error;
218
+ while (current && !seen.has(current)) {
219
+ seen.add(current);
220
+ const code = completionErrorCode(current);
221
+ const status = current && typeof current === "object" && "httpStatus" in current ? Number(current.httpStatus) : null;
222
+ if (code === "network" || code === "request_timeout" || (status !== null && status >= 500 && status <= 599)
223
+ || (code !== null && /^http_5\d\d$/.test(code)))
224
+ return true;
225
+ current = current && typeof current === "object" && "cause" in current ? current.cause : undefined;
226
+ }
227
+ return false;
176
228
  }
177
229
  function defaultCompletionSleep(ms) {
178
230
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -248,6 +300,7 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps,
248
300
  contentType: "text/plain",
249
301
  label: record.pending_full_log.label,
250
302
  claim: record.pending_full_log.claim,
303
+ idempotencyKey: record.pending_full_log.idempotency_key ?? uxEvidenceIdempotencyKey(record.job_id, "diagnostic-log"),
251
304
  });
252
305
  record.body = {
253
306
  ...record.body,
@@ -265,14 +318,18 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps,
265
318
  const delays = deps.completionRetryDelaysMs ?? UX_JOB_COMPLETION_RETRY_DELAYS_MS;
266
319
  const sleep = deps.sleep ?? defaultCompletionSleep;
267
320
  const route = `/machines/me/ux-jobs/${encodeURIComponent(record.job_id)}/complete`;
321
+ const reportDeadline = (deps.now ?? Date.now)() + 5 * 60_000;
268
322
  const attempts = delays.length + 1;
269
323
  for (let attempt = 0; attempt < attempts; attempt++) {
270
- if (attempt > 0)
324
+ if (attempt > 0) {
325
+ const remaining = reportDeadline - (deps.now ?? Date.now)();
326
+ if (remaining <= 0)
327
+ break;
271
328
  await reconcileCancellation();
272
- if (attempt > 0)
273
- await sleep(delays[attempt - 1]);
329
+ await sleep(Math.min(delays[attempt - 1], remaining));
330
+ }
274
331
  try {
275
- await machineClient.call("POST", route, record.body);
332
+ await machineClient.call("POST", route, record.body, { retryForMs: Math.max(0, reportDeadline - (deps.now ?? Date.now)()) });
276
333
  try {
277
334
  rmSync(path, { force: true });
278
335
  }
@@ -300,7 +357,7 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps,
300
357
  log(`UX job ${record.job_id}: cancellation is waiting for the machine lock to be released`);
301
358
  return "pending";
302
359
  }
303
- if (retryableCompletionError(error) && attempt + 1 < attempts) {
360
+ if (retryableCompletionError(error) && attempt + 1 < attempts && (deps.now ?? Date.now)() < reportDeadline) {
304
361
  log(`UX job ${record.job_id}: completion report attempt ${attempt + 1}/${attempts} failed; retrying: ${message}`);
305
362
  continue;
306
363
  }
@@ -711,20 +768,66 @@ async function defaultUploadEvidence(agentCreds, project, file) {
711
768
  if (bytes.length === 0)
712
769
  throw new Error(`artifact ${file.filename} is empty`);
713
770
  const sha = createHash("sha256").update(bytes).digest("hex");
714
- const client = Client.forAgent(agentCreds, undefined, { presence: false });
771
+ const client = Client.forAgent(agentCreds, undefined, {
772
+ presence: false,
773
+ requestTimeoutMs: 30_000,
774
+ retryForMs: 5 * 60_000,
775
+ onRequest: (event) => { if (event.phase === "end")
776
+ recordMachineNetworkRequest(event); },
777
+ });
715
778
  const headers = {
716
779
  ...client.headers(),
717
780
  "content-type": file.contentType,
718
781
  "x-bschat-sha256": sha,
719
782
  "x-bschat-filename": file.filename,
720
783
  "x-bschat-kind": file.kind,
784
+ "x-bschat-idempotency-key": file.idempotencyKey,
721
785
  ...await evidenceTextHeaders(client, project, { label: file.label.slice(0, 500), claim: file.claim.slice(0, 300) }),
722
786
  };
723
- const res = await fetch(`${agentCreds.url}/projects/${encodeURIComponent(project)}/evidence`, {
724
- method: "POST",
725
- headers,
726
- body: new Uint8Array(bytes),
727
- });
787
+ const deadline = Date.now() + 5 * 60_000;
788
+ let attempt = 0;
789
+ let lastError;
790
+ let res;
791
+ for (;;) {
792
+ if (attempt > 0 && Date.now() >= deadline)
793
+ throw lastError ?? new Error("evidence upload retry window expired");
794
+ try {
795
+ res = await fetch(`${agentCreds.url}/projects/${encodeURIComponent(project)}/evidence`, {
796
+ method: "POST",
797
+ headers,
798
+ body: new Uint8Array(bytes),
799
+ signal: AbortSignal.timeout(Math.max(1, Math.min(30_000, deadline - Date.now()))),
800
+ });
801
+ }
802
+ catch (error) {
803
+ lastError = error instanceof Error ? error : new Error(String(error));
804
+ const evidencePath = `/projects/${encodeURIComponent(project)}/evidence`;
805
+ recordMachineNetworkRequest({ phase: "end", method: "POST", path: evidencePath, attempt: attempt + 1, error: lastError.message });
806
+ process.stderr.write(`b9s: POST ${evidencePath} attempt ${attempt + 1} failed (network error)${Date.now() < deadline ? "; retrying" : "; retry window exhausted"}\n`);
807
+ if (Date.now() >= deadline)
808
+ throw error;
809
+ const delay = Math.min(8000, 500 * 2 ** Math.min(attempt++, 4), deadline - Date.now());
810
+ if (delay <= 0)
811
+ throw error;
812
+ await new Promise((resolve) => setTimeout(resolve, delay));
813
+ continue;
814
+ }
815
+ if (res.status >= 500) {
816
+ lastError = new Error(`evidence upload failed (${res.status})`);
817
+ const evidencePath = `/projects/${encodeURIComponent(project)}/evidence`;
818
+ recordMachineNetworkRequest({ phase: "end", method: "POST", path: evidencePath, attempt: attempt + 1, error: `http_${res.status}` });
819
+ process.stderr.write(`b9s: POST ${evidencePath} attempt ${attempt + 1} failed (HTTP ${res.status})${Date.now() < deadline ? "; retrying" : "; retry window exhausted"}\n`);
820
+ }
821
+ else {
822
+ recordMachineNetworkRequest({ phase: "end", method: "POST", path: `/projects/${encodeURIComponent(project)}/evidence`, attempt: attempt + 1 });
823
+ }
824
+ if (res.status < 500 || Date.now() >= deadline)
825
+ break;
826
+ const delay = Math.min(8000, 500 * 2 ** Math.min(attempt++, 4), deadline - Date.now());
827
+ if (delay <= 0)
828
+ break;
829
+ await new Promise((resolve) => setTimeout(resolve, delay));
830
+ }
728
831
  const text = await res.text();
729
832
  let json;
730
833
  try {
@@ -738,6 +841,9 @@ async function defaultUploadEvidence(agentCreds, project, file) {
738
841
  }
739
842
  return json.evidence.id;
740
843
  }
844
+ function uxEvidenceIdempotencyKey(jobId, artifactPath) {
845
+ return createHash("sha256").update(`${jobId}\0${artifactPath}`).digest("hex");
846
+ }
741
847
  function forwardLockedChunks(onOutput, onLine) {
742
848
  let pending = "";
743
849
  return (text, final = false) => {
@@ -759,7 +865,10 @@ function forwardLockedChunks(onOutput, onLine) {
759
865
  async function defaultRunWithLock(opts, agentClient, log) {
760
866
  const token = opts.remoteJobId ? `b9sjob_${createHash("sha256").update(opts.remoteJobId).digest("hex").slice(0, 32)}` : `b9sjob_${randomBytes(16).toString("hex")}`;
761
867
  const lockDeps = {
762
- call: (method, path, body) => agentClient.call(method, path, body, path.endsWith("/running") ? { signal: AbortSignal.timeout(10_000) } : {}),
868
+ call: (method, path, body) => agentClient.call(method, path, body, {
869
+ requestTimeoutMs: path.endsWith("/running") ? 10_000 : path.endsWith("/output") ? 5_000 : 30_000,
870
+ retryForMs: 5 * 60_000,
871
+ }),
763
872
  run: (_command, context) => opts.run(context),
764
873
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
765
874
  interrupted: () => opts.signal?.aborted ?? false,
@@ -783,12 +892,15 @@ async function defaultRunWithLock(opts, agentClient, log) {
783
892
  ...(opts.pollMs === undefined ? {} : { pollMs: opts.pollMs }),
784
893
  }, lockDeps);
785
894
  }
786
- export async function executeUxJob(machineClient, job, ctx, deps = {}) {
895
+ export async function executeUxJob(machineClient, job, ctx, deps = {}, resume, claimAttemptIdOverride) {
787
896
  const runner = deps.runCommand ?? spawnAsyncCommand;
788
897
  const nowMs = deps.now ?? Date.now;
789
898
  const runWithLock = deps.runWithLock ?? defaultRunWithLock;
790
899
  const uploadEvidence = deps.uploadEvidence ?? defaultUploadEvidence;
791
900
  const jobKind = job.job_kind ?? "ux";
901
+ // Kept constant across Client.call's network retries so a committed claim with a lost
902
+ // response replays the same server-side claim instead of becoming a 409/orphaned job.
903
+ const claimAttemptId = resume?.claim_attempt_id ?? claimAttemptIdOverride ?? randomUUID();
792
904
  let b9sBin = deps.b9sBin;
793
905
  let npmBin = deps.npmBin;
794
906
  if (!b9sBin || !npmBin) {
@@ -807,23 +919,43 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
807
919
  }
808
920
  catch (error) {
809
921
  const message = error.message;
922
+ if (resume?.checkpoint) {
923
+ ctx.log(`gate job ${job.id}: passed candidate retained until its project session is available: ${message}`);
924
+ return { id: job.id, status: "skipped", evidence_ids: [], resolved_head: resume.checkpoint.candidate_sha };
925
+ }
810
926
  try {
811
- await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
927
+ if (!resume)
928
+ savePendingClaim({ version: 1, job, claim_attempt_id: claimAttemptId }, deps);
929
+ await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, { claim_attempt_id: claimAttemptId }, { retryForMs: 5 * 60_000 });
930
+ if (!resume)
931
+ removePendingClaim(job.id, deps);
812
932
  await reportUxJobCompletion(machineClient, job.id, {
813
933
  status: "failed",
814
934
  error: message,
815
935
  }, ctx.log, deps);
816
936
  }
817
- catch {
937
+ catch (claimError) {
818
938
  // Ignore secondary report error if claim failed.
939
+ if (!resume && !retryableCompletionError(claimError))
940
+ removePendingClaim(job.id, deps);
941
+ if (retryableCompletionError(claimError))
942
+ ctx.log(`job ${job.id}: unresolved claim remains pending for daemon retry: ${claimError.message}`);
819
943
  }
820
944
  return { id: job.id, status: "failed", evidence_ids: [], error: message };
821
945
  }
822
946
  let claimRes;
947
+ if (!resume)
948
+ savePendingClaim({ version: 1, job, claim_attempt_id: claimAttemptId }, deps);
823
949
  try {
824
- claimRes = await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
950
+ claimRes = await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, { claim_attempt_id: claimAttemptId }, { retryForMs: 5 * 60_000 });
951
+ if (!resume)
952
+ removePendingClaim(job.id, deps);
825
953
  }
826
- catch {
954
+ catch (error) {
955
+ if (!retryableCompletionError(error) && !resume)
956
+ removePendingClaim(job.id, deps);
957
+ if (retryableCompletionError(error))
958
+ ctx.log(`job ${job.id}: claim attempt remains pending for daemon retry: ${error.message}`);
827
959
  return { id: job.id, status: "skipped", evidence_ids: [] };
828
960
  }
829
961
  const jobCancellation = new AbortController();
@@ -848,6 +980,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
848
980
  const jobWorktreeDir = join(workRoot, job.project, ".ux-jobs", job.id);
849
981
  let baseDir = null;
850
982
  let worktreeCreated = false;
983
+ let passedGateCheckpoint = resume?.checkpoint ?? null;
851
984
  let resolvedHead = job.head;
852
985
  let logTail = "";
853
986
  const uploadedIds = [];
@@ -855,18 +988,18 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
855
988
  const diagnosticLogPath = diagnosticLogPathForJob(job.id, deps);
856
989
  const diagnosticLogDir = dirname(diagnosticLogPath);
857
990
  const stepTimeline = [];
858
- let activeStep = null;
991
+ const stepOutputContext = new AsyncLocalStorage();
859
992
  let fullLogBytes = 0;
860
993
  let logPending = "";
861
- const writeRedactedLog = (rawLine) => {
994
+ const writeRedactedLog = (rawLine, context = stepOutputContext.getStore()) => {
862
995
  const redacted = redactUxJobDiagnosticText(rawLine);
863
996
  if (!redacted)
864
997
  return;
865
998
  const bytes = Buffer.byteLength(redacted, "utf8");
866
999
  writeFileSync(diagnosticLogPath, redacted, { flag: "a", mode: 0o600 });
867
1000
  fullLogBytes += bytes;
868
- if (activeStep)
869
- activeStep.output += redacted;
1001
+ if (context)
1002
+ context.output += redacted;
870
1003
  logTail = `${logTail}${redacted}`;
871
1004
  if (logTail.length > MAX_UX_JOB_LOG_TAIL)
872
1005
  logTail = logTail.slice(-MAX_UX_JOB_LOG_TAIL);
@@ -875,17 +1008,26 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
875
1008
  const appendLog = (chunk) => {
876
1009
  if (!chunk)
877
1010
  return;
878
- logPending += chunk;
879
- const lines = logPending.split(/\r?\n/);
880
- logPending = lines.pop() ?? "";
1011
+ const context = stepOutputContext.getStore();
1012
+ const pending = `${context?.pending ?? logPending}${chunk}`;
1013
+ const lines = pending.split(/\r?\n/);
1014
+ if (context)
1015
+ context.pending = lines.pop() ?? "";
1016
+ else
1017
+ logPending = lines.pop() ?? "";
881
1018
  for (const line of lines)
882
- writeRedactedLog(`${line}\n`);
1019
+ writeRedactedLog(`${line}\n`, context);
883
1020
  };
884
1021
  const flushLogPending = () => {
885
- if (!logPending)
1022
+ const context = stepOutputContext.getStore();
1023
+ const pending = context?.pending ?? logPending;
1024
+ if (!pending)
886
1025
  return;
887
- writeRedactedLog(logPending);
888
- logPending = "";
1026
+ writeRedactedLog(pending, context);
1027
+ if (context)
1028
+ context.pending = "";
1029
+ else
1030
+ logPending = "";
889
1031
  };
890
1032
  mkdirSync(diagnosticLogDir, { recursive: true, mode: 0o700 });
891
1033
  writeFileSync(diagnosticLogPath, "", { mode: 0o600 });
@@ -904,38 +1046,41 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
904
1046
  if (!sawErr && result.stderr)
905
1047
  appendLog(result.stderr);
906
1048
  flushLogPending();
907
- if (activeStep && result.status !== null)
908
- activeStep.entry.exit_code = result.status;
1049
+ const stepContext = stepOutputContext.getStore();
1050
+ if (stepContext && result.status !== null)
1051
+ stepContext.entry.exit_code = result.status;
909
1052
  return result;
910
1053
  };
911
1054
  const runStep = async (name, run, exitCode) => {
912
1055
  const entry = { name, started_at: new Date(nowMs()).toISOString(), duration_ms: 0, exit_code: null, output_tail: "" };
913
1056
  const active = { entry, output: "" };
914
1057
  stepTimeline.push(entry);
915
- activeStep = active;
916
1058
  const started = nowMs();
917
- try {
918
- const result = await run();
919
- const reported = exitCode?.(result);
920
- if (reported !== undefined)
921
- entry.exit_code = reported;
922
- else if (entry.exit_code === null)
923
- entry.exit_code = 0;
924
- return result;
925
- }
926
- catch (error) {
927
- flushLogPending();
928
- const message = redactUxJobDiagnosticText(error.message || String(error));
929
- appendLog(`${message}\n`);
930
- if (entry.exit_code === null)
931
- entry.exit_code = 1;
932
- throw error;
933
- }
934
- finally {
935
- entry.duration_ms = Math.max(0, nowMs() - started);
936
- entry.output_tail = lastOutputLines(active.output);
937
- activeStep = null;
938
- }
1059
+ return stepOutputContext.run({ ...active, pending: "" }, async () => {
1060
+ const context = stepOutputContext.getStore();
1061
+ try {
1062
+ const result = await run();
1063
+ const reported = exitCode?.(result);
1064
+ if (reported !== undefined)
1065
+ entry.exit_code = reported;
1066
+ else if (entry.exit_code === null)
1067
+ entry.exit_code = 0;
1068
+ return result;
1069
+ }
1070
+ catch (error) {
1071
+ flushLogPending();
1072
+ const message = redactUxJobDiagnosticText(error.message || String(error));
1073
+ appendLog(`${message}\n`);
1074
+ if (entry.exit_code === null)
1075
+ entry.exit_code = 1;
1076
+ throw error;
1077
+ }
1078
+ finally {
1079
+ flushLogPending();
1080
+ entry.duration_ms = Math.max(0, nowMs() - started);
1081
+ entry.output_tail = lastOutputLines(context.output);
1082
+ }
1083
+ });
939
1084
  };
940
1085
  const environmentFingerprint = async (lockedEnv, lockContext) => {
941
1086
  const executable = (command) => {
@@ -990,6 +1135,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
990
1135
  filename: `remote-job-${job.id}.log`,
991
1136
  label: `WU #${job.work_unit_number} ${head} ${taskTag} remote-job-${job.id}.log`,
992
1137
  claim,
1138
+ idempotency_key: uxEvidenceIdempotencyKey(job.id, "diagnostic-log"),
993
1139
  };
994
1140
  };
995
1141
  const determineCheckoutRetention = () => {
@@ -1048,7 +1194,13 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1048
1194
  continue;
1049
1195
  }
1050
1196
  const label = `WU #${job.work_unit_number} ${(resolvedHead ?? job.head ?? "unknown").slice(0, 9)} ${taskTag} ${artifact.filename}`;
1051
- const evidenceId = await uploadEvidence(agentCreds, job.project, { ...artifact, label, claim });
1197
+ const artifactIdentity = artifact.path === diagnosticLogPath ? "diagnostic-log" : relative(jobArtifactDir, artifact.path);
1198
+ const evidenceId = await uploadEvidence(agentCreds, job.project, {
1199
+ ...artifact,
1200
+ label,
1201
+ claim,
1202
+ idempotencyKey: uxEvidenceIdempotencyKey(job.id, artifactIdentity),
1203
+ });
1052
1204
  uploadedArtifacts.set(artifact.path, evidenceId);
1053
1205
  if (!uploadedIds.includes(evidenceId))
1054
1206
  uploadedIds.push(evidenceId);
@@ -1061,6 +1213,16 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1061
1213
  const claimedTrainRun = claimRes.train_run;
1062
1214
  await runStep("worktree", async () => {
1063
1215
  baseDir = await resolveProjectRepoDir(job, ctx, diagnosticRunner, childEnv);
1216
+ if (resume && existsSync(jobWorktreeDir)) {
1217
+ const existing = await diagnosticRunner("git", ["-C", jobWorktreeDir, "rev-parse", "--is-inside-work-tree"], {
1218
+ cwd: jobWorktreeDir, env: childEnv, timeoutMs: 15_000,
1219
+ });
1220
+ if (existing.status === 0) {
1221
+ resolvedHead = resume.checkpoint.candidate_sha;
1222
+ worktreeCreated = true;
1223
+ return resolvedHead;
1224
+ }
1225
+ }
1064
1226
  resolvedHead = await prepareUxJobWorktree(baseDir, jobWorktreeDir, claimedTrainRun.target_branch, job.head, diagnosticRunner, childEnv, {
1065
1227
  requireBranchAncestry: false,
1066
1228
  fetchOrigin: true,
@@ -1069,7 +1231,13 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1069
1231
  return resolvedHead;
1070
1232
  }, () => 0);
1071
1233
  fingerprint = await environmentFingerprint(childEnv);
1072
- const agentClient = Client.forAgent(agentCreds, undefined, { presence: false });
1234
+ const agentClient = Client.forAgent(agentCreds, undefined, {
1235
+ presence: false,
1236
+ requestTimeoutMs: 30_000,
1237
+ retryForMs: 5 * 60_000,
1238
+ onRequest: (event) => { if (event.phase === "end")
1239
+ recordMachineNetworkRequest(event); },
1240
+ });
1073
1241
  const trainOutcome = await runMergeTrainWorkflow(job, claimedTrainRun, {
1074
1242
  worktreeDir: jobWorktreeDir,
1075
1243
  jobArtifactDir,
@@ -1088,6 +1256,12 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1088
1256
  setFingerprint: (fp) => { fingerprint = fp; },
1089
1257
  buildFingerprint: environmentFingerprint,
1090
1258
  setResolvedHead: (head) => { resolvedHead = head; },
1259
+ ...(resume ? { resumePassedGate: resume.checkpoint } : {}),
1260
+ persistPassedGate: async (checkpoint) => {
1261
+ savePassedTrainGate({ version: 1, job, claim_attempt_id: claimAttemptId, train_run: claimedTrainRun, checkpoint }, deps);
1262
+ passedGateCheckpoint = checkpoint;
1263
+ },
1264
+ apiRetryForMs: deps.mergeTrainApiRetryForMs,
1091
1265
  });
1092
1266
  if (trainOutcome.resolvedHead)
1093
1267
  resolvedHead = trainOutcome.resolvedHead;
@@ -1104,6 +1278,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1104
1278
  return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1105
1279
  }
1106
1280
  if (trainOutcome.status === "failed") {
1281
+ removePassedTrainGate(job.id, deps);
1282
+ passedGateCheckpoint = null;
1107
1283
  const errMsg = redactUxJobDiagnosticText((trainOutcome.error ?? "merge train failed").slice(0, 500));
1108
1284
  determineCheckoutRetention();
1109
1285
  appendLog(`${errMsg}\n`);
@@ -1129,7 +1305,16 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1129
1305
  return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1130
1306
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
1131
1307
  }
1132
- await uploadJobArtifacts("succeeded");
1308
+ removePassedTrainGate(job.id, deps);
1309
+ passedGateCheckpoint = null;
1310
+ try {
1311
+ await uploadJobArtifacts("succeeded");
1312
+ }
1313
+ catch (error) {
1314
+ // Artifact transport is not the result of the gate itself. Keep its successful
1315
+ // completion durable; the redacted diagnostic log is retried with the completion.
1316
+ ctx.log(`gate job ${job.id}: artifact upload remains pending after gate success: ${error.message || String(error)}`);
1317
+ }
1133
1318
  const completion = await reportUxJobCompletion(machineClient, job.id, {
1134
1319
  status: "succeeded",
1135
1320
  resolved_head: resolvedHead,
@@ -1173,7 +1358,13 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1173
1358
  throw new Error("job worktree setup returned no resolved head");
1174
1359
  const shortHead = resolvedHead.slice(0, 9);
1175
1360
  fingerprint = await environmentFingerprint(childEnv);
1176
- const agentClient = Client.forAgent(agentCreds, undefined, { presence: false });
1361
+ const agentClient = Client.forAgent(agentCreds, undefined, {
1362
+ presence: false,
1363
+ requestTimeoutMs: 30_000,
1364
+ retryForMs: 5 * 60_000,
1365
+ onRequest: (event) => { if (event.phase === "end")
1366
+ recordMachineNetworkRequest(event); },
1367
+ });
1177
1368
  const commandLabel = jobKind === "gate"
1178
1369
  ? ["scripts/gate.sh", resolvedHead]
1179
1370
  : [
@@ -1400,7 +1591,14 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1400
1591
  return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1401
1592
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
1402
1593
  }
1403
- await uploadJobArtifacts("succeeded");
1594
+ try {
1595
+ await uploadJobArtifacts("succeeded");
1596
+ }
1597
+ catch (error) {
1598
+ // The task result is already known. A telemetry outage cannot turn a successful
1599
+ // command into a failed job; its persisted completion retries the primary log.
1600
+ ctx.log(`${jobKind} job ${job.id}: artifact upload remains pending after success: ${error.message || String(error)}`);
1601
+ }
1404
1602
  const completion = await reportUxJobCompletion(machineClient, job.id, {
1405
1603
  status: "succeeded",
1406
1604
  resolved_head: resolvedHead,
@@ -1435,6 +1633,20 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1435
1633
  return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1436
1634
  }
1437
1635
  const message = redactUxJobDiagnosticText((error.message || `${jobKind} job failed`).slice(0, 500));
1636
+ if (passedGateCheckpoint && retryableCompletionError(error)) {
1637
+ // A passed merge-train gate is durable local work. Let the next daemon pass replay the
1638
+ // stored candidate and tested tree rather than reporting this transport/continuation error
1639
+ // as a failed gate or dropping its train run.
1640
+ preserveCheckout = true;
1641
+ ctx.log(`gate job ${job.id}: passed candidate retained for resume after continuation error: ${message}`);
1642
+ return { id: job.id, status: "skipped", evidence_ids: uploadedIds, resolved_head: resolvedHead };
1643
+ }
1644
+ if (passedGateCheckpoint) {
1645
+ // A permanent refusal (for example, stale approvals) is a job failure, not a transport
1646
+ // outage. Remove the retry checkpoint so it cannot replay a candidate the API rejected.
1647
+ removePassedTrainGate(job.id, deps);
1648
+ passedGateCheckpoint = null;
1649
+ }
1438
1650
  // Once the complete log has been uploaded, later artifact-posting errors belong
1439
1651
  // in daemon output; mutating the local log would make its evidence stale.
1440
1652
  if (!fullLogEvidenceId)
@@ -1498,3 +1710,54 @@ export function reconcilePendingUxJobs(machineClient, jobs, ctx, opts = {}) {
1498
1710
  }
1499
1711
  return opts.awaitCompletion ? Promise.all(started) : Promise.resolve([]);
1500
1712
  }
1713
+ /** Replay claims whose server commit may have succeeded but whose response never reached the daemon. */
1714
+ export function retryPendingUxJobClaims(machineClient, ctx, deps = {}, inFlight = defaultUxJobsInFlight) {
1715
+ const dir = pendingClaimDir(deps);
1716
+ if (!existsSync(dir))
1717
+ return Promise.resolve([]);
1718
+ const started = [];
1719
+ for (const name of readdirSync(dir).filter((item) => item.endsWith(".json"))) {
1720
+ const path = join(dir, name);
1721
+ let record;
1722
+ try {
1723
+ record = JSON.parse(readFileSync(path, "utf8"));
1724
+ if (record.version !== 1 || !record.job?.id || !record.claim_attempt_id)
1725
+ throw new Error("invalid pending claim record");
1726
+ }
1727
+ catch (error) {
1728
+ throw new Error(`cannot read pending UX job claim ${path}: ${error.message}`);
1729
+ }
1730
+ if (inFlight.has(record.job.id))
1731
+ continue;
1732
+ inFlight.add(record.job.id);
1733
+ started.push(executeUxJob(machineClient, record.job, ctx, deps, undefined, record.claim_attempt_id)
1734
+ .finally(() => inFlight.delete(record.job.id)));
1735
+ }
1736
+ return Promise.all(started);
1737
+ }
1738
+ /** Resume local passed candidates whose API continuation failed after the test gate completed. */
1739
+ export function retryPendingPassedTrainGates(machineClient, ctx, deps = {}, inFlight = defaultUxJobsInFlight) {
1740
+ const dir = passedTrainGateDir(deps);
1741
+ if (!existsSync(dir))
1742
+ return Promise.resolve([]);
1743
+ const started = [];
1744
+ for (const name of readdirSync(dir).filter((item) => item.endsWith(".json"))) {
1745
+ const path = join(dir, name);
1746
+ let record;
1747
+ try {
1748
+ record = JSON.parse(readFileSync(path, "utf8"));
1749
+ if (record.version !== 1 || !record.job?.id || !record.claim_attempt_id || !record.train_run?.id
1750
+ || record.checkpoint?.version !== 1 || record.checkpoint.train_run_id !== record.train_run.id) {
1751
+ throw new Error("invalid passed gate checkpoint");
1752
+ }
1753
+ }
1754
+ catch (error) {
1755
+ throw new Error(`cannot read passed gate checkpoint ${path}: ${error.message}`);
1756
+ }
1757
+ if (inFlight.has(record.job.id))
1758
+ continue;
1759
+ inFlight.add(record.job.id);
1760
+ started.push(executeUxJob(machineClient, record.job, ctx, deps, record).finally(() => inFlight.delete(record.job.id)));
1761
+ }
1762
+ return Promise.all(started);
1763
+ }
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
- export const CLI_VERSION = "0.12.163";
1
+ export const CLI_VERSION = "0.12.166";
2
2
  /** First release allowed to consume single-use join tokens with the save-before-install flow. */
3
3
  export const CLI_JOIN_MIN_VERSION = "0.12.159";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.164",
3
+ "version": "0.12.166",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {