benignswarm 0.12.165 → 0.12.167

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.
File without changes
package/dist/args.js CHANGED
@@ -16,7 +16,7 @@ export const STRING_FLAGS = [
16
16
  "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval",
17
17
  "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "startup-jitter-seconds", "env", "scope",
18
18
  "session-harness", "session-sandbox", "session-machine", "session-machine-label", "scope-file", "scope-from", "append", "pr", "note", "note-file", "add", "remove", "merged", "tag",
19
- "activity", "max-unanswered", "to", "replay-of", "branch", "base", "effort", "max-budget-usd", "by", "target", "lands-with",
19
+ "activity", "max-unanswered", "to", "replay-of", "branch", "base", "effort", "max-budget-usd", "by", "target", "lands-with", "group", "study",
20
20
  "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling",
21
21
  "gaps", "unit", "units", "blocks", "sla", "takeover", "stall", "max-open", "max-in-progress", "require-scope",
22
22
  "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit",
@@ -32,10 +32,11 @@ export const STRING_FLAGS = [
32
32
  "instance-id", "machine-id", "machine-name", "node-sha256", "node-version", "path", "recipe-version", "region",
33
33
  "root", "signing-key", "catalog", "context", "context-action", "context-checkpoint-ref", "context-old-thread", "context-new-thread", "source-commit", "component", "normalized-key",
34
34
  "drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
35
+ "override-reason",
35
36
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
37
  "machine-session-id", "harness-binary", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
37
38
  "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
- "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route",
39
+ "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route", "intent", "brief", "brief-file",
39
40
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
41
  "choices", "choice", "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate", "outcome",
41
42
  ];
@@ -43,8 +44,9 @@ export const BOOL_FLAGS = [
43
44
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
44
45
  "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread",
45
46
  "clear-session", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "log",
46
- "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
47
+ "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "review-hold", "clear", "met", "shared", "archive",
47
48
  "approve", "turn", "service", "print-hooks", "create", "rotate", "drain", "codex-userns", "bwrap-userns", "agy-userns", "print-apparmor", "overdue",
49
+ "override-unwakeable",
48
50
  "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "assessment-only", "continue",
49
51
  "no-wait-verify", "preview", "remove-empty", "dry-run", "quota-substitution", "auto-merge",
50
52
  "in-container", "retrieve-ec2", "stdin", "context-confirmed", "confirm-compatible", "move-provisioned", "provisioned", "no-commits-beyond-target", "train",
@@ -63,7 +65,7 @@ export function parse(argv) {
63
65
  // replacement command needs its value. Resolve that spelling by command.
64
66
  if (argv[0] === "wu" && argv[1] === "reviewer")
65
67
  options.replace = { type: "string" };
66
- if ((argv[0] === "mock" || argv[0] === "design-study") && argv[1] === "gaps")
68
+ if ((argv[0] === "mock" || argv[0] === "design-study") && (argv[1] === "gaps" || argv[1] === "review" && (argv[2] === "gaps" || argv[2] === "propose")))
67
69
  options.json = { type: "string" };
68
70
  try {
69
71
  const seen = new Set();
package/dist/client.js CHANGED
@@ -154,9 +154,9 @@ function expectedTextReceiptFields(method, path, body, response) {
154
154
  if (verb === "POST" && /^\/projects\/[^/]+\/locks\/[^/]+\/acquire$/.test(route))
155
155
  return strings("note");
156
156
  if (verb === "POST" && /^\/projects\/[^/]+\/ask-operator$/.test(route))
157
- return strings("text", "blocks", "proposal", "plain", "if_yes", "if_no");
157
+ return strings("text", "decision", "blocks", "proposal", "plain", "if_yes", "if_no");
158
158
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/amend$/.test(route))
159
- return strings("text", "plain", "blocks", "if_yes", "if_no", "proposal");
159
+ return strings("text", "decision", "plain", "blocks", "if_yes", "if_no", "proposal");
160
160
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/withdraw$/.test(route))
161
161
  return strings("note");
162
162
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/explanation$/.test(route))
@@ -6,7 +6,7 @@ const INHERITED_OPTION_CONTRACTS = new Map([["codex start", ["start"]]]);
6
6
  const PROJECT_COMMANDS = new Set([
7
7
  "mock", "design-study", "flow-agent", "notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
8
8
  "wu", "process", "record", "milestones", "milestone", "lock", "unlock", "locks", "ask", "ask-operator",
9
- "explain", "worktrees", "measures", "measure", "environment", "test-results", "ux", "gate",
9
+ "explain", "worktrees", "measures", "measure", "environment", "test-results", "ux", "gate", "health",
10
10
  ]);
11
11
  function supportsProject(command) {
12
12
  return PROJECT_COMMANDS.has(command[0] ?? "") || (command[0] === "status" && command[1] === "history");
@@ -18,15 +18,19 @@ import { cloudAdmin } from "./cloud-admin.js";
18
18
  import { projectImageAdmin } from "./image-admin.js";
19
19
  import { environmentAdmin } from "./environment-admin.js";
20
20
  import { flowAdmin } from "./flow.js";
21
+ import { healthAdmin } from "./health.js";
21
22
  import { projectSecrets } from "./project-secrets.js";
22
23
  import { standingRuleAdmin } from "./standing-rules.js";
23
24
  import { diagAdmin } from "./diag-admin.js";
25
+ import { mockAdmin } from "./mock-admin.js";
24
26
  function adminClient(p) {
25
27
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
26
28
  }
27
29
  export async function admin(p, out) {
28
30
  const [, group, action, ...rest] = p.positionals;
29
31
  switch (group) {
32
+ case "mock":
33
+ return mockAdmin(action, rest, p, adminClient(p), out);
30
34
  case "login": {
31
35
  const url = (str(p.flags, "url") ?? process.env.BSCHAT_URL ?? DEFAULT_URL).replace(/\/$/, "");
32
36
  if (str(p.flags, "key") === undefined)
@@ -134,6 +138,8 @@ export async function admin(p, out) {
134
138
  return needsAdmin(p, out, action);
135
139
  case "flow":
136
140
  return flowAdmin(action, rest, p, out);
141
+ case "health":
142
+ return healthAdmin(action, rest, p, out);
137
143
  case "diag":
138
144
  return diagAdmin(action, rest, p, out);
139
145
  case "notice":
@@ -696,7 +702,13 @@ async function workUnitAdmin(action, rest, p, out) {
696
702
  if (!to)
697
703
  throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
698
704
  const reason = str(p.flags, "reason");
699
- const r = await adminClient(p).call("POST", `/projects/${rest[0]}/work-units/${Number(rest[1])}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
705
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
706
+ const overrideReason = str(p.flags, "override-reason");
707
+ if (overrideWakeability && !overrideReason?.trim())
708
+ throw new CliError("usage", '--override-unwakeable requires --override-reason "why this unavailable target must receive work"');
709
+ if (overrideReason !== undefined && !overrideWakeability)
710
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
711
+ const r = await adminClient(p).call("POST", `/projects/${rest[0]}/work-units/${Number(rest[1])}/assign`, { to, ...(reason === undefined ? {} : { reason }), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}) });
700
712
  out.print(`WU #${r.unit.number} reassigned to ${r.unit.owner_name || r.unit.preferred_name}${r.unit.status === "queued" ? "; queued until they are free" : ""}.`, r);
701
713
  }
702
714
  async function channel(action, rest, p, out) {
@@ -32,11 +32,12 @@ Hard invariants (every level; the server refuses these with 403):
32
32
  - Never approve a unit, request changes, or close one as done.
33
33
  - Never lift an operator hold.
34
34
  - Never touch billing, authentication or production data.
35
+ - Never change or exceed operator-owned per-session-hour, per-account-day, turns-per-hour, or per-turn limits.
35
36
 
36
37
  At ${level} you may:
37
38
  ${may}
38
39
 
39
- Limits: at most ${limits.max_turns_per_hour} turns per hour and $${limits.daily_budget_usd} per day. Check b9s flow-agent status before acting; when either is used up, stop and say so.
40
+ Flow Agent action cap: at most ${limits.max_actions_per_hour} actions per hour. Account budget caps are shared with unattended turns and are owned by the operator: ${limits.account_day_tokens === null ? "no account-day token cap" : `${limits.account_day_tokens.toLocaleString()} tokens`} · ${limits.account_day_cost_micros === null ? "no account-day cost cap" : `$${(limits.account_day_cost_micros / 1_000_000).toFixed(4)}`}. Check b9s flow-agent status before acting. If the account budget is disabled, unconfigured, or reached, stop and hold for the operator.
40
41
 
41
42
  Operating loop, once per wake-up:
42
43
  1. Read the triggers in the wake-up message, then b9s flow-agent status.
@@ -64,9 +65,13 @@ export async function flowAgent(p, out) {
64
65
  const s = await client.call("GET", `/projects/${project}/flow-agent/status`);
65
66
  if (sub === "status") {
66
67
  const recent = (s.recent_actions ?? []);
68
+ const budget = s.account_budget;
69
+ const tokenCap = budget.account_day_tokens === null ? "unconfigured" : `${budget.tokens_counted.toLocaleString()}/${budget.account_day_tokens.toLocaleString()} tokens`;
70
+ const costCap = budget.account_day_cost_micros === null ? "unconfigured" : `$${(budget.cost_micros_counted / 1_000_000).toFixed(4)}/$${(budget.account_day_cost_micros / 1_000_000).toFixed(4)}`;
67
71
  const lines = [
68
72
  `flow agent: ${s.enabled ? "enabled" : "disabled"} · ${s.autonomy_level}`,
69
- `turns this hour: ${s.turns_this_hour}/${s.max_turns_per_hour} · spend today: $${Number(s.spend_today_usd).toFixed(2)}/$${s.daily_budget_usd}`,
73
+ `actions this hour: ${s.actions_this_hour}/${s.max_actions_per_hour}`,
74
+ `account budget · rolling 24h: ${budget.enabled ? `${tokenCap} · ${costCap}` : "disabled"}${budget.reached ? " · held" : ""} · ${budget.pending_count} pending · ${budget.uncertain_count} uncertain`,
70
75
  `last run: ${s.last_run_at ?? "never"}`,
71
76
  ...recent.slice(0, 10).map((a) => ` ${a.at} ${a.kind}${a.unit_number === null ? "" : ` #${a.unit_number}`}${a.outcome ? ` (${a.outcome})` : ""}: ${a.summary}`),
72
77
  ];
@@ -77,6 +82,7 @@ export async function flowAgent(p, out) {
77
82
  if (requested !== undefined && !FLOW_AGENT_LEVELS.includes(requested))
78
83
  throw new CliError("usage", `--level must be one of ${FLOW_AGENT_LEVELS.join(", ")}`);
79
84
  const level = (requested ?? s.autonomy_level);
80
- const text = flowAgentPrompt(level, { daily_budget_usd: s.daily_budget_usd, max_turns_per_hour: s.max_turns_per_hour });
85
+ const budget = s.account_budget;
86
+ const text = flowAgentPrompt(level, { ...budget, max_actions_per_hour: s.max_actions_per_hour });
81
87
  out.print(text, { autonomy_level: level, enabled: s.enabled, prompt: text });
82
88
  }
@@ -54,6 +54,11 @@ function flowText(snapshot) {
54
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
55
  if (counts.eligibility_coverage)
56
56
  lines.push(` eligibility: ${counts.eligibility_coverage}`);
57
+ const agentSummary = record(snapshot.agent_summary);
58
+ if (Object.keys(agentSummary).length) {
59
+ const states = record(agentSummary.states);
60
+ lines.push(`Agent utilization: ${agentSummary.utilization == null ? "unavailable (no working, idle, or waiting agents)" : `${Math.round(agentSummary.utilization * 100)}% working`} · working ${show(states.working)}, idle ${show(states.idle)}, waiting ${show(states.waiting)}, not responding ${show(states.not_responding)} faults, away ${show(states.away)}, benched ${show(agentSummary.benched_agent_count)}`);
61
+ }
57
62
  const units = record(snapshot.units), items = list(units.items);
58
63
  lines.push(`Open units: ${show(units.total_open)} total; ${items.length} shown${units.next_cursor ? `; next page: ${units.next_cursor}` : ""}`);
59
64
  for (const itemValue of items) {
@@ -6,6 +6,57 @@ import { Client } from "../client.js";
6
6
  import { loadAgent, resolveAgentName } from "../config.js";
7
7
  import { CliError } from "../errors.js";
8
8
  import { githubCredentialForRepository, remoteRepository } from "./git-credential.js";
9
+ const GH_RERUN_USAGE = 'Usage: b9s gh run rerun <run-id> --failed [--job <job-id>] --reason "..."';
10
+ export function parseFailedRerunArgs(args) {
11
+ if (args[0] !== "run" || args[1] !== "rerun")
12
+ throw new CliError("usage", GH_RERUN_USAGE);
13
+ const runId = args[2];
14
+ if (!runId || !/^[1-9][0-9]{0,19}$/.test(runId))
15
+ throw new CliError("usage", `run-id must be a positive numeric GitHub Actions run id.\n${GH_RERUN_USAGE}`);
16
+ let failed = false;
17
+ let jobId;
18
+ let reason;
19
+ for (let index = 3; index < args.length; index += 1) {
20
+ const arg = args[index];
21
+ if (arg === "--failed") {
22
+ if (failed)
23
+ throw new CliError("usage", `--failed may be specified only once.\n${GH_RERUN_USAGE}`);
24
+ failed = true;
25
+ }
26
+ else if (arg === "--job") {
27
+ if (jobId !== undefined)
28
+ throw new CliError("usage", `--job may be specified only once.\n${GH_RERUN_USAGE}`);
29
+ const value = args[++index];
30
+ if (!value || !/^[1-9][0-9]{0,19}$/.test(value))
31
+ throw new CliError("usage", `--job requires a positive numeric GitHub job id.\n${GH_RERUN_USAGE}`);
32
+ jobId = value;
33
+ }
34
+ else if (arg === "--reason") {
35
+ if (reason !== undefined)
36
+ throw new CliError("usage", `--reason may be specified only once.\n${GH_RERUN_USAGE}`);
37
+ const value = args[++index];
38
+ if (!value)
39
+ throw new CliError("usage", `--reason requires a value.\n${GH_RERUN_USAGE}`);
40
+ reason = value.trim();
41
+ }
42
+ else {
43
+ throw new CliError("github_option_unsupported", `b9s gh run rerun does not support ${arg}; it never permits full-run or arbitrary GitHub commands.\n${GH_RERUN_USAGE}`);
44
+ }
45
+ }
46
+ if (!failed)
47
+ throw new CliError("usage", `--failed is required; full workflow-run reruns are not supported.\n${GH_RERUN_USAGE}`);
48
+ if (!reason || reason.length > 800)
49
+ throw new CliError("usage", `--reason must contain 1 to 800 non-whitespace characters.\n${GH_RERUN_USAGE}`);
50
+ return { runId, ...(jobId ? { jobId } : {}), reason };
51
+ }
52
+ export async function requestFailedRerun(args, project, api, parsed = parseFailedRerunArgs(args)) {
53
+ const request = parsed;
54
+ return api("POST", `/projects/${encodeURIComponent(project)}/github/runs/${encodeURIComponent(request.runId)}/rerun-failed`, {
55
+ failed: true,
56
+ ...(request.jobId ? { job_id: request.jobId } : {}),
57
+ reason: request.reason,
58
+ });
59
+ }
9
60
  const run = (command, args, options) => spawnSync(command, args, options);
10
61
  function repositoryArgument(value) {
11
62
  if (!value)
@@ -15,18 +66,28 @@ function repositoryArgument(value) {
15
66
  }
16
67
  const GH_COMMAND_OPTIONS = {
17
68
  "pr view": {
18
- values: new Set(["--repo", "-R", "--hostname", "-H", "--json", "--jq", "--template"]),
69
+ values: new Set(["--json", "--jq", "--template"]),
19
70
  booleans: new Set(["--comments"]),
20
71
  },
21
72
  "pr checks": {
22
- values: new Set(["--repo", "-R", "--hostname", "-H", "--interval", "--json", "--jq", "--template"]),
73
+ values: new Set(["--interval", "--json", "--jq", "--template"]),
23
74
  booleans: new Set(["--watch", "--required", "--fail-fast"]),
24
75
  },
25
76
  "pr status": {
26
- values: new Set(["--repo", "-R", "--hostname", "-H", "--json", "--jq", "--template"]),
77
+ values: new Set(["--json", "--jq", "--template"]),
78
+ booleans: new Set(),
79
+ },
80
+ "pr edit": {
81
+ values: new Set(["--add-label"]),
27
82
  booleans: new Set(),
28
83
  },
84
+ "run view": { values: new Set(["--job", "--json"]), booleans: new Set(["--log-failed"]) },
85
+ "run download": { values: new Set(["-n", "-p", "-D"]), booleans: new Set() },
86
+ "run list": { values: new Set(["--branch", "--commit", "--limit", "--json"]), booleans: new Set() },
29
87
  };
88
+ function positiveGitHubId(value) {
89
+ return /^[1-9]\d{0,19}$/.test(value);
90
+ }
30
91
  function pullRequestTarget(value, linkedRepository) {
31
92
  if (/^\d+$/.test(value))
32
93
  return Number(value) > 0;
@@ -45,12 +106,13 @@ function validateGhOperation(args, linkedRepository, env) {
45
106
  const operation = `${args[0] ?? ""} ${args[1] ?? ""}`;
46
107
  const contract = GH_COMMAND_OPTIONS[operation];
47
108
  if (!contract) {
48
- throw new CliError("github_command_unsupported", "b9s gh supports only read-only gh pr view, gh pr checks, and gh pr status operations.");
109
+ throw new CliError("github_command_unsupported", "b9s gh supports only read-only gh pr view/checks/status and gh run view/download/list operations.");
49
110
  }
50
111
  if (env.GH_REPO && repositoryArgument(env.GH_REPO) !== linkedRepository) {
51
112
  throw new CliError("github_repository_mismatch", `GH_REPO points to ${env.GH_REPO}, not the linked project repository ${linkedRepository}.`);
52
113
  }
53
114
  const positional = [];
115
+ const seen = new Map();
54
116
  for (let index = 2; index < args.length; index += 1) {
55
117
  const arg = args[index];
56
118
  if (arg === "--")
@@ -63,23 +125,22 @@ function validateGhOperation(args, linkedRepository, env) {
63
125
  const flag = equal > 0 ? arg.slice(0, equal) : (arg.startsWith("-R") && arg !== "-R" ? "-R" : arg);
64
126
  const inlineValue = equal > 0 ? arg.slice(equal + 1) : (flag === "-R" && arg !== "-R" ? arg.slice(2) : undefined);
65
127
  if (contract.values.has(flag)) {
128
+ if (seen.has(flag))
129
+ throw new CliError("github_option_unsupported", `${flag} may be supplied only once.`);
66
130
  const value = inlineValue ?? args[index + 1];
67
131
  if (!value || value.startsWith("--"))
68
132
  throw new CliError("usage", `${flag} requires a value.`);
69
133
  if (inlineValue === undefined)
70
134
  index += 1;
71
- if (flag === "--repo" || flag === "-R") {
72
- if (repositoryArgument(value) !== linkedRepository) {
73
- throw new CliError("github_repository_mismatch", `gh target ${value} is not the linked project repository ${linkedRepository}.`);
74
- }
75
- }
76
- else if ((flag === "--hostname" || flag === "-H") && value.toLowerCase() !== "github.com") {
77
- throw new CliError("github_host_unsupported", "b9s gh is pinned to github.com.");
78
- }
135
+ seen.set(flag, value);
79
136
  continue;
80
137
  }
81
- if (contract.booleans.has(flag) && inlineValue === undefined)
138
+ if (contract.booleans.has(flag) && inlineValue === undefined) {
139
+ if (seen.has(flag))
140
+ throw new CliError("github_option_unsupported", `${flag} may be supplied only once.`);
141
+ seen.set(flag, true);
82
142
  continue;
143
+ }
83
144
  throw new CliError("github_option_unsupported", `b9s gh does not support ${arg}.`);
84
145
  }
85
146
  if (operation === "pr status" && positional.length > 0) {
@@ -88,9 +149,57 @@ function validateGhOperation(args, linkedRepository, env) {
88
149
  if ((operation === "pr view" || operation === "pr checks") && positional.some((value) => !pullRequestTarget(value, linkedRepository))) {
89
150
  throw new CliError("github_repository_mismatch", "b9s gh accepts only a pull request number or a github.com URL in the linked repository.");
90
151
  }
152
+ if (operation === "pr edit") {
153
+ if (positional.length !== 1) {
154
+ throw new CliError("github_target_unsupported", "b9s gh pr edit requires one pull request number or URL in the linked repository.");
155
+ }
156
+ if (!pullRequestTarget(positional[0], linkedRepository))
157
+ throw new CliError("github_repository_mismatch", "b9s gh accepts only a pull request number or a github.com URL in the linked repository.");
158
+ const label = seen.get("--add-label");
159
+ if (label !== "ci" && label !== "workflow") {
160
+ throw new CliError("github_label_unsupported", "b9s gh pr edit can add only the allowlisted labels: ci, workflow.");
161
+ }
162
+ }
91
163
  if (positional.length > 1 || (operation === "pr status" && positional.length !== 0)) {
92
164
  throw new CliError("github_target_unsupported", `b9s gh ${operation} accepts at most one pull request target.`);
93
165
  }
166
+ if (operation === "run view" || operation === "run download") {
167
+ if (positional.length !== 1 || !positiveGitHubId(positional[0])) {
168
+ throw new CliError("github_target_unsupported", `b9s gh ${operation} requires one positive numeric GitHub run ID.`);
169
+ }
170
+ }
171
+ if (operation === "run view") {
172
+ const logFailed = seen.has("--log-failed");
173
+ const job = seen.get("--job");
174
+ const json = seen.get("--json");
175
+ if (job !== undefined && !positiveGitHubId(String(job)))
176
+ throw new CliError("github_target_unsupported", "--job requires a positive numeric GitHub job ID.");
177
+ if (job !== undefined && !logFailed)
178
+ throw new CliError("github_option_unsupported", "--job is supported only with --log-failed.");
179
+ if (json !== undefined && (!/^[A-Za-z][A-Za-z0-9]*(,[A-Za-z][A-Za-z0-9]*)*$/.test(String(json)) || logFailed || job !== undefined)) {
180
+ throw new CliError("github_option_unsupported", "run view --json requires a comma-separated field list and cannot be combined with log options.");
181
+ }
182
+ }
183
+ if (operation === "run download" && seen.has("-n") && seen.has("-p")) {
184
+ throw new CliError("github_option_unsupported", "run download accepts either -n <name> or -p <pattern>, not both.");
185
+ }
186
+ if (operation === "run list") {
187
+ if (positional.length !== 0)
188
+ throw new CliError("github_target_unsupported", "b9s gh run list does not accept a run ID.");
189
+ if (seen.has("--branch") && seen.has("--commit"))
190
+ throw new CliError("github_option_unsupported", "run list accepts either --branch or --commit, not both.");
191
+ const commit = seen.get("--commit");
192
+ if (commit !== undefined && !/^[0-9a-f]{7,64}$/i.test(String(commit)))
193
+ throw new CliError("github_option_unsupported", "--commit requires a 7-64 character hexadecimal commit SHA.");
194
+ const limit = seen.get("--limit");
195
+ if (limit !== undefined && (!/^\d+$/.test(String(limit)) || Number(limit) < 1 || Number(limit) > 1000)) {
196
+ throw new CliError("github_option_unsupported", "--limit must be an integer from 1 to 1000.");
197
+ }
198
+ const json = seen.get("--json");
199
+ if (json !== undefined && !/^[A-Za-z][A-Za-z0-9]*(,[A-Za-z][A-Za-z0-9]*)*$/.test(String(json))) {
200
+ throw new CliError("github_option_unsupported", "--json requires a comma-separated field list.");
201
+ }
202
+ }
94
203
  }
95
204
  export async function runGhWithProjectCredential(args, cwd, api, runner = run, parentEnv = process.env) {
96
205
  if (args.length === 0)
@@ -104,7 +213,10 @@ export async function runGhWithProjectCredential(args, cwd, api, runner = run, p
104
213
  throw new CliError("github_repository_required", "b9s gh only supports GitHub HTTPS or SSH repository origins.");
105
214
  }
106
215
  validateGhOperation(args, repository.path, parentEnv);
107
- const credential = await githubCredentialForRepository(repository.path, api, true);
216
+ const needsActionsRead = args[0] === "run";
217
+ const needsPullRequestWrite = args[0] === "pr" && args[1] === "edit";
218
+ const requiredPermission = needsActionsRead ? "actions:read" : needsPullRequestWrite ? "pull_requests:write" : undefined;
219
+ const credential = await githubCredentialForRepository(repository.path, api, true, requiredPermission);
108
220
  if (!credential?.password)
109
221
  throw new CliError("github_credential_missing", "The linked repository did not return a GitHub credential.");
110
222
  // The scoped installation token exists only in the gh child's environment. It is never
@@ -132,6 +244,8 @@ export async function runGhWithProjectCredential(args, cwd, api, runner = run, p
132
244
  encoding: "utf8",
133
245
  env: childEnv,
134
246
  stdio: ["inherit", "pipe", "pipe"],
247
+ // Failed workflow logs can be much larger than the 1 MiB spawnSync default.
248
+ maxBuffer: 64 * 1024 * 1024,
135
249
  });
136
250
  }
137
251
  finally {
@@ -151,6 +265,12 @@ export async function gh(args) {
151
265
  if (!agent.project)
152
266
  throw new CliError("github_not_connected", "b9s gh requires a project-scoped agent identity.");
153
267
  const client = Client.forAgent(agent, undefined, { presence: false });
268
+ if (args[0] === "run" && args[1] === "rerun") {
269
+ const request = parseFailedRerunArgs(args);
270
+ const result = await requestFailedRerun(args, agent.project, (method, path, body) => client.call(method, path, body), request);
271
+ process.stdout.write(`Requested failed-job rerun for run ${request.runId}${request.jobId ? `, job ${request.jobId}` : ""}. Audit: ${typeof result === "object" && result !== null && "audit_id" in result ? String(result.audit_id) : "recorded"}.\n`);
272
+ return 0;
273
+ }
154
274
  const base = `/projects/${encodeURIComponent(agent.project)}/git-credentials`;
155
275
  return runGhWithProjectCredential(args, process.cwd(), (method, _path, body) => client.call(method, base, body));
156
276
  }
@@ -39,7 +39,7 @@ export async function credentialResponse(input, api) {
39
39
  return `username=${credential.username}\npassword=${credential.password}\n\n`;
40
40
  }
41
41
  /** Resolve a short-lived token through the same scoped credential endpoint used by Git. */
42
- export async function githubCredentialForRepository(wanted, api, refuseUnlinkedRepository = false) {
42
+ export async function githubCredentialForRepository(wanted, api, refuseUnlinkedRepository = false, requiredPermission) {
43
43
  const metadata = await api("GET", "");
44
44
  if (!metadata.linked || !metadata.repository) {
45
45
  throw new CliError("github_not_connected", "GitHub is not connected for this project. Connect GitHub in the console to enable repository access.");
@@ -51,7 +51,7 @@ export async function githubCredentialForRepository(wanted, api, refuseUnlinkedR
51
51
  }
52
52
  return null;
53
53
  }
54
- return api("POST", "", {});
54
+ return api("POST", "", requiredPermission ? { required_permission: requiredPermission } : {});
55
55
  }
56
56
  function missingRepositoryPathHint(input) {
57
57
  const request = credentialInput(input);
@@ -0,0 +1,44 @@
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 { projectOf } from "./agent.js";
6
+ export function formatHealthText(data) {
7
+ const scopeLabel = data.project ? `project ${data.project.name}` : "account";
8
+ const lines = [
9
+ `Machinery health · ${scopeLabel} · overall: ${data.overall} (checked ${data.generated_at})`,
10
+ ];
11
+ for (const component of data.components) {
12
+ const status = component.status;
13
+ const since = component.since ? ` · since ${component.since}` : "";
14
+ const cause = component.cause ? ` · ${component.cause}` : "";
15
+ lines.push(` [${status}] ${component.label}${since}${cause}`);
16
+ }
17
+ return lines.join("\n");
18
+ }
19
+ export async function health(p, out) {
20
+ if (p.positionals.length > 1) {
21
+ throw new CliError("usage", "b9s health [--project <p>] [--json]");
22
+ }
23
+ const agentName = resolveAgentName(str(p.flags, "as"));
24
+ const creds = loadAgent(agentName);
25
+ const client = Client.forAgent(creds, undefined);
26
+ const explicitProject = str(p.flags, "project");
27
+ const project = explicitProject !== undefined ? projectOf(p, creds) : creds.project ?? undefined;
28
+ const path = project ? `/projects/${encodeURIComponent(project)}/health` : "/account/machinery-health";
29
+ const data = await client.call("GET", path);
30
+ out.print(formatHealthText(data), data);
31
+ }
32
+ export async function healthAdmin(action, rest, p, out) {
33
+ if (action || rest.length) {
34
+ throw new CliError("usage", "b9s-admin health [--project <p>] [--json]");
35
+ }
36
+ const project = str(p.flags, "project");
37
+ if (project !== undefined && !project.trim()) {
38
+ throw new CliError("usage", "--project must be a non-empty project name");
39
+ }
40
+ const client = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
41
+ const path = project ? `/projects/${encodeURIComponent(project)}/health` : "/account/machinery-health";
42
+ const data = await client.call("GET", path);
43
+ out.print(formatHealthText(data), data);
44
+ }
@@ -4,9 +4,10 @@ import { agentRef, DEFAULT_URL, loadAgent, resolveModel, saveAgent } from "../co
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { join as pathJoin } from "node:path";
7
+ import { homedir } from "node:os";
7
8
  import { CliError } from "../errors.js";
8
9
  import { defaultMachine } from "../git.js";
9
- import { assertMachineInstallNotNewer, ensureMachineInstall } from "../install.js";
10
+ import { assertMachineInstallNotNewer, ensureInstall, isLiveExecutable, readInstall, requireInstall } from "../install.js";
10
11
  import { claudeCheckoutOwner, claudeCheckoutTaken, reconcileCodexHooks, HARNESSES, findIdentityFile, installForHarness, normalizeVendor, readIdentityFile, writeIdentity } from "../harness.js";
11
12
  import { detectVendor } from "../vendor.js";
12
13
  import { CLI_VERSION } from "../version.js";
@@ -103,6 +104,15 @@ export async function join(p, out, expectedProject) {
103
104
  // A newer recorded install must reject this copy before the single-use enrollment token is sent.
104
105
  // Otherwise wait to move/install the machine-wide CLI until credentials have been saved.
105
106
  assertMachineInstallNotNewer(CLI_VERSION);
107
+ // Validate the recorded binary (or canonical bootstrap runtime) before consuming a token.
108
+ if (readInstall()) {
109
+ const recorded = requireInstall();
110
+ if (!isLiveExecutable(recorded.bin))
111
+ throw new CliError("recorded_bin_unavailable", `the recorded b9s executable ${recorded.bin} is not executable`, "Ask the machine operator to repair the recorded install before joining");
112
+ }
113
+ else if (!isLiveExecutable(pathJoin(homedir(), ".local", "node", "bin", "npm")) || !isLiveExecutable(pathJoin(homedir(), ".local", "node", "bin", "node"))) {
114
+ throw new CliError("canonical_node_missing", "the canonical ~/.local/node npm is missing", `Follow ${url}/onboard to prepare Node before joining`);
115
+ }
106
116
  let res;
107
117
  try {
108
118
  res = await fetch(`${url}/enroll`, { method: "POST", headers: { "content-type": "application/json", "user-agent": cliUserAgent() }, body: JSON.stringify({ token, name, vendor, machine }) });
@@ -192,14 +202,16 @@ export function assertVendorMatchesRepo(root, name, vendor, replace) {
192
202
  throw new CliError("vendor_mismatch", `${p} says ${name} runs in ${mapped.join(" and ")} here, but this command detected ${vendor}`, `If ${name} runs in ${mapped[0]}, run this from that harness or pass --vendor ${mapped[0]}. If the file is wrong, pass --replace.`);
193
203
  }
194
204
  /** This machine's one install, at least this CLI's version (installed or upgraded when needed). */
195
- /**
196
- * The machine's install, upgraded to this version if older. An existing record keeps its npm, so a
197
- * join run from another Node (an nvm shell, an npx cache) upgrades the machine's install in place
198
- * instead of moving it there and leaving every watcher on the old copy. Only a first install uses
199
- * the npm next to the running Node.
200
- */
205
+ /** Reuse an existing machine install without rewriting it or restarting services. */
201
206
  function machineInstall() {
202
- return ensureMachineInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`));
207
+ assertMachineInstallNotNewer(CLI_VERSION);
208
+ if (readInstall())
209
+ return requireInstall();
210
+ const npm = pathJoin(homedir(), ".local", "node", "bin", "npm");
211
+ const node = pathJoin(homedir(), ".local", "node", "bin", "node");
212
+ if (!isLiveExecutable(npm) || !isLiveExecutable(node))
213
+ throw new CliError("canonical_node_missing", "the canonical ~/.local/node runtime is missing", "Follow the /onboard instructions before joining");
214
+ return ensureInstall(CLI_VERSION, (m) => process.stderr.write(`b9s: ${m}\n`), npm, true, false, node);
203
215
  }
204
216
  function writeIdentityDryRun(root, vendor, name, replace) {
205
217
  const p = findIdentityFile(root);
@@ -186,6 +186,17 @@ export function bareDigestOf(imageRef) {
186
186
  }
187
187
  const MACHINE_REQUEST_TIMEOUT_MS = 45_000;
188
188
  const MACHINE_NETWORK_RETRY_MS = 5 * 60_000;
189
+ const MACHINE_REPORT_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
190
+ /** Keep malformed local UX job state from making the server reject an otherwise valid machine report. */
191
+ export function validatedUxJobIdsForMachineReport(ids, log) {
192
+ return ids.filter((id) => {
193
+ if (MACHINE_REPORT_UUID.test(id))
194
+ return true;
195
+ const printable = id.replace(/[\u0000-\u001f\u007f]/g, "?").slice(0, 100);
196
+ log(`ignoring non-UUID active UX job id in machine report: ${printable}`);
197
+ return false;
198
+ });
199
+ }
189
200
  const MACHINE_PASS_BUDGET_MS = 4 * 60_000;
190
201
  const MACHINE_WATCHDOG_MS = 5 * 60_000;
191
202
  export function resolvePinnedImageRef(image) {
@@ -2214,7 +2225,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
2214
2225
  report_interval_seconds: reportIntervalSeconds,
2215
2226
  sessions: out,
2216
2227
  capabilities,
2217
- active_ux_job_ids: uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps),
2228
+ active_ux_job_ids: validatedUxJobIdsForMachineReport(uxJobIdsForMachineReport(deps?.uxJobsInFlight, deps?.uxJobDeps), log),
2218
2229
  ...(imageProbes.length ? { image_probes: imageProbes } : {}),
2219
2230
  }, { retryForMs: MACHINE_NETWORK_RETRY_MS });
2220
2231
  const uxSessionHints = desired.map((session) => ({
@@ -0,0 +1,74 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { need, repeated, str } from "../args.js";
3
+ import { consoleLink } from "../console-links.js";
4
+ import { CliError } from "../errors.js";
5
+ const usage = "mock create|list|iterate|approve <project> ... (see b9s-admin --help)";
6
+ function describeStudy(study, project) {
7
+ if (!study || typeof study.id !== "string" || !Array.isArray(study.rounds))
8
+ throw new CliError("bad_response", "design study response omitted study id or rounds; inspect the study before retrying a write");
9
+ const units = study.rounds.flatMap(round => round.variants.map(v => `${v.label}: ${v.work_unit_number == null ? "unavailable" : `WU #${v.work_unit_number}`}`));
10
+ return `Study ${study.id}${units.length ? `\nVariants: ${units.join(", ")}` : ""}\nViewer: ${consoleLink("mock", project, study.id)}`;
11
+ }
12
+ export async function mockAdmin(action, args, p, client, out) {
13
+ const [project, studyId, variantId] = args;
14
+ if (!action || !project || !["create", "list", "iterate", "approve"].includes(action))
15
+ throw new CliError("usage", usage);
16
+ if ((action === "create" || action === "list") && args.length !== 1 || action === "iterate" && args.length !== 2 || action === "approve" && args.length !== 3)
17
+ throw new CliError("usage", usage);
18
+ const base = `/projects/${encodeURIComponent(project)}/design-studies`;
19
+ if (action === "list") {
20
+ const status = str(p.flags, "status");
21
+ if (status !== undefined && !["active", "approved", "archived"].includes(status))
22
+ throw new CliError("usage", "--status must be active, approved, or archived");
23
+ const result = await client.call("GET", `${base}${status ? `?status=${encodeURIComponent(status)}` : ""}`);
24
+ if (!Array.isArray(result.studies))
25
+ throw new CliError("bad_response", "design study list response omitted studies");
26
+ out.print(result.studies.map((s) => `${s.id} [${s.status}] ${s.title}\n ${consoleLink("mock", project, s.id)}`).join("\n") || "No design studies.", result);
27
+ return;
28
+ }
29
+ if (action === "create") {
30
+ const title = need(p.flags, "title"), target = need(p.flags, "target");
31
+ const briefText = str(p.flags, "brief"), briefFile = str(p.flags, "brief-file");
32
+ if ((briefText === undefined) === (briefFile === undefined))
33
+ throw new CliError("usage", "choose exactly one of --brief or --brief-file");
34
+ const brief = briefFile !== undefined ? readFileSync(briefFile, "utf8") : briefText;
35
+ if (!brief.trim())
36
+ throw new CliError("usage", "brief must not be empty");
37
+ const intent = str(p.flags, "intent");
38
+ if (intent !== undefined && !["explore", "refine", "focus", "audit"].includes(intent))
39
+ throw new CliError("usage", "--intent must be explore, refine, focus, or audit");
40
+ const variants = repeated(p, "variant").map(v => v.trim());
41
+ if (variants.length < 1 || variants.length > 8 || variants.some(v => !v || /^(agent|model):\s*$/.test(v)))
42
+ throw new CliError("usage", "supply 1..8 nonempty --variant values");
43
+ let names = new Set();
44
+ if (variants.some(v => !v.startsWith("agent:") && !v.startsWith("model:"))) {
45
+ const agents = await client.call("GET", `/projects/${encodeURIComponent(project)}/agents`);
46
+ if (!Array.isArray(agents.agents) || agents.agents.some((a) => !a || typeof a !== "object" || typeof a.name !== "string"))
47
+ throw new CliError("bad_response", "project agent response omitted agent names");
48
+ names = new Set(agents.agents.map((a) => a.name));
49
+ }
50
+ const specs = variants.map(raw => {
51
+ const v = raw.trim();
52
+ if (v.startsWith("agent:"))
53
+ return { agent_name: v.slice(6).trim() };
54
+ if (v.startsWith("model:"))
55
+ return { model: v.slice(6).trim() };
56
+ return names.has(v) ? { agent_name: v } : { model: v };
57
+ });
58
+ const route = str(p.flags, "route");
59
+ const result = await client.call("POST", base, { title, target_area: target, brief, variants: specs, ...(route !== undefined ? { target_route: route } : {}), ...(intent !== undefined ? { intent_mode: intent } : {}) });
60
+ out.print(describeStudy(result.study, project), { ...result, viewer_url: consoleLink("mock", project, result.study.id) });
61
+ return;
62
+ }
63
+ if (action === "iterate") {
64
+ const variants = repeated(p, "variant");
65
+ if (variants.length > 1 || variants.some(v => !v.trim()))
66
+ throw new CliError("usage", "iterate accepts at most one nonempty --variant");
67
+ const note = str(p.flags, "note");
68
+ const result = await client.call("POST", `${base}/${encodeURIComponent(studyId)}/iterate`, { ...(variants.length ? { variant_id: variants[0] } : {}), ...(note !== undefined ? { note } : {}) });
69
+ out.print(describeStudy(result.study, project), { ...result, viewer_url: consoleLink("mock", project, result.study.id) });
70
+ return;
71
+ }
72
+ const result = await client.call("POST", `${base}/${encodeURIComponent(studyId)}/approve`, { variant_id: variantId });
73
+ out.print(describeStudy(result.study, project), { ...result, viewer_url: consoleLink("mock", project, result.study.id) });
74
+ }