benignswarm 0.12.96 → 0.12.98

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.
Files changed (41) hide show
  1. package/dist/admin-index.js +0 -0
  2. package/dist/args.js +40 -3
  3. package/dist/brief.js +5 -1
  4. package/dist/client.js +248 -0
  5. package/dist/commands/admin.js +84 -22
  6. package/dist/commands/agent.js +15 -2
  7. package/dist/commands/cloud-admin.js +56 -3
  8. package/dist/commands/codex-start.js +340 -241
  9. package/dist/commands/environment-admin.js +130 -0
  10. package/dist/commands/environment.js +53 -0
  11. package/dist/commands/evidence.js +6 -3
  12. package/dist/commands/feedback.js +12 -1
  13. package/dist/commands/flow.js +153 -0
  14. package/dist/commands/hook.js +29 -9
  15. package/dist/commands/image-admin.js +77 -0
  16. package/dist/commands/install.js +81 -3
  17. package/dist/commands/lists.js +4 -0
  18. package/dist/commands/machine-admin.js +444 -111
  19. package/dist/commands/machine-resize.js +234 -0
  20. package/dist/commands/machine.js +960 -41
  21. package/dist/commands/operator.js +5 -8
  22. package/dist/commands/retire.js +4 -0
  23. package/dist/commands/templates.js +27 -0
  24. package/dist/commands/turn.js +21 -0
  25. package/dist/commands/watch.js +256 -21
  26. package/dist/commands/wu.js +131 -81
  27. package/dist/container.js +480 -0
  28. package/dist/environment-checks.js +79 -0
  29. package/dist/git.js +28 -0
  30. package/dist/help.js +94 -37
  31. package/dist/index.js +7 -1
  32. package/dist/install.js +43 -1
  33. package/dist/macos-readiness.js +173 -0
  34. package/dist/output.js +17 -4
  35. package/dist/templates.js +218 -0
  36. package/dist/test-workers.js +17 -0
  37. package/dist/turn-guard.js +5 -5
  38. package/dist/turn.js +6 -0
  39. package/dist/usage.js +117 -0
  40. package/dist/version.js +1 -1
  41. package/package.json +1 -1
@@ -0,0 +1,130 @@
1
+ import { bool, repeated, str } from "../args.js";
2
+ import { CliError } from "../errors.js";
3
+ import { table } from "../output.js";
4
+ function splitCsvFlag(p, name) {
5
+ const raw = str(p.flags, name);
6
+ if (raw === undefined)
7
+ return undefined;
8
+ const values = (repeated(p, name).length ? repeated(p, name) : [raw])
9
+ .flatMap((entry) => entry.split(","))
10
+ .map((entry) => entry.trim())
11
+ .filter(Boolean);
12
+ return [...new Set(values)];
13
+ }
14
+ function intFlag(p, name) {
15
+ const raw = str(p.flags, name);
16
+ if (raw === undefined)
17
+ return undefined;
18
+ const n = Number(raw);
19
+ if (!Number.isInteger(n))
20
+ throw new CliError("usage", `--${name} must be an integer`);
21
+ return n;
22
+ }
23
+ function parseBoolChoice(value, flag) {
24
+ if (value === undefined)
25
+ return undefined;
26
+ const v = value.trim().toLowerCase();
27
+ if (v === "on" || v === "true" || v === "yes")
28
+ return true;
29
+ if (v === "off" || v === "false" || v === "no")
30
+ return false;
31
+ throw new CliError("usage", `--${flag} must be on|off (or true|false)`);
32
+ }
33
+ async function resolveProjectIds(c, refs) {
34
+ if (!refs.length)
35
+ return [];
36
+ const res = await c.call("GET", "/projects");
37
+ const byName = new Map((res.projects ?? []).map((p) => [p.name, p.id]));
38
+ return refs.map((r) => byName.get(r) ?? r);
39
+ }
40
+ async function resolveMachineIds(c, refs) {
41
+ if (!refs.length)
42
+ return [];
43
+ const res = await c.call("GET", "/machines");
44
+ const byName = new Map((res.machines ?? []).map((m) => [m.id, m.id]));
45
+ for (const m of res.machines ?? [])
46
+ byName.set(m.name, m.id);
47
+ return refs.map((r) => byName.get(r) ?? r);
48
+ }
49
+ function formatSettings(s) {
50
+ const lines = [
51
+ `Environment stage: ${s.stage}`,
52
+ `Staged scope: ${s.enabled_project_ids.length} project(s) [${s.enabled_project_ids.join(", ") || "none"}], ${s.enabled_machine_ids.length} machine(s) [${s.enabled_machine_ids.join(", ") || "none"}]`,
53
+ `Retention: resolved ${s.resolved_retention_days}d, wont_fix ${s.wont_fix_retention_days}d (last prune: ${s.last_retention_at ? `${s.last_retention_at}, deleted ${s.last_retention_deleted}` : "never"})`,
54
+ `Alerts: ${s.alerts_enabled ? "enabled" : "disabled"} (cooldown ${s.alert_cooldown_minutes}m)`,
55
+ ];
56
+ return lines.join("\n");
57
+ }
58
+ const USAGE = "b9s-admin environment settings show | settings set [--stage disabled|report_only|staged|enabled] [--projects a,b] [--machines m1,m2] [--resolved-retention-days n] [--wont-fix-retention-days n] [--alerts on|off] [--alert-cooldown-minutes n] | retention run [--dry-run] | alerts [list|evaluate]";
59
+ export async function environmentAdmin(c, action, rest, p, out) {
60
+ if (action === "settings") {
61
+ const sub = rest[0] ?? "show";
62
+ if (sub === "show" && rest.length <= 1) {
63
+ const r = await c.call("GET", "/account/environment/settings");
64
+ out.print(formatSettings(r.settings), r);
65
+ return;
66
+ }
67
+ if (sub === "set" && rest.length === 1) {
68
+ const body = {};
69
+ const stage = str(p.flags, "stage");
70
+ if (stage !== undefined)
71
+ body.stage = stage;
72
+ const projects = splitCsvFlag(p, "projects");
73
+ if (projects !== undefined)
74
+ body.enabled_project_ids = await resolveProjectIds(c, projects);
75
+ const machines = splitCsvFlag(p, "machines");
76
+ if (machines !== undefined)
77
+ body.enabled_machine_ids = await resolveMachineIds(c, machines);
78
+ const resolvedDays = intFlag(p, "resolved-retention-days");
79
+ if (resolvedDays !== undefined)
80
+ body.resolved_retention_days = resolvedDays;
81
+ const wontFixDays = intFlag(p, "wont-fix-retention-days");
82
+ if (wontFixDays !== undefined)
83
+ body.wont_fix_retention_days = wontFixDays;
84
+ const alertsEnabled = parseBoolChoice(str(p.flags, "alerts"), "alerts");
85
+ if (alertsEnabled !== undefined)
86
+ body.alerts_enabled = alertsEnabled;
87
+ const cooldown = intFlag(p, "alert-cooldown-minutes");
88
+ if (cooldown !== undefined)
89
+ body.alert_cooldown_minutes = cooldown;
90
+ if (!Object.keys(body).length)
91
+ throw new CliError("usage", USAGE);
92
+ const r = await c.call("PATCH", "/account/environment/settings", body);
93
+ out.print(formatSettings(r.settings), r);
94
+ return;
95
+ }
96
+ throw new CliError("usage", USAGE);
97
+ }
98
+ if (action === "retention" && rest[0] === "run" && rest.length === 1) {
99
+ const dryRun = bool(p.flags, "dry-run");
100
+ const r = await c.call("POST", "/account/environment/retention/run", { dry_run: dryRun });
101
+ const res = r.result;
102
+ out.print(`${res.dry_run ? "Retention dry run" : "Retention prune"} (${res.ran_at}): ${res.candidates_resolved} resolved + ${res.candidates_wont_fix} wont_fix candidate(s); deleted ${res.deleted_issues}.`, r);
103
+ return;
104
+ }
105
+ if (action === "alerts") {
106
+ const sub = rest[0] ?? "list";
107
+ if (sub === "list" && rest.length <= 1) {
108
+ const r = await c.call("GET", "/account/environment/alerts");
109
+ const rows = (r.alerts ?? []).map((a) => ({
110
+ issue: a.issue_title,
111
+ scope: a.issue_scope,
112
+ kind: a.alert_kind,
113
+ last_alerted: a.last_alerted_at,
114
+ sent: a.alert_count,
115
+ suppressed: a.suppressed_count,
116
+ error: a.last_error ?? "",
117
+ }));
118
+ out.print(rows.length ? table(rows, ["issue", "scope", "kind", "last_alerted", "sent", "suppressed", "error"]) : "No environment alerts recorded.", r);
119
+ return;
120
+ }
121
+ if (sub === "evaluate" && rest.length === 1) {
122
+ const r = await c.call("POST", "/account/environment/alerts/evaluate", {});
123
+ const res = r.result;
124
+ out.print(`Evaluated ${res.evaluated} alertable issue(s): ${res.sent} sent, ${res.suppressed} suppressed by cooldown, ${res.failed} failed${res.skipped_reason ? ` (skipped: ${res.skipped_reason})` : ""}.`, r);
125
+ return;
126
+ }
127
+ throw new CliError("usage", USAGE);
128
+ }
129
+ throw new CliError("usage", USAGE);
130
+ }
@@ -0,0 +1,53 @@
1
+ import { repeated, str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAgent, resolveAgentName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ const values = (parsed, key) => {
6
+ const repeatedValues = repeated(parsed, key);
7
+ const raw = repeatedValues.length ? repeatedValues : str(parsed.flags, key) ? [str(parsed.flags, key)] : [];
8
+ return [...new Set(raw.flatMap((value) => value.split(",").map((item) => item.trim()).filter(Boolean)))];
9
+ };
10
+ /** Submit a bounded observation to the project or machine Environment issue list. */
11
+ export async function environment(p, out) {
12
+ if (p.positionals[1] !== "report") {
13
+ throw new CliError("usage", "environment report --project <project> | --machine <machine> --title <title> --category <category> --component <component> --description <what failed> [--normalized-key <key>] [--evidence <id,...>] [--units <id,...]");
14
+ }
15
+ const project = str(p.flags, "project");
16
+ const machine = str(p.flags, "machine");
17
+ const title = str(p.flags, "title");
18
+ const category = str(p.flags, "category");
19
+ const component = str(p.flags, "component");
20
+ const description = str(p.flags, "description");
21
+ const normalizedKey = str(p.flags, "normalized-key");
22
+ const evidenceIds = values(p, "evidence");
23
+ const blockedUnits = values(p, "units");
24
+ if (!!project === !!machine || !title || !category || !component || !description) {
25
+ throw new CliError("usage", "environment report needs exactly one of --project or --machine, plus --title, --category, --component and --description");
26
+ }
27
+ if (title.trim().length < 3 || title.length > 160)
28
+ throw new CliError("usage", "--title must be 3..160 characters");
29
+ if (!/^[a-z0-9][a-z0-9_-]{1,31}$/.test(category))
30
+ throw new CliError("usage", "--category must be 2..32 lowercase letters, digits, hyphens or underscores");
31
+ if (component.trim().length < 2 || component.length > 120)
32
+ throw new CliError("usage", "--component must be 2..120 characters");
33
+ if (!description.trim() || description.length > 2000)
34
+ throw new CliError("usage", "--description must be 1..2000 characters");
35
+ if (normalizedKey !== undefined && (!normalizedKey.trim() || normalizedKey.length > 160))
36
+ throw new CliError("usage", "--normalized-key must be 1..160 characters");
37
+ for (const [label, ids] of [["--evidence", evidenceIds], ["--units", blockedUnits]]) {
38
+ if (ids.length > 20 || ids.some((id) => id.length > 100))
39
+ throw new CliError("usage", `${label} accepts at most 20 IDs of at most 100 characters each`);
40
+ }
41
+ const agent = resolveAgentName(str(p.flags, "as"));
42
+ const client = Client.forAgent(loadAgent(agent), undefined);
43
+ const path = project
44
+ ? `/projects/${encodeURIComponent(project)}/environment/issues`
45
+ : `/machines/${encodeURIComponent(machine)}/environment/issues`;
46
+ const result = await client.call("POST", path, {
47
+ title: title.trim(), category, component: component.trim(), description: description.trim(),
48
+ ...(normalizedKey !== undefined ? { normalized_key: normalizedKey.trim() } : {}),
49
+ ...(evidenceIds.length ? { evidence_ids: evidenceIds } : {}),
50
+ ...(blockedUnits.length ? { blocked_units: blockedUnits } : {}),
51
+ });
52
+ out.print(`Reported ${result.issue.scope} environment problem ${result.issue.id}${result.deduplicated ? " (added to existing issue)" : ""}.`, result);
53
+ }
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { readFileSync, writeFileSync } from "node:fs";
3
3
  import { basename, extname } from "node:path";
4
4
  import { str } from "../args.js";
5
- import { Client } from "../client.js";
5
+ import { Client, verifyTextReceipts } from "../client.js";
6
6
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
7
7
  import { projectOf } from "./agent.js";
8
8
  import { CliError } from "../errors.js";
@@ -55,13 +55,15 @@ export async function evidence(p, out) {
55
55
  const filename = str(p.flags, "name") ?? basename(file);
56
56
  const contentType = str(p.flags, "type") ?? guessType(filename);
57
57
  const headers = { ...client.headers(), "content-type": contentType, "x-bschat-sha256": sha, "x-bschat-filename": filename };
58
- const label = str(p.flags, "label");
58
+ // Fetch normalizes leading/trailing whitespace in HTTP header values; model those exact
59
+ // transmitted bytes here so the receipt verifies what the server actually received.
60
+ const label = str(p.flags, "label")?.trim();
59
61
  if (label)
60
62
  headers["x-bschat-label"] = label;
61
63
  const kind = str(p.flags, "kind");
62
64
  if (kind)
63
65
  headers["x-bschat-kind"] = kind;
64
- const claim = str(p.flags, "claim");
66
+ const claim = str(p.flags, "claim")?.trim();
65
67
  if (claim)
66
68
  headers["x-bschat-claim"] = claim;
67
69
  const res = await fetch(`${creds.url}/projects/${project}/evidence`, { method: "POST", headers, body: new Uint8Array(bytes) });
@@ -77,6 +79,7 @@ export async function evidence(p, out) {
77
79
  }
78
80
  if (!res.ok)
79
81
  throw new CliError(typeof json?.error === "string" ? json.error : `http_${res.status}`, typeof json?.message === "string" ? json.message : responseText);
82
+ verifyTextReceipts(json, { ...(label ? { label } : {}), ...(claim ? { claim } : {}) }, [...(label ? ["label"] : []), ...(claim ? ["claim"] : [])]);
80
83
  const storedType = json?.evidence?.content_type;
81
84
  if (typeof storedType !== "string")
82
85
  throw new CliError("bad_response", "evidence upload response omitted evidence.content_type");
@@ -8,13 +8,24 @@ import { CLI_VERSION } from "../version.js";
8
8
  /** Product feedback to BenignSwarm's maintainers. Never includes message content or keys. */
9
9
  export async function feedback(p, out) {
10
10
  const name = resolveAgentName(str(p.flags, "as"));
11
- const creds = loadAgent(name);
11
+ if (p.positionals[1] === "get") {
12
+ const id = p.positionals[2];
13
+ if (!id || p.positionals.length !== 3)
14
+ throw new CliError("usage", "feedback get <id> (available to the sender for 24 hours)");
15
+ const creds = loadAgent(name);
16
+ const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
17
+ const r = await client.call("GET", `/feedback/${encodeURIComponent(id)}`);
18
+ return out.print(`Feedback ${r.id} from ${r.created_at}:\n${r.text}`, r);
19
+ }
12
20
  let text = p.positionals.slice(1).join(" ");
13
21
  const file = str(p.flags, "body-file");
22
+ if (file && text.length)
23
+ throw new CliError("usage", "feedback accepts positional text or --body-file, not both");
14
24
  if (file)
15
25
  text = file === "-" ? readFileSync(0, "utf8") : readFileSync(file, "utf8");
16
26
  if (!text.trim())
17
27
  throw new CliError("usage", 'feedback "<what got in your way or what would help>" [--category bug|friction|idea|docs] [--body-file f|-]');
28
+ const creds = loadAgent(name);
18
29
  const category = str(p.flags, "category") ?? "other";
19
30
  const context = { harness: detectVendor() ?? creds.vendor, model: resolveModel(str(p.flags, "model"), process.env, process.cwd(), name), cli_version: CLI_VERSION, platform: process.platform };
20
31
  const cmd = str(p.flags, "command");
@@ -0,0 +1,153 @@
1
+ import { str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAdmin, resolveAdminName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ const adminClient = (p) => Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
6
+ const DAY = 86_400_000;
7
+ function utcRange(from, to) {
8
+ if ((from === undefined) !== (to === undefined))
9
+ throw new CliError("usage", "--from and --to must be supplied together");
10
+ if (from === undefined || to === undefined)
11
+ return null;
12
+ const utcInput = (value, end) => {
13
+ if (/^\d{4}-\d\d-\d\d$/.test(value)) {
14
+ const base = Date.parse(`${value}T${end ? "23:59:59.999" : "00:00:00.000"}Z`);
15
+ if (!Number.isFinite(base) || new Date(base).toISOString().slice(0, 10) !== value)
16
+ throw new CliError("usage", "--from/--to must be valid ISO dates or timestamps with an explicit UTC offset");
17
+ return base;
18
+ }
19
+ if (!/^\d{4}-\d\d-\d\dT.*(?:Z|[+-]\d\d:\d\d)$/.test(value))
20
+ throw new CliError("usage", "--from/--to timestamps must include Z or an explicit UTC offset");
21
+ const parsed = Date.parse(value);
22
+ if (!Number.isFinite(parsed))
23
+ throw new CliError("usage", "--from/--to must be valid ISO dates or timestamps with an explicit UTC offset");
24
+ return parsed;
25
+ };
26
+ const start = utcInput(from, false), end = utcInput(to, true);
27
+ if (start >= end)
28
+ throw new CliError("usage", "--from must be earlier than --to");
29
+ if (end - start > 90 * DAY)
30
+ throw new CliError("usage", "Flow reports cover at most 90 days");
31
+ if (end > Date.now() + 60_000)
32
+ throw new CliError("usage", "--to cannot be in the future");
33
+ return { from: start, to: end };
34
+ }
35
+ const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
36
+ const list = (value) => Array.isArray(value) ? value : [];
37
+ const show = (value) => value === null || value === undefined || value === "" ? "unknown" : typeof value === "string" ? value : String(value);
38
+ function duration(ms) {
39
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)
40
+ return "unknown";
41
+ const mins = Math.round(ms / 60_000);
42
+ if (mins < 60)
43
+ return `${mins}m`;
44
+ const hours = Math.floor(mins / 60), rem = mins % 60;
45
+ if (hours < 48)
46
+ return rem ? `${hours}h ${rem}m` : `${hours}h`;
47
+ const days = Math.floor(hours / 24), hoursLeft = hours % 24;
48
+ return hoursLeft ? `${days}d ${hoursLeft}h` : `${days}d`;
49
+ }
50
+ function flowText(snapshot) {
51
+ const scope = record(snapshot.scope), window = record(snapshot.window), counts = record(snapshot.state_counts);
52
+ const scopeName = scope.kind === "project" ? `project ${show(scope.project)}` : "account scope";
53
+ const lines = [`Flow · ${scopeName}`, `Window: ${show(window.from)} to ${show(window.to)} (${show(window.timezone ?? "UTC")}); generated ${show(snapshot.generated_at ?? record(snapshot.freshness).generated_at)}`];
54
+ lines.push("State counts: " + ["held", "blocked_on_dependency", "changes_requested", "in_review", "approved_waiting_to_merge", "in_progress", "assigned_not_started", "waiting_on_person", "ready", "starved", "unknown"].map((key) => `${key}=${show(counts[key])}`).join(" "));
55
+ if (counts.eligibility_coverage)
56
+ lines.push(` eligibility: ${counts.eligibility_coverage}`);
57
+ const units = record(snapshot.units), items = list(units.items);
58
+ lines.push(`Open units: ${show(units.total_open)} total; ${items.length} shown${units.next_cursor ? `; next page: ${units.next_cursor}` : ""}`);
59
+ for (const itemValue of items) {
60
+ const item = record(itemValue), reasons = list(item.reasons).map((value) => show(record(value).code)).filter((value) => value !== "unknown");
61
+ const owner = item.owner ? `; owner ${item.owner}` : "", reviewer = item.reviewer ? `; reviewer ${item.reviewer}` : "";
62
+ const since = record(item.state_since);
63
+ const sinceText = since.state === "known" ? `since ${show(since.at)} (${show(since.source_kind)})` : `state age unknown: ${show(since.reason)}`;
64
+ lines.push(` #${show(item.number)} [${show(item.primary_state)}] ${show(item.title)}${item.project ? ` · ${item.project}` : ""}${owner}${reviewer}; ${sinceText}${reasons.length ? `; reasons ${reasons.join(", ")}` : ""}`);
65
+ for (const dependencyValue of list(item.dependencies)) {
66
+ if (!dependencyValue || typeof dependencyValue !== "object")
67
+ continue;
68
+ const dependency = record(dependencyValue);
69
+ lines.push(` waits on #${show(dependency.number)} ${show(dependency.status)}${dependency.title ? `: ${dependency.title}` : ""}`);
70
+ }
71
+ }
72
+ const capacity = record(snapshot.capacity), agents = record(capacity.agents), reviewers = record(capacity.reviewers);
73
+ lines.push("Capacity:");
74
+ for (const [label, value] of [["idle with ready work", agents.idle_with_ready_work], ["idle with no ready work", agents.idle_no_ready_work], ["reviewer load", reviewers.load], ["review latency", reviewers.latency]]) {
75
+ const item = record(value);
76
+ lines.push(` ${label}: ${show(item.state)}${item.reason ? ` (${item.reason})` : ""}${item.count !== undefined ? `; count ${item.count}` : ""}`);
77
+ }
78
+ const machines = list(capacity.machines);
79
+ if (!machines.length)
80
+ lines.push(` machines: ${show(capacity.freshness ?? "missing")}`);
81
+ for (const machineValue of machines) {
82
+ const machine = record(machineValue), sessions = record(machine.sessions);
83
+ lines.push(` machine ${show(machine.name)}: ${show(machine.freshness)}; slots ${show(machine.slots)}; sessions ${show(sessions.active_running)}/${show(sessions.desired_running)} active/desired; faults ${show(sessions.faults)}; report ${show(machine.last_report_at)}`);
84
+ }
85
+ lines.push("Critical paths:");
86
+ const paths = list(snapshot.critical_paths);
87
+ if (!paths.length)
88
+ lines.push(" none recorded");
89
+ for (const value of paths) {
90
+ const path = record(value);
91
+ const steps = list(path.path).map((step) => {
92
+ const item = record(step);
93
+ return `#${show(item.number ?? item.unit)}${item.state ? ` [${item.state}]` : ""}`;
94
+ });
95
+ lines.push(` ${show(path.project)} · ${show(path.milestone)} ${show(path.title)}: ${show(path.state)}${steps.length ? ` · ${steps.join(" → ")}` : ""}${path.reason ? ` · ${path.reason}` : ""}`);
96
+ }
97
+ lines.push("Attention:");
98
+ const attention = list(snapshot.attention);
99
+ if (!attention.length)
100
+ lines.push(" none supported by current evidence");
101
+ for (const value of attention.slice(0, 3))
102
+ lines.push(` ${show(record(value).sentence ?? value)}`);
103
+ const trends = record(snapshot.trends);
104
+ lines.push("Trends (UTC):");
105
+ const daily = list(trends.daily);
106
+ if (!daily.length)
107
+ lines.push(" no recorded daily events");
108
+ // The API returns daily buckets inside the selected bounded window; retain all of them.
109
+ for (const value of daily) {
110
+ const day = record(value);
111
+ lines.push(` ${show(day.day)}: opened ${show(day.opened)}, merged ${show(day.merged)}, completed unmerged ${show(day.completed_unmerged)}, abandoned ${show(day.abandoned)}`);
112
+ }
113
+ const stateTimes = record(trends.state_time);
114
+ for (const [state, value] of Object.entries(stateTimes)) {
115
+ const stat = record(value);
116
+ lines.push(` ${state}: median ${duration(stat.median_ms)} across ${show(stat.episodes)} episodes (${show(stat.coverage)})`);
117
+ }
118
+ const review = record(trends.review);
119
+ if (Object.keys(review).length)
120
+ lines.push(` review submit to verdict: median ${duration(review.median_submit_to_verdict_ms)} across ${show(review.completed_reviews)} completed reviews`);
121
+ if (record(trends.current_open_age).state === "unknown")
122
+ lines.push(` current open age: unknown (${show(record(trends.current_open_age).reason)})`);
123
+ const freshness = record(snapshot.freshness);
124
+ lines.push(`Freshness: current state ${show(freshness.current_state)}; machine reports ${show(freshness.machine_reports)}; generated ${show(freshness.generated_at ?? snapshot.generated_at)}`);
125
+ lines.push("Coverage:");
126
+ const coverage = record(snapshot.coverage);
127
+ if (!Object.keys(coverage).length)
128
+ lines.push(" unavailable");
129
+ for (const [source, state] of Object.entries(coverage))
130
+ lines.push(` ${source}: ${show(state)}`);
131
+ return lines.join("\n");
132
+ }
133
+ export async function flowAdmin(action, rest, p, out) {
134
+ if (action || rest.length)
135
+ throw new CliError("usage", "b9s-admin flow [--project <p>] [--from <UTC date/time>] [--to <UTC date/time>] [--json]");
136
+ const unsupportedFlags = Object.keys(p.flags).filter((name) => !["admin", "json", "help", "version", "project", "from", "to"].includes(name));
137
+ if (unsupportedFlags.length)
138
+ throw new CliError("usage", `unsupported flow option --${unsupportedFlags[0]}; run b9s-admin flow --help`);
139
+ const project = str(p.flags, "project"), from = str(p.flags, "from"), to = str(p.flags, "to");
140
+ if (project !== undefined && !project.trim())
141
+ throw new CliError("usage", "--project must be a non-empty project name");
142
+ utcRange(from, to);
143
+ const query = new URLSearchParams();
144
+ if (project !== undefined)
145
+ query.set("project", project);
146
+ if (from !== undefined)
147
+ query.set("from", from);
148
+ if (to !== undefined)
149
+ query.set("to", to);
150
+ const path = `/flow${query.size ? `?${query}` : ""}`;
151
+ const snapshot = await adminClient(p).call("GET", path);
152
+ out.print(flowText(snapshot), snapshot);
153
+ }
@@ -157,6 +157,7 @@ export async function gatherUpdates(name, opts) {
157
157
  return null;
158
158
  let messages;
159
159
  let items = [];
160
+ let questions = [];
160
161
  // A poll on the agent's behalf: no presence header, so last_seen keeps meaning "the agent acted".
161
162
  const client = Client.forAgent(creds, resolveModel(opts.model, process.env, process.cwd(), name), { presence: false });
162
163
  try {
@@ -166,6 +167,7 @@ export async function gatherUpdates(name, opts) {
166
167
  const r = await client.call("GET", `/inbox?${qs}`);
167
168
  messages = r.messages;
168
169
  items = r.items ?? [];
170
+ questions = r.questions ?? [];
169
171
  }
170
172
  catch (e) {
171
173
  process.stderr.write(`b9s: ${e.message}\n`);
@@ -281,15 +283,20 @@ export async function gatherUpdates(name, opts) {
281
283
  else {
282
284
  writeState(name, { ...next, ...(noticeChanges ? { notice_state: noticeChanges.next } : {}) });
283
285
  }
284
- if (!messages.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length)
286
+ if (!messages.length && !questions.length && !items.length && !digest.length && !followed.length && !noticeLines.length && !measureLines.length)
285
287
  return null;
286
288
  const lines = messages.map((m) => `${creds.project ? "" : `[${m.project}] `}${fmtMessage(m)}${m.reply_to_seq ? ` (reply to #${m.reply_to_seq})` : ""}`);
289
+ const questionLines = questions.slice(0, 4).map((q) => ` ${q.project} #${q.channel} seq ${q.seq} from ${q.from} (${q.age_minutes} min ago): ${q.question} — ${q.next}`);
290
+ if (questions.length > questionLines.length)
291
+ questionLines.push(` ${questions.length - questionLines.length} more open questions; run b9s inbox`);
292
+ const questionBlock = questionLines.length ? ["Questions waiting on you:", ...questionLines].join("\n") : "";
287
293
  const protectedDirect = messages.flatMap((m, i) => m.role_name === "human" ? [lines[i]] : []);
288
294
  const directLines = messages.flatMap((m, i) => m.role_name === "human" ? [] : [lines[i]]);
289
295
  const itemLines = items.map((i) => ` list "${i.list}"${i.project && !creds.project ? ` [${i.project}]` : ""}: [${i.status}] ${i.title} (item ${i.id}, by ${i.updated_by})`);
290
296
  const noticeBlock = noticeLines.length ? [`Notices for this machine or project:`, ...noticeLines].join("\n") : "";
291
297
  const head = [
292
298
  messages.length ? `${messages.length} message${messages.length === 1 ? "" : "s"} for you` : null,
299
+ questions.length ? `${questions.length} question${questions.length === 1 ? "" : "s"} waiting on you` : null,
293
300
  items.length ? `${items.length} list item${items.length === 1 ? "" : "s"} assigned to you` : null,
294
301
  followed.length ? `new messages in followed channels` : null,
295
302
  digest.length ? `unread channels` : null,
@@ -318,16 +325,25 @@ export async function gatherUpdates(name, opts) {
318
325
  const directPointer = firstDeferred ? inboxPointer : "b9s inbox --unread";
319
326
  const itemPointer = firstItemDeferred ? inboxPointer : "b9s inbox --unread";
320
327
  const followedPointer = pendingReads.size ? "b9s read --pending" : readCommands.join("; ") || "b9s read --pending";
321
- const parts = { header, protectedDirect: [...protectedDirect, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
328
+ const parts = { header, protectedDirect: [...(questionBlock ? [questionBlock] : []), ...protectedDirect, ...(noticeBlock ? [noticeBlock] : []), ...measureLines], direct: directLines, directPointer, itemPointer, followedPointer, digestPointer: digestCommands.length ? "b9s read --pending" : "b9s inbox --unread", items: itemLines, followed, digest, footer, readCommand: `b9s read <channel> --since <seq>`, budget };
322
329
  const delivery = budgetDelivery(parts);
323
330
  const operator = messages.filter((m) => m.role_name === "human").map((m) => m.created_at).sort().pop() ?? null;
324
331
  const visibleReadCommands = readCommands.slice(0, 8);
325
332
  if (deferredReads.length)
326
333
  visibleReadCommands.push("b9s read --pending");
327
- const cmds = [...(messages.length || items.length ? ["b9s inbox --unread"] : []), ...visibleReadCommands];
328
- const direct = items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some((m) => m.role_name === "human" || !!m.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(m.body));
334
+ const cmds = [...(messages.length || questions.length || items.length ? ["b9s inbox --unread"] : []), ...visibleReadCommands];
335
+ const isDirectMessage = (message) => message.role_name === "human" || !!message.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(message.body);
336
+ const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some(isDirectMessage);
329
337
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
330
- return { text: delivery.text, counts: { messages: messages.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
338
+ const directTimes = [
339
+ ...messages.filter(isDirectMessage).map((message) => message.created_at),
340
+ ...questions.map((question) => question.asked_at),
341
+ ...items.map((item) => item.updated_at),
342
+ ].filter((at) => !!at && Number.isFinite(Date.parse(at)));
343
+ const firstDirectAt = directTimes.sort()[0] ?? null;
344
+ const urgent = messages.some((message) => message.urgent === true || message.priority === "urgent")
345
+ || items.some((item) => item.urgent === true || item.priority === "urgent");
346
+ return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
331
347
  }
332
348
  /** Command patterns warn without blocking; errors remain visible to the caller. */
333
349
  export async function commandWarnings(name, command) {
@@ -378,7 +394,7 @@ export async function hook(p) {
378
394
  writeState(name, { ...state, model: observed, model_observed_at: Date.now() });
379
395
  }
380
396
  if (harness === "claude-code" && typeof input?.transcript_path === "string")
381
- noteSession(name, "claude-code", input.transcript_path, typeof input.session_id === "string" ? input.session_id : null);
397
+ noteSession(name, "claude-code", input.transcript_path, typeof input.session_id === "string" ? input.session_id : null, event === "SessionStart" && input?.source === "compact");
382
398
  if (event === "PostModelSwitch")
383
399
  return;
384
400
  if (harness === "claude-code" && event === "PreToolUse") {
@@ -659,10 +675,14 @@ async function codexHook(p) {
659
675
  await acknowledgeStanding(name, standing, formatted.acknowledge);
660
676
  }
661
677
  /** Records where this agent's harness session writes, so `wu submit` can read its token counts. */
662
- function noteSession(name, harness, transcript, sessionId) {
678
+ function noteSession(name, harness, transcript, sessionId, compacted = false) {
663
679
  const st = readState(name);
664
680
  const cur = st.harness_session;
665
- if (cur && cur.transcript === transcript && cur.harness === harness)
681
+ const same = !!cur && cur.transcript === transcript && cur.harness === harness;
682
+ if (same && !compacted)
666
683
  return;
667
- writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: Date.now(), ...(cur?.harness === harness && cur.session_id === sessionId && cur.provider ? { provider: cur.provider } : {}) } });
684
+ const compactions = same ? [...(cur.compactions ?? [])] : [];
685
+ if (compacted)
686
+ compactions.push(Date.now());
687
+ writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: same ? cur.at : Date.now(), ...(compactions.length ? { compactions: compactions.slice(-1000) } : {}), ...(same && cur.provider ? { provider: cur.provider } : {}) } });
668
688
  }
@@ -0,0 +1,77 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { need, str } from "../args.js";
3
+ import { Client } from "../client.js";
4
+ import { loadAdmin, resolveAdminName } from "../config.js";
5
+ import { validateDevcontainerSpec } from "../container.js";
6
+ import { CliError } from "../errors.js";
7
+ export async function projectImageAdmin(rest, p, out) {
8
+ const [sub, project] = rest;
9
+ if (sub === "validate") {
10
+ const file = need(p.flags, "file");
11
+ const dockerfile = str(p.flags, "dockerfile");
12
+ const arch = str(p.flags, "arch") ?? "linux/amd64";
13
+ const raw = readFileSync(file, "utf8");
14
+ const df = dockerfile ? readFileSync(dockerfile, "utf8") : null;
15
+ const res = validateDevcontainerSpec(raw, { dockerfileContent: df, targetArch: arch });
16
+ if (!res.ok)
17
+ throw new CliError("usage", res.error ?? "invalid devcontainer spec");
18
+ out.print(`Devcontainer ${file} pinned (${res.base_image_digest}); recipe ${res.recipe_hash}`, res);
19
+ return;
20
+ }
21
+ const c = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
22
+ if (!sub || !project) {
23
+ throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | rollback <p> (<sha256:...> | clear)>");
24
+ }
25
+ switch (sub) {
26
+ case "config": {
27
+ const rawCache = str(p.flags, "caches") ?? str(p.flags, "cache");
28
+ const caches = rawCache ? rawCache.split(",").map((s) => s.trim()).filter(Boolean) : [];
29
+ const r = await c.call("PUT", `/projects/${encodeURIComponent(project)}/image-config`, {
30
+ ...(str(p.flags, "path") ? { devcontainer_path: str(p.flags, "path") } : {}),
31
+ ...(str(p.flags, "arch") ? { target_arch: str(p.flags, "arch") } : {}),
32
+ ...(caches.length ? { allowed_caches: caches } : {}),
33
+ });
34
+ out.print(`Project ${project} image namespace ${r.image.registry_namespace} (${r.image.target_arch}, ${r.image.devcontainer_path})`, r);
35
+ return;
36
+ }
37
+ case "show": {
38
+ const r = await c.call("GET", `/projects/${encodeURIComponent(project)}/image`);
39
+ out.print(`Project ${project} active digest: ${r.image.active_digest ?? "(none)"}${r.image.rollback_digest ? ` (rollback pinned to ${r.image.rollback_digest})` : ""}`, r);
40
+ return;
41
+ }
42
+ case "build": {
43
+ const commit = need(p.flags, "commit");
44
+ const file = need(p.flags, "file");
45
+ const dockerfile = str(p.flags, "dockerfile");
46
+ const arch = str(p.flags, "arch");
47
+ let dc;
48
+ try {
49
+ dc = JSON.parse(readFileSync(file, "utf8"));
50
+ }
51
+ catch (e) {
52
+ throw new CliError("usage", `could not parse ${file}: ${e.message}`);
53
+ }
54
+ const df = dockerfile ? readFileSync(dockerfile, "utf8") : undefined;
55
+ const r = await c.call("POST", `/projects/${encodeURIComponent(project)}/image/builds`, {
56
+ source_commit: commit,
57
+ devcontainer: dc,
58
+ ...(df !== undefined ? { dockerfile_content: df } : {}),
59
+ ...(arch ? { target_arch: arch } : {}),
60
+ });
61
+ out.print(`Build ${r.build.id}: ${r.build.status} (commit ${r.build.source_commit.slice(0, 12)}, namespace ${r.build.registry_namespace})`, r);
62
+ return;
63
+ }
64
+ case "rollback": {
65
+ const digest = rest[2];
66
+ if (!digest)
67
+ throw new CliError("usage", "project image rollback <project> (<sha256:...> | clear)");
68
+ const r = await c.call("POST", `/projects/${encodeURIComponent(project)}/image/rollback`, {
69
+ image_digest: digest === "clear" ? null : digest,
70
+ });
71
+ out.print(`Project ${project} active digest is now ${r.image.active_digest ?? "(none)"}`, r);
72
+ return;
73
+ }
74
+ default:
75
+ throw new CliError("usage", "project image validate|config|show|build|rollback ...");
76
+ }
77
+ }