benignswarm 0.12.164 → 0.12.165
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/antigravity.js +10 -4
- package/dist/args.js +5 -3
- package/dist/build-caches.js +1 -1
- package/dist/client.js +83 -36
- package/dist/command-flags.js +2 -2
- package/dist/commands/codex-start.js +35 -10
- package/dist/commands/flow-agent.js +82 -0
- package/dist/commands/hook.js +23 -5
- package/dist/commands/lock-run.js +7 -15
- package/dist/commands/machine.js +176 -49
- package/dist/commands/mock.js +64 -0
- package/dist/commands/watch.js +5 -3
- package/dist/commands/wu.js +116 -8
- package/dist/config.js +5 -7
- package/dist/errors.js +3 -1
- package/dist/git-sandbox-paths.js +12 -1
- package/dist/git.js +19 -9
- package/dist/harnesses.js +5 -2
- package/dist/help.js +19 -5
- package/dist/index.js +7 -2
- package/dist/machine-network-health.js +50 -0
- package/dist/machine-processes.js +2 -2
- package/dist/machine-report.js +1 -1
- package/dist/merge-train.js +400 -42
- package/dist/model.js +42 -14
- package/dist/scratch-cleanup.js +468 -0
- package/dist/ux-jobs.js +329 -66
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/commands/machine.js
CHANGED
|
@@ -2,13 +2,14 @@ import { spawn, spawnSync } from "node:child_process";
|
|
|
2
2
|
import { Worker } from "node:worker_threads";
|
|
3
3
|
import { FileFactsCache, scanLinesBackward, TAIL_CHUNK_BYTES, TAIL_MAX_BYTES } from "../tail-lines.js";
|
|
4
4
|
import { rotateLogs } from "../log-rotation.js";
|
|
5
|
-
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
5
|
+
import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
|
|
6
6
|
import { chmodSync, closeSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
7
|
import { arch, cpus, freemem, homedir, hostname, loadavg, platform, tmpdir, totalmem, userInfo } from "node:os";
|
|
8
8
|
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
9
9
|
import { str } from "../args.js";
|
|
10
10
|
import { interfaceFacts } from "../network.js";
|
|
11
11
|
import { Client } from "../client.js";
|
|
12
|
+
import { machineNetworkOutages, recordMachineNetworkRequest } from "../machine-network-health.js";
|
|
12
13
|
import { agentRef, configRoot, loadAgent, resolveAgentName, saveAgent } from "../config.js";
|
|
13
14
|
import { CliError } from "../errors.js";
|
|
14
15
|
import { AGY_APPARMOR_PATH, agyAppArmorProfile, BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
|
|
@@ -41,12 +42,13 @@ import { collectModelChecksQueued, modelCheckRuntimeTuple, probeModelRunAsync }
|
|
|
41
42
|
import { authorizeWorktreeScope, redactProcessCommand, scanWorktreeProcesses } from "../machine-processes.js";
|
|
42
43
|
import { runMachineDaemonLoop } from "../machine-daemon.js";
|
|
43
44
|
import { boundMachineReport } from "../machine-report.js";
|
|
45
|
+
import { cleanupStaleVitestScratchDirs, detectLocalDiskPressure } from "../scratch-cleanup.js";
|
|
44
46
|
import { ECRClient } from "@aws-sdk/client-ecr";
|
|
45
47
|
import { EcrHostedRegistry } from "../hosted-registry-ecr.js";
|
|
46
48
|
import { publishHostedImage } from "../hosted-registry.js";
|
|
47
49
|
import { assumeHostedBuilder } from "../hosted-registry-session.js";
|
|
48
50
|
import { pushHostedImage } from "../hosted-registry-push.js";
|
|
49
|
-
import { reconcilePendingUxJobs, retryPendingUxJobCompletions, sweepExpiredUxJobWorktrees, uxJobIdsForMachineReport } from "../ux-jobs.js";
|
|
51
|
+
import { reconcilePendingUxJobs, retryPendingPassedTrainGates, retryPendingUxJobClaims, retryPendingUxJobCompletions, sweepExpiredUxJobWorktrees, uxJobIdsForMachineReport } from "../ux-jobs.js";
|
|
50
52
|
export const machineFile = () => join(configRoot(), "machine.json");
|
|
51
53
|
export function loadMachine() {
|
|
52
54
|
const f = machineFile();
|
|
@@ -59,6 +61,7 @@ const readMachineState = () => {
|
|
|
59
61
|
const state = existsSync(stateFile()) ? JSON.parse(readFileSync(stateFile(), "utf8")) : { sessions: {} };
|
|
60
62
|
state.starting_sessions ??= {};
|
|
61
63
|
state.unsettled_turns ??= {};
|
|
64
|
+
state.resume_restart_handled_at ??= {};
|
|
62
65
|
return state;
|
|
63
66
|
};
|
|
64
67
|
function writeMachineState(s) {
|
|
@@ -75,9 +78,10 @@ function writeMachineState(s) {
|
|
|
75
78
|
* 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
|
|
76
79
|
* 11: Antigravity's linked-worktree Git permissions are narrowed to required data paths.
|
|
77
80
|
* 12: Claude Code workspace-write roots name only the checkout, active unit worktree, narrowed Git metadata, config and caches.
|
|
81
|
+
* 13: subagent mode/model changes restart pool sessions with their new harness controls.
|
|
78
82
|
*/
|
|
79
|
-
const START_REV =
|
|
80
|
-
export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [`image:${imageDigest}`] : []), ...(s.secret_context_hash ? [`secrets:${s.secret_context_hash}`] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
|
|
83
|
+
const START_REV = 13;
|
|
84
|
+
export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.subagents ?? "default", s.subagent_model ?? null, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, ...(s.max_budget_usd != null ? [`budget:${s.max_budget_usd}`] : []), ...(s.harness_binary ? [`binary:${s.harness_binary}`] : []), s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [`image:${imageDigest}`] : []), ...(s.secret_context_hash ? [`secrets:${s.secret_context_hash}`] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
|
|
81
85
|
/** A server thread update must restart the watcher even if a stored fingerprint is unexpectedly stale. */
|
|
82
86
|
export function sessionConfigChanged(s, local, fingerprint) {
|
|
83
87
|
const serverThreadChanged = s.thread !== null && s.thread !== (local?.thread ?? null);
|
|
@@ -90,6 +94,24 @@ export function reconcileThread(s, local) {
|
|
|
90
94
|
return clearing ? null : s.thread ?? local?.thread ?? null;
|
|
91
95
|
}
|
|
92
96
|
export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
|
|
97
|
+
/**
|
|
98
|
+
* A resume timestamp is a one-shot restart request only when it is newer than the signal we
|
|
99
|
+
* handled locally and, for an errored server report, newer than that error itself. This keeps a
|
|
100
|
+
* failed resume from becoming a restart loop while still allowing a later operator resume.
|
|
101
|
+
*/
|
|
102
|
+
export function resumeRestartDue(session, handledAt, watcherActive) {
|
|
103
|
+
if (session.desired !== "running" || !session.turn_resume_at)
|
|
104
|
+
return false;
|
|
105
|
+
if (session.reported?.state !== "error" && watcherActive)
|
|
106
|
+
return false;
|
|
107
|
+
const signalAt = Date.parse(session.turn_resume_at);
|
|
108
|
+
const handledAtMs = handledAt ? Date.parse(handledAt) : Number.NaN;
|
|
109
|
+
const errorAtMs = session.reported?.state === "error" && session.reported_at
|
|
110
|
+
? Date.parse(session.reported_at)
|
|
111
|
+
: Number.NaN;
|
|
112
|
+
const priorAt = Math.max(Number.isFinite(handledAtMs) ? handledAtMs : 0, Number.isFinite(errorAtMs) ? errorAtMs : 0);
|
|
113
|
+
return Number.isFinite(signalAt) && signalAt > priorAt;
|
|
114
|
+
}
|
|
93
115
|
/**
|
|
94
116
|
* During a maintenance drain or window, a session that would be started fresh (no known thread, so
|
|
95
117
|
* `b9s start` runs its first turn at once, past the watchers' check) waits; adopting a known
|
|
@@ -113,6 +135,8 @@ export function startArgs(s, thread, writable = [], startupJitterSeconds) {
|
|
|
113
135
|
...(s.harness_binary ? ["--harness-binary", s.harness_binary] : []),
|
|
114
136
|
...(s.model ? ["--model", s.model] : []),
|
|
115
137
|
...(s.effort ? ["--effort", s.effort] : []),
|
|
138
|
+
"--subagents", s.subagents ?? "default",
|
|
139
|
+
...(s.subagent_model ? ["--subagent-model", s.subagent_model] : []),
|
|
116
140
|
...(thread ? ["--thread", thread] : []),
|
|
117
141
|
...(writable.length && s.sandbox === "workspace-write" ? writable.flatMap((path) => ["--writable-root", path]) : []),
|
|
118
142
|
...(startupJitterSeconds === undefined ? [] : ["--startup-jitter-seconds", String(startupJitterSeconds)]),
|
|
@@ -122,6 +146,7 @@ const KEY_CHECK_MS = 10 * 60_000;
|
|
|
122
146
|
const CAPABILITY_PROBE_MS = 60 * 60_000;
|
|
123
147
|
const lastCapabilityProbe = new Map();
|
|
124
148
|
const WORKTREE_PRUNE_INTERVAL_MS = 60 * 60_000;
|
|
149
|
+
const WORKTREE_PRUNE_PRESSURE_INTERVAL_MS = 15 * 60_000;
|
|
125
150
|
const WORKTREE_PRUNE_TIMEOUT_MS = 2 * 60_000;
|
|
126
151
|
const lastWorktreePrune = new Map();
|
|
127
152
|
export function resetWorktreePrune() {
|
|
@@ -130,6 +155,20 @@ export function resetWorktreePrune() {
|
|
|
130
155
|
void state.worker.terminate();
|
|
131
156
|
lastWorktreePrune.clear();
|
|
132
157
|
}
|
|
158
|
+
function logPruneReclaimed(projectName, result, log) {
|
|
159
|
+
if (result.status === "error" || result.status === "skipped")
|
|
160
|
+
return;
|
|
161
|
+
const removed = typeof result.removed === "number" && Number.isFinite(result.removed) ? Math.max(0, result.removed) : 0;
|
|
162
|
+
const freedBytes = Array.isArray(result.free_space)
|
|
163
|
+
? result.free_space.reduce((sum, entry) => {
|
|
164
|
+
const bytes = entry && typeof entry === "object" ? entry.freedBytes : undefined;
|
|
165
|
+
return sum + (typeof bytes === "number" && Number.isFinite(bytes) ? Math.max(0, bytes) : 0);
|
|
166
|
+
}, 0)
|
|
167
|
+
: 0;
|
|
168
|
+
if (removed > 0 || freedBytes > 0) {
|
|
169
|
+
log(`${projectName}: worktree prune removed ${removed} worktree(s), reclaimed ${freedBytes} bytes`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
133
172
|
export function turnFaultSessionFields(fault, agent) {
|
|
134
173
|
const binding = agent ? readState(agent).watch_turn_binding : undefined;
|
|
135
174
|
return {
|
|
@@ -146,6 +185,7 @@ export function bareDigestOf(imageRef) {
|
|
|
146
185
|
return /^sha256:[a-f0-9]{64}$/i.test(candidate.trim()) ? candidate.trim().toLowerCase() : null;
|
|
147
186
|
}
|
|
148
187
|
const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
|
|
188
|
+
const MACHINE_NETWORK_RETRY_MS = 5 * 60_000;
|
|
149
189
|
const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
|
|
150
190
|
const MACHINE_WATCHDOG_MS = 5 * 60_000;
|
|
151
191
|
export function resolvePinnedImageRef(image) {
|
|
@@ -1120,9 +1160,13 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1120
1160
|
requestTimeoutMs: MACHINE_REQUEST_TIMEOUT_MS,
|
|
1121
1161
|
stagedPoolPreparation: true,
|
|
1122
1162
|
signal: deps?.signal,
|
|
1123
|
-
onRequest: (event) =>
|
|
1124
|
-
|
|
1125
|
-
|
|
1163
|
+
onRequest: (event) => {
|
|
1164
|
+
if (event.phase === "end")
|
|
1165
|
+
recordMachineNetworkRequest(event);
|
|
1166
|
+
log(event.phase === "start"
|
|
1167
|
+
? `request start ${event.method} ${event.path} attempt ${event.attempt}`
|
|
1168
|
+
: `request end ${event.method} ${event.path} attempt ${event.attempt} in ${event.durationMs}ms${event.error ? " (failed)" : ""}`);
|
|
1169
|
+
},
|
|
1126
1170
|
});
|
|
1127
1171
|
if (Date.now() - lastLogRotationAt >= LOG_ROTATION_EVERY_MS) {
|
|
1128
1172
|
lastLogRotationAt = Date.now();
|
|
@@ -1142,7 +1186,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1142
1186
|
const bundle = collectMachineDiagnosticBundle(m.name, workdir, (me.projects ?? []).map((project) => project.name ?? "").filter(Boolean));
|
|
1143
1187
|
for (const query of diagnosticQueries) {
|
|
1144
1188
|
try {
|
|
1145
|
-
await client.call("POST", `/machines/me/diagnostics/${encodeURIComponent(query.id)}`, { bundle }, {
|
|
1189
|
+
await client.call("POST", `/machines/me/diagnostics/${encodeURIComponent(query.id)}`, { bundle }, { retryForMs: MACHINE_NETWORK_RETRY_MS });
|
|
1146
1190
|
log(`uploaded diagnostic evidence for ${query.requester_name}`);
|
|
1147
1191
|
}
|
|
1148
1192
|
catch (error) {
|
|
@@ -1206,6 +1250,12 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1206
1250
|
const service = localWatcherServices.find((entry) => entry.label === watchLabelOf(session.agent));
|
|
1207
1251
|
if (!service || serviceActive(service))
|
|
1208
1252
|
continue;
|
|
1253
|
+
if (resumeRestartDue(session, state.resume_restart_handled_at?.[session.id], false))
|
|
1254
|
+
continue;
|
|
1255
|
+
// An errored session only gets one recovery attempt per operator resume signal. Do not let
|
|
1256
|
+
// the general inactive-watcher recovery sweep retry a failed resume on every daemon poll.
|
|
1257
|
+
if (session.reported?.state === "error")
|
|
1258
|
+
continue;
|
|
1209
1259
|
const sessionWritable = session.sandbox === "workspace-write"
|
|
1210
1260
|
? [...new Set([...defaultWorkspaceWritableRoots(), ...writable])]
|
|
1211
1261
|
: writable;
|
|
@@ -1331,6 +1381,19 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1331
1381
|
const agentStateEnv = containerMode
|
|
1332
1382
|
? { ...process.env, B9S_HOME: join(agentHomeDirOf(s), ".b9s"), BSCHAT_HOME: join(agentHomeDirOf(s), ".b9s") }
|
|
1333
1383
|
: process.env;
|
|
1384
|
+
let local = state.sessions[s.id];
|
|
1385
|
+
const hostSvc = svc();
|
|
1386
|
+
const resumeWatcherActive = containerMode && local?.container_name && local.container_runtime
|
|
1387
|
+
? isContainerRunning(local.container_runtime, local.container_name, runner)
|
|
1388
|
+
: Boolean(hostSvc && serviceActive(hostSvc));
|
|
1389
|
+
const resumeRestart = resumeRestartDue(s, state.resume_restart_handled_at?.[s.id], resumeWatcherActive);
|
|
1390
|
+
if (resumeRestart) {
|
|
1391
|
+
state.resume_restart_handled_at[s.id] = s.turn_resume_at;
|
|
1392
|
+
// Persist before any checkout, credential, or launch work. A failure at any later stage
|
|
1393
|
+
// is still the one attempt authorized by this signal.
|
|
1394
|
+
writeMachineState(state);
|
|
1395
|
+
log(`${s.agent}: handling new turn resume signal; reconciling errored/inactive watcher once`);
|
|
1396
|
+
}
|
|
1334
1397
|
if (!s.dir) {
|
|
1335
1398
|
// A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
|
|
1336
1399
|
const c = ensureCheckout(s, log, workdir);
|
|
@@ -1342,7 +1405,6 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1342
1405
|
}
|
|
1343
1406
|
if (!existsSync(s.dir))
|
|
1344
1407
|
throw new Error(`checkout ${s.dir} does not exist on this machine`);
|
|
1345
|
-
let local = state.sessions[s.id];
|
|
1346
1408
|
if (s.desired === "prepared") {
|
|
1347
1409
|
if (svc() || local?.container_name || state.starting_sessions?.[s.id] || state.unsettled_turns?.[s.dir])
|
|
1348
1410
|
throw new Error("target already has a watcher or recorded container; preparation will not start another");
|
|
@@ -1506,7 +1568,6 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1506
1568
|
const thread = reconcileThread(s, local);
|
|
1507
1569
|
const fp = sessionFingerprint({ ...s, thread }, s.sandbox === "workspace-write" ? sessionWritable : [], pinnedImageRef);
|
|
1508
1570
|
const configChanged = sessionConfigChanged(s, local, fp);
|
|
1509
|
-
const hostSvc = svc();
|
|
1510
1571
|
if (containerMode && hostSvc) {
|
|
1511
1572
|
removeService(hostSvc);
|
|
1512
1573
|
log(`${s.agent}: removed host watcher service before container supervision`);
|
|
@@ -1520,12 +1581,27 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1520
1581
|
const containerActive = containerMode && activeContainerRuntime && activeContainerName
|
|
1521
1582
|
? isContainerRunning(activeContainerRuntime, activeContainerName, runner)
|
|
1522
1583
|
: false;
|
|
1584
|
+
const watcherActive = containerMode ? containerActive : Boolean(hostSvc && serviceActive(hostSvc));
|
|
1585
|
+
if (s.reported?.state === "error" && !resumeRestart && !watcherActive && !state.starting_sessions?.[s.id] && !configChanged) {
|
|
1586
|
+
out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error: s.reported.error ?? "session remains errored; a newer resume signal is required" });
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1523
1589
|
if (!s.secret_grant_required) {
|
|
1524
1590
|
clearSessionSecrets(s.id);
|
|
1525
1591
|
}
|
|
1592
|
+
if (resumeRestart) {
|
|
1593
|
+
if (!containerMode && hostSvc) {
|
|
1594
|
+
removeService(hostSvc);
|
|
1595
|
+
log(`${s.agent}: removed previous watcher before the one-shot resume restart`);
|
|
1596
|
+
}
|
|
1597
|
+
if (containerMode && local?.container_name && local.container_runtime) {
|
|
1598
|
+
removeAgentContainer(local.container_runtime, local.container_name, runner);
|
|
1599
|
+
log(`${s.agent}: removed previous container before the one-shot resume restart`);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1526
1602
|
const needsLaunch = containerMode
|
|
1527
|
-
? (configChanged || !containerActive)
|
|
1528
|
-
: (!hostSvc || configChanged);
|
|
1603
|
+
? (configChanged || !containerActive || resumeRestart)
|
|
1604
|
+
: (!hostSvc || configChanged || resumeRestart);
|
|
1529
1605
|
if (needsLaunch) {
|
|
1530
1606
|
if (local?.has_project_secrets && configChanged) {
|
|
1531
1607
|
if (!containerMode && hostSvc) {
|
|
@@ -1886,15 +1962,25 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1886
1962
|
log(`build cache fault on ${fault.volume} (${fault.free_pct}% < ${fault.floor_pct}% floor): ${fault.caches.join(", ")} in use by ${fault.processes.join(", ")}`);
|
|
1887
1963
|
}
|
|
1888
1964
|
const clones = refreshClones(workdir, [...new Set(desired.filter((s) => !s.dir && s.project && s.desired === "running").map((s) => s.project))], log);
|
|
1889
|
-
const
|
|
1965
|
+
const readHomeDir = deps?.homeDir ?? homedir;
|
|
1966
|
+
const readVolumeSpace = deps?.volumeSpace ?? volumeSpace;
|
|
1967
|
+
const actualWorkdir = workdir ?? join(readHomeDir(), "bschat");
|
|
1968
|
+
const floorPct = me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT;
|
|
1969
|
+
const homeSpaceBefore = readVolumeSpace(readHomeDir(), "home");
|
|
1970
|
+
const workSpaceBefore = readVolumeSpace(actualWorkdir, "workdir");
|
|
1971
|
+
const pressure = detectLocalDiskPressure([homeSpaceBefore, workSpaceBefore], floorPct);
|
|
1972
|
+
const pruneIntervalMs = pressure.underPressure ? WORKTREE_PRUNE_PRESSURE_INTERVAL_MS : WORKTREE_PRUNE_INTERVAL_MS;
|
|
1890
1973
|
const worktreePrune = [];
|
|
1891
1974
|
for (const project of projects) {
|
|
1892
1975
|
const repo = join(actualWorkdir, project.name, "main");
|
|
1893
1976
|
if (!existsSync(join(repo, ".git")))
|
|
1894
1977
|
continue;
|
|
1895
1978
|
let prior = lastWorktreePrune.get(project.id);
|
|
1896
|
-
const due = !prior || Date.now() - prior.at >=
|
|
1979
|
+
const due = !prior || Date.now() - prior.at >= pruneIntervalMs;
|
|
1897
1980
|
if (due && !prior?.worker) {
|
|
1981
|
+
if (pressure.underPressure) {
|
|
1982
|
+
log(`${project.name}: disk pressure (${pressure.reasons.join(", ")}; floor ${floorPct}%): triggering clean closed-worktree prune`);
|
|
1983
|
+
}
|
|
1898
1984
|
// Mark the attempt before starting the isolated worker, so overlapping reconcile passes
|
|
1899
1985
|
// cannot start a second scan or removal for the same project.
|
|
1900
1986
|
const attemptedAt = Date.now();
|
|
@@ -1912,8 +1998,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1912
1998
|
lastWorktreePrune.set(project.id, prior);
|
|
1913
1999
|
if (deps?.pruneRunner) {
|
|
1914
2000
|
void Promise.resolve().then(() => deps.pruneRunner(creds, project.name, repo, log)).then((result) => {
|
|
1915
|
-
if (lastWorktreePrune.get(project.id)
|
|
1916
|
-
|
|
2001
|
+
if (lastWorktreePrune.get(project.id) !== prior)
|
|
2002
|
+
return;
|
|
2003
|
+
prior.result = result;
|
|
2004
|
+
logPruneReclaimed(project.name, result, log);
|
|
1917
2005
|
}).catch((error) => {
|
|
1918
2006
|
if (lastWorktreePrune.get(project.id) !== prior)
|
|
1919
2007
|
return;
|
|
@@ -1945,8 +2033,10 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1945
2033
|
return;
|
|
1946
2034
|
settled = true;
|
|
1947
2035
|
clearTimeout(timer);
|
|
1948
|
-
if (lastWorktreePrune.get(project.id)
|
|
1949
|
-
|
|
2036
|
+
if (lastWorktreePrune.get(project.id) !== prior)
|
|
2037
|
+
return;
|
|
2038
|
+
prior.result = result;
|
|
2039
|
+
logPruneReclaimed(project.name, result, log);
|
|
1950
2040
|
};
|
|
1951
2041
|
worker.on("message", (message) => {
|
|
1952
2042
|
if (message.type === "log" && message.line)
|
|
@@ -1980,9 +2070,35 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1980
2070
|
}
|
|
1981
2071
|
worktreePrune.push(prior?.result ?? { project: project.name, repo, status: "running" });
|
|
1982
2072
|
}
|
|
1983
|
-
|
|
2073
|
+
let scratchCleanup = {
|
|
2074
|
+
disk_pressure: false, removed_dirs: 0, reclaimed_bytes: 0, skipped_active: 0, errors: 0, capped: false,
|
|
2075
|
+
};
|
|
2076
|
+
if (pressure.underPressure) {
|
|
2077
|
+
const scratchResult = cleanupStaleVitestScratchDirs({
|
|
2078
|
+
tempDir: (deps?.tmpdir ?? tmpdir)(),
|
|
2079
|
+
...deps?.scratchCleanupOps,
|
|
2080
|
+
});
|
|
2081
|
+
scratchCleanup = {
|
|
2082
|
+
disk_pressure: true,
|
|
2083
|
+
removed_dirs: scratchResult.removed_dirs,
|
|
2084
|
+
reclaimed_bytes: scratchResult.reclaimed_bytes,
|
|
2085
|
+
skipped_active: scratchResult.skipped_active,
|
|
2086
|
+
errors: scratchResult.errors,
|
|
2087
|
+
capped: scratchResult.capped,
|
|
2088
|
+
...(scratchResult.aborted_reason ? { aborted_reason: scratchResult.aborted_reason } : {}),
|
|
2089
|
+
};
|
|
2090
|
+
if (scratchResult.aborted_reason) {
|
|
2091
|
+
log(`disk pressure (${pressure.reasons.join(", ")}; floor ${floorPct}%): scratch cleanup skipped (${scratchResult.aborted_reason}; kept ${scratchResult.skipped_active} candidate(s))`);
|
|
2092
|
+
}
|
|
2093
|
+
else {
|
|
2094
|
+
log(`disk pressure (${pressure.reasons.join(", ")}; floor ${floorPct}%): scratch cleanup in ${scratchResult.tmpdir} removed ${scratchResult.removed_dirs} stale b9s-vitest-* dir(s), reclaimed ${scratchResult.reclaimed_bytes} bytes${scratchResult.skipped_active ? ` (kept ${scratchResult.skipped_active} active/unverified)` : ""}${scratchResult.capped ? " (per-pass limit reached)" : ""}`);
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
const homeSpace = readVolumeSpace(readHomeDir(), "home");
|
|
2098
|
+
const workSpace = readVolumeSpace(actualWorkdir, "workdir");
|
|
1984
2099
|
const facts = machineFacts([...providerChecks], {
|
|
1985
2100
|
workdir: actualWorkdir,
|
|
2101
|
+
homeSpace,
|
|
1986
2102
|
modelsToCheck: me.models_to_check ?? [],
|
|
1987
2103
|
modelRunProbe: deps?.modelRunProbe,
|
|
1988
2104
|
verifyClaudeEgress: true,
|
|
@@ -1990,7 +2106,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
1990
2106
|
ec2Probe: () => onEc2,
|
|
1991
2107
|
...(imdsContainerProbe ? { containerImdsProbe: () => imdsContainerProbe } : {}),
|
|
1992
2108
|
...(hostContainerProbe ? { probes: { container: () => hostContainerProbe } } : {}),
|
|
1993
|
-
}, desired,
|
|
2109
|
+
}, desired, floorPct);
|
|
1994
2110
|
const environmentChecks = machineEnvironmentChecks({ ...facts, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null }, writable)
|
|
1995
2111
|
.map(({ check, status, observation, remedy, recovery_verified }) => ({ check, status, diagnosis: observation, remedy, recovery_verified, observed_at: new Date().toISOString() }));
|
|
1996
2112
|
const dirtyClosedWorktrees = worktreePrune.flatMap((result) => Array.isArray(result.dirty_closed) ? result.dirty_closed.filter((item) => typeof item === "string") : []);
|
|
@@ -2012,9 +2128,11 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
2012
2128
|
workdir: actualWorkdir, workdir_free_bytes: workSpace?.freeBytes ?? null, workdir_total_bytes: workSpace?.totalBytes ?? null, clones,
|
|
2013
2129
|
metric_availability: { ...facts.metric_availability, work_volume: workSpace ? "available" : "unavailable" },
|
|
2014
2130
|
worktree_prune: worktreePrune,
|
|
2131
|
+
scratch_cleanup: scratchCleanup,
|
|
2015
2132
|
build_caches: buildCaches,
|
|
2016
2133
|
// The daemon's own confirmation that it is holding turns back, and how many are still running.
|
|
2017
2134
|
maintenance: maintenanceReport(drainingUntil(), out),
|
|
2135
|
+
network_outages: machineNetworkOutages(),
|
|
2018
2136
|
});
|
|
2019
2137
|
const capabilities = {};
|
|
2020
2138
|
const imageProbes = [];
|
|
@@ -2091,13 +2209,14 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
2091
2209
|
}
|
|
2092
2210
|
log(`machine report size: ${new TextEncoder().encode(JSON.stringify(report)).byteLength} UTF-8 bytes`);
|
|
2093
2211
|
await client.call("POST", "/machines/me/report", {
|
|
2212
|
+
client_id: randomUUID(),
|
|
2094
2213
|
report,
|
|
2095
2214
|
report_interval_seconds: reportIntervalSeconds,
|
|
2096
2215
|
sessions: out,
|
|
2097
2216
|
capabilities,
|
|
2098
2217
|
active_ux_job_ids: uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps),
|
|
2099
2218
|
...(imageProbes.length ? { image_probes: imageProbes } : {}),
|
|
2100
|
-
});
|
|
2219
|
+
}, { retryForMs: MACHINE_NETWORK_RETRY_MS });
|
|
2101
2220
|
const uxSessionHints = desired.map((session) => ({
|
|
2102
2221
|
id: session.id,
|
|
2103
2222
|
agent: session.agent,
|
|
@@ -2114,42 +2233,50 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
2114
2233
|
for (const item of probedProjects) {
|
|
2115
2234
|
lastCapabilityProbe.set(item.id, { at: Date.now(), signature: item.signature });
|
|
2116
2235
|
}
|
|
2117
|
-
const warning = diskSpaceNotice(
|
|
2236
|
+
const warning = diskSpaceNotice(homeSpace, workSpace);
|
|
2118
2237
|
if (warning !== undefined)
|
|
2119
2238
|
await client.call("PUT", "/machines/me/notices/disk", { text: warning });
|
|
2239
|
+
const uxJobContext = {
|
|
2240
|
+
accountId,
|
|
2241
|
+
machineName: m.name,
|
|
2242
|
+
workdir,
|
|
2243
|
+
diskFloorPct: me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT,
|
|
2244
|
+
sessions: desired.map((s) => ({
|
|
2245
|
+
id: s.id,
|
|
2246
|
+
agent: s.agent,
|
|
2247
|
+
agent_name: s.agent_name,
|
|
2248
|
+
project: s.project,
|
|
2249
|
+
project_id: s.project_id ?? null,
|
|
2250
|
+
dir: s.dir,
|
|
2251
|
+
desired: s.desired,
|
|
2252
|
+
benched_at: s.benched_at ?? null,
|
|
2253
|
+
retired_at: null,
|
|
2254
|
+
})),
|
|
2255
|
+
log,
|
|
2256
|
+
};
|
|
2257
|
+
const uxJobDeps = {
|
|
2258
|
+
ensureSessionKey: async (hint) => {
|
|
2259
|
+
const match = desired.find((s) => s.id === hint.id);
|
|
2260
|
+
if (match)
|
|
2261
|
+
await ensureCredentials(client, m, match, state.sessions[match.id], log);
|
|
2262
|
+
},
|
|
2263
|
+
...deps?.uxJobDeps,
|
|
2264
|
+
};
|
|
2265
|
+
const claimResumePromise = retryPendingUxJobClaims(client, uxJobContext, uxJobDeps, deps?.uxJobsInFlight);
|
|
2266
|
+
if (deps?.awaitUxJobs)
|
|
2267
|
+
await claimResumePromise;
|
|
2120
2268
|
if (Array.isArray(me.ux_jobs) && me.ux_jobs.length) {
|
|
2121
|
-
const uxPromise = reconcilePendingUxJobs(client, me.ux_jobs, {
|
|
2122
|
-
accountId,
|
|
2123
|
-
machineName: m.name,
|
|
2124
|
-
workdir,
|
|
2125
|
-
diskFloorPct: me.machine?.cache_floor_pct ?? DEFAULT_CACHE_FLOOR_PCT,
|
|
2126
|
-
sessions: desired.map((s) => ({
|
|
2127
|
-
id: s.id,
|
|
2128
|
-
agent: s.agent,
|
|
2129
|
-
agent_name: s.agent_name,
|
|
2130
|
-
project: s.project,
|
|
2131
|
-
project_id: s.project_id ?? null,
|
|
2132
|
-
dir: s.dir,
|
|
2133
|
-
desired: s.desired,
|
|
2134
|
-
benched_at: s.benched_at ?? null,
|
|
2135
|
-
retired_at: null,
|
|
2136
|
-
})),
|
|
2137
|
-
log,
|
|
2138
|
-
}, {
|
|
2269
|
+
const uxPromise = reconcilePendingUxJobs(client, me.ux_jobs, uxJobContext, {
|
|
2139
2270
|
inFlight: deps?.uxJobsInFlight,
|
|
2140
2271
|
awaitCompletion: deps?.awaitUxJobs ?? false,
|
|
2141
|
-
deps:
|
|
2142
|
-
ensureSessionKey: async (hint) => {
|
|
2143
|
-
const match = desired.find((s) => s.id === hint.id);
|
|
2144
|
-
if (match)
|
|
2145
|
-
await ensureCredentials(client, m, match, state.sessions[match.id], log);
|
|
2146
|
-
},
|
|
2147
|
-
...deps?.uxJobDeps,
|
|
2148
|
-
},
|
|
2272
|
+
deps: uxJobDeps,
|
|
2149
2273
|
});
|
|
2150
2274
|
if (deps?.awaitUxJobs)
|
|
2151
2275
|
await uxPromise;
|
|
2152
2276
|
}
|
|
2277
|
+
const resumePromise = retryPendingPassedTrainGates(client, uxJobContext, uxJobDeps, deps?.uxJobsInFlight);
|
|
2278
|
+
if (deps?.awaitUxJobs)
|
|
2279
|
+
await resumePromise;
|
|
2153
2280
|
return { sessions: out, report };
|
|
2154
2281
|
}
|
|
2155
2282
|
export async function answerWorktreeProcessQueries(client, desired, queries, log, scan = scanWorktreeProcesses) {
|
|
@@ -3057,7 +3184,7 @@ export function machineFacts(providersInUse = ["anthropic"], workdirOrOpts, sess
|
|
|
3057
3184
|
const probeAgent = antigravityProbeAgent(sessions);
|
|
3058
3185
|
const readAntigravityFacts = () => probes?.antigravity ? probes.antigravity(probeAgent) : antigravityFacts(path, readInstall()?.bin ?? null, probeAgent);
|
|
3059
3186
|
const antigravity = readAntigravityFacts();
|
|
3060
|
-
const homeSpace = volumeSpace(homedir(), "home");
|
|
3187
|
+
const homeSpace = opts.homeSpace !== undefined ? opts.homeSpace : volumeSpace(homedir(), "home");
|
|
3061
3188
|
const readTelemetryFile = (path) => { try {
|
|
3062
3189
|
return readFileSync(path, "utf8");
|
|
3063
3190
|
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { str } from "../args.js";
|
|
2
|
+
import { Client } from "../client.js";
|
|
3
|
+
import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
4
|
+
import { CliError, WrittenReceiptMismatchError } from "../errors.js";
|
|
5
|
+
import { projectOf } from "./agent.js";
|
|
6
|
+
import { evidence } from "./evidence.js";
|
|
7
|
+
export async function mock(p, out) {
|
|
8
|
+
const [, sub, study, variant, file] = p.positionals;
|
|
9
|
+
if (sub !== "upload" && sub !== "gaps")
|
|
10
|
+
throw new CliError("usage", "mock upload <studyId> <variantId> <file.html> [--summary text] | mock gaps <studyId> --json <gapsJson> | --clear");
|
|
11
|
+
if (!study)
|
|
12
|
+
throw new CliError("usage", "studyId is required");
|
|
13
|
+
if (sub === "upload" && (!variant || !file || p.positionals.length !== 5))
|
|
14
|
+
throw new CliError("usage", "mock upload <studyId> <variantId> <file.html> [--summary text]");
|
|
15
|
+
if (sub === "gaps" && p.positionals.length !== 3)
|
|
16
|
+
throw new CliError("usage", "mock gaps <studyId> --json <gapsJson> | --clear");
|
|
17
|
+
let gaps;
|
|
18
|
+
if (sub === "gaps") {
|
|
19
|
+
const raw = str(p.flags, "json");
|
|
20
|
+
if ((p.flags.clear === true) === (raw !== undefined))
|
|
21
|
+
throw new CliError("usage", "choose --json <gapsJson> or --clear");
|
|
22
|
+
if (raw !== undefined) {
|
|
23
|
+
let value;
|
|
24
|
+
try {
|
|
25
|
+
value = JSON.parse(raw);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new CliError("usage", "--json must be a JSON array of gaps");
|
|
29
|
+
}
|
|
30
|
+
if (!Array.isArray(value))
|
|
31
|
+
throw new CliError("usage", "--json must be a JSON array of gaps");
|
|
32
|
+
gaps = value;
|
|
33
|
+
}
|
|
34
|
+
else
|
|
35
|
+
gaps = [];
|
|
36
|
+
}
|
|
37
|
+
const name = resolveAgentName(str(p.flags, "as"));
|
|
38
|
+
const creds = loadAgent(name);
|
|
39
|
+
const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
|
|
40
|
+
const project = projectOf(p, creds);
|
|
41
|
+
const base = `/projects/${encodeURIComponent(project)}/design-studies/${encodeURIComponent(study)}`;
|
|
42
|
+
if (sub === "gaps") {
|
|
43
|
+
const result = await client.call("POST", `${base}/gaps`, { gaps });
|
|
44
|
+
out.print("Reality Check submitted.", result);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
let uploaded;
|
|
48
|
+
await evidence({ ...p, positionals: ["evidence", "post", file], flags: { ...p.flags, type: "text/html", kind: "other" } }, { json: true, print: (_human, data) => { uploaded = data; } });
|
|
49
|
+
const id = typeof uploaded?.evidence?.id === "string" ? uploaded.evidence.id : typeof uploaded?.ref === "string" ? uploaded.ref.replace(/^evidence:/, "") : null;
|
|
50
|
+
if (!id)
|
|
51
|
+
throw new CliError("bad_response", "evidence upload response omitted evidence id");
|
|
52
|
+
const summary = str(p.flags, "summary");
|
|
53
|
+
try {
|
|
54
|
+
const result = await client.call("POST", `${base}/variants/${encodeURIComponent(variant)}/artifact`, { evidence_id: id, ...(summary !== undefined ? { summary } : {}) });
|
|
55
|
+
out.print(`Mock uploaded and attached: evidence:${id}`, result);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
if (error instanceof WrittenReceiptMismatchError) {
|
|
59
|
+
error.actionResult = `Mock evidence:${id} attached`;
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
throw new CliError("attach_failed", `Mock evidence:${id} was uploaded, but attachment failed: ${error.message}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
package/dist/commands/watch.js
CHANGED
|
@@ -121,6 +121,8 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
121
121
|
const value = JSON.parse(claudeRuntimeText);
|
|
122
122
|
if (typeof value.sandbox !== "string" || !Array.isArray(value.writableRoots) || !value.writableRoots.every((root) => typeof root === "string")
|
|
123
123
|
|| (value.effort !== undefined && typeof value.effort !== "string")
|
|
124
|
+
|| (value.subagents !== undefined && !["default", "encourage", "disabled"].includes(value.subagents))
|
|
125
|
+
|| (value.subagentModel !== undefined && (typeof value.subagentModel !== "string" || !value.subagentModel.trim() || value.subagentModel.length > 100))
|
|
124
126
|
|| (value.maxBudgetUsd !== undefined && (typeof value.maxBudgetUsd !== "number" || !Number.isFinite(value.maxBudgetUsd) || value.maxBudgetUsd <= 0))) {
|
|
125
127
|
throw new Error("invalid Claude turn runtime fields");
|
|
126
128
|
}
|
|
@@ -151,7 +153,7 @@ export async function watch(p, out, dependencies = {}) {
|
|
|
151
153
|
...(value.secretEgress.sessionKey ? { sessionKey: value.secretEgress.sessionKey } : {}),
|
|
152
154
|
};
|
|
153
155
|
}
|
|
154
|
-
claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}), ...(secretEgress ? { secretEgress } : {}) };
|
|
156
|
+
claudeRuntime = { sandbox: value.sandbox, writableRoots: value.writableRoots, ...(value.effort ? { effort: value.effort } : {}), ...(value.maxBudgetUsd ? { maxBudgetUsd: value.maxBudgetUsd } : {}), ...(value.subagents ? { subagents: value.subagents } : {}), ...(value.subagentModel ? { subagentModel: value.subagentModel } : {}), ...(secretEgress ? { secretEgress } : {}) };
|
|
155
157
|
}
|
|
156
158
|
catch (error) {
|
|
157
159
|
throw new CliError("usage", `--turn-claude-runtime must be valid Claude runtime JSON: ${error.message}`);
|
|
@@ -1021,7 +1023,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
|
|
|
1021
1023
|
const workUnitBinding = bindingResolution?.binding ?? null;
|
|
1022
1024
|
let turnExec = exec;
|
|
1023
1025
|
let turnCwd;
|
|
1024
|
-
if (turnSink && (dependencies.claudeRuntime?.sandbox === "workspace-write" ||
|
|
1026
|
+
if (turnSink && (dependencies.claudeRuntime?.sandbox === "workspace-write" || dependencies.antigravityRuntime?.sandbox === "workspace-write")) {
|
|
1025
1027
|
if (bindingToPrepare && !preparedWorktree) {
|
|
1026
1028
|
throw new CliError("unit_worktree_missing", `workspace-write ${dependencies.antigravityRuntime ? "Antigravity" : "Claude Code"} cannot start WU #${bindingToPrepare.work_unit_number}: the watcher did not prepare its unit worktree`);
|
|
1027
1029
|
}
|
|
@@ -1055,7 +1057,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
|
|
|
1055
1057
|
socksProxyPort: turnEgressRuntime.socksProxyPort,
|
|
1056
1058
|
}
|
|
1057
1059
|
: undefined;
|
|
1058
|
-
const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined, secretEgress);
|
|
1060
|
+
const args = claudeSettings(runtime.sandbox, model, runtime.effort, process.cwd(), configRoot(), runtime.writableRoots, preparedWorktree ?? undefined, secretEgress, runtime.subagents ?? "default");
|
|
1059
1061
|
turnExec = turnExec.replace(CLAUDE_SETTINGS_PLACEHOLDER, args.map(shellQuote).join(" "));
|
|
1060
1062
|
}
|
|
1061
1063
|
if (turnSink && dependencies.antigravityRuntime && turnExec?.includes(ANTIGRAVITY_SETTINGS_PLACEHOLDER)) {
|