benignswarm 0.12.95 → 0.12.97

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.
@@ -1,10 +1,12 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { bool, str } from "../args.js";
2
+ import { createInterface } from "node:readline/promises";
3
+ import { bool, need, str } from "../args.js";
3
4
  import { Client } from "../client.js";
4
5
  import { loadAdmin, resolveAdminName } from "../config.js";
5
6
  import { CliError } from "../errors.js";
6
7
  import { table } from "../output.js";
7
8
  import { CLI_VERSION } from "../version.js";
9
+ import { runMachineResize } from "./machine-resize.js";
8
10
  /**
9
11
  * b9s-admin machine: provision machines over the operator's own ssh and declare the agent
10
12
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
@@ -62,6 +64,36 @@ export function machineCapabilityLines(projects) {
62
64
  return [` ${project.project} capabilities: ${values.join("; ")}`];
63
65
  });
64
66
  }
67
+ export function machineMacLines(macos) {
68
+ if (!macos || typeof macos !== "object")
69
+ return [];
70
+ const policy = macos.disk_policy ?? { floor_pct: 15, source: "machine cache floor" };
71
+ const lines = [
72
+ ` macOS ${macos.product_version ?? "unknown"} (${macos.product_build ?? "build unknown"}), ${macos.model ?? "model unknown"}, ${macos.architecture ?? "architecture unknown"}; Xcode ${macos.xcode?.version ?? "unknown"} (${macos.xcode?.build ?? "build unknown"}), license ${macos.xcode?.license_accepted === true ? "accepted" : macos.xcode?.license_accepted === false ? "not accepted" : "unknown"}, developer directory ${macos.developer_directory ?? "not selected"}`,
73
+ ` machine volume floor: ${policy.floor_pct}% (source: ${policy.source})`,
74
+ ` disk: ${[macos.disk?.home, macos.disk?.checkout_build].filter(Boolean).map((disk) => `${disk.path}: ${disk.free_bytes == null ? "unknown" : `${Math.round(disk.free_bytes / 1e9)} GB free`}${disk.total_bytes == null ? "" : ` / ${Math.round(disk.total_bytes / 1e9)} GB (${disk.free_pct}% free)`}; ${disk.status === "ready" ? "meets" : disk.status === "below_floor" ? "below" : "unknown against"} machine cache floor ${disk.floor_pct}%`).join("; ") || "home/checkout capacity unknown"}`,
75
+ ];
76
+ const runtimes = Array.isArray(macos.simulators?.runtimes) ? macos.simulators.runtimes : [];
77
+ lines.push(...(runtimes.length
78
+ ? runtimes.map((runtime) => ` simulator: ${runtime.platform} ${runtime.version ?? "version unknown"} (${runtime.build ?? "build unknown"}) ${runtime.available && runtime.disk?.status === "ready" ? "available; runtime volume meets floor" : `NOT READY (${runtime.available ? runtime.disk?.status === "below_floor" ? `runtime volume ${runtime.disk.free_pct}% below machine cache floor ${runtime.disk.floor_pct}%` : "runtime volume space unknown" : "runtime unavailable"})`}; ${runtime.available_devices ?? 0} available device(s)${runtime.disk?.free_bytes == null ? "" : `; runtime volume ${Math.round(runtime.disk.free_bytes / 1e9)} GB free / ${Math.round(runtime.disk.total_bytes / 1e9)} GB (${runtime.disk.free_pct}% free)`}`)
79
+ : [` simulator: ${macos.simulators?.error ?? "no installed runtimes reported"}`]));
80
+ for (const refusal of [...(macos.readiness_refusals?.build ?? []), ...(macos.readiness_refusals?.simulators ?? []).filter((r) => !(macos.readiness_refusals?.build ?? []).includes(r))])
81
+ lines.push(` REFUSAL: ${refusal}`);
82
+ if (!macos.xcode?.ready)
83
+ lines.push(` Xcode readiness: ${macos.xcode?.error ?? "not ready"}`);
84
+ if (!macos.simulators?.probe_ok)
85
+ lines.push(` simulator probe: ${macos.simulators?.error ?? "not ready"}`);
86
+ return lines;
87
+ }
88
+ export function machineGitLines(gitFacts) {
89
+ if (!gitFacts || typeof gitFacts !== "object")
90
+ return [];
91
+ const repositories = Array.isArray(gitFacts.repositories) ? gitFacts.repositories : [];
92
+ return [
93
+ ` Git identity: ${gitFacts.identity_configured === true ? "configured" : "MISSING"}`,
94
+ ...repositories.map((repo) => ` Git access ${repo.project}: ${repo.accessible === true ? "ok" : repo.accessible === false ? `FAILED (${repo.error ?? "access check failed"})` : `unknown (${repo.error ?? "not checked"})`}`),
95
+ ];
96
+ }
65
97
  /**
66
98
  * Runs `command` on `host` with /bin/sh, whatever the account's login shell: zsh aborts a command
67
99
  * whose glob matches nothing (mini1: the archived-sessions pattern of a thread lookup). Output may be
@@ -77,6 +109,12 @@ function ssh(host, command, input) {
77
109
  const remoteBschat = (host, args, input) => ssh(host, `bash -lc ${JSON.stringify(`b9s ${args}`)}`, input);
78
110
  export async function machineAdmin(action, rest, p, out) {
79
111
  const c = adminClient(p);
112
+ if (action === "companion") {
113
+ if (rest[0] !== "run" || !rest[1] || !/^bs_handoff_[A-Za-z0-9_-]{20,}$/.test(rest[1])) {
114
+ throw new CliError("usage", "machine companion run <handoff-code> [--confirm <machine-name>] (paste the short-lived code from the signed-in console)");
115
+ }
116
+ return runMachineCompanion(rest[1], p, out);
117
+ }
80
118
  if (action === "add") {
81
119
  const name = rest[0];
82
120
  const host = str(p.flags, "ssh");
@@ -138,7 +176,13 @@ export async function machineAdmin(action, rest, p, out) {
138
176
  throw new CliError("usage", "machine show <name>");
139
177
  const r = await c.call("GET", `/machines/${rest[0]}`);
140
178
  const m = r.machine;
141
- const rep = m.report ?? {};
179
+ let liveReport = null;
180
+ try {
181
+ const live = await c.call("GET", `/machines/${rest[0]}/live`);
182
+ liveReport = live.latest?.report ?? null;
183
+ }
184
+ catch { /* A machine without a live sample still uses its last stable report. */ }
185
+ const rep = liveReport ?? m.report ?? {};
142
186
  const head = [
143
187
  `${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}%)`,
144
188
  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?)",
@@ -173,10 +217,11 @@ export async function machineAdmin(action, rest, p, out) {
173
217
  }
174
218
  }
175
219
  const capabilityLines = machineCapabilityLines(m.capabilities ?? []);
176
- const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", 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\[[^\]]+\]: /, "") }));
220
+ 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\[[^\]]+\]: /, "") }));
177
221
  const providers = rep.claude_code?.providers ?? {};
178
222
  const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
179
- return out.print([...head, ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), r);
223
+ const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
224
+ 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);
180
225
  }
181
226
  if (action === "maintenance") {
182
227
  // A window on the machine: no new turns from 15 min before, its agents away until it ends.
@@ -194,6 +239,13 @@ export async function machineAdmin(action, rest, p, out) {
194
239
  const w = r.maintenance;
195
240
  return out.print(`${name}: maintenance ${w.start.slice(0, 16).replace("T", " ")} to ${w.end.slice(11, 16)} UTC (${w.phase}). No new turns start there from 15 min before; its agents are away until it ends, which happens when the machine reports after booting or at the end time. Projects with agents there were told.`, r);
196
241
  }
242
+ if (action === "resize") {
243
+ const name = rest[0];
244
+ if (!name) {
245
+ throw new CliError("usage", "machine resize <machine> --type <instance-type> [--instance-id <id>] [--drain-timeout 5m] [--yes] [--on-running-turn wait|proceed|abort] [--extend 5m] [--ssh <host>]");
246
+ }
247
+ return runMachineResize(c, p, out, name);
248
+ }
197
249
  if (action === "writable") {
198
250
  const name = rest[0];
199
251
  if (!name || rest.length < 2)
@@ -269,31 +321,100 @@ export async function machineAdmin(action, rest, p, out) {
269
321
  const r = await c.call("PATCH", `/machines/${name}`, body);
270
322
  return out.print(`${name}: labels ${r.machine.labels.join(", ") || "(none)"}; slots ${r.machine.slots ?? "auto"}. Pools were re-placed: b9s-admin pool list`, r);
271
323
  }
324
+ if (action === "readiness") {
325
+ const name = rest[0];
326
+ if (!name)
327
+ throw new CliError("usage", "machine readiness <name> [--project <p>]");
328
+ const proj = str(p.flags, "project");
329
+ const r = await c.call("GET", `/machines/${encodeURIComponent(name)}/readiness${proj ? `?project=${encodeURIComponent(proj)}` : ""}`);
330
+ const ev = r.readiness;
331
+ const lines = [
332
+ `${r.machine.name}: ${ev.ready ? "READY" : "NOT READY"}`,
333
+ ` daemon checked in: ${ev.daemon_checked_in ? "yes" : "no"}`,
334
+ ` git identity: ${ev.git_identity.ok ? `${ev.git_identity.user_name} <${ev.git_identity.user_email}>` : "missing"}`,
335
+ ` nested container sandbox: ${ev.container_sandbox.ok ? "ok" : `MISSING (${(ev.container_sandbox.missing ?? []).join(", ") || "failed"})`}`,
336
+ ...(ev.blockers.length ? [` blockers: ${ev.blockers.join("; ")}`] : []),
337
+ ];
338
+ return out.print(lines.join("\n"), r);
339
+ }
340
+ if (action === "login") {
341
+ const sub = rest[0];
342
+ if (sub === "status") {
343
+ const name = rest[1];
344
+ if (!name)
345
+ throw new CliError("usage", "machine login status <machine>");
346
+ const r = await c.call("GET", `/machines/${encodeURIComponent(name)}/device-logins`);
347
+ const lines = r.device_logins.map((d) => `${d.id} ${d.harness}/${d.provider} ${d.status} ${d.verification_uri ? `${d.verification_uri} (${d.user_code})` : ""}`);
348
+ return out.print(lines.join("\n") || "No device logins recorded.", r);
349
+ }
350
+ if (sub === "cancel") {
351
+ const [_, name, id] = rest;
352
+ if (!name || !id)
353
+ throw new CliError("usage", "machine login cancel <machine> <login-id>");
354
+ const r = await c.call("POST", `/machines/${encodeURIComponent(name)}/device-login/${encodeURIComponent(id)}/cancel`, {});
355
+ return out.print(`Cancelled device login ${id} on ${name}.`, r);
356
+ }
357
+ const name = sub;
358
+ if (!name)
359
+ throw new CliError("usage", "machine login <machine> --harness codex|claude-code|antigravity [--provider p] | status <machine> | cancel <machine> <id>");
360
+ const harness = need(p.flags, "harness");
361
+ const provider = str(p.flags, "provider");
362
+ const r = await c.call("POST", `/machines/${encodeURIComponent(name)}/device-login`, { harness, ...(provider ? { provider } : {}) });
363
+ return out.print(`Requested ${harness} device login (${r.device_login.id}) on ${name}; check b9s-admin machine login status ${name} or b9s-admin needs for verification URL and code.`, r);
364
+ }
272
365
  if (action === "remove") {
273
366
  if (!rest[0])
274
367
  throw new CliError("usage", "machine remove <name> (forgets it and revokes its keys; stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine)");
275
- await c.call("DELETE", `/machines/${rest[0]}`);
276
- return out.print(`Removed machine ${rest[0]}; its machine key and the agent keys minted for it are revoked. Its daemon stops reaching the API; stop it on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS)`, { removed: rest[0] });
368
+ const name = rest[0];
369
+ const preview = await c.call("GET", `/machines/${name}/removal-impact`);
370
+ const impact = preview.impact;
371
+ const details = [
372
+ `Machine ${name} removal impact:`,
373
+ ` sessions: ${impact.sessions.length}; active work: ${impact.active_work.length}; pending reviews: ${impact.review_work.length}; affected pools: ${impact.affected_pools.length}`,
374
+ ` machine-scoped keys to revoke: ${impact.machine_scoped_keys_to_revoke}; restricted recovery records: ${impact.restricted_recovery_records}`,
375
+ ...impact.blockers.map((blocker) => ` BLOCKED: ${blocker}`),
376
+ ...impact.sessions.map((s) => ` session ${s.agent}: ${s.desired}${s.pool ? ` (pool ${s.pool})` : ""}`),
377
+ ...impact.active_work.map((w) => ` active WU #${w.number} ${w.project}: ${w.title} (${w.status})`),
378
+ ...impact.review_work.map((w) => ` review WU #${w.number} ${w.project}: ${w.title}`),
379
+ ...impact.expected_placements.map((p) => ` ${p.project}/${p.pool}/${p.slot}: ${p.machine ?? `unplaced (${p.reason ?? "no eligible machine"})`}`),
380
+ ` revokes the machine key and its machine-scoped agent keys; agent identities remain`,
381
+ ];
382
+ if (bool(p.flags, "preview"))
383
+ return out.print(details.join("\n"), impact);
384
+ if (!out.json)
385
+ process.stderr.write(`${details.join("\n")}\n`);
386
+ const suppliedRevision = str(p.flags, "impact-revision");
387
+ if (suppliedRevision !== undefined && suppliedRevision !== impact.source_revision)
388
+ throw new CliError("stale_preview", "machine removal impact changed; run machine remove <name> --preview and review the new result");
389
+ if ((!process.stdin.isTTY || !process.stdout.isTTY) && suppliedRevision === undefined)
390
+ throw new CliError("confirmation_required", `non-interactive removal requires a reviewed revision: run machine remove ${name} --preview, then pass --confirm ${name} --impact-revision <revision>`);
391
+ await confirmMachineName(name, p);
392
+ await c.call("DELETE", `/machines/${name}`, { source_revision: impact.source_revision, confirmation: name });
393
+ return out.print(`Removed machine ${name}; its machine key and machine-scoped agent keys are revoked. Agent identities remain. Stop its daemon on the machine with: systemctl --user disable --now org.benignswarm.machine (Linux) or launchctl bootout gui/$(id -u)/org.benignswarm.machine (macOS)`, { removed: name, impact });
277
394
  }
278
395
  if (action === "session") {
279
396
  const [sub, machineName, ref] = rest;
280
397
  const [project, agent] = (ref ?? "").split("/");
281
398
  if (!sub || !machineName || !project || !agent)
282
- throw new CliError("usage", "machine session add|stop|start|resume|limit|remove <machine> <project>/<agent> [...]");
399
+ throw new CliError("usage", "machine session add|stop|start|resume|limit|coalesce|remove <machine> <project>/<agent> [...]");
283
400
  if (sub === "add") {
284
401
  const turnTimeout = str(p.flags, "turn-timeout");
285
402
  const turnsPerHour = str(p.flags, "turns-per-hour");
286
403
  const unproductivePerHour = str(p.flags, "unproductive-per-hour");
404
+ const coalesceSeconds = str(p.flags, "turn-coalesce-seconds");
287
405
  if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 60))
288
406
  throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 60");
289
407
  if (unproductivePerHour !== undefined && (!/^\d+$/.test(unproductivePerHour) || Number(unproductivePerHour) < 1 || Number(unproductivePerHour) > 60))
290
408
  throw new CliError("usage", "--unproductive-per-hour must be a whole number from 1 to 60");
409
+ if (coalesceSeconds !== undefined && (!/^\d+$/.test(coalesceSeconds) || Number(coalesceSeconds) > 3600))
410
+ throw new CliError("usage", "--turn-coalesce-seconds must be a whole number from 0 to 3600");
291
411
  const body = {
292
412
  project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
293
413
  model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
294
414
  ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
295
415
  ...(turnsPerHour ? { turns_per_hour: Number(turnsPerHour) } : {}),
296
416
  ...(unproductivePerHour ? { unproductive_per_hour: Number(unproductivePerHour) } : {}),
417
+ ...(coalesceSeconds !== undefined ? { turn_coalesce_seconds: Number(coalesceSeconds) } : {}),
297
418
  create: bool(p.flags, "create"), role: str(p.flags, "role"),
298
419
  };
299
420
  const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
@@ -326,12 +447,120 @@ export async function machineAdmin(action, rest, p, out) {
326
447
  const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { ...(value ? { turns_per_hour: Number(value) } : {}), ...(unproductive ? { unproductive_per_hour: Number(unproductive) } : {}) });
327
448
  return out.print(`${ref} on ${machineName}: ${value ? `busy cap ${value}/hour` : "busy cap unchanged"}; ${unproductive ? `${unproductive} unproductive turns/hour` : "unproductive fault threshold unchanged"}; the daemon applies changes within 30 s.`, r);
328
449
  }
450
+ if (sub === "coalesce") {
451
+ const value = str(p.flags, "turn-coalesce-seconds");
452
+ if (value === undefined || !/^\d+$/.test(value) || Number(value) > 3600)
453
+ throw new CliError("usage", "machine session coalesce <machine> <project>/<agent> --turn-coalesce-seconds <0..3600>");
454
+ const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { turn_coalesce_seconds: Number(value) });
455
+ return out.print(`${ref} on ${machineName}: turn coalescing ${r.session.turn_coalesce_seconds}s; the daemon applies it within 30 s.`, r);
456
+ }
329
457
  if (sub === "remove") {
330
458
  await c.call("DELETE", `/machines/${machineName}/sessions/${project}/${agent}`);
331
459
  return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
332
460
  }
333
461
  }
334
- throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | remove <name> | session add|stop|start|resume|limit|thread|remove <machine> <project>/<agent> [...]");
462
+ throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | resize <name> --type <instance-type> | remove <name> | session add|stop|start|resume|limit|coalesce|thread|remove <machine> <project>/<agent> [...]");
463
+ }
464
+ async function confirmMachineName(machine, p) {
465
+ const supplied = str(p.flags, "confirm");
466
+ if (supplied !== undefined) {
467
+ if (supplied !== machine)
468
+ throw new CliError("confirmation_required", `--confirm must exactly match ${machine}`);
469
+ return;
470
+ }
471
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
472
+ throw new CliError("confirmation_required", `type ${machine} at an interactive prompt or pass --confirm ${machine} with the reviewed impact revision`);
473
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
474
+ try {
475
+ const answer = await rl.question(`Type ${machine} to confirm: `);
476
+ if (answer !== machine)
477
+ throw new CliError("confirmation_required", "machine name did not match; operation cancelled");
478
+ }
479
+ finally {
480
+ rl.close();
481
+ }
482
+ }
483
+ async function runMachineCompanion(code, p, out) {
484
+ const adminCredentials = loadAdmin(resolveAdminName(str(p.flags, "admin")));
485
+ const c = Client.forAdmin(adminCredentials);
486
+ const preview = await c.call("POST", "/machine-operations/handoff-preview", { handoff_code: code });
487
+ const previewOp = preview.operation;
488
+ const summary = `Local companion will ${previewOp.kind === "provision" ? "provision" : "rotate the key for"} machine ${previewOp.machine} over SSH host ${previewOp.ssh_host}. SSH credentials remain with your SSH agent/config; the machine key will be sent to the machine over SSH stdin.`;
489
+ if (!out.json)
490
+ process.stderr.write(`${summary}\n`);
491
+ await confirmMachineName(previewOp.machine, p);
492
+ const claimed = await c.call("POST", `/machine-operations/${previewOp.id}/claim`, { handoff_code: code });
493
+ const operation = claimed.operation;
494
+ const companion = Client.raw(adminCredentials.url, claimed.companion_token);
495
+ const report = async (step, status, detail = "") => {
496
+ await companion.call("POST", `/machine-operations/${operation.id}/progress`, { step, status, detail });
497
+ if (!out.json)
498
+ process.stderr.write(` ${step}: ${status}${detail ? ` — ${detail}` : ""}\n`);
499
+ };
500
+ const checkCancel = async () => {
501
+ const state = await companion.call("GET", `/machine-operations/${operation.id}`);
502
+ if (state.operation.status === "cancel_requested" || state.operation.status === "cancelled") {
503
+ await companion.call("POST", `/machine-operations/${operation.id}/finish`, { status: "cancelled", result: "Stopped at the operator's cancellation request" });
504
+ throw new CliError("cancelled", "machine companion operation cancelled by the operator");
505
+ }
506
+ };
507
+ try {
508
+ await checkCancel();
509
+ await report("bootstrap", "started", `Preparing ${operation.ssh_host}`);
510
+ const boot = ssh(operation.ssh_host, "bash -l -s", bootstrapScript(CLI_VERSION));
511
+ const steps = boot.stdout.split("\n").filter((line) => line.startsWith("BSCHAT-STEP ")).map((line) => line.slice(12));
512
+ for (const line of steps)
513
+ if (!out.json)
514
+ process.stderr.write(` ${line}\n`);
515
+ if (boot.status !== 0) {
516
+ const failure = steps.length ? steps[steps.length - 1] : boot.stderr.trim().slice(-300);
517
+ throw new CliError("provision_failed", `bootstrapping ${operation.ssh_host} failed: ${failure}`);
518
+ }
519
+ await report("bootstrap", "completed", "Node and b9s are ready on the target machine");
520
+ await checkCancel();
521
+ await report("prepare", "started", "Checking machine services and harness prerequisites");
522
+ const prep = remoteBschat(operation.ssh_host, `machine prepare --json${operation.options.codex_userns ? " --codex-userns" : ""}${operation.options.bwrap_userns ? " --bwrap-userns" : ""}`);
523
+ if (prep.status !== 0)
524
+ throw new CliError("provision_failed", `b9s machine prepare on ${operation.ssh_host} failed: ${prep.stderr.trim().slice(-300)}`);
525
+ const prepared = JSON.parse(prep.stdout).steps;
526
+ await report("prepare", "completed", prepared.map((step) => `${step.step} ${step.result}`).join("; ").slice(0, 450));
527
+ await checkCancel();
528
+ await report("machine-key", "started", "Issuing one-time machine key to the local companion");
529
+ const registration = await companion.call("POST", `/machine-operations/${operation.id}/machine-key`, {});
530
+ await report("key-transfer", "started", "Sending the key directly to the machine over SSH stdin");
531
+ const wrote = ssh(operation.ssh_host, `umask 077 && mkdir -p ~/.b9s && cat > ~/.b9s/machine.json`, JSON.stringify({ url: adminCredentials.url, key: registration.key, name: operation.machine }, null, 2) + "\n");
532
+ if (wrote.status !== 0)
533
+ throw new CliError("provision_failed", `writing ~/.b9s/machine.json on ${operation.ssh_host} failed: ${wrote.stderr.trim()}`);
534
+ await report("key-transfer", "completed", "Machine key delivered; it was not returned to the console");
535
+ await checkCancel();
536
+ await report("daemon", "started", "Installing and starting the machine daemon");
537
+ const svc = remoteBschat(operation.ssh_host, "machine service --json");
538
+ if (svc.status !== 0)
539
+ throw new CliError("provision_failed", `installing the machine daemon on ${operation.ssh_host} failed: ${svc.stderr.trim().slice(-300)}`);
540
+ const daemon = JSON.parse(svc.stdout);
541
+ await report("daemon", "completed", `Daemon installed at ${daemon.path}`);
542
+ const outcome = operation.kind === "provision" ? "is provisioned" : "has its machine key rotated";
543
+ const completed = await companion.call("POST", `/machine-operations/${operation.id}/finish`, { status: "succeeded", result: `Machine ${operation.machine} ${outcome} and its daemon is running` });
544
+ const result = { operation: completed.operation, machine: operation.machine, ssh_host: operation.ssh_host, daemon_path: daemon.daemon_path, prepare: prepared };
545
+ return out.print(`Machine ${operation.machine} ${outcome} and its daemon is running. Declare its sessions with: b9s-admin machine session add ${operation.machine} <project>/<agent> --sandbox <mode> [--create --role <role>]`, result);
546
+ }
547
+ catch (error) {
548
+ if (error.code === "cancelled")
549
+ throw error;
550
+ const message = error instanceof Error ? error.message : String(error);
551
+ const auditDetail = `Local operation failed (${error instanceof CliError ? error.code : "local_error"}); inspect the local companion output`;
552
+ let reportingError;
553
+ try {
554
+ await companion.call("POST", `/machine-operations/${operation.id}/progress`, { step: "operation", status: "failed", detail: auditDetail });
555
+ await companion.call("POST", `/machine-operations/${operation.id}/finish`, { status: "failed", result: auditDetail });
556
+ }
557
+ catch (reportError) {
558
+ reportingError = reportError;
559
+ }
560
+ if (reportingError)
561
+ throw new CliError("operation_reporting_failed", `${message}; also failed to record the operation failure: ${reportingError instanceof Error ? reportingError.message : String(reportingError)}`);
562
+ throw error;
563
+ }
335
564
  }
336
565
  /** `[tag=]harness:model[:effort][*weight][@provider]`, e.g. `luna=claude-code:deepseek-flash@deepseek`. */
337
566
  export function parseVariant(spec) {
@@ -358,6 +587,9 @@ export function repeated(argv, flag) {
358
587
  * pool list [project] | show <project>/<name> | remove <project>/<name>
359
588
  */
360
589
  export async function poolAdmin(action, rest, p, out, argv) {
590
+ if (action === "set" && p.flags["turn-coalesce-seconds"] !== undefined) {
591
+ throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
592
+ }
361
593
  const c = adminClient(p);
362
594
  const statusLines = (pool) => [
363
595
  `${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` : ""}`,
@@ -464,15 +696,51 @@ function on(host, command, input) {
464
696
  }
465
697
  return ssh(host, command, input);
466
698
  }
699
+ function machineMoveReadinessError(machine, harness, provider, sandbox, nowMs = Date.now()) {
700
+ const report = machine?.report;
701
+ if (!report || typeof report !== "object")
702
+ return `${machine?.name ?? "destination machine"} has not reported; no move was started there`;
703
+ const intervalSeconds = Number(report.report_interval_seconds ?? 30);
704
+ const reportedAt = Date.parse(machine.last_report_at ?? "");
705
+ if (!Number.isFinite(reportedAt) || !Number.isFinite(intervalSeconds) || intervalSeconds <= 0 || nowMs - reportedAt > intervalSeconds * 4_000) {
706
+ return `${machine.name} has a missing or stale report; refresh the machine before moving an agent there`;
707
+ }
708
+ let facts = report[harness];
709
+ if (harness === "claude-code") {
710
+ facts = report.claude_code ?? report["claude-code"];
711
+ const providers = facts?.providers;
712
+ facts = providers?.[provider] ?? (provider === "anthropic" ? facts : undefined);
713
+ }
714
+ if (!facts || typeof facts !== "object")
715
+ return `${machine.name} has no ${harness} report`;
716
+ if (harness === "codex" || harness === "claude-code") {
717
+ if (facts.logged_in !== true)
718
+ return `${harness} ${provider === "anthropic" ? "login" : `${provider} login`} is not verified on ${machine.name}`;
719
+ }
720
+ if (harness === "dsh" && facts.available !== true)
721
+ return `DeepSeek Harness is unavailable on ${machine.name}: ${facts.error ?? "not installed"}`;
722
+ if (harness === "antigravity") {
723
+ if (facts.available !== true)
724
+ return `Antigravity is unavailable on ${machine.name}: ${facts.error ?? "not installed"}`;
725
+ if (facts.logged_in !== true)
726
+ return `Antigravity is not logged in on ${machine.name}`;
727
+ }
728
+ if (sandbox !== "danger-full-access" && facts.sandbox?.ok !== true) {
729
+ return facts.sandbox?.ok === false
730
+ ? `${harness} sandbox does not work on ${machine.name}: ${facts.sandbox.error ?? "probe failed"}`
731
+ : `${harness} sandbox has not been verified on ${machine.name}`;
732
+ }
733
+ return null;
734
+ }
467
735
  /**
468
736
  * agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir path|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--model m] [--effort e]
469
- * [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min] [--force]
737
+ * [--carry note|thread] [--from local|<ssh host>] [--to-ssh <host>] [--thread id] [--wait min]
738
+ * [--force --confirm-force <project>/<agent>]
470
739
  *
471
- * The agent (name, role, record, units, chat) is on the server and does not move; its harness
472
- * session does. Its units in progress must be pushed (checked on --from); its context travels as a
473
- * resume note it writes now (--carry note, the default) or as its Codex thread itself, copied over
474
- * the operator's ssh (--carry thread; same thread id, full history). The new machine's daemon then
475
- * runs it, and every key not minted for that machine is revoked, so the old copy stops.
740
+ * The server records an authorized move operation first. This trusted CLI checks source worktrees,
741
+ * transfers the requested context over the operator's SSH, then asks the API to commit the session
742
+ * change. The API does not receive source paths or SSH material and is not told the move completed
743
+ * until the local handoff succeeded.
476
744
  */
477
745
  export async function agentMove(rest, p, out) {
478
746
  const ref = rest[0] ?? "";
@@ -483,127 +751,192 @@ export async function agentMove(rest, p, out) {
483
751
  const provider = str(p.flags, "provider") ?? "anthropic";
484
752
  const carry = str(p.flags, "carry") ?? "note";
485
753
  const from = str(p.flags, "from");
754
+ const forceConfirmation = str(p.flags, "confirm-force");
486
755
  if (!project || !agent || !to || !sandbox)
487
- throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]");
756
+ throw new CliError("usage", "agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread] [--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]");
757
+ if (forceConfirmation && !bool(p.flags, "force"))
758
+ throw new CliError("usage", "--confirm-force is valid only with --force");
759
+ if (forceConfirmation && forceConfirmation !== ref)
760
+ throw new CliError("confirmation_required", `--confirm-force must exactly match ${ref}`);
761
+ if (harness !== "codex" && harness !== "claude-code")
762
+ throw new CliError("usage", "agent move currently supports codex and claude-code sessions; DSH and Antigravity session behavior is unchanged");
488
763
  if (provider !== "anthropic" && provider !== "deepseek")
489
764
  throw new CliError("usage", "--provider must be anthropic or deepseek");
490
765
  if (provider === "deepseek" && harness !== "claude-code")
491
766
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
492
767
  if (carry !== "note" && carry !== "thread")
493
768
  throw new CliError("usage", "--carry note (a resume note it writes now) or thread (its Codex thread, copied)");
769
+ if (carry !== "thread" && str(p.flags, "thread"))
770
+ throw new CliError("usage", "--thread is valid only with --carry thread");
494
771
  if (carry === "thread" && (str(p.flags, "harness") ?? "codex") !== "codex")
495
772
  throw new CliError("usage", "--carry thread copies a Codex thread; a Claude Code agent moves with --carry note (its resume note), and its new machine starts a fresh session");
496
773
  if (carry === "thread" && !from)
497
774
  throw new CliError("usage", "--carry thread needs --from local|<ssh host>: the machine whose ~/.codex holds its thread");
775
+ if (!from)
776
+ throw new CliError("usage", "--from local|<ssh host> is required so the trusted CLI can check the source before authorizing completion");
498
777
  const c = adminClient(p);
499
778
  const say = (l) => { if (!out.json)
500
779
  process.stderr.write(`${l}\n`); };
501
- // 1. Work in progress must be on origin, or it stays behind on the old machine.
502
- 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));
503
- const problems = [];
504
- for (const u of units) {
505
- if (!from || !u.worktree) {
506
- say(` #${u.number} [${u.status}] ${u.branch ?? ""}${u.worktree ? ` in ${u.worktree}` : ""}: not checked (no --from)`);
507
- continue;
508
- }
509
- const r = on(from, `cd ${JSON.stringify(u.worktree)} 2>/dev/null || exit 3; echo "dirty=$(git status --porcelain | wc -l) unpushed=$(git rev-list --count HEAD --not --remotes)"`);
510
- if (r.status === 3) {
511
- say(` #${u.number}: ${u.worktree} is not on ${from}`);
512
- continue;
513
- }
514
- const m = /dirty=\s*(\d+) unpushed=\s*(\d+)/.exec(r.stdout);
515
- if (!m) {
516
- problems.push(`#${u.number}: cannot read ${u.worktree} on ${from}: ${r.stderr.trim().slice(0, 200)}`);
517
- continue;
518
- }
519
- if (Number(m[1]) || Number(m[2]))
520
- problems.push(`#${u.number} (${u.branch}): ${m[2]} unpushed commit(s), ${m[1]} uncommitted file(s) in ${u.worktree}`);
521
- else
522
- say(` #${u.number} [${u.status}] ${u.branch}: pushed and clean`);
523
- }
524
- if (problems.length && !bool(p.flags, "force"))
525
- 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; --force moves anyway and leaves that work there");
526
- // 2. Its context, and the model it runs: a resumed thread without -m takes the new machine's
527
- // default (fabricbios coordinator and luna-worker came up on ronald as gpt-6.1-terra low).
780
+ const moveRoute = `/projects/${project}/agents/${agent}/moves`;
781
+ const requested = await c.call("POST", moveRoute, {
782
+ to, carry, harness, provider, dir: str(p.flags, "dir") ?? "auto", sandbox,
783
+ ...(str(p.flags, "model") ? { model: str(p.flags, "model") } : {}),
784
+ ...(str(p.flags, "effort") ? { effort: str(p.flags, "effort") } : {}),
785
+ ...(str(p.flags, "thread") ? { thread: str(p.flags, "thread") } : {}),
786
+ ...(str(p.flags, "turn-timeout") ? { turn_timeout: Number(str(p.flags, "turn-timeout")) } : {}),
787
+ });
788
+ const move = requested.move;
789
+ const progressRoute = `${moveRoute}/${move.id}`;
790
+ if (!out.json)
791
+ say(` move ${move.id}: ${move.from ?? "source"} → ${to}; other agent keys will be revoked only after completion`);
792
+ await c.call("PATCH", progressRoute, { status: "checking", detail: "trusted CLI is checking local readiness and preparing the handoff" });
528
793
  let thread = str(p.flags, "thread") ?? null;
529
794
  let model = str(p.flags, "model");
530
795
  let effort = str(p.flags, "effort");
531
- if (carry === "thread") {
532
- if (!thread) {
533
- const map = on(from, remoteCodexMapCommand());
534
- if (map.status !== 0)
535
- throw new CliError("codex_map_unavailable", `could not read the Codex thread map on ${from}: ${map.stderr.trim()}`);
536
- let conversationMap;
537
- try {
538
- const parsed = JSON.parse(map.stdout);
539
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
540
- throw new Error("map must be an object");
541
- const conversations = parsed.conversations ?? {};
542
- if (!conversations || typeof conversations !== "object" || Array.isArray(conversations))
543
- throw new Error("conversations must be an object");
544
- conversationMap = conversations;
796
+ let problems = [];
797
+ try {
798
+ const destination = await c.call("GET", `/machines/${to}`);
799
+ const readinessError = machineMoveReadinessError(destination.machine, harness, provider, sandbox);
800
+ if (readinessError)
801
+ throw new CliError("destination_not_ready", readinessError);
802
+ // 1. Work in progress must be on origin, or it stays behind on the old machine.
803
+ 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));
804
+ for (const u of units) {
805
+ if (!u.worktree) {
806
+ problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): no worktree is recorded, so its Git state cannot be verified`);
807
+ continue;
545
808
  }
546
- catch (error) {
547
- throw new CliError("bad_codex_map", `the Codex thread map on ${from} is not valid JSON: ${error.message}`);
809
+ const unavailableMarker = "BSCHAT_MOVE_WORKTREE_UNAVAILABLE";
810
+ const cd = `cd ${shellSingle(u.worktree)} 2>/dev/null || { printf '%s\\n' '${unavailableMarker}' >&2; exit 97; }; `;
811
+ const unavailable = (result) => result.status === 97 && result.stderr.trim() === unavailableMarker;
812
+ const status = on(from, `${cd}git status --porcelain`);
813
+ if (unavailable(status)) {
814
+ problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): ${u.worktree} is not available on ${from}`);
815
+ continue;
548
816
  }
549
- const ids = Object.entries(conversationMap).filter(([, a]) => a === ref).map(([id]) => id);
550
- if (!ids.length)
551
- throw new CliError("no_thread", `no Codex thread is bound to ${ref} on ${from} (~/.b9s/codex.json or ~/.bschat/codex.json)`, "Pass --thread <id>");
552
- const newest = on(from, `ls -t ${ids.map((id) => `~/.codex/sessions/*/*/*/rollout-*${id}.jsonl ~/.codex/archived_sessions/rollout-*${id}.jsonl`).join(" ")} 2>/dev/null | head -1`).stdout.trim();
553
- thread = ids.find((id) => newest.includes(id)) ?? null;
554
- if (!thread)
555
- throw new CliError("no_thread", `the threads bound to ${ref} on ${from} have no session file`, "Pass --thread <id>, or use --carry note");
556
- }
557
- // The Codex app moves an archived thread's file to ~/.codex/archived_sessions (flat); it is copied
558
- // into the dated sessions folder on the new machine either way, where codex exec resume finds it.
559
- const src = on(from, threadFileCommand(thread));
560
- if (src.status !== 0)
561
- throw new CliError("no_thread", `${from} has no session file for thread ${thread}`);
562
- const nl = src.stdout.indexOf("\n");
563
- const rel = src.stdout.slice(0, nl);
564
- const last = lastTurnSettings(src.stdout.slice(nl + 1));
565
- model ??= last.model ?? undefined;
566
- effort ??= last.effort ?? undefined;
567
- const toHost = str(p.flags, "to-ssh") ?? to;
568
- const put = ssh(toHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
569
- if (put.status !== 0)
570
- throw new CliError("copy_failed", `copying thread ${thread} to ${toHost}: ${put.stderr.trim()}`);
571
- say(` thread ${thread} copied to ${toHost} (${Math.round((src.stdout.length - nl) / 1024)} KB); the copy on ${from} is now a dead end: archive it in the Codex app there so nobody types into it`);
572
- }
573
- else {
574
- const wait = Number(str(p.flags, "wait") ?? "10");
575
- if (wait > 0) {
576
- const asked = new Date().toISOString();
577
- await c.call("POST", `/projects/${project}/channels/general/messages`, { body: `@${agent} you are being moved to the machine ${to}. Before anything else, save a resume note: b9s checkpoint "<one line>" --body "<what you are doing, your open units and branches (pushed?), waits and next steps>". Your next session there reads it first. Then end your turn.` });
578
- say(` asked ${agent} for a resume note; waiting up to ${wait} min`);
579
- let note = null;
580
- for (let i = 0; i < wait * 6 && !note; i++) {
581
- await new Promise((r) => setTimeout(r, 10_000));
582
- note = (await c.call("GET", `/projects/${project}/handoffs?agent=${encodeURIComponent(agent)}&limit=1`)).handoffs.find((h) => h.created_at > asked) ?? null;
817
+ if (status.status !== 0)
818
+ throw new CliError("git_preflight_failed", `cannot inspect Git status for #${u.number} (${u.branch ?? "no branch recorded"}) on ${from}: ${status.stderr.trim().slice(0, 200) || `git status exited ${status.status}`}`);
819
+ const unpushed = on(from, `${cd}git rev-list --count HEAD --not --remotes`);
820
+ if (unavailable(unpushed)) {
821
+ problems.push(`#${u.number} (${u.branch ?? "no branch recorded"}): ${u.worktree} is not available on ${from}`);
822
+ continue;
583
823
  }
584
- say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
585
- }
586
- }
587
- if (!model || !effort) {
588
- const st = ((await c.call("GET", `/projects/${project}/agents/status`)).statuses ?? []).find((s) => s.agent_name === agent);
589
- if (!model && st?.model && st.model !== "unknown")
590
- model = st.model;
591
- if (!effort && st?.effort && st.effort !== "unknown")
592
- effort = st.effort;
593
- }
594
- if (!model)
595
- say(` no model known for ${ref}: it runs with the new machine's Codex default (pass --model to choose)`);
596
- // 3. The new machine runs it; every other key stops working.
597
- const turnTimeout = str(p.flags, "turn-timeout");
598
- const r = await c.call("POST", `/machines/${to}/sessions`, {
599
- project, agent, move: true, harness, provider, dir: str(p.flags, "dir") ?? "auto", sandbox,
600
- model, effort, ...(thread ? { thread } : {}), ...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
824
+ if (unpushed.status !== 0 || !/^\d+$/.test(unpushed.stdout.trim()))
825
+ throw new CliError("git_preflight_failed", `cannot inspect unpushed commits for #${u.number} (${u.branch ?? "no branch recorded"}) on ${from}: ${unpushed.stderr.trim().slice(0, 200) || `git rev-list exited ${unpushed.status}`}`);
826
+ const dirtyCount = status.stdout.trim() ? status.stdout.trimEnd().split("\n").length : 0;
827
+ const unpushedCount = Number(unpushed.stdout.trim());
828
+ if (dirtyCount || unpushedCount)
829
+ problems.push(`#${u.number} (${u.branch}): ${unpushedCount} unpushed commit(s), ${dirtyCount} uncommitted file(s) in ${u.worktree}`);
830
+ else
831
+ say(` #${u.number} [${u.status}] ${u.branch}: pushed and clean`);
832
+ }
833
+ if (problems.length && !bool(p.flags, "force"))
834
+ 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}`);
835
+ if (problems.length && forceConfirmation !== ref) {
836
+ throw new CliError("force_confirmation_required", `These worktrees or changes cannot be moved and will remain only on ${from}:\n ${problems.join("\n ")}`, `Review the list, then rerun with --force --confirm-force ${ref}`);
837
+ }
838
+ // 2. Its context, and the model it runs: a resumed thread without -m takes the new machine's
839
+ // default (fabricbios coordinator and luna-worker came up on ronald as gpt-6.1-terra low).
840
+ if (carry === "thread") {
841
+ if (!thread) {
842
+ const map = on(from, remoteCodexMapCommand());
843
+ if (map.status !== 0)
844
+ throw new CliError("codex_map_unavailable", `could not read the Codex thread map on ${from}: ${map.stderr.trim()}`);
845
+ let conversationMap;
846
+ try {
847
+ const parsed = JSON.parse(map.stdout);
848
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
849
+ throw new Error("map must be an object");
850
+ const conversations = parsed.conversations ?? {};
851
+ if (!conversations || typeof conversations !== "object" || Array.isArray(conversations))
852
+ throw new Error("conversations must be an object");
853
+ conversationMap = conversations;
854
+ }
855
+ catch (error) {
856
+ throw new CliError("bad_codex_map", `the Codex thread map on ${from} is not valid JSON: ${error.message}`);
857
+ }
858
+ const ids = Object.entries(conversationMap).filter(([, a]) => a === ref).map(([id]) => id);
859
+ if (!ids.length)
860
+ throw new CliError("no_thread", `no Codex thread is bound to ${ref} on ${from} (~/.b9s/codex.json or ~/.bschat/codex.json)`, "Pass --thread <id>");
861
+ const newest = on(from, `ls -t ${ids.map((id) => `~/.codex/sessions/*/*/*/rollout-*${id}.jsonl ~/.codex/archived_sessions/rollout-*${id}.jsonl`).join(" ")} 2>/dev/null | head -1`).stdout.trim();
862
+ thread = ids.find((id) => newest.includes(id)) ?? null;
863
+ if (!thread)
864
+ throw new CliError("no_thread", `the threads bound to ${ref} on ${from} have no session file`, "Pass --thread <id>, or use --carry note");
865
+ }
866
+ // The Codex app moves an archived thread's file to ~/.codex/archived_sessions (flat); it is copied
867
+ // into the dated sessions folder on the new machine either way, where codex exec resume finds it.
868
+ const src = on(from, threadFileCommand(thread));
869
+ if (src.status !== 0)
870
+ throw new CliError("no_thread", `${from} has no session file for thread ${thread}`);
871
+ const nl = src.stdout.indexOf("\n");
872
+ const rel = src.stdout.slice(0, nl);
873
+ const last = lastTurnSettings(src.stdout.slice(nl + 1));
874
+ model ??= last.model ?? undefined;
875
+ effort ??= last.effort ?? undefined;
876
+ const toHost = str(p.flags, "to-ssh") ?? to;
877
+ const put = ssh(toHost, `mkdir -p ~/.codex/sessions/${JSON.stringify(rel.slice(0, rel.lastIndexOf("/")))} && cat > ~/.codex/sessions/${JSON.stringify(rel)}`, src.stdout.slice(nl + 1));
878
+ if (put.status !== 0)
879
+ throw new CliError("copy_failed", `copying thread ${thread} to ${toHost}: ${put.stderr.trim()}`);
880
+ say(` thread ${thread} copied to ${toHost} (${Math.round((src.stdout.length - nl) / 1024)} KB); the copy on ${from} is now a dead end: archive it in the Codex app there so nobody types into it`);
881
+ }
882
+ else {
883
+ const wait = Number(str(p.flags, "wait") ?? "10");
884
+ if (wait > 0) {
885
+ const asked = new Date().toISOString();
886
+ await c.call("POST", `/projects/${project}/channels/general/messages`, { body: `@${agent} you are being moved to the machine ${to}. Before anything else, save a resume note: b9s checkpoint "<one line>" --body "<what you are doing, your open units and branches (pushed?), waits and next steps>". Your next session there reads it first. Then end your turn.` });
887
+ say(` asked ${agent} for a resume note; waiting up to ${wait} min`);
888
+ let note = null;
889
+ for (let i = 0; i < wait * 6 && !note; i++) {
890
+ await new Promise((r) => setTimeout(r, 10_000));
891
+ note = (await c.call("GET", `/projects/${project}/handoffs?agent=${encodeURIComponent(agent)}&limit=1`)).handoffs.find((h) => h.created_at > asked) ?? null;
892
+ }
893
+ say(note ? ` resume note saved: ${note.title}` : ` no resume note within ${wait} min; it starts from its units, status and chat`);
894
+ }
895
+ }
896
+ if (!model || !effort) {
897
+ const st = ((await c.call("GET", `/projects/${project}/agents/status`)).statuses ?? []).find((s) => s.agent_name === agent);
898
+ if (!model && st?.model && st.model !== "unknown")
899
+ model = st.model;
900
+ if (!effort && st?.effort && st.effort !== "unknown")
901
+ effort = st.effort;
902
+ }
903
+ if (!model)
904
+ say(` no model known for ${ref}: it runs with the new machine's Codex default (pass --model to choose)`);
905
+ }
906
+ catch (error) {
907
+ const detail = error instanceof Error ? error.message : String(error);
908
+ const recordedDetail = error instanceof CliError && error.code === "destination_not_ready"
909
+ ? "destination harness, login, or sandbox readiness check failed"
910
+ : error instanceof CliError && error.code === "unpushed_work"
911
+ ? "source Git preflight found dirty, unpushed, or unavailable worktrees"
912
+ : error instanceof CliError && error.code === "git_preflight_failed"
913
+ ? "source Git inspection could not confirm worktree state"
914
+ : error instanceof CliError && error.code === "force_confirmation_required"
915
+ ? "source-only work was not explicitly confirmed"
916
+ : "local source check or context handoff failed";
917
+ try {
918
+ await c.call("PATCH", progressRoute, { status: "blocked", detail: recordedDetail });
919
+ }
920
+ catch (recordError) {
921
+ throw new CliError("move_progress_failed", `${detail}\nCould not record the blocked move operation: ${recordError instanceof Error ? recordError.message : String(recordError)}`);
922
+ }
923
+ if (error instanceof Error)
924
+ error.message = `Move operation ${move.id} was blocked: ${error.message}`;
925
+ throw error;
926
+ }
927
+ // 3. The operation becomes transferring only after all local checks and context copy/checkpoint
928
+ // work completed. The server then atomically replaces the session and revokes old keys.
929
+ await c.call("PATCH", progressRoute, {
930
+ status: "transferring", detail: "local checks and context handoff completed",
931
+ ...(carry === "thread" && thread ? { thread } : {}),
932
+ ...(model ? { model } : {}), ...(effort ? { effort } : {}),
601
933
  });
934
+ const r = await c.call("POST", `${progressRoute}/complete`, {});
602
935
  return out.print([
603
- `${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.`,
936
+ `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.`,
604
937
  r.moved_from.length ? `Its session on ${r.moved_from.join(", ")} was removed.` : null,
605
938
  `${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.`,
606
- problems.length ? `Left behind (--force): ${problems.join("; ")}` : null,
939
+ problems.length ? `Left behind on ${from} (--force confirmed): ${problems.join("; ")}` : null,
607
940
  `Follow it: b9s-admin machine show ${to}`,
608
941
  ].filter(Boolean).join("\n"), r);
609
942
  }