benignswarm 0.12.166 → 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.
@@ -0,0 +1,76 @@
1
+ import { arch, platform } from 'node:os';
2
+ const TARGETS = {
3
+ 'merge-train-gate-api-tests-pg': { stage: 'api tests', engine: 'pg', workspace: 'apps/api' },
4
+ 'merge-train-gate-api-tests-miniflare': { stage: 'api tests', engine: 'miniflare', workspace: 'apps/api' },
5
+ 'merge-train-gate-cli-tests-node': { stage: 'cli tests', engine: 'node', workspace: 'packages/cli' },
6
+ 'merge-train-gate-web-tests-node': { stage: 'web tests', engine: 'node', workspace: 'apps/web' },
7
+ };
8
+ /** Fetch every page; never turn an unavailable or malformed snapshot into an empty one. */
9
+ export async function loadGateQuarantines(client, project, branch) {
10
+ const expectations = [];
11
+ const seenCursors = new Set();
12
+ let cursor;
13
+ do {
14
+ const query = cursor ? `?limit=100&cursor=${encodeURIComponent(cursor)}` : '?limit=100';
15
+ const page = await client.call('GET', `/projects/${encodeURIComponent(project)}/test-expectations${query}`);
16
+ if (!Array.isArray(page?.expectations))
17
+ throw new Error('test-expectations response omitted its expectations array');
18
+ expectations.push(...page.expectations);
19
+ if (page.next_cursor !== undefined && (typeof page.next_cursor !== 'string' || !page.next_cursor || seenCursors.has(page.next_cursor)))
20
+ throw new Error('test-expectations returned an invalid or repeated cursor');
21
+ cursor = page.next_cursor;
22
+ if (cursor)
23
+ seenCursors.add(cursor);
24
+ } while (cursor);
25
+ const runCache = new Map();
26
+ const result = [];
27
+ for (const expectation of expectations) {
28
+ if (expectation?.status !== 'quarantined')
29
+ continue;
30
+ if (typeof expectation.target_key !== 'string' || typeof expectation.expires_at !== 'string' || !Number.isFinite(Date.parse(expectation.expires_at)))
31
+ throw new Error('quarantined expectation has invalid target or expiry');
32
+ if (Date.parse(expectation.expires_at) <= Date.now())
33
+ continue;
34
+ let target;
35
+ try {
36
+ target = JSON.parse(expectation.target_key);
37
+ }
38
+ catch {
39
+ throw new Error('quarantined expectation has an invalid target key');
40
+ }
41
+ if (!target || typeof target !== 'object' || Array.isArray(target))
42
+ throw new Error('quarantined expectation has an invalid target key');
43
+ const spec = TARGETS[target.target_config];
44
+ if (!spec || target.branch !== branch || target.package !== spec.workspace || target.workspace != null)
45
+ continue;
46
+ const os = platform() === 'darwin' ? 'macos' : platform() === 'win32' ? 'windows' : platform();
47
+ if (target.runner?.os !== os || target.runner?.arch !== arch() || target.runner?.runtime !== `node-${process.versions.node}` || target.runner?.sandbox !== 'unknown' || target.runner?.toolchain != null || target.runner?.container != null || target.runner?.test_configuration != null)
48
+ continue;
49
+ if (typeof expectation.opened_from_run_id !== 'string' || typeof expectation.test_id !== 'string')
50
+ throw new Error('gate quarantine is missing its report or test identity');
51
+ let run = runCache.get(expectation.opened_from_run_id);
52
+ if (!run) {
53
+ const response = await client.call('GET', `/projects/${encodeURIComponent(project)}/test-runs/${encodeURIComponent(expectation.opened_from_run_id)}`);
54
+ run = response?.run;
55
+ if (!run || !Array.isArray(run.tests))
56
+ throw new Error('gate quarantine source report is unavailable');
57
+ runCache.set(expectation.opened_from_run_id, run);
58
+ }
59
+ if (run.source?.package !== spec.workspace || run.source?.target_config !== target.target_config || run.source?.target_branch !== branch || !run.artifact?.evidence_id)
60
+ throw new Error('gate quarantine source report does not match its target');
61
+ const matches = run.tests.filter((test) => test?.id === expectation.test_id && test.identity_comparable !== false);
62
+ if (matches.length !== 1 || typeof matches[0].suite !== 'string')
63
+ throw new Error('gate quarantine does not identify exactly one comparable reported test');
64
+ const suite = matches[0].suite;
65
+ if (!/^(test|src)\/[A-Za-z0-9_.\-/]+$/.test(suite) || suite.split('/').some((part) => !part || part === '.' || part === '..'))
66
+ throw new Error('gate quarantine source report has an unsafe test path');
67
+ const prefix = `${suite}/${suite} :: `;
68
+ if (!expectation.test_id.startsWith(prefix))
69
+ throw new Error('gate quarantine source report has an ambiguous test identity');
70
+ const test = expectation.test_id.slice(prefix.length);
71
+ if (!test || test === '(suite failure)' || /[\x00-\x1f\x7f]/.test(test))
72
+ throw new Error('gate quarantine source report has an invalid test name');
73
+ result.push({ stage: spec.stage, engine: spec.engine, file: `${spec.workspace}/${suite}`, test, expires_at: new Date(expectation.expires_at).toISOString() });
74
+ }
75
+ return result;
76
+ }
@@ -0,0 +1,45 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { platform, arch } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { parseTestRunReport } from './test-results.js';
6
+ const STAGES = [
7
+ { stage: 'api tests', engine: 'pg', workspace: 'apps/api', filename: 'api-pg.xml' },
8
+ { stage: 'api tests', engine: 'miniflare', workspace: 'apps/api', filename: 'api-miniflare.xml' },
9
+ { stage: 'cli tests', engine: 'node', workspace: 'packages/cli', filename: 'cli.xml' },
10
+ { stage: 'web tests', engine: 'node', workspace: 'apps/web', filename: 'web.xml' },
11
+ ];
12
+ /** Import real failing Vitest reports as canonical test runs for later quarantine decisions. */
13
+ export async function importFailingGateReports(options) {
14
+ if (!/^[A-Za-z0-9-]{1,100}$/.test(options.trainRunId))
15
+ throw new Error('invalid merge train run ID');
16
+ const imported = [];
17
+ for (const item of STAGES) {
18
+ const path = join(options.dir, item.filename);
19
+ if (!existsSync(path))
20
+ continue; // A pre-test or suite startup error has no importable report.
21
+ const bytes = readFileSync(path);
22
+ const metadata = {
23
+ schema_version: 1,
24
+ source: { commit: options.candidate, target_commit: options.base, target_branch: options.branch, package: item.workspace, target_config: `merge-train-gate-${item.stage.replaceAll(" ", "-")}-${item.engine}` },
25
+ invocation: { argv: ['scripts/gate.sh', item.stage], cwd: '.' },
26
+ runner: { machine: options.creds.machine, os: platform() === 'darwin' ? 'macos' : platform() === 'win32' ? 'windows' : platform(), arch: arch(), runtime: `node-${process.versions.node}`, sandbox: 'unknown' },
27
+ run: { started_at: options.startedAt, ended_at: options.endedAt, exit_status: 1, state: 'completed' },
28
+ };
29
+ const draft = parseTestRunReport(item.filename, bytes, Buffer.from(JSON.stringify(metadata)));
30
+ if (!draft.tests.some(test => test.outcome === 'failed'))
31
+ continue;
32
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
33
+ const response = await fetch(`${options.creds.url.replace(/\/$/, '')}/projects/${encodeURIComponent(options.project)}/evidence`, {
34
+ method: 'POST', headers: { ...options.client.headers(), 'content-type': 'application/xml', 'x-bschat-sha256': sha256, 'x-bschat-filename': `train-${options.trainRunId}-${item.filename}`, 'x-bschat-kind': 'test' }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(30_000),
35
+ });
36
+ const result = await response.json();
37
+ if (!response.ok || typeof result?.evidence?.id !== 'string' || result.evidence.sha256 !== sha256)
38
+ throw new Error(`failed to upload ${item.stage} report (HTTP ${response.status})`);
39
+ const created = await options.client.call('POST', `/projects/${encodeURIComponent(options.project)}/test-runs`, { ...draft, artifact: { evidence_id: result.evidence.id, sha256 } });
40
+ if (typeof created?.run?.run_id !== 'string')
41
+ throw new Error(`${item.stage} report import did not return a run ID`);
42
+ imported.push({ stage: item.stage, runId: created.run.run_id });
43
+ }
44
+ return imported;
45
+ }
package/dist/help.js CHANGED
@@ -29,7 +29,7 @@ Mac capacity/signing API (profiles, leases, signer-only references, TestFlight a
29
29
  Standing rules are resolved by account, project, role, and exact-agent scope. GET /agents/me/standing-rules and GET /projects/:p/standing-rules return complete authorized sets and fingerprints; their separate ack endpoints accept only a current fingerprint after complete delivery. Operators and authorized assigners manage rules through the API; limits, compatibility confirmation, audit, and authorization are in packages/skill/references/api.md. Console management and chat promotion are WU #313.
30
30
  Claude Code, Codex, and Antigravity SessionStart hooks retrieve the complete effective rules at fresh start, resume, compaction, and clear into a new thread. They acknowledge only after complete output; an unavailable or over-budget payload points to b9s process without acknowledgment. b9s me shows concise rule text and acknowledgment, b9s process shows the full project rules and acknowledges that fingerprint after display, and b9s resume includes the effective rulesets.
31
31
 
32
- GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Open or reuse a PR for a unit's pushed branch with b9s wu pr <n>; add --auto-merge to ask GitHub to merge it after required checks pass. Use b9s gh <args> for read-only PR view/checks/status and workflow run view/download/list from that linked repository. Run views support --log-failed, --job <job-id> --log-failed, or --json <fields>; downloads support -n <name> or -p <pattern> and -D <dir>; run lists support --branch, --commit, --limit, and --json. Rerun transient failures with b9s gh run rerun <run-id> --failed [--job <job-id>] --reason "..."; full-run reruns are refused, with a cap of two reruns per project/head SHA and one rerun per run ID per five minutes. This server-proxied operation requires Actions: write on the linked GitHub App and keeps credentials server-side. Workflow read commands require the linked GitHub App to grant Actions: read. The wrapper pins GH_HOST and GH_REPO, requests repository-scoped credentials, and sets GH_TOKEN only in the gh child environment. Other commands, hosts, repositories, and repository/host override flags are refused before token issuance; the token is never printed or stored. The API scopes its installation token to the linked repository, stores the PR URL on the unit, and never prints or persists the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
32
+ GitHub connection and repository status are available in the console and through b9s-admin github status and b9s-admin project github <project> status|unlink. A repository link enables agent credentials without requiring a ruleset. An agent can inspect its effective repository permission with GET /projects/:p/git-credentials; a project admin can inspect a named agent with GET /projects/:p/git-credentials?agent=<name-or-id>. Each issuance records its permission reason without storing the token. Open or reuse a PR for a unit's pushed branch with b9s wu pr <n>; add --auto-merge to ask GitHub to merge it after required checks pass. Use b9s gh <args> for PR view/checks/status, workflow run view/download/list, and the guarded gh pr edit <pr-number> --add-label <ci|workflow> operation from that linked repository. Label edits accept exactly one allowlisted ci or workflow label; removals, other labels, and non-linked PR targets are refused before token issuance. PR write requires repository-write role access and Pull requests: write on the linked GitHub App. Run views support --log-failed, --job <job-id> --log-failed, or --json <fields>; downloads support -n <name> or -p <pattern> and -D <dir>; run lists support --branch, --commit, --limit, and --json. Rerun transient failures with b9s gh run rerun <run-id> --failed [--job <job-id>] --reason "..."; full-run reruns are refused, with a cap of two reruns per project/head SHA and one rerun per run ID per five minutes. This server-proxied operation requires Actions: write on the linked GitHub App and keeps credentials server-side. Workflow read commands require the linked GitHub App to grant Actions: read. The wrapper pins GH_HOST and GH_REPO, requests repository-scoped credentials, and sets GH_TOKEN only in the gh child environment. Other commands, hosts, repositories, and repository/host override flags are refused before token issuance; the token is never printed or stored. The API scopes its installation token to the linked repository, stores the PR URL on the unit, and never prints or persists the token. Verify an exact target ruleset in Account -> GitHub connection before enabling hosted merge; the CLI cannot perform this owner OAuth step. Disconnect an installation with b9s-admin github disconnect <installation-id>. Hosted merge execution and status use b9s wu merge <n> and b9s wu merge status <n>; they call POST/GET /projects/:p/work-units/:n/merge and never inspect local Git state. API role checks use merge.merged_by and operator override; operator_hold is checked, merges serialize in MergeTargetDO, and retries reconcile idempotently. Manual wu done remains disabled for enabled linked targets. Enable with b9s-admin project hosted-merge <project> enable --confirm-bypass-signal only after ruleset verification and the live GitHub bypass-change check; disable with b9s-admin project hosted-merge <project> disable. The console control is WU #196. App setup steps are in packages/skill-admin/references/setup.md.
33
33
 
34
34
  Environment problems: agents report bounded, redacted observations with b9s environment report; reports use scoped project or machine access, account-scoped evidence, and only the agent's own blocked units. Agents can append observations but cannot claim, diagnose, or resolve issues. Operators and agents whose role has own_environment_problems can manage visible issues. Operators use Account → Environment in the console to filter and inspect issues, claim/assign/reassign, record diagnoses, and resolve with a note and verification. Manual diagnoses use source agent; doctor/daemon provenance is for actual check results. Banner links open the same issue detail with impact context. Issue detail links active notices in the same scope and current machine-session faults related to its machine or explicitly linked unit owner. The read-only steward summary lists active linked issues and currently waiting linked units, without publishing notices or creating work. Machine issue views respect linked-project access. Spending impact is unknown and creates no banner until unit-attributed telemetry lands in WU #236; see packages/skill/references/api.md.
35
35
 
@@ -46,7 +46,7 @@ Agent commands
46
46
  b9s identities list saved identities on this machine
47
47
  b9s me who am I, role, permissions, channels, standing rules and acknowledgment; --json includes your machine sessions
48
48
  b9s git-credential get|store|erase linked GitHub helper; Git must send the repo path (credential.https://github.com.useHttpPath true)
49
- b9s gh <gh arguments> read PR status and Actions run details, or request a guarded failed-job rerun from this linked checkout
49
+ b9s gh <gh arguments> inspect PRs and Actions, add an allowlisted PR label, or request a guarded failed-job rerun
50
50
  b9s gh run rerun <run-id> --failed [--job <job-id>] --reason "..." request an audited failed-job rerun (max 2 per head SHA)
51
51
  b9s resume compact recovery brief: units, reviews, asks, slices, decisions, outcomes, process, standing rules and notices
52
52
  b9s notice add --project <p> "<text>" [--until <time>] [--command-pattern <regex>]
@@ -76,24 +76,25 @@ Agent commands
76
76
  b9s rule supersede <rule-id> --text "..." [--step cut|start|submit|verdict|merge|close] [--expires-at <UTC>] [--conflicts-with id,id] --confirm-compatible
77
77
  b9s rule retire <rule-id> authorized assigner; project agent credentials restrict scope
78
78
  review current charter/agreements before --confirm-compatible; no rule is inferred from chat
79
- b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
79
+ b9s wu open "<title>" --scope "..." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--review-hold] [--force] [--evidence id[,id...]] [--target <branch>] [--here] [--json] open a work unit in its own
80
80
  worktree; tags come from the vocabulary; --target is the branch it lands in (default: the
81
81
  process target), e.g. a lane branch; wu target <n> <branch|default> changes it before review
82
- b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--json] hand out a unit (assigner roles);
82
+ b9s wu assign "<title>" --to <agent|auto|queue> --scope ".." [--summary "plain work summary"] [--scope-file <path> | --scope-from <n>] [--tags a,b] [--lands-with <n>] [--reworks n,m] [--after <n>[,<m>]] [--requires cap,cap] [--session-harness h] [--session-sandbox mode] [--session-machine name] [--session-machine-label label] [--priority urgent|normal] [--milestone <key>] [--branch <branch>] [--base <branch-or-sha>] [--continue] [--hold] [--review-hold] [--evidence id[,id...]] [--force] [--replay-of n] [--template] [--reason "why"] [--override-unwakeable --override-reason "why"] [--json] hand out a unit (assigner roles);
83
83
  --to auto picks the active qualified worker with the lightest load; it queues when nobody fits,
84
84
  reports why candidates were passed over, and the sweep chases it;
85
85
  --to queue waits deliberately; naming a busy worker reserves it for them (theirs when free,
86
86
  anyone's after the takeover window); --hold keeps it assigned to them however long it takes;
87
+ --review-hold keeps it queued and undispatched until an assigner or operator releases it;
87
88
  --branch pins a branch (--base records its starting commit or branch, else --after's head or target; --continue marks an existing pushed branch);
88
89
  --template --tags a,b prints the scope skeleton; --force records missing required sections, including for queue;
89
90
  assignment reports advisory scope suggestions from recorded causes, with counts and source dates; nothing is applied.
90
91
  Creation prints WU #<n> created first; --json returns {number,title,status,owner}.
91
92
  b9s wu list --json keeps complete titles.
92
- b9s wu assign <n> --to <agent> [--reason "why"] reassign an assigned or queued unit in place
93
+ b9s wu assign <n> --to <agent> [--reason "why"] [--override-unwakeable --override-reason "why"] reassign an assigned or queued unit in place
93
94
  b9s wu lands-with <n> <base-unit|clear> set or clear the base WU whose landing gates this unit
94
95
  b9s wu priority <n> urgent|normal --note "why this priority changed" operator or assigner: change dispatch priority; urgent work is dispatched first
95
96
  b9s wu expedite <n> [--confirm-agent <id> --confirm-parked <n>] operator or assigner: preview exact targets first, then confirm them; 409 means preview again
96
- b9s wu take <n> [--to <agent>] [--reason "why"] pull a unit or hand it to someone
97
+ b9s wu take <n> [--to <agent>] [--reason "why"] [--override-unwakeable --override-reason "why"] pull a unit or hand it to someone
97
98
  reason is required when an assigner uses its assign_outside_qualifications role capability
98
99
  b9s wu next take the oldest queued unit you qualify for
99
100
  b9s wu decline <n> --note "why" [--waits-on <milestone,...> | --defer] decline and requeue an assignment (use wu abandon to close); a steward planning unit
@@ -200,6 +201,7 @@ Machine placement enforces configured session slots and reports machine pressure
200
201
  b9s wu explain <n> "..." the same for a unit's question waiting on the operator
201
202
  b9s wu tags <n> --add a --remove b retag (owner before review, a reviewer during it; may add a reviewer)
202
203
  b9s wu kind <n> --kind <kind> --reason "why" assigner/operator overrides the progress-view kind, with an audit event
204
+ b9s wu release-for-review <n>[,<n>...] assigner or operator: release units explicitly held before dispatch
203
205
  b9s wu hold <n> --note ".." operator or assigner: no verdict and no merge until the owner resubmits;
204
206
  wu release <n> [--note ..] lifts it earlier
205
207
  b9s wu evidence replace <n> <old> <new> [--note ".."] owner replaces attached evidence; old id is retained in the unit history
@@ -230,11 +232,16 @@ Machine placement enforces configured session slots and reports machine pressure
230
232
  threads and DeepSeek keep it where no file shows it; Claude Code's hook reads it itself)
231
233
  b9s mock upload <studyId> <variantId> <file.html> [--summary <text>] upload and attach a mock
232
234
  b9s mock gaps <studyId> --json <gapsJson> | --clear submit gaps (field, missing, build_summary, adapt_summary, omit_summary?, prerequisite_tags?)
235
+ b9s mock review show --group <groupId> | --study <studyId> inspect the platform review, shortlisted mocks, gaps, operator direction and proposals
236
+ b9s mock review gaps <reviewId> --json <gapsArray> submit de-duplicated platform findings [{title,description}]
237
+ b9s mock review propose <reviewId> --json <proposalsArray> turn operator direction into draft prerequisite units [{title,scope,tags}]
238
+ b9s mock review revise <reviewId> iterate every shortlisted mock after operator confirmation
233
239
  b9s flow-agent run [--force] [--admin <name>] [--project <name>] request a Flow Agent tick
234
240
  b9s flow-agent status Flow Agent: autonomy level, actions this hour, rolling account budget, recent actions
235
241
  b9s flow-agent prompt [--level advisory|flow_ops|autonomous_ops]
236
242
  the Flow Agent's operating rules for the project's level (or --level): hard
237
243
  invariants, what the level may change, limits and the per-wake-up loop
244
+ b9s health [--project <p>] [--json] server-derived machinery health per component (ok, degraded, stopped, since-when, cause)
238
245
  b9s hook claude-code [--event E] harness hook: prints new inbox items as hook JSON (installed by join)
239
246
  b9s watch --exec "<cmd>" [--interval seconds] [--unacked-after seconds] [--follow-delay seconds] [--startup-jitter-seconds 0..60] [--once] [--full] [--env A,B] [--activity path] [--prune] [--turn] [--harness codex|claude-code|dsh|antigravity] [--provider anthropic|deepseek] [--session id] [--machine-session-id uuid] [--turn-timeout min] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--turn-claude-runtime JSON] [--turn-antigravity-runtime JSON] [--service|--launchd] event bridge: queue ONE numbered wake-up when something new arrives, then
240
247
  nothing more, for any reason, until the agent runs b9s wake ack <n>. An
@@ -452,7 +459,7 @@ Project agents inspect work waits with b9s wu stalled [--all]; its default inclu
452
459
  max_actions_per_hour}. The steward wakes its holders on coalesced stall, dependency,
453
460
  send-back and merge-train triggers (3-minute debounce) and a 30-minute sweep while a unit is open;
454
461
  the agent reads its rules with b9s flow-agent prompt and shared account budget with b9s flow-agent status.
455
- b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] operator: reassign a unit in place
462
+ b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] [--override-unwakeable --override-reason "why"] operator: reassign a unit in place
456
463
  b9s-admin wu abandon <project> <n> --note "why" operator: close work that is no longer needed
457
464
  b9s-admin wu supersede <project> <n> --by <m> operator: close this unit as continued by #m
458
465
  b9s-admin wu park|unpark <project> <n> --note "why" operator: park open or sent-back work, or return parked work to open
@@ -502,6 +509,8 @@ Project agents inspect work waits with b9s wu stalled [--all]; its default inclu
502
509
  b9s-admin milestone <project> gap-units <key> --units n,m
503
510
  b9s-admin flow [--project <p>] [--from <UTC date/time>] [--to <UTC date/time>] [--json]
504
511
  read-only state counts, waits, qualified worker/reviewer capacity, critical paths, attention, trends, freshness and coverage
512
+ b9s-admin health [--project <p>] [--json]
513
+ server-derived machinery health per component for one project or rolled up across the account
505
514
  b9s-admin diag load [--since 1h|24h|7d] [--route <pattern>] [--json]
506
515
  anomalous production request and cron load; scoped to this account unless this is the verified platform account
507
516
  b9s-admin role edit <name> [--project p] --reviews a,b --works c --trials d which tags a role reviews, works and trials ("*" all, "" none)
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@ import { watch } from "./commands/watch.js";
11
11
  import { feedback } from "./commands/feedback.js";
12
12
  import { goal } from "./commands/goal.js";
13
13
  import { flowAgent } from "./commands/flow-agent.js";
14
+ import { health } from "./commands/health.js";
14
15
  import { wake } from "./commands/wake.js";
15
16
  import { turn } from "./commands/turn.js";
16
17
  import { antigravity } from "./commands/antigravity.js";
@@ -92,6 +93,7 @@ const COMMANDS = {
92
93
  feedback,
93
94
  goal,
94
95
  "flow-agent": flowAgent,
96
+ health,
95
97
  wake,
96
98
  turn,
97
99
  antigravity,
@@ -1,4 +1,6 @@
1
- import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
1
+ import { loadGateQuarantines } from "./gate-quarantines.js";
2
+ import { importFailingGateReports } from "./gate-test-reports.js";
3
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
4
  import { randomBytes } from "node:crypto";
3
5
  import { dirname, join } from "node:path";
4
6
  import { agentRef } from "./config.js";
@@ -28,7 +30,7 @@ export function shaMatches(left, right) {
28
30
  return false;
29
31
  return a.startsWith(b) || b.startsWith(a);
30
32
  }
31
- export const TRAIN_GATE_STAGES = ["typecheck", "api tests", "cli tests", "web tests", "web build", "cli build", "published CLI contract"];
33
+ export const TRAIN_GATE_STAGES = ["deployment script tests", "migration preflight", "pg baseline", "typecheck", "api tests", "cli tests", "web tests", "web build", "cli build", "published CLI contract"];
32
34
  export function supportedTrainGateStage(stage) {
33
35
  return TRAIN_GATE_STAGES.find(name => name === stage);
34
36
  }
@@ -540,6 +542,12 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
540
542
  throw new Error(`could not inspect merged migration paths: ${(changed.stderr || changed.stdout).trim().slice(0, 300)}`);
541
543
  if (!pgBaselineRefreshRequired(changed.stdout.split(/\r?\n/).filter(Boolean)))
542
544
  return 0;
545
+ const apiPackage = JSON.parse(readFileSync(join(h.worktreeDir, "apps/api/package.json"), "utf8"));
546
+ const baselineGenerator = apiPackage.scripts?.["pg:generate-baseline"];
547
+ if (typeof baselineGenerator !== "string") {
548
+ h.onLogLine("no PostgreSQL baseline generator in this tree; skipping refresh");
549
+ return 0;
550
+ }
543
551
  const generate = await h.runner("npm", ["run", "pg:generate-baseline", "-w", "apps/api"], {
544
552
  cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
545
553
  });
@@ -685,15 +693,33 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
685
693
  const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
686
694
  throw new CliError(code, `job ${lockContext?.jobId ?? job.id} stopped because its lock lease could not be renewed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
687
695
  };
696
+ const gateSpec = resolveTrainGateCommand(trainRun.gate_command, anchorUnit, candidateSha, h.worktreeDir);
697
+ const usesRepositoryGate = gateSpec?.execArgs[0] === "scripts/gate.sh";
698
+ let quarantineSnapshot;
688
699
  const runGateAtHead = async (stepName, unitForCmd, headSha, options = {}) => {
689
700
  throwIfHeartbeatFailed();
690
701
  const worktreeDir = options.worktreeDir ?? h.worktreeDir;
691
702
  const gateEnv = { ...(options.env ?? lockedEnv) };
692
703
  delete gateEnv.GATE_STAGE;
704
+ delete gateEnv.B9S_GATE_QUARANTINES;
705
+ delete gateEnv.B9S_GATE_TEST_ENGINE;
706
+ delete gateEnv.B9S_GATE_REPORT_DIR;
707
+ gateEnv.B9S_GATE_NODE_VERSION = process.versions.node;
708
+ if (quarantineSnapshot !== undefined)
709
+ gateEnv.B9S_GATE_QUARANTINES = quarantineSnapshot;
710
+ if (options.scanReceipt) {
711
+ const reportDir = join(gateArtifactDir, "test-reports");
712
+ rmSync(reportDir, { recursive: true, force: true });
713
+ mkdirSync(reportDir, { recursive: true });
714
+ gateEnv.B9S_GATE_REPORT_DIR = reportDir;
715
+ }
693
716
  const lockContextForGate = options.lockContext ?? lockContext;
694
717
  const spec = resolveTrainGateCommand(trainRun.gate_command, unitForCmd, headSha, worktreeDir, options.stage);
695
718
  if (!spec)
696
719
  return { status: 0, output: "" };
720
+ if (quarantineSnapshot && quarantineSnapshot !== "[]" && spec.execArgs[0] === "scripts/gate.sh" && !existsSync(join(worktreeDir, "scripts", "gate-quarantine-report.mjs"))) {
721
+ throw new CliError("quarantine_unsupported", `gate checkout ${headSha} cannot apply the active quarantine snapshot`);
722
+ }
697
723
  return h.runStep(stepName, async () => {
698
724
  let output = "";
699
725
  const res = await h.runner(spec.execCmd, spec.execArgs, {
@@ -788,6 +814,15 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
788
814
  BSCHAT_UX_JOB_ARTIFACT_DIR: artifactDir,
789
815
  };
790
816
  delete probeEnv.GATE_STAGE;
817
+ delete probeEnv.B9S_GATE_QUARANTINES;
818
+ delete probeEnv.B9S_GATE_REPORT_DIR;
819
+ delete probeEnv.B9S_GATE_TEST_ENGINE;
820
+ probeEnv.B9S_GATE_NODE_VERSION = process.versions.node;
821
+ if (quarantineSnapshot !== undefined)
822
+ probeEnv.B9S_GATE_QUARANTINES = quarantineSnapshot;
823
+ if (quarantineSnapshot && quarantineSnapshot !== "[]" && spec.execArgs[0] === "scripts/gate.sh" && !existsSync(join(probeWorktree, "scripts", "gate-quarantine-report.mjs"))) {
824
+ throw new CliError("quarantine_unsupported", `probe checkout ${probeSha} cannot apply the active quarantine snapshot`);
825
+ }
791
826
  if (probeLock?.jobId)
792
827
  probeEnv.B9S_LOCK_JOB_ID = probeLock.jobId;
793
828
  if (!Number.isSafeInteger(probeLock?.slot) || probeLock.slot < 1 || probeLock.slot > 3) {
@@ -915,7 +950,21 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
915
950
  };
916
951
  const scanner = createGateMarkerScanner();
917
952
  try {
953
+ if (usesRepositoryGate)
954
+ quarantineSnapshot = JSON.stringify(await loadGateQuarantines(h.agentClient, job.project, trainRun.target_branch));
955
+ const gateStartedAt = new Date().toISOString();
918
956
  const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha, { scanReceipt: true, keepSuccessfulResultOnHeartbeatError: true });
957
+ if (mainRun.status !== 0) {
958
+ const imported = await importFailingGateReports({
959
+ dir: join(gateArtifactDir, "test-reports"), project: job.project, trainRunId: trainRun.id, branch: trainRun.target_branch,
960
+ candidate: candidateSha, base: baseSha, startedAt: gateStartedAt, endedAt: new Date().toISOString(),
961
+ creds: h.agentCreds, client: h.agentClient,
962
+ });
963
+ for (const report of imported)
964
+ h.onLogLine(`merge-train ${trainRun.id}: imported ${report.stage} report ${report.runId}`);
965
+ if (!imported.length)
966
+ h.onLogLine(`merge-train ${trainRun.id}: failure has no importable individual test report`);
967
+ }
919
968
  scanner.push("", true);
920
969
  const scanResult = scanner.result();
921
970
  gateOutputText = mainRun.output;