benignswarm 0.12.123 → 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";
@@ -210,11 +211,11 @@ export async function watch(p, out, dependencies = {}) {
210
211
  bindSession("codex", freshThread, name);
211
212
  }
212
213
  if (freshThread && clear?.status === "pending") {
213
- 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 } }));
214
215
  log(`context clear opened fresh Codex thread ${freshThread}; the pending unit start will complete its recorded decision`);
215
216
  }
216
217
  else if (freshThread && clear?.status === "completed") {
217
- writeState(name, { ...readState(name), pending_context_clear: undefined });
218
+ updateState(name, (onDisk) => ({ ...onDisk, pending_context_clear: undefined }));
218
219
  log(`context clear completed; watcher now follows fresh Codex thread ${freshThread}`);
219
220
  }
220
221
  }
@@ -371,7 +372,7 @@ export async function watch(p, out, dependencies = {}) {
371
372
  // record the same actual payload bytes and kinds through the hook's existing metric call.
372
373
  await reportDelivery(name, update.text, update.delivery.by_kind, "watch");
373
374
  if (delivered)
374
- 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 } : {}) }));
375
376
  resumeBriefDelivered = resumeBriefDelivered || recoveryBriefWasDelivered(recovery, delivered);
376
377
  if (stopping)
377
378
  return stoppingCode;
@@ -468,12 +469,13 @@ async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, bef
468
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);
469
470
  if (!delivered)
470
471
  return { sent: false, recoveryBriefDelivered: false };
471
- writeState(name, {
472
- ...readState(name),
472
+ const queuedAt = Date.now();
473
+ updateState(name, (onDisk) => ({
474
+ ...onDisk,
473
475
  watch_seq: seq,
474
- 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 ?? {} },
475
477
  watch_dormant_logged_at: undefined,
476
- });
478
+ }));
477
479
  return { sent: true, recoveryBriefDelivered: false };
478
480
  }
479
481
  export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
@@ -484,14 +486,14 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
484
486
  if (pending) {
485
487
  // Acknowledged (b9s wake ack clears it too; this covers an ack written by another process).
486
488
  if (pending.seq !== undefined && (state.watch_acked ?? 0) >= pending.seq) {
487
- writeState(name, { ...state, watch_pending: undefined, watch_dormant_logged_at: undefined });
489
+ updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }));
488
490
  log(`wake-up #${pending.seq} acknowledged`);
489
491
  }
490
492
  else if (pending.seq === undefined) {
491
493
  // Queued by a watcher before 0.12.37, unnumbered: the old reading rule still releases it.
492
494
  const readSince = state.inbox_after !== pending.inbox_after || JSON.stringify(state.channel_read ?? {}) !== JSON.stringify(pending.channel_read);
493
495
  if (readSince) {
494
- writeState(name, { ...state, watch_pending: undefined, watch_dormant_logged_at: undefined });
496
+ updateState(name, (onDisk) => ({ ...onDisk, watch_pending: undefined, watch_dormant_logged_at: undefined }));
495
497
  log("agent has read since the last (unnumbered) wake-up; pending cleared");
496
498
  }
497
499
  }
@@ -502,7 +504,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
502
504
  const waited = Date.now() - st.watch_pending.at;
503
505
  if (waited > unackedAfter * 1000 && Date.now() - (st.watch_dormant_logged_at ?? 0) > 3_600_000) {
504
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`);
505
- writeState(name, { ...st, watch_dormant_logged_at: Date.now() });
507
+ updateState(name, (onDisk) => ({ ...onDisk, watch_dormant_logged_at: Date.now() }));
506
508
  }
507
509
  else if (once)
508
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`);
@@ -524,9 +526,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
524
526
  const commitWatchCursor = () => {
525
527
  if (!u?.watchCursorAfter)
526
528
  return;
527
- const current = readState(name);
528
- if (!current.watch_inbox_after || current.watch_inbox_after < u.watchCursorAfter)
529
- 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);
530
531
  };
531
532
  // A process change is news too. Watched harnesses never see the Claude Code hook re-deliver the
532
533
  // standing rules, so the watcher compares the version the agent last read with the current one.
@@ -539,7 +540,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
539
540
  if (turnSink && u?.tier !== "direct") {
540
541
  commitWatchCursor();
541
542
  if (st.watch_turn_coalesce_since !== undefined)
542
- writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
543
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_coalesce_since: undefined }));
543
544
  debug(`no wake: ${u ? `${u.tier}-level activity is not direct work` : "no direct work pending"}`);
544
545
  if (once)
545
546
  log(u ? `only ${u.tier}-level unread; not starting a turn` : "no direct work pending; not starting a turn");
@@ -551,7 +552,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
551
552
  ? Math.min(updateAt, st.watch_turn_coalesce_since ?? updateAt)
552
553
  : st.watch_turn_coalesce_since ?? Date.now();
553
554
  if (shouldDeferTurn({ pending: true, firstPendingAt, now: Date.now(), seconds: turnCoalesceSeconds, operator: operatorNew, urgent: u.urgent })) {
554
- writeState(name, { ...readState(name), watch_turn_coalesce_since: firstPendingAt });
555
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_coalesce_since: firstPendingAt }));
555
556
  const readyAt = new Date(firstPendingAt + turnCoalesceSeconds * 1000).toISOString();
556
557
  debug(`no wake: direct work is coalescing until ${readyAt}`);
557
558
  log(`direct wake-up is coalescing until ${readyAt}; later direct items will join it`);
@@ -559,10 +560,10 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
559
560
  }
560
561
  }
561
562
  if (turnSink && st.watch_turn_coalesce_since !== undefined)
562
- writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
563
+ updateState(name, (onDisk) => ({ ...onDisk, watch_turn_coalesce_since: undefined }));
563
564
  if (!u) {
564
565
  if (st.watch_followed_since)
565
- writeState(name, { ...st, watch_followed_since: undefined });
566
+ updateState(name, (onDisk) => ({ ...onDisk, watch_followed_since: undefined }));
566
567
  if (!processNews) {
567
568
  debug("no wake: no updates and no new process version");
568
569
  if (once)
@@ -582,7 +583,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
582
583
  else if (u.tier === "followed" && !processNews) {
583
584
  const since = st.watch_followed_since ?? Date.now();
584
585
  if (!st.watch_followed_since)
585
- writeState(name, { ...st, watch_followed_since: since });
586
+ updateState(name, (onDisk) => ({ ...onDisk, watch_followed_since: since }));
586
587
  const waited = Date.now() - since;
587
588
  if (waited < followDelay * 1000) {
588
589
  commitWatchCursor();
@@ -622,19 +623,20 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
622
623
  debug("no wake: delivery failed or turn guard denied the launch");
623
624
  return { sent: false, recoveryBriefDelivered: false };
624
625
  }
625
- writeState(name, {
626
- ...readState(name),
626
+ const queuedAt = Date.now();
627
+ updateState(name, (onDisk) => ({
628
+ ...onDisk,
627
629
  ...(u?.watchCursorAfter ? { watch_inbox_after: u.watchCursorAfter } : {}),
628
630
  watch_seq: seq,
629
631
  ...(processNews ? { watch_process_woken: lag.version } : {}),
630
- 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 ?? {} },
631
633
  watch_operator_at: u?.latestOperatorAt ?? st.watch_operator_at,
632
634
  ...(u ? { notice_state: u.noticeNext } : {}),
633
635
  ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
634
636
  watch_followed_since: undefined,
635
637
  watch_turn_coalesce_since: undefined,
636
638
  watch_dormant_logged_at: undefined,
637
- });
639
+ }));
638
640
  return { sent: true, recoveryBriefDelivered: recoveryBriefWasDelivered(recovery, true) };
639
641
  }
640
642
  async function recoveryBriefText(name, log) {
@@ -866,7 +868,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
866
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.`);
867
869
  }
868
870
  if (!turn.confirmed)
869
- 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);
870
872
  ctl.failedAt = Date.now();
871
873
  }
872
874
  ctl.turn = null;
@@ -1010,7 +1012,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1010
1012
  debug(`no inbox poll: wake-up ${st.watch_pending.seq ?? "(legacy)"} is still pending`);
1011
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.
1012
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`);
1013
- 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);
1014
1016
  }
1015
1017
  let oomKillCountBefore = null;
1016
1018
  await wake((t) => {
@@ -1046,8 +1048,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1046
1048
  log(`turn meter is unresolved (${state.state ?? "operator review"}); no next turn starts until the operator reconciles usage`);
1047
1049
  return false;
1048
1050
  }
1049
- current = { ...current, turn_telemetry_completion_pending: undefined };
1050
- writeState(name, current, env);
1051
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: undefined }), env);
1051
1052
  }
1052
1053
  else {
1053
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);
@@ -1057,13 +1058,11 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1057
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);
1058
1059
  }
1059
1060
  if (needsMeterReconciliation && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
1060
- current = { ...current, turn_telemetry_completion_pending: { ...waiting, settlement_recorded: true } };
1061
- writeState(name, current, env);
1061
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: { ...waiting, settlement_recorded: true } }), env);
1062
1062
  log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
1063
1063
  return false;
1064
1064
  }
1065
- current = { ...current, turn_telemetry_completion_pending: undefined };
1066
- writeState(name, current, env);
1065
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: undefined }), env);
1067
1066
  if (result?.pause_before_next_turn) {
1068
1067
  log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
1069
1068
  return false;
@@ -1087,7 +1086,8 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1087
1086
  }
1088
1087
  const pendingStart = current.turn_telemetry_start_pending;
1089
1088
  const turnId = pendingStart && pendingStart.session_id === machineSessionId ? pendingStart.turn_id : crypto.randomUUID();
1090
- 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);
1091
1091
  if (!begun.start) {
1092
1092
  if (begun.unverified)
1093
1093
  log(`NOT STARTING A TURN: the previous turn is unverified (${begun.unverified.last_error}); it is sampled again on the next tick`);
@@ -1101,7 +1101,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1101
1101
  let reservation;
1102
1102
  if (machineSessionId) {
1103
1103
  let intent = { session_id: machineSessionId, turn_id: turnId, ...(pendingStart?.session_id === machineSessionId && pendingStart.turn_id === turnId ? pendingStart : {}) };
1104
- writeState(name, { ...current, turn_telemetry_start_pending: intent }, env);
1104
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_start_pending: intent }), env);
1105
1105
  try {
1106
1106
  const turnState = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/agents/me/sessions/${intent.session_id}/turn-state`);
1107
1107
  if (turnState.paused) {
@@ -1130,7 +1130,7 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1130
1130
  meter_available: true,
1131
1131
  };
1132
1132
  intent = { ...intent, exposure, reservation_body: reservationBody };
1133
- writeState(name, { ...readState(name, env), turn_telemetry_start_pending: intent }, env);
1133
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_start_pending: intent }), env);
1134
1134
  const reserveResponse = await spendClient.call("POST", `/machines/me/sessions/${intent.session_id}/turn-spend/reservations`, reservationBody);
1135
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") {
1136
1136
  throw new Error("the budget service did not confirm this turn's exact open reservation; no turn starts");
@@ -1154,21 +1154,35 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
1154
1154
  log("turn policy changed while a budget reservation was pending; no turn starts until the reservation is reconciled");
1155
1155
  return false;
1156
1156
  }
1157
- current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
1158
- writeState(name, current, env);
1157
+ current = updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_start_pending: undefined }), env);
1159
1158
  }
1160
1159
  else {
1161
1160
  throw new Error("the API could not confirm the session's turn policy state; no unattended turn starts");
1162
1161
  }
1163
- current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
1164
1162
  }
1165
1163
  catch (e) {
1166
1164
  log(`turn launch policy is not durably satisfied; no turn starts (retrying the same turn id): ${e.message}`);
1167
1165
  return false;
1168
1166
  }
1169
1167
  }
1170
- 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;
1171
- 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
+ }
1172
1186
  return true;
1173
1187
  }
1174
1188
  function logTurnExcerptDisposition(result, log) {
@@ -1196,8 +1210,21 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1196
1210
  // unproductive) and the next watcher tick samples again. activity_seq only grows, so a later
1197
1211
  // sample still answers for this turn.
1198
1212
  const reason = `could not verify the agent's BenignSwarm activity: ${e.message}`;
1199
- const marked = markTurnUnverified(guard, Date.now(), reason);
1200
- 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
+ }
1201
1228
  log(`turn left unverified (attempt ${unverifiedTurn(marked).unverified.attempts}): ${reason}; counted neither as productive nor unproductive, no new turn until it is verified`);
1202
1229
  return;
1203
1230
  }
@@ -1234,10 +1261,11 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1234
1261
  const usage = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()) : null;
1235
1262
  const tokenValue = tokenOverride !== undefined ? tokenOverride : directTokens !== null ? directTokens : usage?.tokens?.total ?? null;
1236
1263
  const tokenCount = tokenValue !== null && Number.isSafeInteger(tokenValue) && tokenValue >= 0 ? tokenValue : null;
1237
- const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount, pending.telemetry_enabled === true);
1238
- let nextState = { ...current, turn_guard: nextGuard, turn_note: undefined };
1239
- if (pending.telemetry_enabled && pending.turn_id && current.turn_telemetry_start_pending)
1240
- 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;
1241
1269
  const rawTokens = usage?.tokens;
1242
1270
  const tokens = rawTokens && [rawTokens.input, rawTokens.cached_input, rawTokens.output, rawTokens.reasoning, rawTokens.total].every((value) => Number.isSafeInteger(value) && value >= 0) ? rawTokens : null;
1243
1271
  const reservation = pending.reservation;
@@ -1267,29 +1295,42 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1267
1295
  } : undefined;
1268
1296
  if (pending.telemetry_enabled || settlementBody) {
1269
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 } : {}) };
1270
- nextState.turn_telemetry_completion_pending = waiting;
1298
+ completionPending = waiting;
1271
1299
  }
1272
1300
  }
1273
- 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);
1274
1316
  if ((pending.telemetry_enabled || pending.reservation) && pending.turn_id && env.BSCHAT_MACHINE_SESSION_ID) {
1275
1317
  try {
1276
1318
  const result = pending.telemetry_enabled
1277
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)
1278
1320
  : null;
1279
1321
  logTurnExcerptDisposition(result, log);
1280
- const settlementBody = nextState.turn_telemetry_completion_pending?.settlement_body;
1322
+ const settlementBody = completionPending?.settlement_body;
1281
1323
  let settlement;
1282
1324
  if (settlementBody) {
1283
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);
1284
1326
  }
1285
1327
  if (settlementBody && settlementBody.meter_status !== "complete" && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
1286
- nextState = { ...readState(name, env), turn_telemetry_completion_pending: { ...nextState.turn_telemetry_completion_pending, settlement_recorded: true } };
1287
- writeState(name, nextState, env);
1328
+ const recorded = { ...completionPending, settlement_recorded: true };
1329
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: recorded }), env);
1288
1330
  log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
1289
1331
  return;
1290
1332
  }
1291
- nextState = { ...readState(name, env), turn_telemetry_completion_pending: undefined };
1292
- writeState(name, nextState, env);
1333
+ updateState(name, (onDisk) => ({ ...onDisk, turn_telemetry_completion_pending: undefined }), env);
1293
1334
  if (result?.pause_before_next_turn)
1294
1335
  log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
1295
1336
  }
@@ -1302,6 +1343,10 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
1302
1343
  else if (nextGuard.consecutive_unproductive === 0)
1303
1344
  log("turn was productive: an agent-key call reached BenignSwarm");
1304
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
+ }
1305
1350
  function turnFaultSummary(fault) {
1306
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}`;
1307
1352
  }
@@ -1315,7 +1360,7 @@ const postAck = (name, env) => async (seq) => {
1315
1360
  * database overload once lost one and the agent read as unreachable for 40 minutes while idle.
1316
1361
  */
1317
1362
  export async function ackTurn(name, seq, log, env = process.env, post = postAck(name, env)) {
1318
- writeState(name, { ...applyAck(readState(name, env), seq).next, watch_ack_unreported: seq }, env);
1363
+ updateState(name, (onDisk) => ({ ...applyAck(onDisk, seq).next, watch_ack_unreported: seq }), env);
1319
1364
  await reportUnreportedAck(name, log, env, post, true);
1320
1365
  }
1321
1366
  /** Sends the kept acknowledgement; clears it only when the server accepted it. */
@@ -1331,9 +1376,8 @@ export async function reportUnreportedAck(name, log, env = process.env, post = p
1331
1376
  log(`could not report the acknowledgement of turn #${seq} to the server (it will be sent again every poll): ${e.message}`);
1332
1377
  return;
1333
1378
  }
1334
- const now = readState(name, env);
1335
- if (now.watch_ack_unreported === seq)
1336
- writeState(name, { ...now, watch_ack_unreported: undefined }, env);
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);
1337
1381
  if (!first)
1338
1382
  log(`acknowledgement of turn #${seq} reached the server on a later attempt`);
1339
1383
  }
@@ -1351,7 +1395,7 @@ async function processLag(name, st, fresh, log) {
1351
1395
  const me = await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/me");
1352
1396
  const proc = me.process;
1353
1397
  p = proc ? { version: proc.version, seen: proc.seen_version, checked_at: Date.now() } : { version: 0, seen: null, checked_at: Date.now() };
1354
- writeState(name, { ...readState(name), watch_process: p });
1398
+ updateState(name, (onDisk) => ({ ...onDisk, watch_process: p }));
1355
1399
  }
1356
1400
  catch (e) {
1357
1401
  log(`could not check the process version: ${e.message}`);
@@ -1388,7 +1432,7 @@ export function installWatcherService(name, exec, interval, followDelay, extraEn
1388
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)];
1389
1433
  const env = { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir(), ...extraEnv };
1390
1434
  const path = join(systemdUserDir(), `${label}.service`);
1391
- writeFileSync(path, systemdUnit(label, args, process.cwd(), env, logDir));
1435
+ writeFileAtomic(path, systemdUnit(label, args, process.cwd(), env, logDir));
1392
1436
  loadSystemdUnit(label);
1393
1437
  const sess = sessionOfExec(exec);
1394
1438
  if (sess)
@@ -1440,7 +1484,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
1440
1484
  </dict></plist>
1441
1485
  `;
1442
1486
  const path = join(dir, `${label}.plist`);
1443
- writeFileSync(path, plist);
1487
+ writeFileAtomic(path, plist);
1444
1488
  // Load it from the file now, replacing a running copy: writing a plist changes nothing launchd
1445
1489
  // has loaded, and a watcher re-pointed at a new session kept waking the old one for two days.
1446
1490
  reloadLaunchAgent(label, path);
@@ -1494,7 +1538,8 @@ export function claimRepoScan(f, by, everyMs, nowMs = Date.now()) {
1494
1538
  return `another watcher (${readFileSync(claim, "utf8")}) claimed this scan`;
1495
1539
  throw e;
1496
1540
  }
1497
- 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 }));
1498
1543
  const base = basename(f);
1499
1544
  for (const old of readdirSync(dirname(f))) {
1500
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)
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 */