benignswarm 0.12.162 → 0.12.164

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
@@ -163,6 +163,11 @@ function completionErrorCode(error) {
163
163
  const code = error && typeof error === "object" && "code" in error ? String(error.code) : null;
164
164
  return code;
165
165
  }
166
+ function completionHttpStatus(error) {
167
+ return error && typeof error === "object" && "httpStatus" in error
168
+ ? Number(error.httpStatus)
169
+ : null;
170
+ }
166
171
  function retryableCompletionError(error) {
167
172
  const code = completionErrorCode(error);
168
173
  const status = error && typeof error === "object" && "httpStatus" in error ? Number(error.httpStatus) : null;
@@ -195,6 +200,34 @@ export async function reportUxJobCompletion(machineClient, jobId, body, log, dep
195
200
  return sendStoredUxJobCompletion(machineClient, record, path, log, deps, sessions);
196
201
  }
197
202
  async function sendStoredUxJobCompletion(machineClient, record, path, log, deps, sessions = []) {
203
+ const reconcileCancellation = async () => {
204
+ if (record.body.status === "cancelled")
205
+ return true;
206
+ try {
207
+ const control = await machineClient.call("GET", `/machines/me/ux-jobs/${encodeURIComponent(record.job_id)}/control`);
208
+ if (!control.job?.cancel_requested_at)
209
+ return false;
210
+ record.body = {
211
+ status: "cancelled",
212
+ resolved_head: record.body.resolved_head,
213
+ step_timeline: record.body.step_timeline,
214
+ environment_fingerprint: record.body.environment_fingerprint,
215
+ checkout_path: null,
216
+ checkout_expires_at: null,
217
+ checkout_retention_note: "Cancelled job checkout removed after lock release.",
218
+ };
219
+ delete record.pending_full_log;
220
+ delete record.refused_error;
221
+ writeFileAtomic(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
222
+ log(`UX job ${record.job_id}: completion reconciled to cancellation requested by its owner`);
223
+ return true;
224
+ }
225
+ catch (error) {
226
+ log(`UX job ${record.job_id}: cancellation state reconciliation failed: ${error.message || String(error)}`);
227
+ return false;
228
+ }
229
+ };
230
+ await reconcileCancellation();
198
231
  if (record.refused_error) {
199
232
  log(`UX job ${record.job_id}: completion remains refused; diagnostic log retained at ${record.diagnostic_log_path ?? "unknown path"}: ${record.refused_error}`);
200
233
  return "refused";
@@ -234,6 +267,8 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps,
234
267
  const route = `/machines/me/ux-jobs/${encodeURIComponent(record.job_id)}/complete`;
235
268
  const attempts = delays.length + 1;
236
269
  for (let attempt = 0; attempt < attempts; attempt++) {
270
+ if (attempt > 0)
271
+ await reconcileCancellation();
237
272
  if (attempt > 0)
238
273
  await sleep(delays[attempt - 1]);
239
274
  try {
@@ -252,10 +287,19 @@ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps,
252
287
  log(`UX job ${record.job_id}: completion was accepted, but its redacted full log could not be removed: ${error.message}`);
253
288
  }
254
289
  }
255
- return "accepted";
290
+ return record.body.status === "cancelled" ? "cancelled" : "accepted";
256
291
  }
257
292
  catch (error) {
258
293
  const message = error.message || String(error);
294
+ if (record.body.status !== "cancelled" && !retryableCompletionError(error) && await reconcileCancellation()) {
295
+ // The ordinary completion lost the race to cancellation. The command has
296
+ // already released its lock, so retry the now-terminal cancellation body.
297
+ return sendStoredUxJobCompletion(machineClient, record, path, log, deps, sessions);
298
+ }
299
+ if (record.body.status === "cancelled" && completionHttpStatus(error) === 409) {
300
+ log(`UX job ${record.job_id}: cancellation is waiting for the machine lock to be released`);
301
+ return "pending";
302
+ }
259
303
  if (retryableCompletionError(error) && attempt + 1 < attempts) {
260
304
  log(`UX job ${record.job_id}: completion report attempt ${attempt + 1}/${attempts} failed; retrying: ${message}`);
261
305
  continue;
@@ -307,7 +351,7 @@ export async function retryPendingUxJobCompletions(machineClient, log, deps = {}
307
351
  try {
308
352
  const parsed = JSON.parse(readFileSync(path, "utf8"));
309
353
  if (parsed.version !== 1 || typeof parsed.job_id !== "string" || !parsed.job_id
310
- || !parsed.body || (parsed.body.status !== "succeeded" && parsed.body.status !== "failed")) {
354
+ || !parsed.body || (parsed.body.status !== "succeeded" && parsed.body.status !== "failed" && parsed.body.status !== "cancelled")) {
311
355
  throw new Error("invalid completion record shape");
312
356
  }
313
357
  record = parsed;
@@ -713,11 +757,12 @@ function forwardLockedChunks(onOutput, onLine) {
713
757
  };
714
758
  }
715
759
  async function defaultRunWithLock(opts, agentClient, log) {
760
+ const token = opts.remoteJobId ? `b9sjob_${createHash("sha256").update(opts.remoteJobId).digest("hex").slice(0, 32)}` : `b9sjob_${randomBytes(16).toString("hex")}`;
716
761
  const lockDeps = {
717
762
  call: (method, path, body) => agentClient.call(method, path, body, path.endsWith("/running") ? { signal: AbortSignal.timeout(10_000) } : {}),
718
763
  run: (_command, context) => opts.run(context),
719
764
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
720
- interrupted: () => false,
765
+ interrupted: () => opts.signal?.aborted ?? false,
721
766
  log,
722
767
  };
723
768
  return runUnderLock({
@@ -729,10 +774,12 @@ async function defaultRunWithLock(opts, agentClient, log) {
729
774
  unit: opts.unit,
730
775
  note: opts.note,
731
776
  command: opts.commandLabel,
732
- token: `b9sjob_${randomBytes(16).toString("hex")}`,
733
- jobId: randomBytes(6).toString("hex"),
777
+ token,
778
+ jobId: createHash("sha256").update(token).digest("hex").slice(0, 12),
734
779
  jobsFile: join(homedir(), ".b9s", "ux-lock-jobs.json"),
735
780
  jobsKey: `${opts.project}:${opts.lock}:${opts.machine}`,
781
+ ...(opts.signal ? { signal: opts.signal } : {}),
782
+ ...(opts.remoteJobId ? { remoteJobId: opts.remoteJobId } : {}),
736
783
  ...(opts.pollMs === undefined ? {} : { pollMs: opts.pollMs }),
737
784
  }, lockDeps);
738
785
  }
@@ -779,6 +826,20 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
779
826
  catch {
780
827
  return { id: job.id, status: "skipped", evidence_ids: [] };
781
828
  }
829
+ const jobCancellation = new AbortController();
830
+ const pollCancellation = async () => {
831
+ try {
832
+ const result = await machineClient.call("GET", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/control`);
833
+ if (result.job?.cancel_requested_at)
834
+ jobCancellation.abort(new Error("remote job cancellation requested"));
835
+ }
836
+ catch (error) {
837
+ ctx.log(`remote job ${job.id}: cancellation state poll failed: ${error.message}`);
838
+ }
839
+ };
840
+ await pollCancellation();
841
+ const cancellationTimer = setInterval(() => { void pollCancellation(); }, 1_000);
842
+ cancellationTimer.unref?.();
782
843
  const jobTaskLabel = jobKind === "gate"
783
844
  ? "complete-suite gate"
784
845
  : [job.task ? `ux:task ${job.task}` : null, job.compare_screen ? `ux:compare ${job.compare_screen}` : null].filter(Boolean).join(" + ");
@@ -834,6 +895,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
834
895
  let sawErr = false;
835
896
  const result = await runner(cmd, args, {
836
897
  ...opts,
898
+ signal: opts.signal ? AbortSignal.any([opts.signal, jobCancellation.signal]) : jobCancellation.signal,
837
899
  onStdoutChunk: (chunk) => { sawOut = true; appendLog(chunk); opts.onStdoutChunk?.(chunk); },
838
900
  onStderrChunk: (chunk) => { sawErr = true; appendLog(chunk); opts.onStderrChunk?.(chunk); },
839
901
  });
@@ -1021,6 +1083,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1021
1083
  stepTimeline,
1022
1084
  lockHeartbeatMs: deps.lockHeartbeatMs,
1023
1085
  lockPollMs: deps.lockPollMs,
1086
+ signal: jobCancellation.signal,
1024
1087
  onLogLine: (line) => ctx.log(line),
1025
1088
  setFingerprint: (fp) => { fingerprint = fp; },
1026
1089
  buildFingerprint: environmentFingerprint,
@@ -1028,12 +1091,24 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1028
1091
  });
1029
1092
  if (trainOutcome.resolvedHead)
1030
1093
  resolvedHead = trainOutcome.resolvedHead;
1094
+ if (jobCancellation.signal.aborted) {
1095
+ await reportUxJobCompletion(machineClient, job.id, {
1096
+ status: "cancelled",
1097
+ resolved_head: resolvedHead,
1098
+ step_timeline: stepTimeline,
1099
+ environment_fingerprint: fingerprint,
1100
+ checkout_path: null,
1101
+ checkout_expires_at: null,
1102
+ checkout_retention_note: "Cancelled job checkout removed after lock release.",
1103
+ }, ctx.log, deps, undefined, ctx.sessions);
1104
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1105
+ }
1031
1106
  if (trainOutcome.status === "failed") {
1032
1107
  const errMsg = redactUxJobDiagnosticText((trainOutcome.error ?? "merge train failed").slice(0, 500));
1033
1108
  determineCheckoutRetention();
1034
1109
  appendLog(`${errMsg}\n`);
1035
1110
  await uploadJobArtifacts("failed");
1036
- await reportUxJobCompletion(machineClient, job.id, {
1111
+ const completion = await reportUxJobCompletion(machineClient, job.id, {
1037
1112
  status: "failed",
1038
1113
  resolved_head: resolvedHead,
1039
1114
  evidence_ids: uploadedIds,
@@ -1050,10 +1125,12 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1050
1125
  path: diagnosticLogPath,
1051
1126
  pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("failed"),
1052
1127
  }, ctx.sessions);
1128
+ if (completion === "cancelled")
1129
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1053
1130
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
1054
1131
  }
1055
1132
  await uploadJobArtifacts("succeeded");
1056
- await reportUxJobCompletion(machineClient, job.id, {
1133
+ const completion = await reportUxJobCompletion(machineClient, job.id, {
1057
1134
  status: "succeeded",
1058
1135
  resolved_head: resolvedHead,
1059
1136
  evidence_ids: uploadedIds,
@@ -1069,6 +1146,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1069
1146
  path: diagnosticLogPath,
1070
1147
  pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("succeeded"),
1071
1148
  }, ctx.sessions);
1149
+ if (completion === "cancelled")
1150
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1072
1151
  ctx.log(`gate job ${job.id}: merge train completed (${trainOutcome.trainResult.landed_units.length} landed, ${trainOutcome.trainResult.skipped_units.length} skipped)`);
1073
1152
  return { id: job.id, status: "succeeded", evidence_ids: uploadedIds, resolved_head: resolvedHead };
1074
1153
  }
@@ -1113,6 +1192,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1113
1192
  unit: job.work_unit_number,
1114
1193
  note: `${jobKind}-job ${job.id}: ${jobTaskLabel} @ ${shortHead}`,
1115
1194
  commandLabel,
1195
+ remoteJobId: job.id,
1196
+ signal: jobCancellation.signal,
1116
1197
  ...(deps.lockPollMs === undefined ? {} : { pollMs: deps.lockPollMs }),
1117
1198
  run: async (lockContext) => {
1118
1199
  const lockedEnv = { ...childEnv };
@@ -1125,6 +1206,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1125
1206
  lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = jobArtifactDir;
1126
1207
  fingerprint = await environmentFingerprint(lockedEnv, lockContext);
1127
1208
  const heartbeatController = new AbortController();
1209
+ const commandSignal = lockContext?.signal ? AbortSignal.any([heartbeatController.signal, lockContext.signal]) : heartbeatController.signal;
1128
1210
  let heartbeatTimer;
1129
1211
  let heartbeatInFlight;
1130
1212
  let heartbeatFailure;
@@ -1166,7 +1248,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1166
1248
  cwd: jobWorktreeDir,
1167
1249
  env: lockedEnv,
1168
1250
  timeoutMs: stepOpts.timeoutMs,
1169
- signal: heartbeatController.signal,
1251
+ signal: commandSignal,
1170
1252
  onStart: stepOpts.onStart,
1171
1253
  onStdoutChunk: (chunk) => {
1172
1254
  if (stepOpts.captureCombined)
@@ -1281,12 +1363,24 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1281
1363
  }
1282
1364
  },
1283
1365
  }, agentClient, ctx.log);
1366
+ if (jobCancellation.signal.aborted) {
1367
+ await reportUxJobCompletion(machineClient, job.id, {
1368
+ status: "cancelled",
1369
+ resolved_head: resolvedHead,
1370
+ step_timeline: stepTimeline,
1371
+ environment_fingerprint: fingerprint,
1372
+ checkout_path: null,
1373
+ checkout_expires_at: null,
1374
+ checkout_retention_note: "Cancelled job checkout removed after lock release.",
1375
+ }, ctx.log, deps, undefined, ctx.sessions);
1376
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1377
+ }
1284
1378
  if (exitCode !== 0) {
1285
1379
  const errMsg = `${jobKind} job exited with code ${exitCode}${logTail ? `: ${logTail.slice(-280)}` : ""}`.slice(0, 500);
1286
1380
  determineCheckoutRetention();
1287
1381
  appendLog(`${errMsg}\n`);
1288
1382
  await uploadJobArtifacts("failed");
1289
- await reportUxJobCompletion(machineClient, job.id, {
1383
+ const completion = await reportUxJobCompletion(machineClient, job.id, {
1290
1384
  status: "failed",
1291
1385
  resolved_head: resolvedHead,
1292
1386
  evidence_ids: uploadedIds,
@@ -1302,10 +1396,12 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1302
1396
  path: diagnosticLogPath,
1303
1397
  pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("failed"),
1304
1398
  }, ctx.sessions);
1399
+ if (completion === "cancelled")
1400
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1305
1401
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
1306
1402
  }
1307
1403
  await uploadJobArtifacts("succeeded");
1308
- await reportUxJobCompletion(machineClient, job.id, {
1404
+ const completion = await reportUxJobCompletion(machineClient, job.id, {
1309
1405
  status: "succeeded",
1310
1406
  resolved_head: resolvedHead,
1311
1407
  evidence_ids: uploadedIds,
@@ -1320,10 +1416,24 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1320
1416
  path: diagnosticLogPath,
1321
1417
  pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("succeeded"),
1322
1418
  }, ctx.sessions);
1419
+ if (completion === "cancelled")
1420
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1323
1421
  ctx.log(`${jobKind} job ${job.id}: completed (${uploadedIds.length} artifact(s) posted for WU #${job.work_unit_number} at ${shortHead})`);
1324
1422
  return { id: job.id, status: "succeeded", evidence_ids: uploadedIds, resolved_head: resolvedHead };
1325
1423
  }
1326
1424
  catch (error) {
1425
+ if (jobCancellation.signal.aborted) {
1426
+ await reportUxJobCompletion(machineClient, job.id, {
1427
+ status: "cancelled",
1428
+ resolved_head: resolvedHead,
1429
+ step_timeline: stepTimeline,
1430
+ environment_fingerprint: fingerprint,
1431
+ checkout_path: null,
1432
+ checkout_expires_at: null,
1433
+ checkout_retention_note: "Cancelled job checkout removed after lock release.",
1434
+ }, ctx.log, deps, undefined, ctx.sessions);
1435
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1436
+ }
1327
1437
  const message = redactUxJobDiagnosticText((error.message || `${jobKind} job failed`).slice(0, 500));
1328
1438
  // Once the complete log has been uploaded, later artifact-posting errors belong
1329
1439
  // in daemon output; mutating the local log would make its evidence stale.
@@ -1338,7 +1448,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1338
1448
  catch (uploadError) {
1339
1449
  appendLog(`full diagnostics evidence upload failed: ${redactUxJobDiagnosticText(uploadError.message || String(uploadError))}\n`);
1340
1450
  }
1341
- await reportUxJobCompletion(machineClient, job.id, {
1451
+ const completion = await reportUxJobCompletion(machineClient, job.id, {
1342
1452
  status: "failed",
1343
1453
  resolved_head: resolvedHead ?? undefined,
1344
1454
  evidence_ids: uploadedIds,
@@ -1354,10 +1464,13 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1354
1464
  path: diagnosticLogPath,
1355
1465
  pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("failed"),
1356
1466
  }, ctx.sessions);
1467
+ if (completion === "cancelled")
1468
+ return { id: job.id, status: "cancelled", evidence_ids: [], resolved_head: resolvedHead };
1357
1469
  ctx.log(`${jobKind} job ${job.id}: failed (${message})`);
1358
1470
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: message };
1359
1471
  }
1360
1472
  finally {
1473
+ clearInterval(cancellationTimer);
1361
1474
  if (worktreeCreated && baseDir && !preserveCheckout) {
1362
1475
  await cleanupUxJobWorktree(baseDir, jobWorktreeDir, runner, childEnv);
1363
1476
  }
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
- export const CLI_VERSION = "0.12.162";
1
+ export const CLI_VERSION = "0.12.163";
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.162",
3
+ "version": "0.12.164",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {