benignswarm 0.12.88 → 0.12.90
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 +3 -3
- package/dist/brief.js +7 -2
- package/dist/client.js +1 -1
- package/dist/commands/admin.js +22 -4
- package/dist/commands/codex-start.js +59 -24
- package/dist/commands/machine-admin.js +45 -17
- package/dist/commands/machine.js +53 -9
- package/dist/commands/operator.js +6 -3
- package/dist/commands/watch.js +133 -12
- package/dist/commands/worktrees.js +55 -12
- package/dist/commands/wu.js +98 -19
- package/dist/git.js +60 -14
- package/dist/harnesses.js +46 -0
- package/dist/help.js +33 -17
- package/dist/providers.js +84 -0
- package/dist/turn-guard.js +69 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -137,7 +137,9 @@ function describeProcess(r) {
|
|
|
137
137
|
}
|
|
138
138
|
export async function processAdmin(action, rest, p, out) {
|
|
139
139
|
const c = adminClient(p);
|
|
140
|
-
const
|
|
140
|
+
const tagProjectFlag = action === "tag" ? str(p.flags, "project") : undefined;
|
|
141
|
+
const tagOperationFirst = action === "tag" && (["add", "edit", "remove"].includes(rest[0]) && (!(["add", "edit", "remove"].includes(rest[1])) || tagProjectFlag !== undefined));
|
|
142
|
+
const proj = tagProjectFlag ?? (tagOperationFirst ? rest[1] : rest[0]);
|
|
141
143
|
if (!proj && action !== undefined)
|
|
142
144
|
throw new CliError("usage", "admin process <show|export|set|tag|timing|merge|assigners|agreements|charter|steward> <project> ...");
|
|
143
145
|
const base = `/projects/${proj}/process`;
|
|
@@ -184,9 +186,10 @@ export async function processAdmin(action, rest, p, out) {
|
|
|
184
186
|
return publish(doc, `from ${file}`);
|
|
185
187
|
}
|
|
186
188
|
case "tag": {
|
|
187
|
-
const
|
|
189
|
+
const op = tagOperationFirst ? rest[0] : rest[1];
|
|
190
|
+
const tag = tagProjectFlag ? (rest[2] ?? rest[1]) : rest[2];
|
|
188
191
|
if (!["add", "edit", "remove"].includes(op) || !tag)
|
|
189
|
-
throw new CliError("usage", 'admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role
|
|
192
|
+
throw new CliError("usage", 'b9s-admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--tier routine|careful|expert] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name] (legacy project-first order also accepted; for operation-first with project add, edit, or remove, use: process tag <op> <tag> --project <project>)');
|
|
190
193
|
const r = await get();
|
|
191
194
|
const tier = str(p.flags, "tier");
|
|
192
195
|
if (tier !== undefined && !["routine", "careful", "expert"].includes(tier))
|
package/dist/commands/watch.js
CHANGED
|
@@ -16,11 +16,14 @@ import { heartbeatIfActive, resolveActivitySource } from "../heartbeat.js";
|
|
|
16
16
|
import { scanProject, unitWorktrees } from "./worktrees.js";
|
|
17
17
|
import { formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
|
|
18
18
|
import { CliError } from "../errors.js";
|
|
19
|
+
import { claudeTurnEnv } from "../providers.js";
|
|
19
20
|
import { acquireWatchLock } from "../lock.js";
|
|
20
21
|
import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
|
|
21
22
|
import { readState, writeState } from "../state.js";
|
|
22
23
|
import { probeCapabilities } from "../capabilities.js";
|
|
23
24
|
import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
|
|
25
|
+
import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
|
|
26
|
+
import { sessionUsage } from "../usage.js";
|
|
24
27
|
function omitMeasuresAlreadyIn(text, updates) {
|
|
25
28
|
if (!text)
|
|
26
29
|
return updates;
|
|
@@ -65,6 +68,11 @@ export async function watch(p, out) {
|
|
|
65
68
|
const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
|
|
66
69
|
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
67
70
|
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
71
|
+
const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
|
|
72
|
+
if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
|
|
73
|
+
throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
|
|
74
|
+
if (!turnMode && p.flags["turns-per-hour"] !== undefined)
|
|
75
|
+
throw new CliError("usage", "--turns-per-hour is only used with --turn");
|
|
68
76
|
const thread = exec ? threadOfExec(exec) : null;
|
|
69
77
|
// Which harness runs the turns and the session they continue. Codex watchers installed before
|
|
70
78
|
// 0.12.66 carry neither flag: their thread is in the exec command.
|
|
@@ -83,7 +91,15 @@ export async function watch(p, out) {
|
|
|
83
91
|
const session = (str(p.flags, "session") ?? (harness === "codex" ? thread : null))?.toLowerCase();
|
|
84
92
|
if (!session)
|
|
85
93
|
throw new CliError("usage", `--turn with --harness ${harness} needs --session <id>: the session its turns continue`);
|
|
86
|
-
|
|
94
|
+
const providerName = str(p.flags, "provider") ?? "anthropic";
|
|
95
|
+
if (providerName !== "anthropic" && providerName !== "deepseek")
|
|
96
|
+
throw new CliError("usage", "--provider must be anthropic or deepseek");
|
|
97
|
+
if (providerName === "deepseek" && harness !== "claude-code")
|
|
98
|
+
throw new CliError("usage", "--provider deepseek requires --harness claude-code");
|
|
99
|
+
turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model: str(p.flags, "model") };
|
|
100
|
+
}
|
|
101
|
+
else if (p.flags.provider !== undefined) {
|
|
102
|
+
throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
|
|
87
103
|
}
|
|
88
104
|
if (bool(p.flags, "launchd") || bool(p.flags, "service")) {
|
|
89
105
|
if (!exec)
|
|
@@ -228,10 +244,10 @@ export async function watch(p, out) {
|
|
|
228
244
|
if (!full) {
|
|
229
245
|
try {
|
|
230
246
|
if (probe)
|
|
231
|
-
await turnStep(ctl, probe, turnTimeout, log, async (sink) => {
|
|
232
|
-
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "dsh", () => probe.beginTurn?.());
|
|
247
|
+
await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
|
|
248
|
+
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" && turn.provider === "deepseek" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn);
|
|
233
249
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
234
|
-
}, name);
|
|
250
|
+
}, name, turn?.turnsPerHour ?? turnsPerHour);
|
|
235
251
|
else {
|
|
236
252
|
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
|
|
237
253
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
@@ -318,7 +334,7 @@ async function waitIntervalOrStop(ms, stopped) {
|
|
|
318
334
|
if (timer)
|
|
319
335
|
clearTimeout(timer);
|
|
320
336
|
}
|
|
321
|
-
async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, turnStdin = false, beforeTurn) {
|
|
337
|
+
async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn) {
|
|
322
338
|
const state = readState(name);
|
|
323
339
|
const pending = state.watch_pending;
|
|
324
340
|
if (pending) {
|
|
@@ -405,7 +421,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
|
|
|
405
421
|
// `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
|
|
406
422
|
// the acknowledgement, operator note, process pointer, read commands, and delivery body.
|
|
407
423
|
const line = wake;
|
|
408
|
-
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, turnStdin, beforeTurn)))
|
|
424
|
+
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, undefined, allowTurn)))
|
|
409
425
|
return { sent: false, recoveryBriefDelivered: false };
|
|
410
426
|
writeState(name, {
|
|
411
427
|
...readState(name),
|
|
@@ -430,7 +446,7 @@ async function recoveryBriefText(name, log) {
|
|
|
430
446
|
}
|
|
431
447
|
}
|
|
432
448
|
/** Runs the wake command (or prints the wake-up without one). False when the command failed: nothing was delivered. */
|
|
433
|
-
async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, turnStdin = false, beforeTurn) {
|
|
449
|
+
export async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, provider, model, turnStdin = false, beforeTurn, dependencies = {}, allowTurn) {
|
|
434
450
|
if (!exec) {
|
|
435
451
|
process.stdout.write(wake + "\n");
|
|
436
452
|
return true;
|
|
@@ -442,8 +458,13 @@ async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq,
|
|
|
442
458
|
// it started, and reports how it ended.
|
|
443
459
|
log(`${prefix}[${tier}] starting turn #${seq}: ${summary}`);
|
|
444
460
|
// The agent's own b9s calls in the turn know who they are without any repo file.
|
|
461
|
+
// Provider credentials are read only when spawning the turn and are never persisted in the
|
|
462
|
+
// launchd/systemd service or its command line.
|
|
463
|
+
const providerEnv = claudeTurnEnv(provider, model, dependencies.providerRoot);
|
|
464
|
+
if (allowTurn && !(await allowTurn()))
|
|
465
|
+
return false;
|
|
445
466
|
beforeTurn?.();
|
|
446
|
-
turnSink(startTurn(cmd, { ...env, BSCHAT_AGENT: name }, seq, turnStdin ? wake : undefined));
|
|
467
|
+
turnSink((dependencies.startTurn ?? startTurn)(cmd, { ...env, BSCHAT_AGENT: name, ...providerEnv }, seq, turnStdin ? wake : undefined));
|
|
447
468
|
}
|
|
448
469
|
else {
|
|
449
470
|
log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
|
|
@@ -501,7 +522,7 @@ const KEY_CHECK_MS = 5 * 60_000;
|
|
|
501
522
|
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
502
523
|
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
503
524
|
*/
|
|
504
|
-
export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
525
|
+
export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR) {
|
|
505
526
|
const turn = ctl.turn;
|
|
506
527
|
if (turn) {
|
|
507
528
|
if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
|
|
@@ -513,7 +534,15 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
513
534
|
const mins = Math.round((Date.now() - turn.startedMs) / 60_000);
|
|
514
535
|
const how = turn.exit.code !== null ? `exit ${turn.exit.code}` : `signal ${turn.exit.signal}`;
|
|
515
536
|
// A harness may exit 0 with an error in its result (Claude Code's is_error), so both count.
|
|
516
|
-
|
|
537
|
+
let error = null;
|
|
538
|
+
if (!turn.killedForTimeout) {
|
|
539
|
+
try {
|
|
540
|
+
error = probe.turnError();
|
|
541
|
+
}
|
|
542
|
+
catch (e) {
|
|
543
|
+
error = `could not read the harness result: ${e.message}`;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
517
546
|
if (turn.exit.code === 0 && !error) {
|
|
518
547
|
if (!turn.confirmed)
|
|
519
548
|
await ackTurn(name, turn.seq, log);
|
|
@@ -539,6 +568,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
539
568
|
ctl.failedAt = Date.now();
|
|
540
569
|
}
|
|
541
570
|
ctl.turn = null;
|
|
571
|
+
await completePendingTurnGuard(name, probe, log);
|
|
542
572
|
return;
|
|
543
573
|
}
|
|
544
574
|
if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
|
|
@@ -562,10 +592,25 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
562
592
|
// running by a watcher that restarted (turns run in their own process group and outlive it).
|
|
563
593
|
// Never start a second one.
|
|
564
594
|
const ph = probe.phase();
|
|
595
|
+
const savedGuard = readState(name).turn_guard;
|
|
596
|
+
if (savedGuard?.fault) {
|
|
597
|
+
log(`TURN MODE FAULT: ${turnFaultSummary(savedGuard.fault)}; operator/assigner must resume this session before turns can continue`);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
565
600
|
if ("missing" in ph) {
|
|
601
|
+
if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
|
|
602
|
+
await completePendingTurnGuard(name, probe, log);
|
|
603
|
+
if (readState(name).turn_guard?.fault)
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
566
606
|
log(ph.missing);
|
|
567
607
|
return;
|
|
568
608
|
}
|
|
609
|
+
if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
|
|
610
|
+
await completePendingTurnGuard(name, probe, log);
|
|
611
|
+
if (readState(name).turn_guard?.fault)
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
569
614
|
if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
|
|
570
615
|
const failedAt = Date.parse(ph.lastErrorAt ?? "");
|
|
571
616
|
if (Number.isFinite(failedAt)) {
|
|
@@ -628,7 +673,83 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
628
673
|
log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
|
|
629
674
|
writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined });
|
|
630
675
|
}
|
|
631
|
-
await wake((t) => { ctl.turn = t; })
|
|
676
|
+
await wake((t) => { ctl.turn = t; }, async () => {
|
|
677
|
+
return beginTurnGuardAttempt(name, turnsPerHour, log);
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
async function turnActivity(name) {
|
|
681
|
+
const snapshot = await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/agents/me/turn-activity");
|
|
682
|
+
if (!Number.isInteger(snapshot.activity_seq) || snapshot.activity_seq < 0)
|
|
683
|
+
throw new Error("server returned an invalid turn activity sequence");
|
|
684
|
+
return snapshot;
|
|
685
|
+
}
|
|
686
|
+
/** Reserve every actual harness launch, including b9s start's onboarding turn. */
|
|
687
|
+
export async function beginTurnGuardAttempt(name, turnsPerHour, log) {
|
|
688
|
+
const before = await turnActivity(name);
|
|
689
|
+
const current = readState(name);
|
|
690
|
+
if (current.turn_guard?.fault) {
|
|
691
|
+
log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq);
|
|
695
|
+
writeState(name, { ...current, turn_guard: begun.state });
|
|
696
|
+
if (!begun.start) {
|
|
697
|
+
log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
700
|
+
return true;
|
|
701
|
+
}
|
|
702
|
+
export async function completePendingTurnGuard(name, probe, log, outputOverride) {
|
|
703
|
+
const current = readState(name);
|
|
704
|
+
const guard = current.turn_guard;
|
|
705
|
+
const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
|
|
706
|
+
if (!guard || !pending || pending.activity_seq_before === undefined)
|
|
707
|
+
return;
|
|
708
|
+
let activitySeq = pending.activity_seq_before;
|
|
709
|
+
let sampleError = null;
|
|
710
|
+
try {
|
|
711
|
+
activitySeq = (await turnActivity(name)).activity_seq;
|
|
712
|
+
}
|
|
713
|
+
catch (e) {
|
|
714
|
+
sampleError = `could not verify the agent's BenignSwarm activity: ${e.message}`;
|
|
715
|
+
}
|
|
716
|
+
const productive = activitySeq > pending.activity_seq_before;
|
|
717
|
+
let error = null;
|
|
718
|
+
let output = "";
|
|
719
|
+
let directTokens = null;
|
|
720
|
+
if (outputOverride === undefined) {
|
|
721
|
+
try {
|
|
722
|
+
error = probe.turnError();
|
|
723
|
+
}
|
|
724
|
+
catch (e) {
|
|
725
|
+
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read the harness result: ${e.message}`;
|
|
726
|
+
}
|
|
727
|
+
try {
|
|
728
|
+
output = probe.turnOutput?.() ?? "";
|
|
729
|
+
}
|
|
730
|
+
catch (e) {
|
|
731
|
+
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read the harness output: ${e.message}`;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
else
|
|
735
|
+
output = outputOverride;
|
|
736
|
+
try {
|
|
737
|
+
directTokens = probe.turnTokens?.() ?? null;
|
|
738
|
+
}
|
|
739
|
+
catch (e) {
|
|
740
|
+
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
|
|
741
|
+
}
|
|
742
|
+
output = (output || error || sampleError || "").slice(-800);
|
|
743
|
+
const measured = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()).tokens?.total ?? 0 : 0;
|
|
744
|
+
const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null);
|
|
745
|
+
writeState(name, { ...current, turn_guard: nextGuard });
|
|
746
|
+
if (!productive)
|
|
747
|
+
log(`turn made no agent-key call to BenignSwarm (${nextGuard.consecutive_unproductive}/${MAX_UNPRODUCTIVE_TURNS} consecutive); ${nextGuard.fault ? `FAULT: ${turnFaultSummary(nextGuard.fault)}` : `last output: ${output || "(empty)"}`}`);
|
|
748
|
+
else if (nextGuard.consecutive_unproductive === 0)
|
|
749
|
+
log("turn was productive: an agent-key call reached BenignSwarm");
|
|
750
|
+
}
|
|
751
|
+
function turnFaultSummary(fault) {
|
|
752
|
+
return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `hourly ceiling reached (${fault.turns_last_hour} turns in the last hour)`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
|
|
632
753
|
}
|
|
633
754
|
/** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
|
|
634
755
|
async function ackTurn(name, seq, log) {
|
|
@@ -752,7 +873,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
752
873
|
bindSession(sess.kind, sess.id, name);
|
|
753
874
|
out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
|
|
754
875
|
}
|
|
755
|
-
const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--harness", t.harness, "--session", t.session] : []);
|
|
876
|
+
const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
|
|
756
877
|
function escapeXml(s) {
|
|
757
878
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
758
879
|
}
|
|
@@ -4,9 +4,27 @@ import { Client } from "../client.js";
|
|
|
4
4
|
import { loadAgent, resolveAgentName } from "../config.js";
|
|
5
5
|
import { CliError } from "../errors.js";
|
|
6
6
|
import { spawnSync } from "node:child_process";
|
|
7
|
-
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable } from "../git.js";
|
|
7
|
+
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
|
|
8
8
|
import { table } from "../output.js";
|
|
9
9
|
const CLOSED = ["done", "abandoned", "superseded"];
|
|
10
|
+
const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
|
|
11
|
+
const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
|
|
12
|
+
async function timedClientCall(client, method, path, body, timeoutMs, operation) {
|
|
13
|
+
const controller = new AbortController();
|
|
14
|
+
let timedOut = false;
|
|
15
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
|
|
16
|
+
try {
|
|
17
|
+
return await client.call(method, path, body, { signal: controller.signal });
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (timedOut)
|
|
21
|
+
throw new CliError("timeout", `timed out waiting for ${operation} after ${timeoutMs} ms`);
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
10
28
|
/**
|
|
11
29
|
* What the project's units say about worktrees on this machine: worktrees of units not yet
|
|
12
30
|
* closed (by path, and by branch for a path recorded elsewhere) are never pruned; clean
|
|
@@ -15,8 +33,24 @@ const CLOSED = ["done", "abandoned", "superseded"];
|
|
|
15
33
|
* disk and are skipped one by one; a failure to read the units is an error, never a quieter
|
|
16
34
|
* prune (before, one missing path threw and silently discarded every closed unit).
|
|
17
35
|
*/
|
|
18
|
-
export async function unitWorktrees(creds, project) {
|
|
19
|
-
const
|
|
36
|
+
export async function unitWorktrees(creds, project, options = {}) {
|
|
37
|
+
const timeoutMs = options.timeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
|
|
38
|
+
options.onProgress?.(`Fetching unit states for project ${project} (timeout ${timeoutMs} ms)`);
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
let timedOut = false;
|
|
41
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
|
|
42
|
+
let all;
|
|
43
|
+
try {
|
|
44
|
+
all = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/work-units?all=1`, undefined, { signal: controller.signal });
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (timedOut)
|
|
48
|
+
throw new CliError("timeout", `timed out waiting for unit states from server for project ${project} after ${timeoutMs} ms`);
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
20
54
|
const closed = new Map();
|
|
21
55
|
const active = { paths: new Map(), branches: new Map() };
|
|
22
56
|
for (const u of all.units) {
|
|
@@ -39,7 +73,7 @@ export async function unitWorktrees(creds, project) {
|
|
|
39
73
|
* b9s worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
|
|
40
74
|
* b9s worktrees scan report every linked worktree of the repository you are in (run on each machine)
|
|
41
75
|
*/
|
|
42
|
-
export async function worktrees(p, out) {
|
|
76
|
+
export async function worktrees(p, out, timeouts = {}) {
|
|
43
77
|
const sub = p.positionals[1];
|
|
44
78
|
const name = resolveAgentName(str(p.flags, "as"));
|
|
45
79
|
const creds = loadAgent(name);
|
|
@@ -50,8 +84,11 @@ export async function worktrees(p, out) {
|
|
|
50
84
|
// Space back: delete linked worktrees that are clean and merged into the base branch. Dry run
|
|
51
85
|
// unless --yes. Branches are kept (deleting a worktree never deletes its branch).
|
|
52
86
|
// Worktrees recorded on units that are done or abandoned: clean ones go even if their branch never merged.
|
|
53
|
-
const
|
|
54
|
-
const
|
|
87
|
+
const progress = (line) => process.stderr.write(`b9s: ${line}\n`);
|
|
88
|
+
const requestTimeoutMs = timeouts.requestTimeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
|
|
89
|
+
const statusTimeoutMs = timeouts.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS;
|
|
90
|
+
const units = await unitWorktrees(creds, project, { timeoutMs: requestTimeoutMs, onProgress: progress });
|
|
91
|
+
const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs });
|
|
55
92
|
// --archive: a closed unit's worktree with uncommitted files is saved to archive/wu<n>-leftovers
|
|
56
93
|
// and then removed. Never for a unit still open, never for a worktree whose status is unreadable.
|
|
57
94
|
const archive = bool(p.flags, "archive") ? rep.kept.filter((k) => k.archivable) : [];
|
|
@@ -93,16 +130,20 @@ export async function worktrees(p, out) {
|
|
|
93
130
|
const kept = [];
|
|
94
131
|
const probe = freeSpaceProbe(candidates.map((c) => c.path));
|
|
95
132
|
for (const c of candidates) {
|
|
96
|
-
const r = removePrunable(c);
|
|
133
|
+
const r = removePrunable(c, process.cwd(), statusTimeoutMs);
|
|
97
134
|
if (r.removed)
|
|
98
135
|
removed.push(c.path);
|
|
99
136
|
else
|
|
100
137
|
kept.push({ path: c.path, reason: r.reason ?? "git refused" });
|
|
101
138
|
}
|
|
102
139
|
try {
|
|
103
|
-
await scanProject(creds, project);
|
|
140
|
+
await scanProject(creds, project, { statusTimeoutMs, onProgress: progress, requestTimeoutMs });
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (error instanceof CliError && error.code === "timeout")
|
|
144
|
+
throw error;
|
|
145
|
+
/* the registry catches up on the next scan */
|
|
104
146
|
}
|
|
105
|
-
catch { /* the registry catches up on the next scan */ }
|
|
106
147
|
out.print(`Removed ${removed.length} worktree(s)${removed.length ? `:\n${removed.map((r) => ` ${r}`).join("\n")}` : ""}${kept.length ? `\nKept ${kept.length}: ${kept.map((k) => `${k.path} (${k.reason})`).join("; ")}` : ""}${removed.length ? freedText(probe) : ""}`, { removed, kept, candidates, free_space: probe.after() });
|
|
107
148
|
return;
|
|
108
149
|
}
|
|
@@ -121,12 +162,14 @@ export async function worktrees(p, out) {
|
|
|
121
162
|
out.print(rows.length ? table(rows, ["suggestion", "machine", "path", "branch", "state", "idle", "who", "unit"]) : "(no worktrees recorded; agents register them by working, or run: b9s worktrees scan)", r);
|
|
122
163
|
}
|
|
123
164
|
/** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
|
|
124
|
-
export async function scanProject(creds, project) {
|
|
125
|
-
const scan = scanWorktrees();
|
|
165
|
+
export async function scanProject(creds, project, options = {}) {
|
|
166
|
+
const scan = scanWorktrees(process.cwd(), options);
|
|
126
167
|
if (!scan)
|
|
127
168
|
throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
|
|
128
169
|
const machine = creds.machine || defaultMachine();
|
|
129
170
|
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
130
|
-
const
|
|
171
|
+
const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
|
|
172
|
+
options.onProgress?.(`Reporting worktrees for project ${project} (timeout ${timeoutMs} ms)`);
|
|
173
|
+
const r = await timedClientCall(client, "POST", `/projects/${project}/worktrees/scan`, { machine, repo: scan.repo, worktrees: scan.worktrees }, timeoutMs, `worktree registry scan for project ${project}`);
|
|
131
174
|
return { machine, repo: scan.repo, recorded: r.recorded, missing: r.missing };
|
|
132
175
|
}
|