benignswarm 0.12.104 → 0.12.106
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 +1 -1
- package/dist/capabilities.js +70 -15
- package/dist/client.js +7 -2
- package/dist/command-runner.js +1 -1
- package/dist/commands/image-admin.js +16 -3
- package/dist/commands/machine-admin.js +101 -13
- package/dist/commands/machine.js +358 -26
- package/dist/commands/measures.js +1 -1
- package/dist/commands/watch.js +154 -29
- package/dist/commands/wu.js +139 -17
- package/dist/container.js +565 -33
- package/dist/errors.js +1 -0
- package/dist/help.js +18 -12
- package/dist/hosted-registry-ecr.js +55 -0
- package/dist/hosted-registry-push.js +40 -0
- package/dist/hosted-registry-session.js +26 -0
- package/dist/hosted-registry.js +73 -0
- package/dist/output.js +9 -7
- package/dist/turn-guard.js +30 -1
- package/dist/version.js +1 -1
- package/package.json +6 -1
package/dist/args.js
CHANGED
|
@@ -32,7 +32,7 @@ export const STRING_FLAGS = [
|
|
|
32
32
|
"root", "signing-key", "catalog", "context", "context-action", "context-checkpoint-ref", "context-old-thread", "context-new-thread", "source-commit", "component", "normalized-key",
|
|
33
33
|
"drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
|
|
34
34
|
"stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
|
|
35
|
-
"machine-session-id", "detail", "worktree",
|
|
35
|
+
"machine-session-id", "pool-sessions", "registry", "detail", "worktree",
|
|
36
36
|
"purpose", "storage-mode", "hosts", "arn", "version-id",
|
|
37
37
|
"mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
|
|
38
38
|
];
|
package/dist/capabilities.js
CHANGED
|
@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";
|
|
|
3
3
|
import { homedir, tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { performance } from "node:perf_hooks";
|
|
6
|
+
import { assertSafeMountPath, isolatedSubprocessEnv } from "./container.js";
|
|
6
7
|
export const DEFAULT_CAPABILITY_TIMEOUT_MS = 60_000;
|
|
7
8
|
const MAX_OUTPUT_BYTES = 64 * 1024;
|
|
8
9
|
function appendLimited(chunks, capturedBytes, chunk) {
|
|
@@ -11,7 +12,7 @@ function appendLimited(chunks, capturedBytes, chunk) {
|
|
|
11
12
|
chunks.push(chunk.subarray(0, remaining));
|
|
12
13
|
return { capturedBytes: capturedBytes + Math.min(chunk.length, Math.max(remaining, 0)), exceeded: chunk.length > remaining };
|
|
13
14
|
}
|
|
14
|
-
function
|
|
15
|
+
function runProbeCommand(cmd, args, cwd, timeoutMs, env) {
|
|
15
16
|
const startedAt = performance.now();
|
|
16
17
|
const stdout = [];
|
|
17
18
|
const stderr = [];
|
|
@@ -21,8 +22,9 @@ function runProbe(command, cwd, timeoutMs) {
|
|
|
21
22
|
let spawnError = null;
|
|
22
23
|
let killError = null;
|
|
23
24
|
let timedOut = false;
|
|
24
|
-
const child = spawn(
|
|
25
|
+
const child = spawn(cmd, args, {
|
|
25
26
|
cwd,
|
|
27
|
+
...(env ? { env } : {}),
|
|
26
28
|
detached: process.platform !== "win32",
|
|
27
29
|
stdio: ["ignore", "pipe", "pipe"],
|
|
28
30
|
});
|
|
@@ -72,25 +74,78 @@ function runProbe(command, cwd, timeoutMs) {
|
|
|
72
74
|
});
|
|
73
75
|
}
|
|
74
76
|
/** Run every declaration and preserve failures as results, so dispatch can explain a missing tool. */
|
|
75
|
-
export async function probeCapabilities(definitions, projectDir) {
|
|
77
|
+
export async function probeCapabilities(definitions, projectDir, opts) {
|
|
76
78
|
const results = [];
|
|
77
79
|
for (const definition of definitions) {
|
|
78
80
|
let cwd = homedir();
|
|
79
81
|
let temporary = null;
|
|
80
82
|
try {
|
|
81
|
-
if (definition.scope === "worktree") {
|
|
82
|
-
temporary = mkdtempSync(join(tmpdir(), "bschat-capability-"));
|
|
83
|
-
const path = join(temporary, "worktree");
|
|
84
|
-
const added = spawnSync("git", ["worktree", "add", "--quiet", "--detach", path, "HEAD"], { cwd: projectDir, encoding: "utf8", timeout: 120_000 });
|
|
85
|
-
if (added.status !== 0)
|
|
86
|
-
throw new Error((added.stderr || added.stdout || "git worktree add failed").trim().split(/\r?\n/, 1)[0]);
|
|
87
|
-
const full = spawnSync("git", ["-C", path, "sparse-checkout", "disable"], { encoding: "utf8", timeout: 30_000 });
|
|
88
|
-
if (full.status !== 0)
|
|
89
|
-
throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
|
|
90
|
-
cwd = path;
|
|
91
|
-
}
|
|
92
83
|
const timeoutMs = definition.timeout_ms ?? DEFAULT_CAPABILITY_TIMEOUT_MS;
|
|
93
|
-
|
|
84
|
+
let result;
|
|
85
|
+
if (definition.scope === "image") {
|
|
86
|
+
if (!opts?.container?.imageDigest) {
|
|
87
|
+
throw new Error("image capability probe requires an active pinned container image");
|
|
88
|
+
}
|
|
89
|
+
const ctx = opts.container;
|
|
90
|
+
const trimmedDir = typeof projectDir === "string" ? projectDir.trim() : "";
|
|
91
|
+
const safeWorktree = trimmedDir
|
|
92
|
+
? assertSafeMountPath(trimmedDir, "worktree", ctx.hostHome ? { hostHome: ctx.hostHome } : {})
|
|
93
|
+
: null;
|
|
94
|
+
const containerArgs = [
|
|
95
|
+
"run",
|
|
96
|
+
"--rm",
|
|
97
|
+
"--security-opt",
|
|
98
|
+
"no-new-privileges",
|
|
99
|
+
"--add-host",
|
|
100
|
+
"169.254.169.254:127.0.0.1",
|
|
101
|
+
"--add-host",
|
|
102
|
+
"metadata.google.internal:127.0.0.1",
|
|
103
|
+
...(ctx.arch ? ["--platform", ctx.arch] : []),
|
|
104
|
+
...(safeWorktree ? ["-v", `${safeWorktree}:/workspace:ro`, "-w", "/workspace"] : []),
|
|
105
|
+
ctx.imageDigest,
|
|
106
|
+
"/bin/sh",
|
|
107
|
+
"-lc",
|
|
108
|
+
definition.probe,
|
|
109
|
+
];
|
|
110
|
+
const probeHostCwd = safeWorktree ?? tmpdir();
|
|
111
|
+
if (ctx.runner) {
|
|
112
|
+
const startedAt = performance.now();
|
|
113
|
+
const res = ctx.runner(ctx.runtime, containerArgs, {
|
|
114
|
+
cwd: probeHostCwd,
|
|
115
|
+
timeout: timeoutMs,
|
|
116
|
+
env: isolatedSubprocessEnv(process.env),
|
|
117
|
+
});
|
|
118
|
+
result = {
|
|
119
|
+
status: res.status,
|
|
120
|
+
stdout: res.stdout ?? "",
|
|
121
|
+
stderr: res.stderr ?? "",
|
|
122
|
+
error: res.error ?? null,
|
|
123
|
+
killError: null,
|
|
124
|
+
timedOut: false,
|
|
125
|
+
elapsedMs: Math.round(performance.now() - startedAt),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
result = await runProbeCommand(ctx.runtime, containerArgs, probeHostCwd, timeoutMs, isolatedSubprocessEnv(process.env));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
if (definition.scope === "worktree") {
|
|
134
|
+
const wtSource = typeof projectDir === "string" ? projectDir.trim() : "";
|
|
135
|
+
if (!wtSource)
|
|
136
|
+
throw new Error("worktree capability probe requires a checked-out project directory");
|
|
137
|
+
temporary = mkdtempSync(join(tmpdir(), "bschat-capability-"));
|
|
138
|
+
const path = join(temporary, "worktree");
|
|
139
|
+
const added = spawnSync("git", ["worktree", "add", "--quiet", "--detach", path, "HEAD"], { cwd: wtSource, encoding: "utf8", timeout: 120_000 });
|
|
140
|
+
if (added.status !== 0)
|
|
141
|
+
throw new Error((added.stderr || added.stdout || "git worktree add failed").trim().split(/\r?\n/, 1)[0]);
|
|
142
|
+
const full = spawnSync("git", ["-C", path, "sparse-checkout", "disable"], { encoding: "utf8", timeout: 30_000 });
|
|
143
|
+
if (full.status !== 0)
|
|
144
|
+
throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
|
|
145
|
+
cwd = path;
|
|
146
|
+
}
|
|
147
|
+
result = await runProbeCommand("/bin/sh", ["-lc", definition.probe], cwd, timeoutMs);
|
|
148
|
+
}
|
|
94
149
|
const output = `${result.stdout}${result.stderr}`.trim().split(/\r?\n/, 1)[0] ?? "";
|
|
95
150
|
const ok = result.status === 0 && !result.error && !result.timedOut;
|
|
96
151
|
const error = result.timedOut
|
package/dist/client.js
CHANGED
|
@@ -115,8 +115,13 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
115
115
|
required.push("replace.new");
|
|
116
116
|
return required;
|
|
117
117
|
}
|
|
118
|
-
if (action === "wait")
|
|
119
|
-
|
|
118
|
+
if (action === "wait") {
|
|
119
|
+
// A unit wait persists its note only. Review waits also persist a supplied partial verdict.
|
|
120
|
+
const required = strings("note");
|
|
121
|
+
if (response?.unit?.review_wait && typeof fields.partial === "string")
|
|
122
|
+
required.push("partial");
|
|
123
|
+
return required;
|
|
124
|
+
}
|
|
120
125
|
if (["approve", "changes", "proceed"].includes(action))
|
|
121
126
|
return strings("note", "unmet");
|
|
122
127
|
if (["park", "requeue", "decline", "classify", "tags", "reopen", "supersede", "done", "abandon", "merge", "evidence/replace", "restore", "note", "hold", "hold/release", "question/escalate"].includes(action))
|
package/dist/command-runner.js
CHANGED
|
@@ -8,7 +8,7 @@ export async function runCommandSafely(run, out) {
|
|
|
8
8
|
catch (error) {
|
|
9
9
|
if (error instanceof WrittenReceiptMismatchError) {
|
|
10
10
|
const detail = error.message.replace(/^write succeeded; receipt mismatch:\s*/, "");
|
|
11
|
-
printWrittenReceiptMismatch(out, error.response, detail);
|
|
11
|
+
printWrittenReceiptMismatch(out, error.response, detail, error.actionResult);
|
|
12
12
|
return WRITTEN_RECEIPT_MISMATCH_EXIT_CODE;
|
|
13
13
|
}
|
|
14
14
|
throw error;
|
|
@@ -20,23 +20,36 @@ export async function projectImageAdmin(rest, p, out) {
|
|
|
20
20
|
}
|
|
21
21
|
const c = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
22
22
|
if (!sub || !project) {
|
|
23
|
-
throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | activate <p> <sha256:...> | rollback <p> (<sha256:...> | clear)>");
|
|
23
|
+
throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] [--pool-sessions on|off] [--registry ns] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | activate <p> <sha256:...> | rollback <p> (<sha256:...> | clear)>");
|
|
24
24
|
}
|
|
25
25
|
switch (sub) {
|
|
26
26
|
case "config": {
|
|
27
27
|
const rawCache = str(p.flags, "caches") ?? str(p.flags, "cache");
|
|
28
28
|
const caches = rawCache ? rawCache.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
29
|
+
const rawPoolSessions = str(p.flags, "pool-sessions");
|
|
30
|
+
let poolSessionsEnabled;
|
|
31
|
+
if (rawPoolSessions !== undefined) {
|
|
32
|
+
if (rawPoolSessions === "on" || rawPoolSessions === "true")
|
|
33
|
+
poolSessionsEnabled = true;
|
|
34
|
+
else if (rawPoolSessions === "off" || rawPoolSessions === "false")
|
|
35
|
+
poolSessionsEnabled = false;
|
|
36
|
+
else
|
|
37
|
+
throw new CliError("usage", "--pool-sessions must be on|off (or true|false)");
|
|
38
|
+
}
|
|
39
|
+
const registry = str(p.flags, "registry");
|
|
29
40
|
const r = await c.call("PUT", `/projects/${encodeURIComponent(project)}/image-config`, {
|
|
30
41
|
...(str(p.flags, "path") ? { devcontainer_path: str(p.flags, "path") } : {}),
|
|
31
42
|
...(str(p.flags, "arch") ? { target_arch: str(p.flags, "arch") } : {}),
|
|
32
43
|
...(caches.length ? { allowed_caches: caches } : {}),
|
|
44
|
+
...(poolSessionsEnabled !== undefined ? { pool_sessions_enabled: poolSessionsEnabled } : {}),
|
|
45
|
+
...(registry !== undefined ? { registry_namespace: registry } : {}),
|
|
33
46
|
});
|
|
34
|
-
out.print(`Project ${project} image namespace ${r.image.registry_namespace} (${r.image.target_arch}, ${r.image.devcontainer_path})`, r);
|
|
47
|
+
out.print(`Project ${project} image namespace ${r.image.registry_namespace} (${r.image.target_arch}, ${r.image.devcontainer_path}, pool sessions ${r.image.pool_sessions_enabled ? "enabled" : "disabled"})`, r);
|
|
35
48
|
return;
|
|
36
49
|
}
|
|
37
50
|
case "show": {
|
|
38
51
|
const r = await c.call("GET", `/projects/${encodeURIComponent(project)}/image`);
|
|
39
|
-
out.print(`Project ${project} active digest: ${r.image.active_digest ?? "(none)"}${r.image.rollback_digest ? ` (rollback pinned to ${r.image.rollback_digest})` : ""}`, r);
|
|
52
|
+
out.print(`Project ${project} active digest: ${r.image.active_digest ?? "(none)"}${r.image.rollback_digest ? ` (rollback pinned to ${r.image.rollback_digest})` : ""}; pool sessions ${r.image.pool_sessions_enabled ? "enabled" : "disabled"}`, r);
|
|
40
53
|
return;
|
|
41
54
|
}
|
|
42
55
|
case "build": {
|
|
@@ -194,6 +194,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
194
194
|
`${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}; cache budget ${m.cache_budget_gb ?? 40} GB (floor ${m.cache_floor_pct ?? 15}%)`,
|
|
195
195
|
rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
|
|
196
196
|
rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
|
|
197
|
+
rep.container_runtime ? ` Container runtime: ${rep.container_runtime.runtime ?? "none"} (${rep.container_runtime.rootless ? "rootless" : "daemon"}, ${rep.container_runtime.usable_without_root === false ? "NO non-root access" : "non-root ok"}, arch ${(rep.container_runtime.architectures ?? []).join(",") || rep.arch || "?"}${rep.on_ec2 ? `, EC2 container IMDS ${rep.container_imds_blocked ? "blocked" : "NOT blocked"}` : ""})` : null,
|
|
197
198
|
m.quarantined ? ` QUARANTINED: ${m.quarantine?.reason ?? "operator containment"}${m.quarantine?.at ? ` (${m.quarantine.at})` : ""}` : null,
|
|
198
199
|
];
|
|
199
200
|
const cacheLines = [];
|
|
@@ -225,11 +226,11 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
225
226
|
}
|
|
226
227
|
}
|
|
227
228
|
const capabilityLines = machineCapabilityLines(m.capabilities ?? []);
|
|
228
|
-
const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", turns_per_hour: s.turns_per_hour ?? 60, coalesce_s: s.turn_coalesce_seconds ?? 180, thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
|
|
229
|
+
const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", turns_per_hour: s.turns_per_hour ?? 60, coalesce_s: s.turn_coalesce_seconds ?? 180, thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", sandbox: s.sandbox, image: s.image_digest ? `${s.container_runtime ?? "container"}@${String(s.image_digest).slice(0, 19)}` : "host", model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
|
|
229
230
|
const providers = rep.claude_code?.providers ?? {};
|
|
230
231
|
const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
|
|
231
232
|
const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
|
|
232
|
-
return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), output);
|
|
233
|
+
return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), output);
|
|
233
234
|
}
|
|
234
235
|
if (action === "maintenance") {
|
|
235
236
|
// A window on the machine: no new turns from 15 min before, its agents away until it ends.
|
|
@@ -631,6 +632,17 @@ export async function poolAdmin(action, rest, p, out, argv) {
|
|
|
631
632
|
throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
|
|
632
633
|
}
|
|
633
634
|
const c = adminClient(p);
|
|
635
|
+
if (action === "slot") {
|
|
636
|
+
const [operation, target, ...extra] = rest;
|
|
637
|
+
const parts = (target ?? "").split("/");
|
|
638
|
+
if (operation !== "stop" || parts.length !== 3 || parts.some((part) => !part) || extra.length) {
|
|
639
|
+
throw new CliError("usage", "pool slot stop <project>/<pool>/<slot> [--reason text]");
|
|
640
|
+
}
|
|
641
|
+
const [project, name, slot] = parts.map(encodeURIComponent);
|
|
642
|
+
const reason = str(p.flags, "reason");
|
|
643
|
+
const r = await c.call("POST", `/projects/${project}/pools/${name}/slots/${slot}/stop`, reason === undefined ? {} : { reason });
|
|
644
|
+
return out.print(`Suspended ${target}; its machine will stop the session.`, r);
|
|
645
|
+
}
|
|
634
646
|
const statusLines = (pool) => [
|
|
635
647
|
`${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/hour; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
|
|
636
648
|
...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
|
|
@@ -954,6 +966,7 @@ export async function agentMove(rest, p, out) {
|
|
|
954
966
|
say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
|
|
955
967
|
await c.call("PATCH", progressRoute, { status: "checking", expected_status: "requested", detail: "trusted CLI is checking local readiness and preparing the handoff" });
|
|
956
968
|
let problems = [];
|
|
969
|
+
const skippedWorktrees = [];
|
|
957
970
|
const destinationHost = str(p.flags, "to-ssh") ?? to;
|
|
958
971
|
try {
|
|
959
972
|
const destination = await c.call("GET", `/machines/${to}`);
|
|
@@ -963,34 +976,108 @@ export async function agentMove(rest, p, out) {
|
|
|
963
976
|
throw new CliError("destination_not_ready", readinessError);
|
|
964
977
|
// 1. Work in progress must be on origin, or it stays behind on the old machine.
|
|
965
978
|
const units = (await c.call("GET", `/projects/${project}/work-units?agent=${encodeURIComponent(agent)}`)).units.filter((u) => ["assigned", "open", "changes_requested", "in_review", "approved"].includes(u.status));
|
|
979
|
+
if (units.length && !move.from)
|
|
980
|
+
throw new CliError("source_machine_unknown", `the move operation has active units but no recorded source machine; cannot scope their worktrees on ${from}`);
|
|
981
|
+
const sourceMachine = move.from ?? from;
|
|
982
|
+
const observedWorktrees = units.length ? (await c.call("GET", `/projects/${project}/worktrees`)).worktrees : [];
|
|
983
|
+
if (!Array.isArray(observedWorktrees))
|
|
984
|
+
throw new CliError("worktrees_unavailable", `cannot determine which worktrees are recorded on source machine ${sourceMachine}`);
|
|
985
|
+
const worktrees = observedWorktrees.filter((w) => w.missing_at == null);
|
|
986
|
+
const attributedToAgent = (worktree) => {
|
|
987
|
+
// Older/scan-only registry rows may have no attribution yet. In that case,
|
|
988
|
+
// an owner's matching unit path/branch is the bounded legacy fallback.
|
|
989
|
+
if (!Array.isArray(worktree.agents) || worktree.agents.length === 0)
|
|
990
|
+
return true;
|
|
991
|
+
return worktree.agents.some((a) => a?.name === agent);
|
|
992
|
+
};
|
|
993
|
+
const inspections = [];
|
|
994
|
+
const inspectedPaths = new Set();
|
|
995
|
+
const addInspection = (unit, path, label) => {
|
|
996
|
+
if (inspectedPaths.has(path))
|
|
997
|
+
return;
|
|
998
|
+
inspectedPaths.add(path);
|
|
999
|
+
inspections.push({ unit, path, label });
|
|
1000
|
+
};
|
|
966
1001
|
for (const u of units) {
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
1002
|
+
const pathRecords = worktrees.filter((w) => w.path === u.worktree);
|
|
1003
|
+
const branchRecords = u.branch ? worktrees.filter((w) => w.branch === u.branch) : [];
|
|
1004
|
+
const related = [...new Map([...pathRecords, ...branchRecords].map((w) => [`${w.machine}\0${w.path}`, w])).values()];
|
|
1005
|
+
const owner = u.owner_name === agent;
|
|
1006
|
+
const reviewer = Array.isArray(u.reviewers) && u.reviewers.some((r) => r?.name === agent);
|
|
1007
|
+
if (owner) {
|
|
1008
|
+
const attributable = related.filter(attributedToAgent);
|
|
1009
|
+
const sourceRecords = attributable.filter((w) => w.machine === sourceMachine);
|
|
1010
|
+
const elsewhere = [...new Set(attributable.filter((w) => w.machine !== sourceMachine).map((w) => String(w.machine)))];
|
|
1011
|
+
if (sourceRecords.length) {
|
|
1012
|
+
for (const record of sourceRecords)
|
|
1013
|
+
addInspection(u, record.path, `#${u.number} (${u.branch ?? "no branch recorded"})`);
|
|
1014
|
+
}
|
|
1015
|
+
else if (elsewhere.length) {
|
|
1016
|
+
skippedWorktrees.push(`#${u.number}: owned worktree ${u.worktree ?? u.branch ?? "(unknown)"} is recorded on ${elsewhere.join(", ")}, not ${sourceMachine}`);
|
|
1017
|
+
}
|
|
1018
|
+
else if (u.worktree) {
|
|
1019
|
+
// Preserve the existing owned-unit check when no machine observation has been recorded yet.
|
|
1020
|
+
addInspection(u, u.worktree, `#${u.number} (${u.branch ?? "no branch recorded"})`);
|
|
1021
|
+
}
|
|
1022
|
+
else if (!u.branch) {
|
|
1023
|
+
skippedWorktrees.push(`#${u.number}: no branch or worktree is recorded, so no source worktree can be left behind`);
|
|
1024
|
+
}
|
|
1025
|
+
else {
|
|
1026
|
+
problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): no worktree is recorded, so its Git state cannot be verified`);
|
|
1027
|
+
}
|
|
970
1028
|
}
|
|
1029
|
+
else if (reviewer) {
|
|
1030
|
+
const attributed = related.filter((w) => Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent));
|
|
1031
|
+
const sourceRecords = attributed.filter((w) => w.machine === sourceMachine);
|
|
1032
|
+
const elsewhere = [...new Set(related.filter((w) => w.machine !== sourceMachine).map((w) => String(w.machine)))];
|
|
1033
|
+
if (sourceRecords.length) {
|
|
1034
|
+
for (const record of sourceRecords)
|
|
1035
|
+
addInspection(u, record.path, `#${u.number} (${u.branch ?? "no branch recorded"})`);
|
|
1036
|
+
}
|
|
1037
|
+
else if (!worktrees.some((w) => w.machine === sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
|
|
1038
|
+
skippedWorktrees.push(`#${u.number}: review assignment is not this agent's source-machine worktree${elsewhere.length ? `; related worktree record(s) are on ${elsewhere.join(", ")}, not ${sourceMachine}` : " (no source-machine worktree is recorded)"}`);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
else {
|
|
1042
|
+
skippedWorktrees.push(`#${u.number}: API work-unit result is neither owned nor reviewed by ${agent}; skipped as unassigned work`);
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
// The registry's agent attribution is authoritative for a review worktree. It
|
|
1046
|
+
// covers detached heads and review branches that differ from the owner's unit
|
|
1047
|
+
// branch/path, which cannot be discovered by matching those fields alone.
|
|
1048
|
+
for (const record of worktrees.filter((w) => w.machine === sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
|
|
1049
|
+
const unit = units.find((u) => u.owner_name === agent && (u.worktree === record.path || (u.branch && u.branch === record.branch)))
|
|
1050
|
+
?? units.find((u) => Array.isArray(u.reviewers) && u.reviewers.some((r) => r?.name === agent));
|
|
1051
|
+
addInspection(unit ?? null, record.path, unit ? `#${unit.number} (${unit.branch ?? "no branch recorded"})` : `agent worktree ${record.path}`);
|
|
1052
|
+
}
|
|
1053
|
+
for (const record of worktrees.filter((w) => w.machine !== sourceMachine && Array.isArray(w.agents) && w.agents.some((a) => a?.name === agent))) {
|
|
1054
|
+
skippedWorktrees.push(`agent worktree ${record.path} is recorded on ${record.machine}, not ${sourceMachine}`);
|
|
1055
|
+
}
|
|
1056
|
+
for (const { unit: u, path: worktree, label } of inspections) {
|
|
1057
|
+
const workLabel = u ? `#${u.number} (${u.branch ?? "no branch recorded"})` : label;
|
|
971
1058
|
const unavailableMarker = "BSCHAT_MOVE_WORKTREE_UNAVAILABLE";
|
|
972
|
-
const cd = `cd ${shellSingle(
|
|
1059
|
+
const cd = `cd ${shellSingle(worktree)} 2>/dev/null || { printf '%s\\n' '${unavailableMarker}' >&2; exit 97; }; `;
|
|
973
1060
|
const unavailable = (result) => result.status === 97 && result.stderr.trim() === unavailableMarker;
|
|
974
1061
|
const status = on(from, `${cd}git status --porcelain`);
|
|
975
1062
|
if (unavailable(status)) {
|
|
976
|
-
problems.push(
|
|
1063
|
+
problems.push(`${workLabel}: ${worktree} is not available on ${from}`);
|
|
977
1064
|
continue;
|
|
978
1065
|
}
|
|
979
1066
|
if (status.status !== 0)
|
|
980
|
-
throw new CliError("git_preflight_failed", `cannot inspect Git status for
|
|
1067
|
+
throw new CliError("git_preflight_failed", `cannot inspect Git status for ${workLabel} on ${from}: ${status.stderr.trim().slice(0, 200) || `git status exited ${status.status}`}`);
|
|
981
1068
|
const unpushed = on(from, `${cd}git rev-list --count HEAD --not --remotes`);
|
|
982
1069
|
if (unavailable(unpushed)) {
|
|
983
|
-
problems.push(
|
|
1070
|
+
problems.push(`${workLabel}: ${worktree} is not available on ${from}`);
|
|
984
1071
|
continue;
|
|
985
1072
|
}
|
|
986
1073
|
if (unpushed.status !== 0 || !/^\d+$/.test(unpushed.stdout.trim()))
|
|
987
|
-
throw new CliError("git_preflight_failed", `cannot inspect unpushed commits for
|
|
1074
|
+
throw new CliError("git_preflight_failed", `cannot inspect unpushed commits for ${workLabel} on ${from}: ${unpushed.stderr.trim().slice(0, 200) || `git rev-list exited ${unpushed.status}`}`);
|
|
988
1075
|
const dirtyCount = status.stdout.trim() ? status.stdout.trimEnd().split("\n").length : 0;
|
|
989
1076
|
const unpushedCount = Number(unpushed.stdout.trim());
|
|
990
1077
|
if (dirtyCount || unpushedCount)
|
|
991
|
-
problems.push(
|
|
1078
|
+
problems.push(`${workLabel}: ${unpushedCount} unpushed commit(s), ${dirtyCount} uncommitted file(s) in ${worktree}`);
|
|
992
1079
|
else
|
|
993
|
-
say(`
|
|
1080
|
+
say(` ${u ? `#${u.number} [${u.status}] ${u.branch}` : label}: pushed and clean`);
|
|
994
1081
|
}
|
|
995
1082
|
if (problems.length && !bool(p.flags, "force"))
|
|
996
1083
|
throw new CliError("unpushed_work", `${ref} has work only on ${from}:\n ${problems.join("\n ")}`, `Have the agent push it (or commit and push), then move it; to leave it on ${from}, rerun with --force --confirm-force ${ref}`);
|
|
@@ -1116,9 +1203,10 @@ export async function agentMove(rest, p, out) {
|
|
|
1116
1203
|
`Move ${move.id} completed: ${ref} now runs on ${to} (${r.session.harness}/${r.session.provider}, ${r.session.sandbox}, ${r.session.dir || "automatic checkout"}${thread ? `, thread ${thread}` : ", a fresh session"}); its daemon starts it within 30 s.`,
|
|
1117
1204
|
r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
|
|
1118
1205
|
`${r.revoked_keys} key(s) elsewhere revoked: a watcher left running there stops and removes itself. Archive its old thread in the Codex app so nobody types into that copy.`,
|
|
1206
|
+
...skippedWorktrees.map((skipped) => `Skipped ${skipped}`),
|
|
1119
1207
|
problems.length ? `Left behind on ${from} (--force confirmed): ${problems.join("; ")}` : null,
|
|
1120
1208
|
`Follow it: b9s-admin machine show ${to}`,
|
|
1121
|
-
].filter(Boolean).join("\n"), r);
|
|
1209
|
+
].filter(Boolean).join("\n"), { ...r, skipped_worktrees: skippedWorktrees });
|
|
1122
1210
|
}
|
|
1123
1211
|
/** --at: an ISO timestamp, or HH:MM in this machine's local time (today, or tomorrow when past). */
|
|
1124
1212
|
export function maintenanceStart(at, nowMs = Date.now()) {
|