benignswarm 0.12.149 → 0.12.152

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
@@ -35,7 +35,7 @@ export const STRING_FLAGS = [
35
35
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
36
  "machine-session-id", "harness-binary", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
37
37
  "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
- "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
38
+ "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
40
  "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate",
41
41
  ];
@@ -44,7 +44,7 @@ export const BOOL_FLAGS = [
44
44
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
45
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
46
46
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
- "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor",
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",
49
49
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution",
50
50
  "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target",
package/dist/client.js CHANGED
@@ -377,10 +377,10 @@ export class Client {
377
377
  timeoutError(method, path) {
378
378
  return new CliError("request_timeout", `${method} ${path} timed out after ${this.requestOptions.requestTimeoutMs}ms`);
379
379
  }
380
- headers() {
380
+ headers(autoOverride) {
381
381
  const h = { authorization: `Bearer ${this.key}`, "user-agent": cliUserAgent() };
382
382
  if (this.auto)
383
- h["x-bschat-auto"] = JSON.stringify(this.auto);
383
+ h["x-bschat-auto"] = JSON.stringify(autoOverride ? { ...this.auto, ...autoOverride } : this.auto);
384
384
  if (this.machineIdentity)
385
385
  h["x-bschat-machine"] = this.machineIdentity;
386
386
  if (this.requestOptions.stagedPoolPreparation)
@@ -403,7 +403,7 @@ export class Client {
403
403
  json = JSON.parse(text);
404
404
  }
405
405
  catch { /* keep response text */ }
406
- throw new CliError(json.error, json.message);
406
+ throw new CliError(json.error, json.message, undefined, response.status);
407
407
  }
408
408
  return response;
409
409
  }
@@ -412,7 +412,7 @@ export class Client {
412
412
  * that are idempotent on the server (posts carry a client_id for exactly this reason).
413
413
  */
414
414
  async call(method, path, body, opts = {}) {
415
- const headers = this.headers();
415
+ const headers = this.headers(opts.auto);
416
416
  if (body !== undefined)
417
417
  headers["content-type"] = "application/json";
418
418
  const retries = opts.retries ?? 0;
@@ -457,7 +457,7 @@ export class Client {
457
457
  const hint = res.status >= 500
458
458
  ? `This is a platform failure, not something to fix on your side. Do not retry in a loop. Report it once: b9s feedback "<what you were doing>${err.reference ? ` ref ${err.reference}` : ""}" and carry on with other work.`
459
459
  : undefined;
460
- throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint);
460
+ throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint, res.status);
461
461
  }
462
462
  const allowsRedactedExcerpt = method.toUpperCase() === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
463
463
  try {
@@ -495,7 +495,7 @@ export class Client {
495
495
  }
496
496
  if (res.status >= 500) {
497
497
  const err = json;
498
- throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text);
498
+ throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, undefined, res.status);
499
499
  }
500
500
  return { status: res.status, ok: res.ok, json: json };
501
501
  }
@@ -20,6 +20,7 @@ import { environmentAdmin } from "./environment-admin.js";
20
20
  import { flowAdmin } from "./flow.js";
21
21
  import { projectSecrets } from "./project-secrets.js";
22
22
  import { standingRuleAdmin } from "./standing-rules.js";
23
+ import { diagAdmin } from "./diag-admin.js";
23
24
  function adminClient(p) {
24
25
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
25
26
  }
@@ -115,10 +116,24 @@ export async function admin(p, out) {
115
116
  throw new CliError("usage", "milestone <project> <add|edit|show|decide|close|reopen|review|verdict|gap-units> <key> ...");
116
117
  return milestoneWith(adminClient(p), action, rest[0], rest[1], p, out, rest.slice(2));
117
118
  }
119
+ case "obligations": {
120
+ const client = adminClient(p);
121
+ const project = str(p.flags, "project");
122
+ const r = await client.call("GET", project
123
+ ? `/projects/${encodeURIComponent(project)}/obligations`
124
+ : "/account/obligations");
125
+ const now = Date.now();
126
+ const obligations = (r.obligations ?? []).filter((item) => !bool(p.flags, "overdue") || (item.due_at !== null && Date.parse(item.due_at) <= now));
127
+ const lines = obligations.map((item) => `${item.due_at ?? "due time unknown"} ${item.action} ${item.subject.project}${item.subject.number ? ` WU #${item.subject.number}` : ` ${item.subject.kind}`} → ${item.actor.name ?? item.actor.kind} — ${item.reason}${item.unknown_reason ? ` (${item.unknown_reason})` : ""}`);
128
+ out.print(lines.length ? lines.join("\n") : "(no obligations)", { ...r, obligations });
129
+ return;
130
+ }
118
131
  case "needs":
119
132
  return needsAdmin(p, out);
120
133
  case "flow":
121
134
  return flowAdmin(action, rest, p, out);
135
+ case "diag":
136
+ return diagAdmin(action, rest, p, out);
122
137
  case "notice":
123
138
  return adminNotice(action, rest, p, out);
124
139
  case "answer":
@@ -15,6 +15,13 @@ function agentClient(p) {
15
15
  const model = resolveModel(str(p.flags, "model"), process.env, process.cwd(), name);
16
16
  return { client: Client.forAgent(creds, model, { effort: str(p.flags, "effort") }), creds };
17
17
  }
18
+ function obligationOrder(a, b) {
19
+ if (a.due_at === null && b.due_at !== null)
20
+ return 1;
21
+ if (a.due_at !== null && b.due_at === null)
22
+ return -1;
23
+ return (a.due_at ?? a.since ?? "").localeCompare(b.due_at ?? b.since ?? "");
24
+ }
18
25
  /**
19
26
  * The project a command acts in. Project agents: their own. Account agents: --project or
20
27
  * BSCHAT_PROJECT, and an error naming the options otherwise.
@@ -32,6 +39,13 @@ export function projectOf(p, creds) {
32
39
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; this command needs --project <name> (or BSCHAT_PROJECT)`, "See your accessible projects with: b9s me");
33
40
  return v;
34
41
  }
42
+ function isOwnObligation(item, me) {
43
+ if (item.actor.kind === "agent")
44
+ return item.actor.id === me.agent?.id || item.actor.name === me.agent?.name;
45
+ if (item.actor.kind === "role")
46
+ return item.actor.name?.split(", ").includes(me.role?.name) ?? false;
47
+ return false;
48
+ }
35
49
  /** Check explicit account-agent project selection before a command mutates anything. */
36
50
  export async function assertProjectUsable(creds, project) {
37
51
  if (creds.project) {
@@ -95,6 +109,17 @@ export async function me(p, out) {
95
109
  ];
96
110
  out.print(lines.join("\n"), r);
97
111
  }
112
+ export async function next(p, out) {
113
+ const { client } = agentClient(p);
114
+ const project = projectOf(p, loadAgent(resolveAgentName(str(p.flags, "as"))));
115
+ const [me, r] = await Promise.all([
116
+ client.call("GET", "/me"),
117
+ client.call("GET", `/projects/${encodeURIComponent(project)}/obligations`),
118
+ ]);
119
+ const mine = r.obligations.filter((item) => isOwnObligation(item, me));
120
+ const lines = mine.map((item) => `${item.due_at ?? "due time unknown"} ${item.action} ${item.subject.project}${item.subject.number ? ` WU #${item.subject.number}` : ` ${item.subject.kind}`} — ${item.reason}${item.unknown_reason ? ` (${item.unknown_reason})` : ""}`);
121
+ out.print(lines.length ? lines.join("\n") : "(no obligations assigned to you in this project)", { project, obligations: mine });
122
+ }
98
123
  export async function who(p, out) {
99
124
  const { client, creds } = agentClient(p);
100
125
  const projectStalls = async (project) => {
@@ -106,19 +131,34 @@ export async function who(p, out) {
106
131
  return `${fmtStatus(status)}${owned.length ? `\n stalled work: ${owned.map((unit) => `WU #${unit.number} · ${unit.age_minutes} min · ${unit.reason}`).join("; ")}` : ""}`;
107
132
  });
108
133
  if (bool(p.flags, "account") || (!creds.project && !str(p.flags, "project") && !process.env.BSCHAT_PROJECT)) {
109
- const r = await client.call("GET", "/account/agents/status");
134
+ const [r, me] = await Promise.all([client.call("GET", "/account/agents/status"), client.call("GET", "/me")]);
110
135
  const acct = r.account.statuses.length ? `## account-wide agents\n${r.account.statuses.map(fmtStatus).join("\n")}\n\n` : "";
111
136
  const projects = await Promise.all(r.projects.map(async (pr) => {
112
- const stalled = await projectStalls(pr.project);
113
- return { ...pr, stalled_units: stalled, text: `## ${pr.project}\n${pr.statuses.length ? statusLines(pr.statuses, stalled).join("\n") : "(no agents have reported)"}` };
137
+ const [stalled, obligations] = await Promise.all([
138
+ projectStalls(pr.project),
139
+ client.call("GET", `/projects/${encodeURIComponent(pr.project)}/obligations`),
140
+ ]);
141
+ const own_obligations = obligations.obligations.filter((item) => isOwnObligation(item, me)).sort(obligationOrder);
142
+ const obligationText = own_obligations.length
143
+ ? `\n your obligations: ${own_obligations.map((item) => `${item.due_at ?? "due time unknown"} ${item.action}${item.subject.number ? ` WU #${item.subject.number}` : ` ${item.subject.kind}`}: ${item.reason}${item.unknown_reason ? ` (unknown: ${item.unknown_reason})` : ""}`).join("; ")}`
144
+ : "";
145
+ return { ...pr, stalled_units: stalled, own_obligations, text: `## ${pr.project}\n${pr.statuses.length ? statusLines(pr.statuses, stalled).join("\n") : "(no agents have reported)"}${obligationText}` };
114
146
  }));
115
147
  const text = acct + projects.map((pr) => pr.text).join("\n\n");
116
- out.print(text, { ...r, projects });
148
+ const own_obligations = projects.flatMap((pr) => pr.own_obligations).sort(obligationOrder);
149
+ out.print(text, { ...r, projects, own_obligations });
117
150
  return;
118
151
  }
119
- const r = await client.call("GET", `/projects/${projectOf(p, creds)}/agents/status`);
120
- const stalled = await projectStalls(projectOf(p, creds));
121
- out.print(r.statuses.length ? statusLines(r.statuses, stalled).join("\n") : "(no agents have reported status yet)", { ...r, stalled_units: stalled });
152
+ const project = projectOf(p, creds);
153
+ const [r, me, obligations, stalled] = await Promise.all([
154
+ client.call("GET", `/projects/${encodeURIComponent(project)}/agents/status`),
155
+ client.call("GET", "/me"),
156
+ client.call("GET", `/projects/${encodeURIComponent(project)}/obligations`),
157
+ projectStalls(project),
158
+ ]);
159
+ const own = obligations.obligations.filter((item) => isOwnObligation(item, me)).sort(obligationOrder);
160
+ const suffix = own.length ? `\n\nYour obligations:\n${own.map((item) => `${item.due_at ?? "due time unknown"} ${item.action}${item.subject.number ? ` WU #${item.subject.number}` : ` ${item.subject.kind}`}: ${item.reason}${item.unknown_reason ? ` (unknown: ${item.unknown_reason})` : ""}`).join("\n")}` : "";
161
+ out.print((r.statuses.length ? statusLines(r.statuses, stalled).join("\n") : "(no agents have reported status yet)") + suffix, { ...r, stalled_units: stalled, own_obligations: own });
122
162
  }
123
163
  export async function status(p, out) {
124
164
  const sub = p.positionals[1];
@@ -0,0 +1,54 @@
1
+ import { str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAdmin, resolveAdminName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ const adminClient = (p) => Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
6
+ const object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
7
+ const list = (value) => Array.isArray(value) ? value : [];
8
+ const value = (v) => v === null || v === undefined ? "—" : String(v);
9
+ function loadText(snapshot) {
10
+ const lines = [`Production load · since ${value(snapshot.since)} · generated ${value(snapshot.generated_at)}`];
11
+ lines.push("Top routes (D1 time / rows):");
12
+ const routes = list(snapshot.routes);
13
+ if (!routes.length)
14
+ lines.push(" no anomalous requests recorded");
15
+ for (const row of routes)
16
+ lines.push(` ${value(row.route)} · ${value(row.requests)} requests · ${value(row.d1_ms)} ms D1 · ${value(row.duration_ms)} ms wall · ${value(row.rows_read)} rows · ${value(row.statements)} statements · ${value(row.errors_5xx)} 5xx`);
17
+ lines.push("Top normalized statements:");
18
+ const statements = list(snapshot.statements);
19
+ if (!statements.length)
20
+ lines.push(" no statement samples recorded");
21
+ for (const row of statements)
22
+ lines.push(` ${value(row.rows_read)} rows across ${value(row.runs)} samples · ${value(row.sql)}`);
23
+ lines.push("5xx per 5 minutes:");
24
+ const errors = list(snapshot.errors_5m);
25
+ if (!errors.length)
26
+ lines.push(" none");
27
+ for (const row of errors)
28
+ lines.push(` ${value(row.bucket)} · ${value(row.route)} · ${value(row.errors)}`);
29
+ lines.push("Cron durations:");
30
+ const cron = list(snapshot.cron);
31
+ if (!cron.length)
32
+ lines.push(" no anomalous cron runs recorded");
33
+ for (const row of cron)
34
+ lines.push(` ${value(row.route)} · ${value(row.runs)} runs · ${value(row.duration_ms)} ms total · ${value(row.max_duration_ms)} ms max · ${value(row.errors)} errors`);
35
+ return lines.join("\n");
36
+ }
37
+ export async function diagAdmin(action, rest, p, out) {
38
+ if (action !== "load" || rest.length)
39
+ throw new CliError("usage", "b9s-admin diag load [--since 1h|24h|7d] [--route <pattern>] [--json]");
40
+ const unsupported = Object.keys(p.flags).filter((key) => !["admin", "json", "help", "version", "since", "route"].includes(key));
41
+ if (unsupported.length)
42
+ throw new CliError("usage", `unsupported diag option --${unsupported[0]}; run b9s-admin diag --help`);
43
+ const since = str(p.flags, "since") ?? "1h";
44
+ if (!new Set(["1h", "24h", "7d"]).has(since))
45
+ throw new CliError("usage", "--since must be 1h, 24h, or 7d");
46
+ const route = str(p.flags, "route");
47
+ if (route !== undefined && (route.length === 0 || route.length > 160 || !/^(?:\/|cron:)[A-Za-z0-9_./:{}-]+$/.test(route)))
48
+ throw new CliError("usage", "--route must be a stable route pattern");
49
+ const query = new URLSearchParams({ since });
50
+ if (route !== undefined)
51
+ query.set("route", route);
52
+ const response = await adminClient(p).call("GET", `/account/diag/load?${query}`);
53
+ out.print(loadText(object(response.load)), response.load);
54
+ }
@@ -0,0 +1,55 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { redactProcessCommand } from "../machine-processes.js";
3
+ function elapsedSeconds(value) {
4
+ const match = value.match(/^(?:(\d+)-)?(\d+):(\d{2}):(\d{2})$/) ?? value.match(/^(?:(\d+):)?(\d{1,2}):(\d{2})$/);
5
+ if (!match)
6
+ return undefined;
7
+ if (match.length === 5)
8
+ return Number(match[1] ?? 0) * 86400 + Number(match[2]) * 3600 + Number(match[3]) * 60 + Number(match[4]);
9
+ return Number(match[1] ?? 0) * 3600 + Number(match[2]) * 60 + Number(match[3]);
10
+ }
11
+ function readProcessGroup(pgid) {
12
+ const result = spawnSync("ps", ["-eo", "pid=,pgid=,etime=,stat=,command="], { encoding: "utf8", windowsHide: true, maxBuffer: 1024 * 1024 });
13
+ if (result.error)
14
+ return { reason: `${result.error.code ?? "process_table_unavailable"}: ${result.error.message}` };
15
+ if (result.status !== 0)
16
+ return { reason: `ps exited ${result.status}: ${(result.stderr ?? "").trim() || "no diagnostic"}` };
17
+ const descendants = [];
18
+ for (const line of result.stdout.split(/\r?\n/)) {
19
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.+)$/);
20
+ if (!match || Number(match[2]) !== pgid || Number(match[1]) === pgid || match[4].includes("Z"))
21
+ continue;
22
+ const age = elapsedSeconds(match[3]);
23
+ if (age === undefined)
24
+ return { reason: `cannot parse process age from ps row: ${line.slice(0, 180)}` };
25
+ descendants.push({ pid: Number(match[1]), command: redactProcessCommand(match[5].trim()).slice(0, 160), age_seconds: age });
26
+ }
27
+ return { descendants: descendants.slice(0, 20) };
28
+ }
29
+ /** A successful signal-0 probe proves the owned process group is present; permission errors do not. */
30
+ export function probeProcessGroup(pid, kill = process.kill, readGroup = readProcessGroup) {
31
+ if (!pid || process.platform === "win32")
32
+ return { state: "gone" };
33
+ try {
34
+ kill(-pid, 0);
35
+ }
36
+ catch (error) {
37
+ const code = error.code;
38
+ if (code === "ESRCH")
39
+ return { state: "gone" };
40
+ return { state: "unknown", reason: `${code ?? "process_check_failed"}: ${error instanceof Error ? error.message : String(error)}` };
41
+ }
42
+ const table = readGroup(pid);
43
+ if ("reason" in table)
44
+ return { state: "unknown", reason: `cannot read the process table: ${table.reason}` };
45
+ if (table.descendants.length === 0)
46
+ return { state: "gone" };
47
+ return { state: "running", descendants: table.descendants };
48
+ }
49
+ export function finalGroupAction(state) {
50
+ if (state.state === "gone")
51
+ return { action: "finish" };
52
+ if (state.state === "unknown")
53
+ return { action: "retain", kind: "descendants_unknown", reason: state.reason };
54
+ return { action: "retain", kind: "descendants_remain", reason: "the command process group remained after SIGKILL", descendants: state.descendants };
55
+ }
@@ -1,6 +1,7 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { createReadStream, writeSync } from "node:fs";
3
3
  import { constants } from "node:os";
4
+ import { finalGroupAction, probeProcessGroup } from "./lock-run-process-group.js";
4
5
  const command = JSON.parse(process.argv[2] ?? "[]");
5
6
  const send = (record) => {
6
7
  try {
@@ -9,57 +10,73 @@ const send = (record) => {
9
10
  catch { /* The lock owner may have died; the command tree must still be stopped. */ }
10
11
  };
11
12
  let stopping = false;
13
+ let faultReported = false;
12
14
  let killTimer;
13
15
  let spawnError;
14
16
  let taskExitCode;
15
17
  let task;
16
- function groupExists(pid) {
17
- if (!pid || process.platform === "win32")
18
- return false;
19
- try {
20
- process.kill(-pid, 0);
21
- return true;
22
- }
23
- catch (error) {
24
- const code = error.code;
25
- if (code === "ESRCH")
26
- return false;
27
- if (code === "EPERM")
28
- return true;
29
- throw error;
30
- }
31
- }
18
+ const groupState = probeProcessGroup;
32
19
  async function waitForGroupGone(pid, timeoutMs) {
33
20
  const deadline = Date.now() + timeoutMs;
34
- while (groupExists(pid) && Date.now() < deadline)
21
+ while (Date.now() < deadline) {
22
+ const state = groupState(pid);
23
+ if (state.state !== "running")
24
+ return state;
35
25
  await new Promise((resolve) => setTimeout(resolve, 50));
36
- return !groupExists(pid);
26
+ }
27
+ return groupState(pid);
37
28
  }
38
29
  function signalTree(signal) {
39
30
  if (!task?.pid)
40
- return;
31
+ return { state: "gone" };
41
32
  if (process.platform === "win32") {
42
33
  const result = spawnSync("taskkill", ["/PID", String(task.pid), "/T", "/F"], { stdio: "ignore" });
43
34
  if (result.error)
44
- throw result.error;
45
- return;
35
+ return { state: "unknown", reason: result.error.message };
36
+ return result.status === 0 ? { state: "running", descendants: [] } : { state: "gone" };
46
37
  }
47
38
  try {
48
39
  process.kill(-task.pid, signal);
49
40
  }
50
41
  catch (error) {
51
- if (error.code !== "ESRCH")
52
- throw error;
42
+ if (error.code === "ESRCH")
43
+ return { state: "gone" };
44
+ return { state: "unknown", reason: `${error.code ?? "signal_failed"}: ${error instanceof Error ? error.message : String(error)}` };
45
+ }
46
+ return { state: "running", descendants: [] };
47
+ }
48
+ function reportUnknown(reason) {
49
+ if (faultReported)
50
+ return;
51
+ faultReported = true;
52
+ send({ type: "descendants_unknown", reason });
53
+ process.stderr.write(`b9s: cannot verify whether command descendants remain: ${reason}; retaining the lock supervisor\n`);
54
+ }
55
+ function reportRetained(state) {
56
+ const result = finalGroupAction(state);
57
+ if (result.action !== "retain")
58
+ return;
59
+ if (result.kind === "descendants_unknown")
60
+ reportUnknown(result.reason);
61
+ else {
62
+ const details = result.descendants?.map(({ pid, command, age_seconds }) => `pid ${pid}, ${command}, age ${age_seconds}s`).join("; ") ?? "no process details";
63
+ send({ type: result.kind, reason: result.reason, descendants: result.descendants ?? [] });
64
+ process.stderr.write(`b9s: ${result.reason}; ${details}; retaining the lock supervisor\n`);
53
65
  }
54
66
  }
55
67
  function stopTree(signal = "SIGTERM") {
56
68
  if (stopping)
57
69
  return;
58
70
  stopping = true;
59
- signalTree(signal);
71
+ const result = signalTree(signal);
72
+ if (result.state === "unknown") {
73
+ reportUnknown(result.reason);
74
+ return result;
75
+ }
60
76
  // Keep the supervisor alive until resistant descendants receive SIGKILL.
61
77
  // An unreferenced timer can disappear when the shell exits, leaving them alive.
62
78
  killTimer = setTimeout(() => signalTree("SIGKILL"), 5_000);
79
+ return result;
63
80
  }
64
81
  for (const output of [process.stdout, process.stderr]) {
65
82
  output.on("error", (error) => {
@@ -100,22 +117,38 @@ else {
100
117
  task.once("error", (error) => { spawnError = error; taskExitCode = 127; });
101
118
  task.once("exit", (code, signal) => {
102
119
  // Stop any detached descendants that remain in the command's process group.
103
- if (process.platform !== "win32" && groupExists(task?.pid))
120
+ const state = groupState(task?.pid);
121
+ if (state.state === "running")
104
122
  stopTree();
123
+ else if (state.state === "unknown")
124
+ reportUnknown(state.reason);
105
125
  taskExitCode = spawnError ? 127 : (code ?? 128 + (signal ? constants.signals[signal] ?? 0 : 0));
106
126
  if (spawnError)
107
127
  send({ type: "spawn_error", message: spawnError.message });
108
128
  });
109
129
  task.once("close", async () => {
110
130
  const pid = task?.pid;
111
- if (pid && process.platform !== "win32" && groupExists(pid)) {
112
- stopTree();
113
- if (!await waitForGroupGone(pid, 5_000)) {
114
- signalTree("SIGKILL");
115
- if (!await waitForGroupGone(pid, 5_000)) {
116
- process.stderr.write("b9s: command descendants remain after SIGKILL; retaining the lock supervisor\n");
131
+ let state = groupState(pid);
132
+ if (state.state === "unknown") {
133
+ reportRetained(state);
134
+ return;
135
+ }
136
+ if (pid && process.platform !== "win32" && state.state === "running") {
137
+ const stopped = stopTree();
138
+ if (stopped?.state === "unknown")
139
+ return;
140
+ state = await waitForGroupGone(pid, 5_000);
141
+ if (state.state === "running") {
142
+ const killed = signalTree("SIGKILL");
143
+ if (killed.state === "unknown") {
144
+ reportUnknown(killed.reason);
117
145
  return;
118
146
  }
147
+ state = await waitForGroupGone(pid, 5_000);
148
+ }
149
+ if (state.state !== "gone") {
150
+ reportRetained(state);
151
+ return;
119
152
  }
120
153
  }
121
154
  finish(taskExitCode ?? (spawnError ? 127 : 1), spawnError?.message);
@@ -16,6 +16,53 @@ import { redactProcessCommand } from "../machine-processes.js";
16
16
  export function lockRunRetries(path) {
17
17
  return path.endsWith("/release") ? 20 : 8;
18
18
  }
19
+ export function createSupervisorRecordReader(onRecord, log) {
20
+ let pending = "";
21
+ const consume = (line) => {
22
+ if (!line.trim())
23
+ return;
24
+ try {
25
+ onRecord(JSON.parse(line));
26
+ }
27
+ catch {
28
+ log("supervisor sent an invalid status record");
29
+ }
30
+ };
31
+ return {
32
+ push(chunk) {
33
+ pending += chunk;
34
+ if (pending.length > 32_768) {
35
+ pending = "";
36
+ log("supervisor status record exceeded 32768 characters");
37
+ return;
38
+ }
39
+ let newline = pending.indexOf("\n");
40
+ while (newline >= 0) {
41
+ consume(pending.slice(0, newline).replace(/\r$/, ""));
42
+ pending = pending.slice(newline + 1);
43
+ newline = pending.indexOf("\n");
44
+ }
45
+ },
46
+ end() {
47
+ consume(pending.replace(/\r$/, ""));
48
+ pending = "";
49
+ },
50
+ };
51
+ }
52
+ export async function reportSupervisorFault(message, jobId, report, log) {
53
+ if (message.type !== "descendants_unknown" && message.type !== "descendants_remain")
54
+ return;
55
+ const descendants = Array.isArray(message.descendants) ? message.descendants : undefined;
56
+ const fault = { kind: message.type, reason: message.reason ?? "the supervisor could not confirm that the command process group exited", ...(descendants ? { descendants } : {}) };
57
+ const diagnostics = fault.descendants?.map(({ pid, command, age_seconds }) => `PID ${pid} · ${command} · age ${age_seconds}s`).join("; ");
58
+ log(`job ${jobId} lock fault ${fault.kind}: ${fault.reason}${diagnostics ? `; ${diagnostics}` : ""}`);
59
+ try {
60
+ await report(fault);
61
+ }
62
+ catch (error) {
63
+ log(`job ${jobId} could not report lock fault: ${error instanceof Error ? error.message : String(error)}`);
64
+ }
65
+ }
19
66
  /** What a listing shows for the command: one line, at most 200 characters. */
20
67
  export function commandLabel(command) {
21
68
  const line = command.join(" ").replace(/\s+/g, " ").trim();
@@ -88,7 +135,7 @@ export async function runUnderLock(o, deps) {
88
135
  const timer = setInterval(flush, Math.min(30000, Math.max(250, seconds * 1000 / 4)));
89
136
  let result;
90
137
  try {
91
- result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), heartbeat: () => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds }), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
138
+ result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), heartbeat: () => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds }), reportFault: (fault) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds, fault }), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
92
139
  }
93
140
  finally {
94
141
  clearInterval(timer);
@@ -258,25 +305,23 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
258
305
  if (error.code !== "EPIPE")
259
306
  log(`job ${context?.jobId ?? "unknown"} supervisor control pipe failed: ${error.message}`);
260
307
  });
261
- child.stdio[4]?.on("data", (chunk) => {
262
- for (const line of chunk.toString("utf8").split(/\r?\n/)) {
263
- if (!line)
264
- continue;
265
- try {
266
- const message = JSON.parse(line);
267
- if (message.type === "spawn_error")
268
- commandStartFailure = message.message ?? "unknown spawn error";
269
- if (message.type === "done") {
270
- commandExitCode = message.exit_code;
271
- if (message.spawn_error)
272
- commandStartFailure = message.spawn_error;
273
- }
274
- }
275
- catch {
276
- log(`job ${context?.jobId ?? "unknown"} supervisor sent an invalid status record`);
277
- }
308
+ const statusReader = createSupervisorRecordReader((message) => {
309
+ if (message.type === "spawn_error")
310
+ commandStartFailure = message.message ?? "unknown spawn error";
311
+ if (message.type === "descendants_unknown" || message.type === "descendants_remain") {
312
+ if (context?.reportFault)
313
+ void reportSupervisorFault(message, context.jobId, context.reportFault, log);
314
+ else
315
+ log(`job ${context?.jobId ?? "unknown"} lock fault ${message.type}: ${message.reason ?? "no report callback is available"}`);
278
316
  }
279
- });
317
+ if (message.type === "done") {
318
+ commandExitCode = message.exit_code;
319
+ if (message.spawn_error)
320
+ commandStartFailure = message.spawn_error;
321
+ }
322
+ }, (line) => log(`job ${context?.jobId ?? "unknown"} ${line}`));
323
+ child.stdio[4]?.on("data", (chunk) => statusReader.push(chunk.toString("utf8")));
324
+ child.stdio[4]?.on("end", () => statusReader.end());
280
325
  forward = (signal) => { child.kill(signal); };
281
326
  if (context?.heartbeat) {
282
327
  heartbeatTimer = setInterval(() => {
@@ -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 } from "../ux-jobs.js";
47
+ import { reconcilePendingUxJobs, retryPendingUxJobCompletions, uxJobIdsForMachineReport } from "../ux-jobs.js";
48
48
  export const machineFile = () => join(configRoot(), "machine.json");
49
49
  export function loadMachine() {
50
50
  const f = machineFile();
@@ -2000,8 +2000,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2000
2000
  report_interval_seconds: reportIntervalSeconds,
2001
2001
  sessions: out,
2002
2002
  capabilities,
2003
+ active_ux_job_ids: uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps),
2003
2004
  ...(imageProbes.length ? { image_probes: imageProbes } : {}),
2004
2005
  });
2006
+ await retryPendingUxJobCompletions(client, log, deps?.uxJobDeps);
2005
2007
  for (const item of probedProjects) {
2006
2008
  lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
2007
2009
  }
@@ -850,8 +850,13 @@ export async function wu(p, out) {
850
850
  remoteCommitBranch = check.remoteBranch;
851
851
  const containingBranch = check.remoteBranch.replace(/^origin\//, "");
852
852
  where.branch = containingBranch;
853
+ // Record the verified advertised tip, not the possibly older local submission SHA.
854
+ // Repeated submissions of ancestors while origin is unchanged must not reset activity.
853
855
  if (submitUnit.owner_name === creds.agent && submitUnit.branch === localBranch && containingBranch === localBranch && where.head) {
854
- await client.call("POST", `${base}/${num()}/activity`, { source: "branch_push", branch: localBranch, head: where.head });
856
+ const observedHead = check.advertisedTip;
857
+ if (!observedHead)
858
+ throw new CliError("push_observation_unavailable", `the CLI verified ${check.remoteBranch} but has no exact advertised tip to record`);
859
+ await client.call("POST", `${base}/${num()}/activity`, { source: "branch_push", branch: localBranch, head: observedHead }, { auto: { head: observedHead } });
855
860
  }
856
861
  }
857
862
  else if (def.merge.require_pushed) {
@@ -1386,9 +1391,17 @@ export async function wu(p, out) {
1386
1391
  for (const k of ["status", "tag", "agent"])
1387
1392
  if (str(p.flags, k))
1388
1393
  qs.set(k, str(p.flags, k));
1389
- const r = await client.call("GET", `${base}${qs.size ? `?${qs}` : ""}`);
1390
- const rows = r.units.map((u) => ({ n: `#${u.number}`, status: u.stalled ? `STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason} · ${u.status}` : u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
1391
- out.print(rows.length ? table(rows, ["n", "status", "tags", "owner", "reviewers", "awaiting", "base", "title"]) : "(no open work units; b9s wu list --all for closed ones)", r);
1394
+ const [r, obligationRead] = await Promise.all([
1395
+ client.call("GET", `${base}${qs.size ? `?${qs}` : ""}`),
1396
+ client.call("GET", `/projects/${encodeURIComponent(project)}/obligations`),
1397
+ ]);
1398
+ const byUnit = new Map();
1399
+ for (const obligation of obligationRead.obligations)
1400
+ if (obligation.subject.kind === "work_unit" && obligation.subject.number)
1401
+ byUnit.set(obligation.subject.number, obligation);
1402
+ const units = r.units.map((u) => ({ ...u, obligation: byUnit.get(u.number) ?? null }));
1403
+ const rows = units.map((u) => ({ age: u.obligation?.since && Number.isFinite(Date.parse(u.obligation.since)) ? `${Math.max(0, Math.floor((Date.now() - Date.parse(u.obligation.since)) / 60_000))}m` : u.obligation ? "unknown" : "-", n: `#${u.number}`, status: u.stalled ? `STALLED ${u.stalled.age_minutes}m · ${u.stalled.reason} · ${u.status}` : u.status, tags: u.tags.map((t) => `#${t}`).join(" "), owner: u.owner_name, reviewers: u.reviewers.map((x) => x.name).join(",") || "-", awaiting: (u.uncovered ?? []).map((t) => `#${t}`).join(" ") || "-", due: u.obligation?.due_at ?? (u.obligation ? "unknown" : "-"), stalled: u.obligation?.due_at && Date.parse(u.obligation.due_at) <= Date.now() ? "yes" : "no", reason: u.obligation ? `${u.obligation.reason}${u.obligation.unknown_reason ? ` (unknown: ${u.obligation.unknown_reason})` : ""}` : "-", base: u.lands_with ? `#${u.lands_with}` : "-", title: u.title.slice(0, 50) }));
1404
+ out.print(rows.length ? table(rows, ["n", "status", "tags", "owner", "reviewers", "awaiting", "age", "due", "stalled", "reason", "base", "title"]) : "(no open work units; b9s wu list --all for closed ones)", { ...r, obligation_read: obligationRead });
1392
1405
  return;
1393
1406
  }
1394
1407
  case "stalled": {
package/dist/errors.js CHANGED
@@ -1,10 +1,12 @@
1
1
  export class CliError extends Error {
2
2
  code;
3
3
  hint;
4
- constructor(code, message, hint) {
4
+ httpStatus;
5
+ constructor(code, message, hint, httpStatus) {
5
6
  super(message);
6
7
  this.code = code;
7
8
  this.hint = hint;
9
+ this.httpStatus = httpStatus;
8
10
  }
9
11
  }
10
12
  /** A 2xx response committed a write, but its text receipt did not prove the stored text. */
package/dist/git.js CHANGED
@@ -626,12 +626,12 @@ export function findRemoteCommitBranch(sha, localBranch, cwd = process.cwd(), re
626
626
  const fetched = spawnSync("git", ["-c", "fetch.prune=false", "-c", `remote.${remote}.prune=false`, "fetch", remote], { cwd, encoding: "utf8", timeout: 120_000 });
627
627
  if (fetched.status !== 0) {
628
628
  const detail = (fetched.stderr || fetched.stdout || `git fetch ${remote} exited with status ${fetched.status ?? "unknown"}`).trim();
629
- return { remoteBranch: null, checkedRef, checked: false, reason: `git fetch ${remote} failed: ${detail}` };
629
+ return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git fetch ${remote} failed: ${detail}` };
630
630
  }
631
631
  const advertised = spawnSync("git", ["ls-remote", "--heads", remote], { cwd, encoding: "utf8", timeout: 30_000 });
632
632
  if (advertised.status !== 0) {
633
633
  const detail = (advertised.stderr || advertised.stdout || `git ls-remote ${remote} exited with status ${advertised.status ?? "unknown"}`).trim();
634
- return { remoteBranch: null, checkedRef, checked: false, reason: `git ls-remote ${remote} failed: ${detail}` };
634
+ return { remoteBranch: null, advertisedTip: null, checkedRef, checked: false, reason: `git ls-remote ${remote} failed: ${detail}` };
635
635
  }
636
636
  const advertisedTips = new Map();
637
637
  for (const line of advertised.stdout.split("\n")) {
@@ -641,11 +641,26 @@ 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
- ? { remoteBranch, checkedRef, checked: true, reason: null }
648
- : { remoteBranch: null, checkedRef, checked: true, reason: `no advertised ${remote} branch contains the submitted commit ${sha}` };
662
+ ? { remoteBranch, advertisedTip: advertisedTips.get(remoteBranch), checkedRef, checked: true, reason: null }
663
+ : { remoteBranch: null, advertisedTip: null, checkedRef, checked: true, reason: `no advertised ${remote} branch contains the submitted commit ${sha}` };
649
664
  }
650
665
  export function formatRemoteCommitFailure(localBranch, checkedRef, reason) {
651
666
  return `Could not verify the submitted commit for local branch ${localBranch}: checked ${checkedRef} and other origin branches; ${reason}`;
package/dist/help.js CHANGED
@@ -49,8 +49,9 @@ Agent commands
49
49
  b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process, standing rules and notices
50
50
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
51
51
  assigner only: add a project notice; matching commands warn but continue
52
- b9s who [--account] agent status (--account: all projects); shows pressure for active machine sessions
52
+ b9s who [--account] agent status (--account: all projects); shows pressure and your obligations
53
53
  b9s status is this machine ready: install, network interfaces, internet reach, daemon, and what the service last heard from it
54
+ b9s next [--project p] your obligations in due order; unknown deadlines include their reason
54
55
  b9s status set [--state s] [--goal g] [--task t] [--blocked-on b] [--tags a,b] [--custom '{json}']
55
56
  [--checks-every <min>|none] not always on but checking on a schedule: say how often
56
57
  b9s status history <agent> [--limit n]
@@ -459,9 +460,12 @@ Use --admin <nickname> to select one of this machine's saved operator identities
459
460
  b9s-admin milestone <project> gap-units <key> --units n,m
460
461
  b9s-admin flow [--project <p>] [--from <UTC date/time>] [--to <UTC date/time>] [--json]
461
462
  read-only state counts, waits, qualified worker/reviewer capacity, critical paths, attention, trends, freshness and coverage
463
+ b9s-admin diag load [--since 1h|24h|7d] [--route <pattern>] [--json]
464
+ anomalous production request and cron load; scoped to this account unless this is the verified platform account
462
465
  b9s-admin role edit <name> [--project p] --reviews a,b --works c --trials d which tags a role reviews, works and trials ("*" all, "" none)
463
466
  --assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
464
467
  --judges yes|no the turn-judge capability: this role may be chosen as the independent judge (docs/TURN-JUDGE.md)
468
+ b9s-admin obligations [--project p] [--overdue] who acts next and by when; unknown deadlines name their reason
465
469
  b9s-admin needs decisions waiting on you with decision/WU/fault IDs and Console links
466
470
  Browser conditional actions and retry receipts: docs/NEEDS-BROWSER-ACTIONS.md; console work #555/#556
467
471
  b9s-admin answer <id or key> "decision" answer one; the asker is @mentioned and a Console link is printed
package/dist/index.js CHANGED
@@ -60,6 +60,7 @@ const COMMANDS = {
60
60
  environment,
61
61
  notice: agentNotice,
62
62
  who: a.who,
63
+ next: a.next,
63
64
  status: a.status,
64
65
  away: a.away,
65
66
  back: a.back,
package/dist/ux-jobs.js CHANGED
@@ -4,16 +4,140 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
4
4
  import { homedir } from "node:os";
5
5
  import { basename, dirname, join } from "node:path";
6
6
  import { Client } from "./client.js";
7
- import { agentRef, loadAgent, listSaved } from "./config.js";
7
+ import { agentRef, configRoot, loadAgent, listSaved } from "./config.js";
8
8
  import { guessType } from "./commands/evidence.js";
9
9
  import { createGateMarkerScanner, runUnderLock } from "./commands/lock-run.js";
10
10
  import { CliError } from "./errors.js";
11
11
  import { composeMachinePath, requireInstall } from "./install.js";
12
12
  import { isolatedSubprocessEnv } from "./container.js";
13
+ import { writeFileAtomic } from "./shared-file.js";
13
14
  const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
14
15
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
15
16
  const MAX_UX_JOB_LOG_TAIL = 2000;
16
17
  export const UX_JOBS_MAX_CONCURRENT = 3;
18
+ const UX_JOB_COMPLETION_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000];
19
+ function completionStatePath(jobId, deps) {
20
+ const name = createHash("sha256").update(jobId).digest("hex");
21
+ return join(deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions"), `${name}.json`);
22
+ }
23
+ function completionErrorCode(error) {
24
+ const code = error && typeof error === "object" && "code" in error ? String(error.code) : null;
25
+ return code;
26
+ }
27
+ function retryableCompletionError(error) {
28
+ const code = completionErrorCode(error);
29
+ const status = error && typeof error === "object" && "httpStatus" in error ? Number(error.httpStatus) : null;
30
+ return code === "network" || (status !== null && status >= 500 && status <= 599)
31
+ || (code !== null && /^http_5\d\d$/.test(code));
32
+ }
33
+ function defaultCompletionSleep(ms) {
34
+ return new Promise((resolve) => setTimeout(resolve, ms));
35
+ }
36
+ /**
37
+ * Completion is the durable result of expensive work. Save it before sending so a daemon restart
38
+ * can resend it, and never reinterpret a reporting failure as a failed UX or gate run.
39
+ */
40
+ export async function reportUxJobCompletion(machineClient, jobId, body, log, deps = {}) {
41
+ const record = { version: 1, job_id: jobId, body };
42
+ const path = completionStatePath(jobId, deps);
43
+ try {
44
+ writeFileAtomic(path, `${JSON.stringify(record)}\n`, { mode: 0o600 });
45
+ }
46
+ catch (error) {
47
+ log(`UX job ${jobId}: could not persist completion before reporting: ${error.message}`);
48
+ return "pending";
49
+ }
50
+ return sendStoredUxJobCompletion(machineClient, record, path, log, deps);
51
+ }
52
+ async function sendStoredUxJobCompletion(machineClient, record, path, log, deps) {
53
+ const delays = deps.completionRetryDelaysMs ?? UX_JOB_COMPLETION_RETRY_DELAYS_MS;
54
+ const sleep = deps.sleep ?? defaultCompletionSleep;
55
+ const route = `/machines/me/ux-jobs/${encodeURIComponent(record.job_id)}/complete`;
56
+ const attempts = delays.length + 1;
57
+ for (let attempt = 0; attempt < attempts; attempt++) {
58
+ if (attempt > 0)
59
+ await sleep(delays[attempt - 1]);
60
+ try {
61
+ await machineClient.call("POST", route, record.body);
62
+ try {
63
+ rmSync(path, { force: true });
64
+ }
65
+ catch (error) {
66
+ log(`UX job ${record.job_id}: completion was accepted, but its local retry record could not be removed: ${error.message}`);
67
+ }
68
+ return "accepted";
69
+ }
70
+ catch (error) {
71
+ const message = error.message || String(error);
72
+ if (retryableCompletionError(error) && attempt + 1 < attempts) {
73
+ log(`UX job ${record.job_id}: completion report attempt ${attempt + 1}/${attempts} failed; retrying: ${message}`);
74
+ continue;
75
+ }
76
+ if (!retryableCompletionError(error)) {
77
+ try {
78
+ rmSync(path, { force: true });
79
+ }
80
+ catch (removeError) {
81
+ log(`UX job ${record.job_id}: server refused completion and its local retry record could not be removed: ${removeError.message}`);
82
+ }
83
+ log(`UX job ${record.job_id}: completion report refused; saved result discarded: ${message}`);
84
+ return "refused";
85
+ }
86
+ log(`UX job ${record.job_id}: completion report remains pending after ${attempts} attempts: ${message}`);
87
+ return "pending";
88
+ }
89
+ }
90
+ return "pending";
91
+ }
92
+ /** Retry durable completion reports on each daemon reconciliation, including after a restart. */
93
+ export async function retryPendingUxJobCompletions(machineClient, log, deps = {}) {
94
+ const dir = deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions");
95
+ if (!existsSync(dir))
96
+ return;
97
+ let files;
98
+ try {
99
+ files = readdirSync(dir).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).sort();
100
+ }
101
+ catch (error) {
102
+ log(`UX job completion state could not be enumerated: ${error.message}`);
103
+ return;
104
+ }
105
+ for (const name of files) {
106
+ const path = join(dir, name);
107
+ let record;
108
+ try {
109
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
110
+ if (parsed.version !== 1 || typeof parsed.job_id !== "string" || !parsed.job_id
111
+ || !parsed.body || (parsed.body.status !== "succeeded" && parsed.body.status !== "failed")) {
112
+ throw new Error("invalid completion record shape");
113
+ }
114
+ record = parsed;
115
+ }
116
+ catch (error) {
117
+ log(`UX job completion state ${name} was retained because it cannot be read: ${error.message}`);
118
+ continue;
119
+ }
120
+ await sendStoredUxJobCompletion(machineClient, record, path, log, deps);
121
+ }
122
+ }
123
+ /** The machine report identifies jobs that are still executing or have a durable result to resend. */
124
+ export function uxJobIdsForMachineReport(inFlight = defaultUxJobsInFlight, deps = {}) {
125
+ const ids = new Set(inFlight);
126
+ const dir = deps.completionStateRoot ?? join(configRoot(), "state", "ux-job-completions");
127
+ if (!existsSync(dir))
128
+ return [...ids].sort();
129
+ for (const name of readdirSync(dir).filter((entry) => /^[a-f0-9]{64}\.json$/.test(entry))) {
130
+ try {
131
+ const record = JSON.parse(readFileSync(join(dir, name), "utf8"));
132
+ if (record.version === 1 && typeof record.job_id === "string" && record.job_id)
133
+ ids.add(record.job_id);
134
+ }
135
+ catch {
136
+ // The retry pass retains and reports malformed files; they cannot name a job to protect.
137
+ }
138
+ }
139
+ return [...ids].sort();
140
+ }
17
141
  const defaultUxJobsInFlight = new Set();
18
142
  export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
19
143
  if (opts.signal?.aborted) {
@@ -293,8 +417,7 @@ export async function cleanupUxJobWorktree(baseDir, jobDir, runner, env) {
293
417
  timeoutMs: 30_000,
294
418
  }).catch(() => { });
295
419
  }
296
- export function collectUxJobArtifacts(worktreeDir) {
297
- const artifactsRoot = join(worktreeDir, "artifacts");
420
+ export function collectUxJobArtifacts(artifactsRoot) {
298
421
  if (!existsSync(artifactsRoot))
299
422
  return [];
300
423
  const results = [];
@@ -426,10 +549,10 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
426
549
  const message = error.message;
427
550
  try {
428
551
  await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/claim`, {});
429
- await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
552
+ await reportUxJobCompletion(machineClient, job.id, {
430
553
  status: "failed",
431
554
  error: message,
432
- });
555
+ }, ctx.log, deps);
433
556
  }
434
557
  catch {
435
558
  // Ignore secondary report error if claim failed.
@@ -460,6 +583,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
460
583
  logTail = logTail.slice(-MAX_UX_JOB_LOG_TAIL);
461
584
  };
462
585
  const uploadedIds = [];
586
+ const jobArtifactDir = join(jobWorktreeDir, "artifacts", "remote-jobs", job.id);
463
587
  try {
464
588
  if (jobKind === "ux") {
465
589
  if (job.task && !SLUG_RE.test(job.task))
@@ -505,6 +629,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
505
629
  lockedEnv.B9S_LOCK_SLOT = String(lockContext.slot);
506
630
  else
507
631
  delete lockedEnv.B9S_LOCK_SLOT;
632
+ lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = jobArtifactDir;
508
633
  const heartbeatController = new AbortController();
509
634
  let heartbeatTimer;
510
635
  let heartbeatInFlight;
@@ -588,7 +713,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
588
713
  });
589
714
  scanner.push("", true);
590
715
  appendLog(fullOutput || gateRes.stdout || gateRes.stderr);
591
- const logDir = join(jobWorktreeDir, "artifacts", "gate");
716
+ const logDir = join(jobArtifactDir, "gate");
592
717
  mkdirSync(logDir, { recursive: true });
593
718
  gateLogFile = join(logDir, `gate-wu${job.work_unit_number}-${shortHead}.log`);
594
719
  writeFileSync(gateLogFile, fullOutput || `${gateRes.stdout}\n${gateRes.stderr}` || `exit ${gateRes.status ?? 1}\n`);
@@ -661,7 +786,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
661
786
  }
662
787
  },
663
788
  }, agentClient, ctx.log);
664
- const artifacts = collectUxJobArtifacts(jobWorktreeDir);
789
+ const artifacts = collectUxJobArtifacts(jobArtifactDir);
665
790
  const taskTag = jobKind === "gate"
666
791
  ? `gate ${exitCode === 0 ? "PASSED" : "FAILED"}`
667
792
  : [job.task, job.compare_screen ? `compare-${job.compare_screen}` : null].filter(Boolean).join(" ");
@@ -679,35 +804,33 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
679
804
  }
680
805
  if (exitCode !== 0) {
681
806
  const errMsg = `${jobKind} job exited with code ${exitCode}${logTail ? `: ${logTail.slice(-280)}` : ""}`.slice(0, 500);
682
- await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
807
+ await reportUxJobCompletion(machineClient, job.id, {
683
808
  status: "failed",
684
809
  resolved_head: resolvedHead,
685
810
  evidence_ids: uploadedIds,
686
811
  error: errMsg,
687
812
  log_excerpt: logTail || undefined,
688
- });
813
+ }, ctx.log, deps);
689
814
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: errMsg };
690
815
  }
691
- await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
816
+ await reportUxJobCompletion(machineClient, job.id, {
692
817
  status: "succeeded",
693
818
  resolved_head: resolvedHead,
694
819
  evidence_ids: uploadedIds,
695
820
  log_excerpt: logTail || undefined,
696
- });
821
+ }, ctx.log, deps);
697
822
  ctx.log(`${jobKind} job ${job.id}: completed (${uploadedIds.length} artifact(s) posted for WU #${job.work_unit_number} at ${shortHead})`);
698
823
  return { id: job.id, status: "succeeded", evidence_ids: uploadedIds, resolved_head: resolvedHead };
699
824
  }
700
825
  catch (error) {
701
826
  const message = (error.message || `${jobKind} job failed`).slice(0, 500);
702
- await machineClient.call("POST", `/machines/me/ux-jobs/${encodeURIComponent(job.id)}/complete`, {
827
+ await reportUxJobCompletion(machineClient, job.id, {
703
828
  status: "failed",
704
829
  resolved_head: resolvedHead ?? undefined,
705
830
  evidence_ids: uploadedIds,
706
831
  error: message,
707
832
  log_excerpt: logTail || undefined,
708
- }).catch((completeError) => {
709
- ctx.log(`${jobKind} job ${job.id}: completion report failed: ${completeError.message}`);
710
- });
833
+ }, ctx.log, deps);
711
834
  ctx.log(`${jobKind} job ${job.id}: failed (${message})`);
712
835
  return { id: job.id, status: "failed", evidence_ids: uploadedIds, resolved_head: resolvedHead, error: message };
713
836
  }
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.149";
1
+ export const CLI_VERSION = "0.12.152";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.149",
3
+ "version": "0.12.152",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {