benignswarm 0.12.82 → 0.12.84
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/admin-index.js +6 -2
- package/dist/args.js +3 -3
- package/dist/brief.js +42 -8
- package/dist/client.js +4 -4
- package/dist/commands/admin.js +55 -16
- package/dist/commands/agent.js +33 -9
- package/dist/commands/antigravity.js +2 -2
- package/dist/commands/codex-start.js +17 -17
- package/dist/commands/codex.js +6 -6
- package/dist/commands/evidence.js +16 -1
- package/dist/commands/goal.js +5 -5
- package/dist/commands/hook.js +125 -57
- package/dist/commands/install.js +34 -28
- package/dist/commands/join.js +15 -14
- package/dist/commands/lists.js +2 -2
- package/dist/commands/machine-admin.js +56 -28
- package/dist/commands/machine.js +53 -29
- package/dist/commands/measures.js +191 -0
- package/dist/commands/notices.js +53 -0
- package/dist/commands/operator.js +68 -25
- package/dist/commands/retire.js +2 -2
- package/dist/commands/wake.js +4 -4
- package/dist/commands/watch.js +75 -28
- package/dist/commands/worktrees.js +4 -4
- package/dist/commands/wu.js +168 -61
- package/dist/config.js +11 -11
- package/dist/directories.js +83 -0
- package/dist/env-aliases.js +10 -0
- package/dist/git.js +2 -2
- package/dist/harness.js +91 -37
- package/dist/harnesses.js +5 -4
- package/dist/help.js +208 -183
- package/dist/index.js +37 -3
- package/dist/install.js +27 -19
- package/dist/legacy-alias.js +42 -0
- package/dist/notices.js +107 -0
- package/dist/output.js +2 -1
- package/dist/sessions.js +1 -1
- package/dist/update.js +1 -1
- package/dist/version.js +1 -1
- package/package.json +5 -3
package/dist/commands/machine.js
CHANGED
|
@@ -6,7 +6,7 @@ import { str } from "../args.js";
|
|
|
6
6
|
import { Client } from "../client.js";
|
|
7
7
|
import { configRoot, loadAgent, saveAgent } from "../config.js";
|
|
8
8
|
import { CliError } from "../errors.js";
|
|
9
|
-
import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR,
|
|
9
|
+
import { BWRAP_APPARMOR_PATH, bwrapAppArmorProfile, CODEX_APPARMOR_PATH, CODEX_MANAGED_DIR, codexAppArmorProfile, codexManagedHooks, isCodexManagedRequirements } from "../harness.js";
|
|
10
10
|
import { applySparse } from "../git.js";
|
|
11
11
|
import { drainingUntil, writeMaintenance } from "../maintenance.js";
|
|
12
12
|
import { TURN_HARNESSES, claudeFacts, claudeSandbox, probeFor, sessionProcesses } from "../harnesses.js";
|
|
@@ -14,11 +14,12 @@ import { readState, writeState } from "../state.js";
|
|
|
14
14
|
import { installService, lingerEnabled, MACHINE_LABEL, removeService, requireInstall, restartWatcher, serviceActive, WATCH_LABEL_PREFIX, watcherServices } from "../install.js";
|
|
15
15
|
import { CLI_VERSION } from "../version.js";
|
|
16
16
|
import { probeCapabilities } from "../capabilities.js";
|
|
17
|
+
import { diskSpaceNotice } from "../notices.js";
|
|
17
18
|
export const machineFile = () => join(configRoot(), "machine.json");
|
|
18
19
|
export function loadMachine() {
|
|
19
20
|
const f = machineFile();
|
|
20
21
|
if (!existsSync(f))
|
|
21
|
-
throw new CliError("no_machine", `${f} does not exist: this machine was not provisioned`, "Run
|
|
22
|
+
throw new CliError("no_machine", `${f} does not exist: this machine was not provisioned`, "Run b9s-admin machine add <name> --ssh <host> from the operator's terminal");
|
|
22
23
|
return JSON.parse(readFileSync(f, "utf8"));
|
|
23
24
|
}
|
|
24
25
|
const stateFile = () => join(configRoot(), "state", "machine.json");
|
|
@@ -29,7 +30,7 @@ function writeMachineState(s) {
|
|
|
29
30
|
}
|
|
30
31
|
/** What a session's watcher is started with; a change means re-running codex start. The thread is compared separately. */
|
|
31
32
|
/**
|
|
32
|
-
* Bumped when `
|
|
33
|
+
* Bumped when `b9s start` builds a session's settings differently, so every session is started
|
|
33
34
|
* again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
|
|
34
35
|
* 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
|
|
35
36
|
*/
|
|
@@ -38,7 +39,7 @@ export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harnes
|
|
|
38
39
|
export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
|
|
39
40
|
/**
|
|
40
41
|
* During a maintenance drain or window, a session that would be started fresh (no known thread, so
|
|
41
|
-
* `
|
|
42
|
+
* `b9s start` runs its first turn at once, past the watchers' check) waits; adopting a known
|
|
42
43
|
* thread starts no turn and proceeds. Returns the session's report while it waits, else null.
|
|
43
44
|
*/
|
|
44
45
|
export function deferredByMaintenance(s, thread, drain) {
|
|
@@ -50,7 +51,7 @@ export function deferredByMaintenance(s, thread, drain) {
|
|
|
50
51
|
export function maintenanceReport(drain, sessions) {
|
|
51
52
|
return drain ? { draining: true, until: drain.end, turns_running: sessions.filter((o) => o.turn?.running).length } : null;
|
|
52
53
|
}
|
|
53
|
-
/** The `
|
|
54
|
+
/** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
|
|
54
55
|
export function startArgs(s, thread, writable = []) {
|
|
55
56
|
return [
|
|
56
57
|
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--json",
|
|
@@ -81,6 +82,16 @@ export async function reconcile(m, log) {
|
|
|
81
82
|
const label = watchLabelOf(s.agent);
|
|
82
83
|
const svc = () => watcherServices().find((w) => w.label === label);
|
|
83
84
|
try {
|
|
85
|
+
if (s.desired === "benched") {
|
|
86
|
+
const w = svc();
|
|
87
|
+
const reason = `benched by ${s.benched_by ?? "the operator"}${s.benched_at ? ` at ${s.benched_at}` : ""}${s.bench_note ? `: ${s.bench_note}` : ""}`;
|
|
88
|
+
if (w) {
|
|
89
|
+
removeService(w);
|
|
90
|
+
log(`${s.agent}: ${reason}; watcher removed`);
|
|
91
|
+
}
|
|
92
|
+
out.push({ id: s.id, state: "benched", thread: state.sessions[s.id]?.thread ?? s.thread, detail: reason });
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
84
95
|
if (s.desired === "stopped") {
|
|
85
96
|
const w = svc();
|
|
86
97
|
if (w) {
|
|
@@ -92,7 +103,7 @@ export async function reconcile(m, log) {
|
|
|
92
103
|
continue;
|
|
93
104
|
}
|
|
94
105
|
if (!TURN_HARNESSES.includes(s.harness))
|
|
95
|
-
throw new Error(`harness ${s.harness} is not supported by this
|
|
106
|
+
throw new Error(`harness ${s.harness} is not supported by this b9s ${CLI_VERSION}`);
|
|
96
107
|
if (!s.dir) {
|
|
97
108
|
// A pool session: the daemon makes the checkout (clone once per machine, a worktree per agent).
|
|
98
109
|
const c = ensureCheckout(s, log, workdir);
|
|
@@ -121,7 +132,7 @@ export async function reconcile(m, log) {
|
|
|
121
132
|
}
|
|
122
133
|
const r = spawnSync(bin, startArgs(s, thread, writable), { cwd: s.dir, encoding: "utf8", timeout: 180_000 });
|
|
123
134
|
if (r.status !== 0)
|
|
124
|
-
throw new Error(`
|
|
135
|
+
throw new Error(`b9s start failed: ${errorText(r.stderr || r.stdout)}`);
|
|
125
136
|
const started = JSON.parse(r.stdout);
|
|
126
137
|
state.sessions[s.id] = { label, fingerprint: fp, thread: started.thread, key_checked_at: state.sessions[s.id]?.key_checked_at ?? Date.now() };
|
|
127
138
|
log(`${s.agent}: ${thread ? "adopted" : "started"} ${s.harness === "codex" ? "thread" : "session"} ${started.thread} in ${s.dir}`);
|
|
@@ -143,7 +154,7 @@ export async function reconcile(m, log) {
|
|
|
143
154
|
out.push({ id: s.id, state: "error", dir: s.dir, thread: th, watcher: w && serviceActive(w) ? "active" : "inactive", error: `its watcher keeps exiting: ${fault}` });
|
|
144
155
|
continue;
|
|
145
156
|
}
|
|
146
|
-
// The operator lifted a usage-limit pause: what
|
|
157
|
+
// The operator lifted a usage-limit pause: what b9s codex unpause does, here.
|
|
147
158
|
if (s.unpause_at && state.sessions[s.id].unpause_applied !== s.unpause_at) {
|
|
148
159
|
writeState(s.agent, { ...readState(s.agent), turn_unpaused_at: Date.parse(s.unpause_at) });
|
|
149
160
|
state.sessions[s.id].unpause_applied = s.unpause_at;
|
|
@@ -194,6 +205,9 @@ export async function reconcile(m, log) {
|
|
|
194
205
|
const declaration = projects.find((p) => p.id === projectId);
|
|
195
206
|
lastCapabilityProbe.set(projectId, { at: Date.now(), signature: JSON.stringify(declaration.capabilities) });
|
|
196
207
|
}
|
|
208
|
+
const warning = diskSpaceNotice(volumeSpace(homedir(), "home"), volumeSpace(workdir ?? join(homedir(), "bschat"), "workdir"));
|
|
209
|
+
if (warning !== undefined)
|
|
210
|
+
await client.call("PUT", "/machines/me/notices/disk", { text: warning });
|
|
197
211
|
return { sessions: out, report };
|
|
198
212
|
}
|
|
199
213
|
const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeout: 600_000 });
|
|
@@ -201,14 +215,14 @@ const git = (args, cwd) => spawnSync("git", args, { cwd, encoding: "utf8", timeo
|
|
|
201
215
|
* The checkout of a pool session: the project's repository cloned once per machine under
|
|
202
216
|
* ~/bschat/<project>/main (in the background, since ester's is 20 GB; "preparing" until it is done),
|
|
203
217
|
* then a worktree per agent beside it, detached at origin's default branch (units branch from their
|
|
204
|
-
* target with wu start). An identity file makes plain `
|
|
218
|
+
* target with wu start). An identity file makes plain `b9s` there the agent; `.b9s/` is ignored
|
|
205
219
|
* through the clone's info/exclude, so no tracked file changes.
|
|
206
220
|
*/
|
|
207
221
|
export function ensureCheckout(s, log, workdir = null) {
|
|
208
222
|
if (!s.project)
|
|
209
223
|
throw new Error("an automatic checkout needs a project agent");
|
|
210
224
|
if (!s.repo_url)
|
|
211
|
-
throw new Error(`project ${s.project} has no repository URL:
|
|
225
|
+
throw new Error(`project ${s.project} has no repository URL: b9s-admin project repo ${s.project} <git url>`);
|
|
212
226
|
if (workdir && !existsSync(workdir))
|
|
213
227
|
mkdirSync(workdir, { recursive: true });
|
|
214
228
|
const root = join(workdir ?? join(homedir(), "bschat"), s.project);
|
|
@@ -253,11 +267,12 @@ export function ensureCheckout(s, log, workdir = null) {
|
|
|
253
267
|
const common = (git(["rev-parse", "--path-format=absolute", "--git-common-dir"], base).stdout ?? "").trim();
|
|
254
268
|
const exclude = join(common, "info", "exclude");
|
|
255
269
|
const ex = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
|
|
256
|
-
|
|
270
|
+
const addExclude = [".b9s/", ".bschat/"].filter((entry) => !ex.split("\n").includes(entry));
|
|
271
|
+
if (addExclude.length) {
|
|
257
272
|
mkdirSync(dirname(exclude), { recursive: true });
|
|
258
|
-
writeFileSync(exclude, `${ex}${ex && !ex.endsWith("\n") ? "\n" : ""}.
|
|
273
|
+
writeFileSync(exclude, `${ex}${ex && !ex.endsWith("\n") ? "\n" : ""}${addExclude.join("\n")}\n`);
|
|
259
274
|
}
|
|
260
|
-
const id = join(dir, ".
|
|
275
|
+
const id = join(dir, ".b9s", "identity.json");
|
|
261
276
|
mkdirSync(dirname(id), { recursive: true });
|
|
262
277
|
writeFileSync(id, JSON.stringify({ agents: { [s.harness]: { name: s.agent_name, project: s.project, ...(s.model ? { model: s.model } : {}) } } }, null, 2) + "\n");
|
|
263
278
|
return { dir };
|
|
@@ -381,7 +396,7 @@ const CRASH_WINDOW_MS = 5 * 60_000;
|
|
|
381
396
|
export function watcherFault(ref, logText, nowMs = Date.now()) {
|
|
382
397
|
let text = logText;
|
|
383
398
|
if (text === undefined) {
|
|
384
|
-
const f = join(
|
|
399
|
+
const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
385
400
|
if (!existsSync(f))
|
|
386
401
|
return null;
|
|
387
402
|
const size = statSync(f).size;
|
|
@@ -394,7 +409,7 @@ export function watcherFault(ref, logText, nowMs = Date.now()) {
|
|
|
394
409
|
const lines = text.split("\n").filter((l) => l.trim());
|
|
395
410
|
const starts = [];
|
|
396
411
|
lines.forEach((l, i) => {
|
|
397
|
-
const m = /^(\d{4}-\d\d-\d\dT[\d:.]+Z)
|
|
412
|
+
const m = /^(\d{4}-\d\d-\d\dT[\d:.]+Z) b9s watch\[[^\]]+\]: watching\b/.exec(l);
|
|
398
413
|
if (m)
|
|
399
414
|
starts.push({ i, at: Date.parse(m[1]) });
|
|
400
415
|
});
|
|
@@ -420,10 +435,10 @@ export function watcherFault(ref, logText, nowMs = Date.now()) {
|
|
|
420
435
|
}
|
|
421
436
|
/** The watcher's latest turn line (started, finished, FAILED, STOPPED, paused), for the report. */
|
|
422
437
|
function lastTurnLine(ref) {
|
|
423
|
-
const f = join(
|
|
438
|
+
const f = join(configRoot(), "logs", `watch.${ref.replace("/", ".")}.err.log`);
|
|
424
439
|
if (!existsSync(f))
|
|
425
440
|
return null;
|
|
426
|
-
const lines = readFileSync(f, "utf8").split("\n").filter((l) => /
|
|
441
|
+
const lines = readFileSync(f, "utf8").split("\n").filter((l) => /b9s watch\[/.test(l) && /turn #|TURN #|usage limit|pause lifted/.test(l));
|
|
427
442
|
return lines.length ? lines[lines.length - 1].slice(0, 300) : null;
|
|
428
443
|
}
|
|
429
444
|
function freeBytes(path) {
|
|
@@ -435,6 +450,15 @@ function freeBytes(path) {
|
|
|
435
450
|
return null;
|
|
436
451
|
}
|
|
437
452
|
}
|
|
453
|
+
function volumeSpace(path, label) {
|
|
454
|
+
try {
|
|
455
|
+
const st = statfsSync(existsSync(path) ? path : dirname(path));
|
|
456
|
+
return { label, freeBytes: st.bavail * st.bsize, totalBytes: st.blocks * st.bsize };
|
|
457
|
+
}
|
|
458
|
+
catch {
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
438
462
|
/** Whether Codex's own sandbox runs here (`codex sandbox -- true`), with its error; checked at most every 10 min. */
|
|
439
463
|
let sandboxCache = null;
|
|
440
464
|
export function codexSandbox(force = false) {
|
|
@@ -485,7 +509,7 @@ export function machineFacts() {
|
|
|
485
509
|
bschat: { version: CLI_VERSION, bin: requireInstall().bin },
|
|
486
510
|
codex: codex.status === 0 ? { version: codex.stdout.trim(), logged_in: login?.status === 0 && /logged in/i.test(`${login.stdout}${login.stderr}`), login: `${login?.stdout ?? ""}${login?.stderr ?? ""}`.trim().slice(0, 200), sandbox: codexSandbox() } : null,
|
|
487
511
|
"claude-code": claudeReport(),
|
|
488
|
-
managed_hooks: existsSync(req) && readFileSync(req, "utf8")
|
|
512
|
+
managed_hooks: existsSync(req) && isCodexManagedRequirements(readFileSync(req, "utf8")),
|
|
489
513
|
linger: platform() === "linux" ? lingerEnabled() : null,
|
|
490
514
|
disk_free_bytes: diskFree,
|
|
491
515
|
at: new Date().toISOString(),
|
|
@@ -493,7 +517,7 @@ export function machineFacts() {
|
|
|
493
517
|
}
|
|
494
518
|
/**
|
|
495
519
|
* Provisioning steps that need this machine's own view, run by `machine add` over ssh: linger on
|
|
496
|
-
* Linux, Codex present and logged in, and
|
|
520
|
+
* Linux, Codex present and logged in, and b9s's hooks in Codex's administrator layer when sudo
|
|
497
521
|
* works without a password. Each step reports ok, done, skipped or failed; nothing is hidden.
|
|
498
522
|
*/
|
|
499
523
|
export function prepare(opts = {}) {
|
|
@@ -526,7 +550,7 @@ export function prepare(opts = {}) {
|
|
|
526
550
|
else if (!opts.codexUserns)
|
|
527
551
|
steps.push({ step: "codex sandbox", result: "failed", detail: `${sb.error}: this system restricts the user namespaces Codex's sandbox needs. Re-run machine add with --codex-userns to install a Codex-only AppArmor profile (${CODEX_APPARMOR_PATH}), or use danger-full-access pools here` });
|
|
528
552
|
else if (!sudo)
|
|
529
|
-
steps.push({ step: "codex sandbox", result: "failed", detail: `--codex-userns needs passwordless sudo; install ${CODEX_APPARMOR_PATH} by hand (
|
|
553
|
+
steps.push({ step: "codex sandbox", result: "failed", detail: `--codex-userns needs passwordless sudo; install ${CODEX_APPARMOR_PATH} by hand (b9s machine prepare --print-apparmor shows it) and run sudo apparmor_parser -r on it` });
|
|
530
554
|
else {
|
|
531
555
|
const t = spawnSync("sudo", ["-n", "tee", CODEX_APPARMOR_PATH], { input: codexAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
|
|
532
556
|
const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", CODEX_APPARMOR_PATH], { encoding: "utf8" }) : t;
|
|
@@ -549,7 +573,7 @@ export function prepare(opts = {}) {
|
|
|
549
573
|
else if (!opts.bwrapUserns)
|
|
550
574
|
steps.push({ step: "claude code sandbox", result: "failed", detail: `${sb.error}: this system restricts the user namespaces bubblewrap needs. Re-run machine add with --bwrap-userns to install an AppArmor profile for /usr/bin/bwrap (${BWRAP_APPARMOR_PATH}; any local user may then use bubblewrap's namespaces), or run only danger-full-access Claude Code agents here` });
|
|
551
575
|
else if (!sudo)
|
|
552
|
-
steps.push({ step: "claude code sandbox", result: "failed", detail: `--bwrap-userns needs passwordless sudo; install ${BWRAP_APPARMOR_PATH} by hand (
|
|
576
|
+
steps.push({ step: "claude code sandbox", result: "failed", detail: `--bwrap-userns needs passwordless sudo; install ${BWRAP_APPARMOR_PATH} by hand (b9s machine prepare --print-apparmor shows it) and run sudo apparmor_parser -r on it` });
|
|
553
577
|
else {
|
|
554
578
|
const t = spawnSync("sudo", ["-n", "tee", BWRAP_APPARMOR_PATH], { input: bwrapAppArmorProfile(), stdio: ["pipe", "ignore", "pipe"], encoding: "utf8" });
|
|
555
579
|
const l = t.status === 0 ? spawnSync("sudo", ["-n", "apparmor_parser", "-r", BWRAP_APPARMOR_PATH], { encoding: "utf8" }) : t;
|
|
@@ -562,14 +586,14 @@ export function prepare(opts = {}) {
|
|
|
562
586
|
const req = "/etc/codex/requirements.toml";
|
|
563
587
|
const { requirements, wrapper } = codexManagedHooks(requireInstall().bin);
|
|
564
588
|
const current = existsSync(req) ? readFileSync(req, "utf8") : null;
|
|
565
|
-
if (current !== null && !current
|
|
566
|
-
steps.push({ step: "codex hooks", result: "skipped", detail: `${req} exists and was not written by
|
|
589
|
+
if (current !== null && !isCodexManagedRequirements(current)) {
|
|
590
|
+
steps.push({ step: "codex hooks", result: "skipped", detail: `${req} exists and was not written by b9s; add b9s's hooks to it by hand (b9s machine prepare --print-hooks shows them) or trust ~/.codex/hooks.json in an interactive codex` });
|
|
567
591
|
}
|
|
568
|
-
else if (current === requirements && existsSync(`${CODEX_MANAGED_DIR}/
|
|
592
|
+
else if (current === requirements && existsSync(`${CODEX_MANAGED_DIR}/b9s`) && readFileSync(`${CODEX_MANAGED_DIR}/b9s`, "utf8") === wrapper) {
|
|
569
593
|
steps.push({ step: "codex hooks", result: "ok", detail: `managed by policy in ${req}` });
|
|
570
594
|
}
|
|
571
595
|
else if (!sudo) {
|
|
572
|
-
steps.push({ step: "codex hooks", result: "skipped", detail: `sudo needs a password here, so
|
|
596
|
+
steps.push({ step: "codex hooks", result: "skipped", detail: `sudo needs a password here, so b9s's hooks are not in ${req}; trust ~/.codex/hooks.json in an interactive codex instead` });
|
|
573
597
|
}
|
|
574
598
|
else {
|
|
575
599
|
const write = (path, text, mode) => {
|
|
@@ -584,9 +608,9 @@ export function prepare(opts = {}) {
|
|
|
584
608
|
const d = spawnSync("sudo", ["-n", "mkdir", "-p", CODEX_MANAGED_DIR], { encoding: "utf8" });
|
|
585
609
|
if (d.status !== 0)
|
|
586
610
|
throw new Error(`sudo mkdir ${CODEX_MANAGED_DIR}: ${(d.stderr ?? "").trim()}`);
|
|
587
|
-
write(`${CODEX_MANAGED_DIR}/
|
|
611
|
+
write(`${CODEX_MANAGED_DIR}/b9s`, wrapper, "755");
|
|
588
612
|
write(req, requirements, "644");
|
|
589
|
-
steps.push({ step: "codex hooks", result: "done", detail: `
|
|
613
|
+
steps.push({ step: "codex hooks", result: "done", detail: `b9s's hooks are in ${req}, trusted by policy` });
|
|
590
614
|
}
|
|
591
615
|
catch (e) {
|
|
592
616
|
steps.push({ step: "codex hooks", result: "failed", detail: e.message });
|
|
@@ -608,10 +632,10 @@ export async function machine(p, out) {
|
|
|
608
632
|
loadMachine();
|
|
609
633
|
const bin = requireInstall().bin;
|
|
610
634
|
const path = installService(MACHINE_LABEL, [bin, "machine", "run"], homedir(), { PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", HOME: homedir() }, "machine");
|
|
611
|
-
return out.print(`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run. Logs: ~/.
|
|
635
|
+
return out.print(`Wrote ${path} and (re)started it: the machine daemon runs ${bin} machine run. Logs: ~/.b9s/logs/machine.*.log`, { path, label: MACHINE_LABEL });
|
|
612
636
|
}
|
|
613
637
|
const m = loadMachine();
|
|
614
|
-
const log = (s) => process.stderr.write(`${new Date().toISOString()}
|
|
638
|
+
const log = (s) => process.stderr.write(`${new Date().toISOString()} b9s machine[${m.name}]: ${s}\n`);
|
|
615
639
|
if (sub === "status") {
|
|
616
640
|
const desired = (await Client.raw(m.url, m.key).call("GET", "/machines/me")).sessions;
|
|
617
641
|
const state = readMachineState();
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { str, bool } from "../args.js";
|
|
5
|
+
import { Client } from "../client.js";
|
|
6
|
+
import { loadAgent, resolveAgentName } from "../config.js";
|
|
7
|
+
import { CliError } from "../errors.js";
|
|
8
|
+
import { branchAndHead } from "../git.js";
|
|
9
|
+
import { table } from "../output.js";
|
|
10
|
+
import { projectOf } from "./agent.js";
|
|
11
|
+
export async function measures(p, out) {
|
|
12
|
+
const { client, project } = measureClient(p);
|
|
13
|
+
const r = await client.call("GET", `/projects/${project}/measures`);
|
|
14
|
+
const rows = await Promise.all(r.measures.map(async (m) => {
|
|
15
|
+
const values = await client.call("GET", `/projects/${project}/measures/${m.id}/values?limit=1`);
|
|
16
|
+
const latest = values.values[0];
|
|
17
|
+
const runs = await client.call("GET", `/projects/${project}/measures/${m.id}/runs`);
|
|
18
|
+
const pendingRuns = runs.runs.filter((x) => x.state !== "complete");
|
|
19
|
+
const merges = pendingRuns.reduce((n, x) => n + x.merge_count, 0);
|
|
20
|
+
const missing = [...new Set(pendingRuns.flatMap((x) => x.dispatch_reasons ?? []).filter((reason) => reason.includes("missing capabilities")))];
|
|
21
|
+
return { name: m.name, version: m.version, latest: latest?.record.value ?? (pendingRuns.length ? `unknown (waiting for a capable runner${missing.length ? `; ${missing.join("; ")}` : ""})` : "unknown"), sha: latest?.record.tested_sha ?? "—", freshness: latest?.created_at ?? "never", merges_since: merges };
|
|
22
|
+
}));
|
|
23
|
+
out.print(table(rows, ["name", "version", "latest", "sha", "freshness", "merges_since"]), { measures: rows });
|
|
24
|
+
}
|
|
25
|
+
export async function measure(p, out) {
|
|
26
|
+
const sub = p.positionals[1], name = p.positionals[2];
|
|
27
|
+
if (!name)
|
|
28
|
+
throw new CliError("usage", "measure <show|run|post|check> <name> ...");
|
|
29
|
+
const { client, project, creds } = measureClient(p);
|
|
30
|
+
const { measures: all } = await client.call("GET", `/projects/${project}/measures`);
|
|
31
|
+
const def = all.find((m) => m.name === name);
|
|
32
|
+
if (!def)
|
|
33
|
+
throw new CliError("not_found", `measure ${name} not found`);
|
|
34
|
+
if (sub === "check") {
|
|
35
|
+
if (!creds.machine.trim())
|
|
36
|
+
throw new CliError("no_machine", "measure check needs this agent's machine identity to verify capabilities and record provenance");
|
|
37
|
+
const before = branchAndHead();
|
|
38
|
+
if (!before.branch || !before.head)
|
|
39
|
+
throw new CliError("not_a_repo", "measure check must run inside the unit's branch worktree");
|
|
40
|
+
const root = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8" });
|
|
41
|
+
if (root.status !== 0 || !root.stdout.trim())
|
|
42
|
+
throw new CliError("not_a_repo", "measure check must run inside the unit's branch worktree");
|
|
43
|
+
const started = new Date().toISOString();
|
|
44
|
+
const rootPath = realpathSync(root.stdout.trim());
|
|
45
|
+
const { units } = await client.call("GET", `/projects/${project}/work-units?all=1`);
|
|
46
|
+
if (!Array.isArray(units))
|
|
47
|
+
throw new CliError("bad_response", "could not identify the current work unit target");
|
|
48
|
+
const closedStatuses = new Set(["done", "abandoned", "superseded"]);
|
|
49
|
+
const matchingUnits = units.filter((unit) => {
|
|
50
|
+
if (closedStatuses.has(unit.status) || unit.branch !== before.branch || typeof unit.worktree !== "string" || !existsSync(unit.worktree))
|
|
51
|
+
return false;
|
|
52
|
+
try {
|
|
53
|
+
return realpathSync(unit.worktree) === rootPath;
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
if (matchingUnits.length === 0)
|
|
60
|
+
throw new CliError("work_unit_not_found", "measure check requires an active work unit matching this branch and worktree");
|
|
61
|
+
if (matchingUnits.length > 1)
|
|
62
|
+
throw new CliError("ambiguous_work_unit", `multiple active work units match branch ${before.branch} and this worktree: ${matchingUnits.map((unit) => `#${unit.number}`).join(", ")}`);
|
|
63
|
+
const currentUnit = matchingUnits[0];
|
|
64
|
+
const targetOverride = typeof currentUnit?.target === "string" ? currentUnit.target : null;
|
|
65
|
+
const targetQuery = targetOverride ? `&target=${encodeURIComponent(targetOverride)}` : "";
|
|
66
|
+
const readiness = await client.call("GET", `/projects/${project}/measures/${def.id}/branch-check?machine=${encodeURIComponent(creds.machine)}${targetQuery}`);
|
|
67
|
+
if (!readiness.can_run)
|
|
68
|
+
throw new CliError("missing_capability", readiness.reason ?? `this machine cannot run measure ${name}`);
|
|
69
|
+
const selected = readiness.measure?.definition;
|
|
70
|
+
if (!selected || selected.producer?.type !== "command")
|
|
71
|
+
throw new CliError("bad_response", `measure ${name} has no command producer`);
|
|
72
|
+
const dirtyBefore = gitWorkingTreeStatus(root.stdout.trim());
|
|
73
|
+
if (dirtyBefore !== "")
|
|
74
|
+
throw new CliError("dirty_worktree", "measure check requires a clean working tree so producer inputs match HEAD; commit or stash changes and retry");
|
|
75
|
+
const definitionVersion = readiness.measure.version;
|
|
76
|
+
if (!Number.isInteger(definitionVersion) || definitionVersion < 1)
|
|
77
|
+
throw new CliError("bad_response", `measure ${name} has no valid definition version`);
|
|
78
|
+
const result = spawnSync(selected.producer.command, { cwd: root.stdout.trim(), encoding: "utf8", shell: true, timeout: 15 * 60_000, maxBuffer: 2 * 1024 * 1024 });
|
|
79
|
+
if (result.error)
|
|
80
|
+
throw new CliError("measure_failed", `producer for ${name} failed: ${result.error.message}`);
|
|
81
|
+
if (result.status !== 0)
|
|
82
|
+
throw new CliError("measure_failed", `producer for ${name} exited ${result.status}: ${(result.stderr ?? "").trim().slice(0, 500)}`);
|
|
83
|
+
const after = branchAndHead();
|
|
84
|
+
if (after.branch !== before.branch || after.head !== before.head)
|
|
85
|
+
throw new CliError("head_changed", `the producer changed HEAD from ${before.head} to ${after.head ?? "unknown"}; no branch value was recorded`);
|
|
86
|
+
if (gitWorkingTreeStatus(root.stdout.trim()) !== "")
|
|
87
|
+
throw new CliError("worktree_changed", "producer changed the working tree during this check; no branch value was recorded");
|
|
88
|
+
const parsed = parseProducerOutput(result.stdout ?? "", selected.kind);
|
|
89
|
+
const ended = new Date().toISOString();
|
|
90
|
+
const evidenceBody = `Measure: ${name}\nDefinition version: ${definitionVersion}\nProducer version: ${selected.producer.version}\nCommand: ${selected.producer.command}\nBranch: ${before.branch}\nCommit: ${before.head}\nExit code: ${result.status}\n\nstdout:\n${result.stdout ?? ""}\nstderr:\n${result.stderr ?? ""}`;
|
|
91
|
+
const evidenceRef = await postBranchEvidence(client, creds.url, project, name, evidenceBody, selected.producer.version);
|
|
92
|
+
const branchValue = await client.call("POST", `/projects/${project}/measures/${def.id}/branch-values`, {
|
|
93
|
+
branch: before.branch,
|
|
94
|
+
tested_sha: before.head,
|
|
95
|
+
target_branch: readiness.target_branch,
|
|
96
|
+
value: parsed.value,
|
|
97
|
+
guard_results: parsed.guardResults,
|
|
98
|
+
unit: selected.unit,
|
|
99
|
+
evidence_ids: [evidenceRef.replace(/^evidence:/, "")],
|
|
100
|
+
machine: creds.machine,
|
|
101
|
+
started_at: started,
|
|
102
|
+
ended_at: ended,
|
|
103
|
+
definition_version: definitionVersion,
|
|
104
|
+
producer_version: selected.producer.version,
|
|
105
|
+
run_id: randomUUID(),
|
|
106
|
+
});
|
|
107
|
+
const stored = branchValue.branch_value;
|
|
108
|
+
const baseline = readiness.baseline ? `vs target ${readiness.baseline.value} ${readiness.baseline.unit} at ${readiness.baseline.tested_sha}` : "no good target baseline";
|
|
109
|
+
const effect = stored.effect?.status ?? "unknown";
|
|
110
|
+
out.print(`measured ${name}: ${parsed.value} ${selected.unit}; ${baseline}; effect ${effect}${stored.effect?.reasons?.length ? ` (${stored.effect.reasons.join(", ")})` : ""}\nevidence ${evidenceRef}`, { branch_value: stored, baseline: readiness.baseline, effect: stored.effect, evidence: evidenceRef });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
if (sub === "show") {
|
|
114
|
+
const [detail, values, runs] = await Promise.all([client.call("GET", `/projects/${project}/measures/${def.id}`), client.call("GET", `/projects/${project}/measures/${def.id}/values`), client.call("GET", `/projects/${project}/measures/${def.id}/runs`)]);
|
|
115
|
+
out.print(JSON.stringify({ measure: detail.measure, history: detail.history, values: values.values, runs: runs.runs }, null, 2), { measure: detail.measure, history: detail.history, values: values.values, runs: runs.runs });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (sub === "run") {
|
|
119
|
+
const sha = str(p.flags, "sha");
|
|
120
|
+
const process = await client.call("GET", `/projects/${project}/process`);
|
|
121
|
+
const target = str(p.flags, "target") ?? process.process.definition.merge.target_branch;
|
|
122
|
+
if (!sha)
|
|
123
|
+
throw new CliError("usage", "measure run <name> --sha <commit> [--target branch] [--rerun]");
|
|
124
|
+
const result = await client.call("POST", `/projects/${project}/measures/${def.id}/runs`, { tested_sha: sha, target_branch: target, rerun: bool(p.flags, "rerun") });
|
|
125
|
+
out.print(result.run ? `queued ${name} as WU #${result.run.unit_number}` : result.queued ? `already queued ${name} as WU #${result.unit_number}` : `reusing value ${result.value_id}`, result);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (sub === "post") {
|
|
129
|
+
const sha = str(p.flags, "sha"), raw = str(p.flags, "value"), evidence = str(p.flags, "evidence");
|
|
130
|
+
if (!sha || raw === undefined || !evidence)
|
|
131
|
+
throw new CliError("usage", "measure post <name> --sha <commit> --value <v> --evidence <id> [--target branch]");
|
|
132
|
+
const [detail, runs, processInfo] = await Promise.all([client.call("GET", `/projects/${project}/measures/${def.id}`), client.call("GET", `/projects/${project}/measures/${def.id}/runs`), client.call("GET", `/projects/${project}/process`)]);
|
|
133
|
+
const target = str(p.flags, "target") ?? processInfo.process.definition.merge.target_branch;
|
|
134
|
+
const activeRun = runs.runs.find((x) => x.target_branch === target && x.tested_sha === sha && x.state !== "complete");
|
|
135
|
+
const version = activeRun?.definition_version ?? def.version;
|
|
136
|
+
const selected = version === def.version ? def.definition : detail.history.find((x) => x.version === version)?.definition;
|
|
137
|
+
if (!selected)
|
|
138
|
+
throw new CliError("bad_response", `definition version ${version} for ${name} is unavailable`);
|
|
139
|
+
const value = selected.kind === "number" ? Number(raw) : raw;
|
|
140
|
+
if (typeof value === "number" && !Number.isFinite(value))
|
|
141
|
+
throw new CliError("usage", "--value must be numeric for this measure");
|
|
142
|
+
const started = new Date().toISOString();
|
|
143
|
+
const result = await client.call("POST", `/projects/${project}/measures/${def.id}/values`, { target_branch: target, tested_sha: sha, value, unit: selected.unit, evidence_ids: evidence.split(",").map((x) => x.trim()), machine: creds.machine, started_at: started, ended_at: new Date().toISOString(), definition_version: version, producer_version: selected.producer.type === "command" ? selected.producer.version : undefined });
|
|
144
|
+
out.print(`posted ${name} at ${sha}`, result);
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
throw new CliError("usage", "measure <show|run|post|check> <name> ...");
|
|
148
|
+
}
|
|
149
|
+
function gitWorkingTreeStatus(cwd) {
|
|
150
|
+
const result = spawnSync("git", ["status", "--porcelain", "--untracked-files=all"], { cwd, encoding: "utf8" });
|
|
151
|
+
if (result.error || result.status !== 0)
|
|
152
|
+
throw new CliError("git_failed", `could not verify working tree state: ${result.error?.message ?? result.stderr?.trim() ?? "git status failed"}`);
|
|
153
|
+
return result.stdout ?? "";
|
|
154
|
+
}
|
|
155
|
+
export function parseProducerOutput(stdout, kind) {
|
|
156
|
+
const text = stdout.trim();
|
|
157
|
+
if (!text)
|
|
158
|
+
throw new CliError("bad_measure_output", "producer printed no value; print one numeric scalar or pass/fail (or JSON with value and guard_results)");
|
|
159
|
+
let decoded = text;
|
|
160
|
+
try {
|
|
161
|
+
decoded = JSON.parse(text);
|
|
162
|
+
}
|
|
163
|
+
catch { /* plain scalar output */ }
|
|
164
|
+
const structured = decoded && typeof decoded === "object" && !Array.isArray(decoded) ? decoded : null;
|
|
165
|
+
const rawValue = structured ? structured.value : decoded;
|
|
166
|
+
const guardResults = structured?.guard_results ?? {};
|
|
167
|
+
if (!guardResults || typeof guardResults !== "object" || Array.isArray(guardResults))
|
|
168
|
+
throw new CliError("bad_measure_output", "guard_results in producer JSON must be an object");
|
|
169
|
+
if (kind === "number") {
|
|
170
|
+
const value = typeof rawValue === "number" ? rawValue : typeof rawValue === "string" && rawValue.trim() !== "" ? Number(rawValue) : Number.NaN;
|
|
171
|
+
if (!Number.isFinite(value))
|
|
172
|
+
throw new CliError("bad_measure_output", "numeric producer must print one finite number or JSON with a numeric value field");
|
|
173
|
+
return { value, guardResults: guardResults };
|
|
174
|
+
}
|
|
175
|
+
if (rawValue !== "pass" && rawValue !== "fail")
|
|
176
|
+
throw new CliError("bad_measure_output", "pass/fail producer must print pass or fail, or JSON with a pass/fail value field");
|
|
177
|
+
return { value: rawValue, guardResults: guardResults };
|
|
178
|
+
}
|
|
179
|
+
async function postBranchEvidence(client, url, project, name, text, version) {
|
|
180
|
+
const bytes = Buffer.from(text, "utf8"), sha = createHash("sha256").update(bytes).digest("hex");
|
|
181
|
+
const headers = { ...client.headers(), "content-type": "text/plain; charset=utf-8", "x-bschat-sha256": sha, "x-bschat-filename": `${name}-branch-check.txt`, "x-bschat-kind": "test", "x-bschat-label": `branch check ${name} producer ${version}` };
|
|
182
|
+
const response = await fetch(`${url}/projects/${project}/evidence`, { method: "POST", headers, body: new Uint8Array(bytes) });
|
|
183
|
+
const json = await response.json();
|
|
184
|
+
if (!response.ok)
|
|
185
|
+
throw new CliError(json.error ?? `http_${response.status}`, json.message ?? "could not post measure check evidence");
|
|
186
|
+
return json.ref;
|
|
187
|
+
}
|
|
188
|
+
function measureClient(p) {
|
|
189
|
+
const creds = loadAgent(resolveAgentName(str(p.flags, "as")));
|
|
190
|
+
return { client: Client.forAgent(creds, undefined), project: projectOf(p, creds), creds };
|
|
191
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { str } from "../args.js";
|
|
2
|
+
import { Client } from "../client.js";
|
|
3
|
+
import { loadAdmin, loadAgent, resolveAdminName, resolveAgentName } from "../config.js";
|
|
4
|
+
import { CliError } from "../errors.js";
|
|
5
|
+
import { table } from "../output.js";
|
|
6
|
+
const noticeTable = (notices) => table(notices.map((n) => ({ id: n.id, scope: n.scope, scope_name: n.scope_name, expires_at: n.expires_at ?? "never", command_pattern: n.command_pattern ?? "-", text: n.text })), ["id", "scope", "scope_name", "expires_at", "command_pattern", "text"]);
|
|
7
|
+
/** Agents can add project-scoped notices only when they hold an assigner role. */
|
|
8
|
+
export async function agentNotice(p, out) {
|
|
9
|
+
const action = p.positionals[1];
|
|
10
|
+
if (action !== "add")
|
|
11
|
+
throw new CliError("usage", 'notice add --project <project> "<text>" [--until <time>] [--command-pattern <regex>]');
|
|
12
|
+
const project = str(p.flags, "project");
|
|
13
|
+
const text = p.positionals.slice(2).join(" ").trim();
|
|
14
|
+
if (!project || !text)
|
|
15
|
+
throw new CliError("usage", 'notice add --project <project> "<text>" [--until <time>] [--command-pattern <regex>]');
|
|
16
|
+
const name = resolveAgentName(str(p.flags, "as"));
|
|
17
|
+
const c = Client.forAgent(loadAgent(name), undefined);
|
|
18
|
+
const r = await c.call("POST", `/projects/${project}/notices`, {
|
|
19
|
+
text,
|
|
20
|
+
...(str(p.flags, "until") !== undefined ? { until: str(p.flags, "until") } : {}),
|
|
21
|
+
...(str(p.flags, "command-pattern") !== undefined ? { command_pattern: str(p.flags, "command-pattern") } : {}),
|
|
22
|
+
});
|
|
23
|
+
out.print(`Added project notice ${r.notice.id} to ${project}.`, r);
|
|
24
|
+
}
|
|
25
|
+
/** Operator-only machine/project notice management. */
|
|
26
|
+
export async function adminNotice(action, rest, p, out) {
|
|
27
|
+
const c = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
28
|
+
if (action === "list") {
|
|
29
|
+
const r = await c.call("GET", "/notices");
|
|
30
|
+
out.print(r.notices.length ? noticeTable(r.notices) : "(no notices)", r);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (action === "remove" && rest[0]) {
|
|
34
|
+
const r = await c.call("DELETE", `/notices/${rest[0]}`);
|
|
35
|
+
out.print(`Removed notice ${rest[0]}.`, r);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (action === "add") {
|
|
39
|
+
const machine = str(p.flags, "machine");
|
|
40
|
+
const project = str(p.flags, "project");
|
|
41
|
+
const text = rest.join(" ").trim();
|
|
42
|
+
if (!!machine === !!project || !text)
|
|
43
|
+
throw new CliError("usage", 'notice add --machine <machine> | --project <project> "<text>" [--until <time>] [--command-pattern <regex>]');
|
|
44
|
+
const r = await c.call("POST", "/notices", {
|
|
45
|
+
...(machine ? { machine } : { project }), text,
|
|
46
|
+
...(str(p.flags, "until") !== undefined ? { until: str(p.flags, "until") } : {}),
|
|
47
|
+
...(str(p.flags, "command-pattern") !== undefined ? { command_pattern: str(p.flags, "command-pattern") } : {}),
|
|
48
|
+
});
|
|
49
|
+
out.print(`Added ${r.notice.scope} notice ${r.notice.id} to ${r.notice.scope_name}.`, r);
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
throw new CliError("usage", 'notice add --machine <machine> | --project <project> "<text>" [--until <time>] [--command-pattern <regex>] | list | remove <id>');
|
|
53
|
+
}
|