benignswarm 0.12.157 → 0.12.159

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,3 +1,4 @@
1
+ import { evidenceTextHeaders } from "./evidence-text.js";
1
2
  import { createHash, randomBytes } from "node:crypto";
2
3
  import { spawn, spawnSync } from "node:child_process";
3
4
  import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
@@ -7,10 +8,13 @@ import { Client } from "./client.js";
7
8
  import { agentRef, configRoot, loadAgent, listSaved } from "./config.js";
8
9
  import { guessType } from "./commands/evidence.js";
9
10
  import { createGateMarkerScanner, runUnderLock } from "./commands/lock-run.js";
11
+ import { createLockHeartbeatReporter } from "./lock-heartbeat.js";
10
12
  import { CliError } from "./errors.js";
11
13
  import { composeMachinePath, requireInstall } from "./install.js";
12
14
  import { isolatedSubprocessEnv } from "./container.js";
13
15
  import { writeFileAtomic } from "./shared-file.js";
16
+ import { runMergeTrainWorkflow } from "./merge-train.js";
17
+ import { retryGitFetch } from "./git-fetch.js";
14
18
  const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
15
19
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
16
20
  const MAX_UX_JOB_LOG_TAIL = 2000;
@@ -346,6 +350,8 @@ export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
346
350
  shell: false,
347
351
  detached: process.platform !== "win32",
348
352
  });
353
+ if (child.pid !== undefined)
354
+ opts.onStart?.(child.pid);
349
355
  let stdout = "";
350
356
  let stderr = "";
351
357
  const append = (cur, chunk) => {
@@ -534,21 +540,11 @@ export async function prepareUxJobWorktree(baseDir, jobDir, branch, head, runner
534
540
  throw new Error(`invalid recorded commit head: ${JSON.stringify(head)}`);
535
541
  }
536
542
  const requireAncestry = options.requireBranchAncestry !== false;
537
- if (options.fetchOrigin) {
538
- const fetchAll = await runner("git", ["-C", baseDir, "fetch", "--prune", "--no-tags", "origin"], {
539
- cwd: baseDir,
540
- env,
541
- timeoutMs: 120_000,
542
- });
543
- if (fetchAll.status !== 0) {
544
- throw new Error(`git fetch origin failed: ${(fetchAll.stderr || fetchAll.stdout).trim().slice(0, 300)}`);
545
- }
546
- }
547
- const fetchBranch = await runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", branch], {
543
+ const fetchBranch = await retryGitFetch(() => runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], {
548
544
  cwd: baseDir,
549
545
  env,
550
546
  timeoutMs: 120_000,
551
- });
547
+ }), `fetch origin/${branch}`);
552
548
  if (fetchBranch.status !== 0 && requireAncestry) {
553
549
  throw new Error(`git fetch origin ${branch} failed: ${(fetchBranch.stderr || fetchBranch.stdout).trim().slice(0, 300)}`);
554
550
  }
@@ -575,7 +571,7 @@ export async function prepareUxJobWorktree(baseDir, jobDir, branch, head, runner
575
571
  timeoutMs: 15_000,
576
572
  });
577
573
  if (hasCommit.status !== 0) {
578
- await runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", head], { cwd: baseDir, env, timeoutMs: 120_000 });
574
+ await retryGitFetch(() => runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", head], { cwd: baseDir, env, timeoutMs: 120_000 }), `fetch commit ${head}`);
579
575
  hasCommit = await runner("git", ["-C", baseDir, "cat-file", "-e", `${head}^{commit}`], { cwd: baseDir, env, timeoutMs: 15_000 });
580
576
  }
581
577
  if (hasCommit.status !== 0) {
@@ -677,9 +673,8 @@ async function defaultUploadEvidence(agentCreds, project, file) {
677
673
  "content-type": file.contentType,
678
674
  "x-bschat-sha256": sha,
679
675
  "x-bschat-filename": file.filename,
680
- "x-bschat-label": file.label.slice(0, 500),
681
676
  "x-bschat-kind": file.kind,
682
- "x-bschat-claim": file.claim.slice(0, 300),
677
+ ...await evidenceTextHeaders(client, project, { label: file.label.slice(0, 500), claim: file.claim.slice(0, 300) }),
683
678
  };
684
679
  const res = await fetch(`${agentCreds.url}/projects/${encodeURIComponent(project)}/evidence`, {
685
680
  method: "POST",
@@ -719,7 +714,7 @@ function forwardLockedChunks(onOutput, onLine) {
719
714
  }
720
715
  async function defaultRunWithLock(opts, agentClient, log) {
721
716
  const lockDeps = {
722
- call: (method, path, body) => agentClient.call(method, path, body),
717
+ call: (method, path, body) => agentClient.call(method, path, body, path.endsWith("/running") ? { signal: AbortSignal.timeout(10_000) } : {}),
723
718
  run: (_command, context) => opts.run(context),
724
719
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
725
720
  interrupted: () => false,
@@ -777,8 +772,9 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
777
772
  }
778
773
  return { id: job.id, status: "failed", evidence_ids: [], error: message };
779
774
  }
775
+ let claimRes;
780
776
  try {
781
- await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
777
+ claimRes = await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
782
778
  }
783
779
  catch {
784
780
  return { id: job.id, status: "skipped", evidence_ids: [] };
@@ -999,6 +995,83 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
999
995
  }
1000
996
  };
1001
997
  try {
998
+ if (job.train_run_id && claimRes?.train_run) {
999
+ const claimedTrainRun = claimRes.train_run;
1000
+ await runStep("worktree", async () => {
1001
+ baseDir = await resolveProjectRepoDir(job, ctx, diagnosticRunner, childEnv);
1002
+ resolvedHead = await prepareUxJobWorktree(baseDir, jobWorktreeDir, claimedTrainRun.target_branch, job.head, diagnosticRunner, childEnv, {
1003
+ requireBranchAncestry: false,
1004
+ fetchOrigin: true,
1005
+ });
1006
+ worktreeCreated = true;
1007
+ return resolvedHead;
1008
+ }, () => 0);
1009
+ fingerprint = await environmentFingerprint(childEnv);
1010
+ const agentClient = Client.forAgent(agentCreds, undefined, { presence: false });
1011
+ const trainOutcome = await runMergeTrainWorkflow(job, claimedTrainRun, {
1012
+ worktreeDir: jobWorktreeDir,
1013
+ jobArtifactDir,
1014
+ childEnv,
1015
+ agentCreds,
1016
+ machineClient,
1017
+ agentClient,
1018
+ runner: diagnosticRunner,
1019
+ runStep,
1020
+ runWithLock,
1021
+ stepTimeline,
1022
+ lockHeartbeatMs: deps.lockHeartbeatMs,
1023
+ lockPollMs: deps.lockPollMs,
1024
+ onLogLine: (line) => ctx.log(line),
1025
+ setFingerprint: (fp) => { fingerprint = fp; },
1026
+ buildFingerprint: environmentFingerprint,
1027
+ setResolvedHead: (head) => { resolvedHead = head; },
1028
+ });
1029
+ if (trainOutcome.resolvedHead)
1030
+ resolvedHead = trainOutcome.resolvedHead;
1031
+ if (trainOutcome.status === "failed") {
1032
+ const errMsg = redactUxJobDiagnosticText((trainOutcome.error ?? "merge train failed").slice(0, 500));
1033
+ determineCheckoutRetention();
1034
+ appendLog(`${errMsg}\n`);
1035
+ await uploadJobArtifacts("failed");
1036
+ await reportUxJobCompletion(machineClient, job.id, {
1037
+ status: "failed",
1038
+ resolved_head: resolvedHead,
1039
+ evidence_ids: uploadedIds,
1040
+ full_log_evidence_id: fullLogEvidenceId,
1041
+ step_timeline: stepTimeline,
1042
+ environment_fingerprint: fingerprint,
1043
+ checkout_path: checkoutPath,
1044
+ checkout_expires_at: checkoutExpiresAt,
1045
+ checkout_retention_note: checkoutRetentionNote,
1046
+ error: errMsg,
1047
+ log_excerpt: logTail || undefined,
1048
+ train_result: trainOutcome.trainResult,
1049
+ }, ctx.log, deps, {
1050
+ path: diagnosticLogPath,
1051
+ pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("failed"),
1052
+ }, ctx.sessions);
1053
+ return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
1054
+ }
1055
+ await uploadJobArtifacts("succeeded");
1056
+ await reportUxJobCompletion(machineClient, job.id, {
1057
+ status: "succeeded",
1058
+ resolved_head: resolvedHead,
1059
+ evidence_ids: uploadedIds,
1060
+ full_log_evidence_id: fullLogEvidenceId,
1061
+ step_timeline: stepTimeline,
1062
+ environment_fingerprint: fingerprint,
1063
+ checkout_path: null,
1064
+ checkout_expires_at: null,
1065
+ checkout_retention_note: "Successful job checkout removed after artifact collection.",
1066
+ log_excerpt: logTail || undefined,
1067
+ train_result: trainOutcome.trainResult,
1068
+ }, ctx.log, deps, {
1069
+ path: diagnosticLogPath,
1070
+ pendingUpload: fullLogEvidenceId ? undefined : fullLogUploadMetadata("succeeded"),
1071
+ }, ctx.sessions);
1072
+ ctx.log(`gate job ${job.id}: merge train completed (${trainOutcome.trainResult.landed_units.length} landed, ${trainOutcome.trainResult.skipped_units.length} skipped)`);
1073
+ return { id: job.id, status: "succeeded", evidence_ids: uploadedIds, resolved_head: resolvedHead };
1074
+ }
1002
1075
  if (jobKind === "ux") {
1003
1076
  if (job.task && !SLUG_RE.test(job.task))
1004
1077
  throw new Error(`invalid ux task name ${job.task}`);
@@ -1055,16 +1128,21 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1055
1128
  let heartbeatTimer;
1056
1129
  let heartbeatInFlight;
1057
1130
  let heartbeatFailure;
1131
+ const reportHeartbeat = lockContext?.heartbeat
1132
+ ? createLockHeartbeatReporter(lockContext.heartbeat, {
1133
+ onRetry: (error, delayMs) => ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) lock heartbeat failed transiently; retrying in ${delayMs}ms: ${error instanceof Error ? error.message : String(error)}`),
1134
+ })
1135
+ : undefined;
1058
1136
  if (lockContext?.heartbeat) {
1059
1137
  const heartbeatMs = deps.lockHeartbeatMs ?? 15_000;
1060
1138
  heartbeatTimer = setInterval(() => {
1061
1139
  if (heartbeatInFlight)
1062
1140
  return;
1063
- heartbeatInFlight = lockContext.heartbeat().then(() => undefined, (error) => {
1141
+ heartbeatInFlight = reportHeartbeat().then(() => undefined, (error) => {
1064
1142
  heartbeatFailure = error;
1065
1143
  if (heartbeatTimer)
1066
1144
  clearInterval(heartbeatTimer);
1067
- ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
1145
+ ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) lost its lock lease; stopping the command`);
1068
1146
  heartbeatController.abort();
1069
1147
  }).finally(() => {
1070
1148
  heartbeatInFlight = undefined;
@@ -1075,7 +1153,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1075
1153
  const throwIfHeartbeatFailed = () => {
1076
1154
  if (!heartbeatFailure)
1077
1155
  return;
1078
- throw new CliError("lock_heartbeat_failed", `job ${lockContext?.jobId ?? job.id} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
1156
+ const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
1157
+ throw new CliError(code, `job ${lockContext?.jobId ?? job.id} stopped because its lock lease could not be renewed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
1079
1158
  };
1080
1159
  const runLockedStep = async (stepName, cmd, args, stepOpts) => {
1081
1160
  throwIfHeartbeatFailed();
@@ -1088,6 +1167,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1088
1167
  env: lockedEnv,
1089
1168
  timeoutMs: stepOpts.timeoutMs,
1090
1169
  signal: heartbeatController.signal,
1170
+ onStart: stepOpts.onStart,
1091
1171
  onStdoutChunk: (chunk) => {
1092
1172
  if (stepOpts.captureCombined)
1093
1173
  combined += chunk;
@@ -1122,6 +1202,17 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1122
1202
  const { res: gateRes, combined: fullOutput } = await runLockedStep("gate", "/bin/sh", ["scripts/gate.sh", resolvedHead], {
1123
1203
  timeoutMs: 1_800_000,
1124
1204
  captureCombined: true,
1205
+ onStart: (pid) => {
1206
+ if (!reportHeartbeat)
1207
+ return;
1208
+ heartbeatInFlight = reportHeartbeat(pid).then(() => undefined, (error) => {
1209
+ heartbeatFailure = error;
1210
+ if (heartbeatTimer)
1211
+ clearInterval(heartbeatTimer);
1212
+ ctx.log(`${jobKind} job ${job.id} (${lockContext?.jobId ?? job.id}) lost its lock lease; stopping the command`);
1213
+ heartbeatController.abort();
1214
+ }).finally(() => { heartbeatInFlight = undefined; });
1215
+ },
1125
1216
  onStdoutLine: (line) => scanner.push(`${line}\n`),
1126
1217
  });
1127
1218
  scanner.push("", true);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.157";
1
+ export const CLI_VERSION = "0.12.159";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.157",
3
+ "version": "0.12.159",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {