benignswarm 0.12.122 → 0.12.124

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.
@@ -19,7 +19,8 @@ import { CliError } from "../errors.js";
19
19
  import { claudeTurnEnv } from "../providers.js";
20
20
  import { acquireWatchLock } from "../lock.js";
21
21
  import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
22
- import { readState, writeState } from "../state.js";
22
+ import { writeFileAtomic } from "../shared-file.js";
23
+ import { readState, updateState } from "../state.js";
23
24
  import { probeCapabilities } from "../capabilities.js";
24
25
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
25
26
  import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS, markTurnUnverified, unverifiedTurn } from "../turn-guard.js";
@@ -195,6 +196,7 @@ export async function watch(p, out, dependencies = {}) {
195
196
  log(`watcher heartbeat failed: ${e.message}`);
196
197
  }
197
198
  }
199
+ await reportUnreportedAck(name, log);
198
200
  if (turn?.harness === "codex") {
199
201
  const current = readState(name);
200
202
  const clear = current.pending_context_clear;
@@ -209,11 +211,11 @@ export async function watch(p, out, dependencies = {}) {
209
211
  bindSession("codex", freshThread, name);
210
212
  }
211
213
  if (freshThread && clear?.status === "pending") {
212
- writeState(name, { ...readState(name), pending_context_clear: { ...clear, new_thread_id: freshThread } });
214
+ updateState(name, (onDisk) => ({ ...onDisk, pending_context_clear: { ...clear, new_thread_id: freshThread } }));
213
215
  log(`context clear opened fresh Codex thread ${freshThread}; the pending unit start will complete its recorded decision`);
214
216
  }
215
217
  else if (freshThread && clear?.status === "completed") {
216
- writeState(name, { ...readState(name), pending_context_clear: undefined });
218
+ updateState(name, (onDisk) => ({ ...onDisk, pending_context_clear: undefined }));
217
219
  log(`context clear completed; watcher now follows fresh Codex thread ${freshThread}`);
218
220
  }
219
221
  }
@@ -370,7 +372,7 @@ export async function watch(p, out, dependencies = {}) {
370
372
  // record the same actual payload bytes and kinds through the hook's existing metric call.
371
373
  await reportDelivery(name, update.text, update.delivery.by_kind, "watch");
372
374
  if (delivered)
373
- writeState(name, { ...readState(name), ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) });
375
+ updateState(name, (onDisk) => ({ ...onDisk, ...(update.noticeNext ? { notice_state: update.noticeNext } : {}), ...(update.measureSnapshot ? { measure_state: update.measureSnapshot } : {}) }));
374
376
  resumeBriefDelivered = resumeBriefDelivered || recoveryBriefWasDelivered(recovery, delivered);
375
377
  if (stopping)
376
378
  return stoppingCode;
@@ -467,12 +469,13 @@ async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, bef
467
469
  const delivered = await deliver(name, command, prompt, `fresh-thread clear for WU #${unit.number}`, "direct", new TextEncoder().encode(prompt).byteLength, log, "context clear; ", seq, turnSink, {}, undefined, model, false, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}) }, allowTurn);
468
470
  if (!delivered)
469
471
  return { sent: false, recoveryBriefDelivered: false };
470
- writeState(name, {
471
- ...readState(name),
472
+ const queuedAt = Date.now();
473
+ updateState(name, (onDisk) => ({
474
+ ...onDisk,
472
475
  watch_seq: seq,
473
- watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
476
+ watch_pending: { seq, at: queuedAt, inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
474
477
  watch_dormant_logged_at: undefined,
475
- });
478
+ }));
476
479
  return { sent: true, recoveryBriefDelivered: false };
477
480
  }
478
481
  export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
@@ -483,14 +486,14 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
483
486
  if (pending) {
484
487
  // Acknowledged (b9s wake ack clears it too; this covers an ack written by another process).
485
488
  if (pending.seq !== undefined && (state.watch_acked ?? 0) >= pending.seq) {
486
- writeState(name, { ...state, watch_pending: undefined, watch_dormant_logged_at: undefined });
489
+ updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }));
487
490
  log(`wake-up #${pending.seq} acknowledged`);
488
491
  }
489
492
  else if (pending.seq === undefined) {
490
493
  // Queued by a watcher before 0.12.37, unnumbered: the old reading rule still releases it.
491
494
  const readSince = state.inbox_after !== pending.inbox_after || JSON.stringify(state.channel_read ?? {}) !== JSON.stringify(pending.channel_read);
492
495
  if (readSince) {
493
- writeState(name, { ...state, watch_pending: undefined, watch_dormant_logged_at: undefined });
496
+ updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }));
494
497
  log("agent has read since the last (unnumbered) wake-up; pending cleared");
495
498
  }
496
499
  }
@@ -501,7 +504,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
501
504
  const waited = Date.now() - st.watch_pending.at;
502
505
  if (waited > unackedAfter * 1000 && Date.now() - (st.watch_dormant_logged_at ?? 0) > 3_600_000) {
503
506
  log(`WAKE-UP ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}NOT ACKNOWLEDGED for ${Math.round(waited / 60_000)} min. Not queueing another. The agent may still be in a long turn; if its session is gone, start one for ${name} and have it run: b9s wake ack`);
504
- writeState(name, { ...st, watch_dormant_logged_at: Date.now() });
507
+ updateState(name, (onDisk) => ({ ...onDisk, watch_dormant_logged_at: Date.now() }));
505
508
  }
506
509
  else if (once)
507
510
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}queued ${Math.round(waited / 1000)}s ago and not acknowledged; not queueing another`);
@@ -523,9 +526,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
523
526
  const commitWatchCursor = () => {
524
527
  if (!u?.watchCursorAfter)
525
528
  return;
526
- const current = readState(name);
527
- if (!current.watch_inbox_after || current.watch_inbox_after < u.watchCursorAfter)
528
- writeState(name, { ...current, watch_inbox_after: u.watchCursorAfter });
529
+ const after = u.watchCursorAfter;
530
+ updateState(name, (onDisk) => !onDisk.watch_inbox_after || onDisk.watch_inbox_after < after ? { ...onDisk, watch_inbox_after: after } : undefined);
529
531
  };
530
532
  // A process change is news too. Watched harnesses never see the Claude Code hook re-deliver the
531
533
  // standing rules, so the watcher compares the version the agent last read with the current one.
@@ -538,7 +540,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
538
540
  if (turnSink && u?.tier !== "direct") {
539
541
  commitWatchCursor();
540
542
  if (st.watch_turn_coalesce_since !== undefined)
541
- writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
543
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_coalesce_since: undefined }));
542
544
  debug(`no wake: ${u ? `${u.tier}-level activity is not direct work` : "no direct work pending"}`);
543
545
  if (once)
544
546
  log(u ? `only ${u.tier}-level unread; not starting a turn` : "no direct work pending; not starting a turn");
@@ -550,7 +552,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
550
552
  ? Math.min(updateAt, st.watch_turn_coalesce_since ?? updateAt)
551
553
  : st.watch_turn_coalesce_since ?? Date.now();
552
554
  if (shouldDeferTurn({ pending: true, firstPendingAt, now: Date.now(), seconds: turnCoalesceSeconds, operator: operatorNew, urgent: u.urgent })) {
553
- writeState(name, { ...readState(name), watch_turn_coalesce_since: firstPendingAt });
555
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_coalesce_since: firstPendingAt }));
554
556
  const readyAt = new Date(firstPendingAt + turnCoalesceSeconds * 1000).toISOString();
555
557
  debug(`no wake: direct work is coalescing until ${readyAt}`);
556
558
  log(`direct wake-up is coalescing until ${readyAt}; later direct items will join it`);
@@ -558,10 +560,10 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
558
560
  }
559
561
  }
560
562
  if (turnSink && st.watch_turn_coalesce_since !== undefined)
561
- writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
563
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_coalesce_since: undefined }));
562
564
  if (!u) {
563
565
  if (st.watch_followed_since)
564
- writeState(name, { ...st, watch_followed_since: undefined });
566
+ updateState(name, (onDisk) => ({ ...onDisk, watch_followed_since: undefined }));
565
567
  if (!processNews) {
566
568
  debug("no wake: no updates and no new process version");
567
569
  if (once)
@@ -581,7 +583,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
581
583
  else if (u.tier === "followed" && !processNews) {
582
584
  const since = st.watch_followed_since ?? Date.now();
583
585
  if (!st.watch_followed_since)
584
- writeState(name, { ...st, watch_followed_since: since });
586
+ updateState(name, (onDisk) => ({ ...onDisk, watch_followed_since: since }));
585
587
  const waited = Date.now() - since;
586
588
  if (waited < followDelay * 1000) {
587
589
  commitWatchCursor();
@@ -621,19 +623,20 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
621
623
  debug("no wake: delivery failed or turn guard denied the launch");
622
624
  return { sent: false, recoveryBriefDelivered: false };
623
625
  }
624
- writeState(name, {
625
- ...readState(name),
626
+ const queuedAt = Date.now();
627
+ updateState(name, (onDisk) => ({
628
+ ...onDisk,
626
629
  ...(u?.watchCursorAfter ? { watch_inbox_after: u.watchCursorAfter } : {}),
627
630
  watch_seq: seq,
628
631
  ...(processNews ? { watch_process_woken: lag.version } : {}),
629
- watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
632
+ watch_pending: { seq, at: queuedAt, inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
630
633
  watch_operator_at: u?.latestOperatorAt ?? st.watch_operator_at,
631
634
  ...(u ? { notice_state: u.noticeNext } : {}),
632
635
  ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
633
636
  watch_followed_since: undefined,
634
637
  watch_turn_coalesce_since: undefined,
635
638
  watch_dormant_logged_at: undefined,
636
- });
639
+ }));
637
640
  return { sent: true, recoveryBriefDelivered: recoveryBriefWasDelivered(recovery, true) };
638
641
  }
639
642
  async function recoveryBriefText(name, log) {
@@ -865,7 +868,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
865
868
  log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged"}${error ? `; ${probe.label} said: ${error}` : ""}${probe.isLimit(error) ? ` (a usage limit with no reset time named)` : ""}. Next turn in 5 min at the earliest; its output is in this log.`);
866
869
  }
867
870
  if (!turn.confirmed)
868
- writeState(name, { ...readState(name, env), watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
871
+ updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }), env);
869
872
  ctl.failedAt = Date.now();
870
873
  }
871
874
  ctl.turn = null;
@@ -1009,7 +1012,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1009
1012
  debug(`no inbox poll: wake-up ${st.watch_pending.seq ?? "(legacy)"} is still pending`);
1010
1013
  // Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
1011
1014
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
1012
- writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
1015
+ updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }), env);
1013
1016
  }
1014
1017
  let oomKillCountBefore = null;
1015
1018
  await wake((t) => {
@@ -1045,8 +1048,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1045
1048
  log(`turn meter is unresolved (${state.state ?? "operator review"}); no next turn starts until the operator reconciles usage`);
1046
1049
  return false;
1047
1050
  }
1048
- current = { ...current, turn_telemetry_completion_pending: undefined };
1049
- writeState(name, current, env);
1051
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: undefined }), env);
1050
1052
  }
1051
1053
  else {
1052
1054
  const result = waiting.capture_enabled === false ? null : await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/agents/me/sessions/${waiting.session_id}/turns/${waiting.turn_id}/complete`, waiting.body);
@@ -1056,13 +1058,11 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1056
1058
  settlement = await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/machines/me/sessions/${waiting.session_id}/turn-spend/reservations/${waiting.turn_id}/settle`, waiting.settlement_body);
1057
1059
  }
1058
1060
  if (needsMeterReconciliation && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
1059
- current = { ...current, turn_telemetry_completion_pending: { ...waiting, settlement_recorded: true } };
1060
- writeState(name, current, env);
1061
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: { ...waiting, settlement_recorded: true } }), env);
1061
1062
  log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
1062
1063
  return false;
1063
1064
  }
1064
- current = { ...current, turn_telemetry_completion_pending: undefined };
1065
- writeState(name, current, env);
1065
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: undefined }), env);
1066
1066
  if (result?.pause_before_next_turn) {
1067
1067
  log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
1068
1068
  return false;
@@ -1086,7 +1086,8 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1086
1086
  }
1087
1087
  const pendingStart = current.turn_telemetry_start_pending;
1088
1088
  const turnId = pendingStart && pendingStart.session_id === machineSessionId ? pendingStart.turn_id : crypto.randomUUID();
1089
- const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour, turnId, false);
1089
+ const attemptAt = Date.now();
1090
+ const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, attemptAt, before.activity_seq, unproductivePerHour, turnId, false);
1090
1091
  if (!begun.start) {
1091
1092
  if (begun.unverified)
1092
1093
  log(`NOT STARTING A TURN: the previous turn is unverified (${begun.unverified.last_error}); it is sampled again on the next tick`);
@@ -1100,7 +1101,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1100
1101
  let reservation;
1101
1102
  if (machineSessionId) {
1102
1103
  let intent = { session_id: machineSessionId, turn_id: turnId, ...(pendingStart?.session_id === machineSessionId && pendingStart.turn_id === turnId ? pendingStart : {}) };
1103
- writeState(name, { ...current, turn_telemetry_start_pending: intent }, env);
1104
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_start_pending: intent }), env);
1104
1105
  try {
1105
1106
  const turnState = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/agents/me/sessions/${intent.session_id}/turn-state`);
1106
1107
  if (turnState.paused) {
@@ -1129,7 +1130,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1129
1130
  meter_available: true,
1130
1131
  };
1131
1132
  intent = { ...intent, exposure, reservation_body: reservationBody };
1132
- writeState(name, { ...readState(name, env), turn_telemetry_start_pending: intent }, env);
1133
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_start_pending: intent }), env);
1133
1134
  const reserveResponse = await spendClient.call("POST", `/machines/me/sessions/${intent.session_id}/turn-spend/reservations`, reservationBody);
1134
1135
  if (reserveResponse.reservation?.reservation_id !== intent.turn_id || reserveResponse.reservation.reserved_tokens !== Number(exposure.max_tokens) || reserveResponse.reservation.reserved_cost_micros !== Number(exposure.max_cost_micros ?? 0) || reserveResponse.reservation.price_catalog_version !== exposure.price_catalog_version || reserveResponse.reservation.state !== "reserved") {
1135
1136
  throw new Error("the budget service did not confirm this turn's exact open reservation; no turn starts");
@@ -1153,21 +1154,35 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1153
1154
  log("turn policy changed while a budget reservation was pending; no turn starts until the reservation is reconciled");
1154
1155
  return false;
1155
1156
  }
1156
- current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
1157
- writeState(name, current, env);
1157
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_start_pending: undefined }), env);
1158
1158
  }
1159
1159
  else {
1160
1160
  throw new Error("the API could not confirm the session's turn policy state; no unattended turn starts");
1161
1161
  }
1162
- current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
1163
1162
  }
1164
1163
  catch (e) {
1165
1164
  log(`turn launch policy is not durably satisfied; no turn starts (retrying the same turn id): ${e.message}`);
1166
1165
  return false;
1167
1166
  }
1168
1167
  }
1169
- const finalGuard = telemetryEnabled || reservation ? { ...begun.state, turns: begun.state.turns.map((t) => t.turn_id === turnId ? { ...t, ...(telemetryEnabled ? { telemetry_enabled: true } : {}), ...(reservation ? { reservation } : {}) } : t) } : begun.state;
1170
- writeState(name, { ...current, turn_guard: finalGuard, turn_telemetry_start_pending: undefined }, env);
1168
+ // The attempt is added to the guard as it is on disk now, inside the lock: the server calls above
1169
+ // took time, and the machine daemon may have resumed (or anything else changed) the guard since
1170
+ // it was read. A guard that no longer allows the turn refuses it; nothing is written over it.
1171
+ let refused = null;
1172
+ updateState(name, (onDisk) => {
1173
+ const again = beginGuardedTurn(onDisk.turn_guard, turnsPerHour, attemptAt, before.activity_seq, unproductivePerHour, turnId, false);
1174
+ if (!again.start) {
1175
+ refused = again;
1176
+ return undefined;
1177
+ }
1178
+ const finalGuard = telemetryEnabled || reservation ? { ...again.state, turns: again.state.turns.map((t) => t.turn_id === turnId ? { ...t, ...(telemetryEnabled ? { telemetry_enabled: true } : {}), ...(reservation ? { reservation } : {}) } : t) } : again.state;
1179
+ return { ...onDisk, turn_guard: finalGuard, turn_telemetry_start_pending: undefined };
1180
+ }, env);
1181
+ if (refused) {
1182
+ const changed = refused;
1183
+ log(`NOT STARTING A TURN: the turn guard changed while the launch was being prepared (${changed.state.fault ? `fault: ${turnFaultSummary(changed.state.fault)}` : changed.unverified ? `the previous turn is unverified: ${changed.unverified.last_error}` : `${changed.state.turns.length}/${turnsPerHour} turns in the rolling hour`}); checked again on the next poll with the same turn id`);
1184
+ return false;
1185
+ }
1171
1186
  return true;
1172
1187
  }
1173
1188
  function logTurnExcerptDisposition(result, log) {
@@ -1195,8 +1210,21 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1195
1210
  // unproductive) and the next watcher tick samples again. activity_seq only grows, so a later
1196
1211
  // sample still answers for this turn.
1197
1212
  const reason = `could not verify the agent's BenignSwarm activity: ${e.message}`;
1198
- const marked = markTurnUnverified(guard, Date.now(), reason);
1199
- writeState(name, { ...current, turn_guard: marked }, env);
1213
+ // Marked on the guard as it is on disk now; if this turn is no longer open there, it was settled elsewhere.
1214
+ let marked = guard;
1215
+ const failedAt = Date.now();
1216
+ updateState(name, (onDisk) => {
1217
+ if (!holdsOpenTurn(onDisk.turn_guard, pending.at)) {
1218
+ marked = onDisk.turn_guard ?? guard;
1219
+ return undefined;
1220
+ }
1221
+ marked = markTurnUnverified(onDisk.turn_guard, failedAt, reason);
1222
+ return { ...onDisk, turn_guard: marked };
1223
+ }, env);
1224
+ if (!unverifiedTurn(marked)) {
1225
+ log(`turn could not be verified (${reason}), and it is no longer open in the turn guard; nothing recorded`);
1226
+ return;
1227
+ }
1200
1228
  log(`turn left unverified (attempt ${unverifiedTurn(marked).unverified.attempts}): ${reason}; counted neither as productive nor unproductive, no new turn until it is verified`);
1201
1229
  return;
1202
1230
  }
@@ -1233,10 +1261,11 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1233
1261
  const usage = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()) : null;
1234
1262
  const tokenValue = tokenOverride !== undefined ? tokenOverride : directTokens !== null ? directTokens : usage?.tokens?.total ?? null;
1235
1263
  const tokenCount = tokenValue !== null && Number.isSafeInteger(tokenValue) && tokenValue >= 0 ? tokenValue : null;
1236
- const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount, pending.telemetry_enabled === true);
1237
- let nextState = { ...current, turn_guard: nextGuard, turn_note: undefined };
1238
- if (pending.telemetry_enabled && pending.turn_id && current.turn_telemetry_start_pending)
1239
- nextState.turn_telemetry_start_pending = undefined;
1264
+ const completedAt = Date.now();
1265
+ // What the guard becomes; settled below on the guard as it is on disk at that moment.
1266
+ let nextGuard = completeGuardedTurn(guard, completedAt, productive, output, tokenCount, pending.telemetry_enabled === true);
1267
+ const clearStartPending = !!(pending.telemetry_enabled && pending.turn_id && current.turn_telemetry_start_pending);
1268
+ let completionPending;
1240
1269
  const rawTokens = usage?.tokens;
1241
1270
  const tokens = rawTokens && [rawTokens.input, rawTokens.cached_input, rawTokens.output, rawTokens.reasoning, rawTokens.total].every((value) => Number.isSafeInteger(value) && value >= 0) ? rawTokens : null;
1242
1271
  const reservation = pending.reservation;
@@ -1266,29 +1295,42 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1266
1295
  } : undefined;
1267
1296
  if (pending.telemetry_enabled || settlementBody) {
1268
1297
  const waiting = { session_id: env.BSCHAT_MACHINE_SESSION_ID, turn_id: pending.turn_id, body: telemetryBody, capture_enabled: pending.telemetry_enabled === true, ...(settlementBody ? { settlement_body: settlementBody } : {}) };
1269
- nextState.turn_telemetry_completion_pending = waiting;
1298
+ completionPending = waiting;
1270
1299
  }
1271
1300
  }
1272
- writeState(name, nextState, env);
1301
+ // The turn's result, applied to the state on disk now (the hook and the agent's commands write
1302
+ // this file while the activity sample above is in flight).
1303
+ // The guard too is completed inside the lock: the machine daemon's resume (which clears a fault
1304
+ // and the consecutive count) may have landed during the activity sample, and must not be undone.
1305
+ updateState(name, (onDisk) => {
1306
+ const open = holdsOpenTurn(onDisk.turn_guard, pending.at);
1307
+ nextGuard = open ? completeGuardedTurn(onDisk.turn_guard, completedAt, productive, output, tokenCount, pending.telemetry_enabled === true) : onDisk.turn_guard ?? nextGuard;
1308
+ return {
1309
+ ...onDisk,
1310
+ ...(open ? { turn_guard: nextGuard } : {}),
1311
+ turn_note: undefined,
1312
+ ...(clearStartPending ? { turn_telemetry_start_pending: undefined } : {}),
1313
+ ...(completionPending ? { turn_telemetry_completion_pending: completionPending } : {}),
1314
+ };
1315
+ }, env);
1273
1316
  if ((pending.telemetry_enabled || pending.reservation) && pending.turn_id && env.BSCHAT_MACHINE_SESSION_ID) {
1274
1317
  try {
1275
1318
  const result = pending.telemetry_enabled
1276
1319
  ? await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", `/agents/me/sessions/${env.BSCHAT_MACHINE_SESSION_ID}/turns/${pending.turn_id}/complete`, telemetryBody)
1277
1320
  : null;
1278
1321
  logTurnExcerptDisposition(result, log);
1279
- const settlementBody = nextState.turn_telemetry_completion_pending?.settlement_body;
1322
+ const settlementBody = completionPending?.settlement_body;
1280
1323
  let settlement;
1281
1324
  if (settlementBody) {
1282
1325
  settlement = await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", `/machines/me/sessions/${env.BSCHAT_MACHINE_SESSION_ID}/turn-spend/reservations/${pending.turn_id}/settle`, settlementBody);
1283
1326
  }
1284
1327
  if (settlementBody && settlementBody.meter_status !== "complete" && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
1285
- nextState = { ...readState(name, env), turn_telemetry_completion_pending: { ...nextState.turn_telemetry_completion_pending, settlement_recorded: true } };
1286
- writeState(name, nextState, env);
1328
+ const recorded = { ...completionPending, settlement_recorded: true };
1329
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: recorded }), env);
1287
1330
  log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
1288
1331
  return;
1289
1332
  }
1290
- nextState = { ...readState(name, env), turn_telemetry_completion_pending: undefined };
1291
- writeState(name, nextState, env);
1333
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: undefined }), env);
1292
1334
  if (result?.pause_before_next_turn)
1293
1335
  log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
1294
1336
  }
@@ -1301,18 +1343,43 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1301
1343
  else if (nextGuard.consecutive_unproductive === 0)
1302
1344
  log("turn was productive: an agent-key call reached BenignSwarm");
1303
1345
  }
1346
+ /** Whether the guard still holds, unsettled, the turn that began at `at`. */
1347
+ function holdsOpenTurn(guard, at) {
1348
+ return !!guard?.turns.some((turn) => turn.at === at && turn.productive === null);
1349
+ }
1304
1350
  function turnFaultSummary(fault) {
1305
1351
  return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `${fault.unproductive_last_hour} unproductive turns in the rolling hour`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
1306
1352
  }
1307
- /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
1308
- async function ackTurn(name, seq, log, env = process.env) {
1309
- writeState(name, applyAck(readState(name, env), seq).next, env);
1353
+ const postAck = (name, env) => async (seq) => {
1354
+ await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
1355
+ };
1356
+ /**
1357
+ * The watcher acknowledges a turn it started: the session shows the agent has the prompt.
1358
+ * The server derives a broken wake path from an acknowledgement it never received, so one that
1359
+ * fails to arrive is kept and sent again every poll (reportUnreportedAck), never dropped: a
1360
+ * database overload once lost one and the agent read as unreachable for 40 minutes while idle.
1361
+ */
1362
+ export async function ackTurn(name, seq, log, env = process.env, post = postAck(name, env)) {
1363
+ updateState(name, (onDisk) => ({ ...applyAck(onDisk, seq).next, watch_ack_unreported: seq }), env);
1364
+ await reportUnreportedAck(name, log, env, post, true);
1365
+ }
1366
+ /** Sends the kept acknowledgement; clears it only when the server accepted it. */
1367
+ export async function reportUnreportedAck(name, log, env = process.env, post = postAck(name, env), first = false) {
1368
+ const seq = readState(name, env).watch_ack_unreported;
1369
+ if (seq === undefined)
1370
+ return;
1310
1371
  try {
1311
- await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
1372
+ await post(seq);
1312
1373
  }
1313
1374
  catch (e) {
1314
- log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
1375
+ if (first)
1376
+ log(`could not report the acknowledgement of turn #${seq} to the server (it will be sent again every poll): ${e.message}`);
1377
+ return;
1315
1378
  }
1379
+ // Only this one: a later acknowledgement recorded while the post was in flight stays to be sent.
1380
+ updateState(name, (onDisk) => onDisk.watch_ack_unreported === seq ? { ...onDisk, watch_ack_unreported: undefined } : undefined, env);
1381
+ if (!first)
1382
+ log(`acknowledgement of turn #${seq} reached the server on a later attempt`);
1316
1383
  }
1317
1384
  const processLine = (lag) => `The project process changed: it is version ${lag.version} now and ${lag.seen ? `you last read version ${lag.seen}` : "you have not read it"}. Read it first: b9s process`;
1318
1385
  const PROCESS_CHECK_MS = 5 * 60_000;
@@ -1328,7 +1395,7 @@ async function processLag(name, st, fresh, log) {
1328
1395
  const me = await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/me");
1329
1396
  const proc = me.process;
1330
1397
  p = proc ? { version: proc.version, seen: proc.seen_version, checked_at: Date.now() } : { version: 0, seen: null, checked_at: Date.now() };
1331
- writeState(name, { ...readState(name), watch_process: p });
1398
+ updateState(name, (onDisk) => ({ ...onDisk, watch_process: p }));
1332
1399
  }
1333
1400
  catch (e) {
1334
1401
  log(`could not check the process version: ${e.message}`);
@@ -1365,7 +1432,7 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
1365
1432
  const args = [requireInstall().bin, "watch", "--as", name, "--exec", exec, "--interval", String(interval), "--follow-delay", String(followDelay), "--startup-jitter-seconds", String(startupJitterSeconds), ...(activity ? ["--activity", activity] : []), ...(prune ? ["--prune"] : []), ...turnArgs(turn)];
1366
1433
  const env = { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir(), ...extraEnv };
1367
1434
  const path = join(systemdUserDir(), `${label}.service`);
1368
- writeFileSync(path, systemdUnit(label, args, process.cwd(), env, logDir));
1435
+ writeFileAtomic(path, systemdUnit(label, args, process.cwd(), env, logDir));
1369
1436
  loadSystemdUnit(label);
1370
1437
  const sess = sessionOfExec(exec);
1371
1438
  if (sess)
@@ -1417,7 +1484,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1417
1484
  </dict></plist>
1418
1485
  `;
1419
1486
  const path = join(dir, `${label}.plist`);
1420
- writeFileSync(path, plist);
1487
+ writeFileAtomic(path, plist);
1421
1488
  // Load it from the file now, replacing a running copy: writing a plist changes nothing launchd
1422
1489
  // has loaded, and a watcher re-pointed at a new session kept waking the old one for two days.
1423
1490
  reloadLaunchAgent(label, path);
@@ -1471,7 +1538,8 @@ export function claimRepoScan(f, by, everyMs, nowMs = Date.now()) {
1471
1538
  return `another watcher (${readFileSync(claim, "utf8")}) claimed this scan`;
1472
1539
  throw e;
1473
1540
  }
1474
- writeFileSync(f, JSON.stringify({ at: nowMs, by }));
1541
+ // Every watcher of the repository reads this marker; a half-written one stopped their scans by name.
1542
+ writeFileAtomic(f, JSON.stringify({ at: nowMs, by }));
1475
1543
  const base = basename(f);
1476
1544
  for (const old of readdirSync(dirname(f))) {
1477
1545
  if (old.startsWith(`${base}.`) && old.endsWith(".claim") && old !== basename(claim))
@@ -6,7 +6,7 @@ import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
6
6
  import { bool, str } from "../args.js";
7
7
  import { Client } from "../client.js";
8
8
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
9
- import { readState, writeState } from "../state.js";
9
+ import { readState, updateState } from "../state.js";
10
10
  import { codexRollout, sessionsOf } from "../sessions.js";
11
11
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
12
12
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
@@ -195,10 +195,8 @@ async function contextDecisionForStart(client, base, unit, name, p, events = [])
195
195
  }
196
196
  const pendingDecision = { ...decision, outcome: "pending", reason: "checkpoint saved; the watcher will start the next turn on a fresh thread", checkpoint_ref: ref, old_thread_id: currentThread };
197
197
  await client.call("POST", `${base}/${unit.number}/context-policy/decision`, pendingDecision);
198
- writeState(name, {
199
- ...state,
200
- pending_context_clear: { project: creds.project, work_unit_number: unit.number, checkpoint_ref: ref, old_thread_id: currentThread, harness, requested_at: new Date().toISOString(), status: "pending" },
201
- });
198
+ const requested = { project: creds.project, work_unit_number: unit.number, checkpoint_ref: ref, old_thread_id: currentThread, harness, requested_at: new Date().toISOString(), status: "pending" };
199
+ updateState(name, (onDisk) => ({ ...onDisk, pending_context_clear: requested }));
202
200
  return { pending_clear: true, checkpoint_ref: ref };
203
201
  }
204
202
  if (!pending.checkpoint_ref || !pending.old_thread_id || pending.harness !== harness) {
@@ -777,9 +775,12 @@ export async function wu(p, out) {
777
775
  }
778
776
  out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
779
777
  if (readState(name).pending_context_clear?.work_unit_number === n) {
780
- const current = readState(name);
781
- const clear = current.pending_context_clear;
782
- writeState(name, { ...current, pending_context_clear: { ...clear, status: "completed", new_thread_id: clear.new_thread_id ?? current.harness_session?.session_id ?? undefined } });
778
+ updateState(name, (onDisk) => {
779
+ const clear = onDisk.pending_context_clear;
780
+ if (clear?.work_unit_number !== n)
781
+ return undefined;
782
+ return { ...onDisk, pending_context_clear: { ...clear, status: "completed", new_thread_id: clear.new_thread_id ?? onDisk.harness_session?.session_id ?? undefined } };
783
+ });
783
784
  }
784
785
  return;
785
786
  }
@@ -950,6 +951,11 @@ export async function wu(p, out) {
950
951
  out.print(`${fmt(r.unit)}\nWU #${num()} priority is ${value}.`, r);
951
952
  return;
952
953
  }
954
+ case "expedite": {
955
+ const r = await client.call("POST", `${base}/${num()}/expedite`, {});
956
+ out.print(`${fmt(r.unit)}\nWU #${num()} expedited to ${r.unit.owner_name}; the owner's current unit is parked until this unit is submitted.`, r);
957
+ return;
958
+ }
953
959
  case "supersede": {
954
960
  const by = str(p.flags, "by");
955
961
  if (!by)
@@ -1281,7 +1287,10 @@ export async function processCmd(p, out) {
1281
1287
  const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
1282
1288
  if (!project)
1283
1289
  throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
1284
- const [r, b] = await Promise.all([client.call("GET", `/projects/${project}/process`), client.call("GET", `/projects/${project}/work-units/board`)]);
1290
+ const [r, b] = await Promise.all([client.call("GET", `/projects/${project}/process`),
1291
+ // Only the roles are needed. This used to fetch the whole Work board, the heaviest read in the
1292
+ // API, and every agent runs this command after each process change.
1293
+ client.call("GET", `/projects/${project}/roles`)]);
1285
1294
  const d = r.process.definition;
1286
1295
  const vocab = r.vocabulary;
1287
1296
  const roles = b.roles;
@@ -1289,7 +1298,10 @@ export async function processCmd(p, out) {
1289
1298
  const lines = [
1290
1299
  `Process v${r.process.version}${r.process.version === 0 ? " (defaults; the operator has not published one)" : ""}`,
1291
1300
  `Machine capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
1292
- `Unlisted heavy workflows use the exclusive unknown-heavy class (the whole safe budget); an unknown budget or stale telemetry waits for operator review.`,
1301
+ // Machine job permits were removed (WU #520). The old line here told agents an unlisted heavy run
1302
+ // "waits for operator review": three units in another project sat for days on asks for a permit
1303
+ // that no longer exists.
1304
+ `Heavy runs (builds, complete suites, device or browser runs) need no permit: run them one at a time under a named lock, b9s lock run <name> --unit <n> -- <command>. Machine pressure in b9s who is advisory.`,
1293
1305
  vocab.length ? `Tags (use them on b9s wu open --tags):` : `No tag vocabulary yet: units route to the default approver (${d.default_approver_role ?? "none"}).`,
1294
1306
  ...vocab.map((t) => ` #${t.name}: ${t.meaning || "(no meaning written)"}${t.require_evidence ? " · requires evidence" : ""}${t.require_rebased ? " · requires a rebased branch" : ""}${t.requires?.length ? ` · requires capabilities ${t.requires.join(", ")}` : ""}${t.focus ? ` · reviewer focus: ${t.focus}` : ""} · reviewed by ${whoReviews(t.name).join(", ") || "NOBODY (the operator must qualify a role)"}`),
1295
1307
  ...Object.entries(d.scope_templates ?? {}).flatMap(([tag, template]) => [` #${tag} scope template:`, ...template.sections.map((section) => ` ${section.name}${section.required ? " (required)" : ""}${section.hint ? ` — ${section.hint}` : ""}`)]),
@@ -1607,6 +1619,16 @@ export function lockActivity(l, nowMs) {
1607
1619
  return ` · running "${l.running.command}" for ${minutes(l.running.started_at)} min`;
1608
1620
  return l.acquired_at ? ` · held ${minutes(l.acquired_at)} min, no command reported` : "";
1609
1621
  }
1622
+ /** A `lock run` waiter remains live by polling; show the server-observed poll age in listings. */
1623
+ export function lockWaiterActivity(waiter, nowMs) {
1624
+ if (!waiter.lock_run)
1625
+ return "";
1626
+ const polledAt = waiter.last_poll_at === undefined ? NaN : Date.parse(waiter.last_poll_at);
1627
+ if (!Number.isFinite(polledAt))
1628
+ return " · last poll unknown";
1629
+ const seconds = Math.floor(Math.max(0, nowMs - polledAt) / 1000);
1630
+ return ` · last poll ${seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m`} ago`;
1631
+ }
1610
1632
  export async function lock(p, out) {
1611
1633
  const name = resolveAgentName(str(p.flags, "as"));
1612
1634
  const creds = loadAgent(name);
@@ -1618,7 +1640,7 @@ export async function lock(p, out) {
1618
1640
  const lockName = p.positionals[1];
1619
1641
  if (cmd === "locks") {
1620
1642
  const r = await client.call("GET", `/projects/${project}/locks`);
1621
- out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${l.holder_name ? `held by ${l.holder_name}${l.unit ? ` (WU #${l.unit})` : ""}${l.holder_legacy === 1 ? " (legacy, no token)" : l.holder_job_id ? ` job ${l.holder_job_id}` : ""}${l.note ? `: ${l.note}` : ""} since ${l.acquired_at.slice(11, 16)} UTC${lockActivity(l, Date.now())}` : "free"}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1643
+ out.print(r.locks.length ? r.locks.map((l) => `${l.name}${l.machine ? ` on ${l.machine}` : " (shared)"}: ${l.holder_name ? `held by ${l.holder_name}${l.unit ? ` (WU #${l.unit})` : ""}${l.holder_legacy === 1 ? " (legacy, no token)" : l.holder_job_id ? ` job ${l.holder_job_id}` : ""}${l.note ? `: ${l.note}` : ""} since ${l.acquired_at.slice(11, 16)} UTC${lockActivity(l, Date.now())}` : "free"}${l.waiting.length ? ` · waiting: ${l.waiting.map((w) => `${w.name}${w.unit ? ` (#${w.unit})` : ""}${w.legacy === 1 ? " (legacy, no token)" : w.job_id ? ` job ${w.job_id}` : ""}${w.note ? `: ${w.note}` : ""}${lockWaiterActivity(w, Date.now())}`).join(", ")}` : ""}`).join("\n") : "No locks in this project. Take one with: b9s lock <name> [--unit n]", r);
1622
1644
  return;
1623
1645
  }
1624
1646
  if (cmd === "lock" && lockName === "run" && (p.rest !== undefined || p.positionals.length > 2)) {
package/dist/config.js CHANGED
@@ -1,9 +1,10 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { existsSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CliError } from "./errors.js";
4
4
  import { findIdentityFile, readIdentityFile, identityWalkStoppedAt } from "./harness.js";
5
5
  import { resolveModelDetailed } from "./model.js";
6
- import { readState, writeState } from "./state.js";
6
+ import { writeFileAtomic } from "./shared-file.js";
7
+ import { readState, updateState } from "./state.js";
7
8
  import { detectVendor } from "./vendor.js";
8
9
  import { configDirectory } from "./directories.js";
9
10
  export const DEFAULT_URL = "https://api.benignswarm.org";
@@ -65,9 +66,9 @@ function migrateLegacyAgents(env) {
65
66
  }
66
67
  }
67
68
  function save(path, data) {
68
- mkdirSync(join(path, ".."), { recursive: true });
69
- writeFileSync(path, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
70
- chmodSync(path, 0o600);
69
+ // Replaced in one step: a key is re-minted (the machine daemon, a rotation) while the agent's
70
+ // watcher and hooks are reading this file, and a half-written one reads as no credentials.
71
+ writeFileAtomic(path, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 });
71
72
  }
72
73
  export function saveAgent(creds, env = process.env) {
73
74
  migrateLegacyAgents(env);
@@ -233,7 +234,7 @@ export function resolveModel(flag, env = process.env, cwd = process.cwd(), agent
233
234
  try {
234
235
  const st = readState(name, env);
235
236
  if (st.model !== r.model)
236
- writeState(name, { ...st, model: r.model, model_observed_at: Date.now() }, env);
237
+ updateState(name, (onDisk) => ({ ...onDisk, model: r.model, model_observed_at: Date.now() }), env);
237
238
  }
238
239
  catch {
239
240
  /* state dir unwritable: nothing to remember */