benignswarm 0.12.166 → 0.12.168

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/harnesses.js CHANGED
@@ -230,11 +230,31 @@ export function dshResultError(text) {
230
230
  }
231
231
  /** DeepSeek emits per-step usage; sum it over the accumulated per-agent turn log. */
232
232
  export function dshUsage(text, since, until) {
233
+ function* records() {
234
+ for (const line of text.split("\n")) {
235
+ try {
236
+ const value = JSON.parse(line);
237
+ if (value !== null && typeof value === "object" && !Array.isArray(value))
238
+ yield value;
239
+ }
240
+ catch { /* a line may still be streaming */ }
241
+ }
242
+ }
243
+ return dshUsageFromRecords(records(), since, until);
244
+ }
245
+ /** DeepSeek per-step usage over already parsed JSONL records. */
246
+ export function dshUsageFromRecords(records, since, until) {
247
+ return dshUsageFromRecordsDetailed(records, since, until).usage;
248
+ }
249
+ export function dshUsageFromRecordsDetailed(records, since, until) {
233
250
  const result = { input: 0, cached_input: 0, output: 0, reasoning: 0, total: 0 };
234
251
  const window = since !== undefined && until !== undefined ? { since: Date.parse(since), until: Date.parse(until) } : null;
235
252
  let invocationAt = null;
236
- for (const e of dshEvents(text)) {
253
+ let hasInvocationStart = false;
254
+ for (const row of records) {
255
+ const e = row;
237
256
  if (e.type === "b9s_invocation_start") {
257
+ hasInvocationStart = true;
238
258
  invocationAt = typeof e.at === "string" ? Date.parse(e.at) : null;
239
259
  continue;
240
260
  }
@@ -251,7 +271,7 @@ export function dshUsage(text, since, until) {
251
271
  result.output += e.usage.outputTokens ?? 0;
252
272
  }
253
273
  result.total = result.input + result.output;
254
- return result;
274
+ return { usage: result, hasInvocationStart };
255
275
  }
256
276
  /** Map the user's selected sandbox to dsh's native permission mode and writable roots. */
257
277
  export function dshSettings(sandbox, cwd, b9sHome, extraWritable = []) {
package/dist/heartbeat.js CHANGED
@@ -84,15 +84,25 @@ export async function heartbeatIfActive(client, src, prev, windowSeconds, log) {
84
84
  return cur;
85
85
  }
86
86
  /** A persistent watcher proves its own wake path independently of harness file activity. */
87
- export async function reportWatcherHeartbeat(client, intervalSeconds, mode, turn) {
87
+ export async function reportWatcherHeartbeat(client, intervalSeconds, mode, turn, wakeAttempt) {
88
88
  await client.call("POST", "/agents/me/watcher/heartbeat", {
89
89
  interval_seconds: intervalSeconds,
90
90
  mode,
91
91
  turn_started_at: mode === "turn" ? turn?.startedAt ?? null : null,
92
92
  work_unit_number: mode === "turn" ? turn?.binding?.work_unit_number ?? null : null,
93
93
  assignment_event_id: mode === "turn" ? turn?.binding?.assignment_event_id ?? null : null,
94
+ ...(wakeAttempt ? { wake_attempt: wakeAttempt } : {}),
94
95
  });
95
96
  }
97
+ /** Immediately report a changed queue wake outcome instead of waiting for the next poll heartbeat. */
98
+ export async function reportWakeOutcomeChange(client, intervalSeconds, previous, current, report = reportWatcherHeartbeat) {
99
+ if (JSON.stringify(previous ?? null) === JSON.stringify(current ?? null))
100
+ return false;
101
+ if (!current)
102
+ throw new Error("changed watcher wake outcome is missing its current state");
103
+ await report(client, intervalSeconds, "queue", { startedAt: null, binding: null }, current);
104
+ return true;
105
+ }
96
106
  /**
97
107
  * The hook variant: the hook running is itself the evidence, so report now, throttled by the
98
108
  * caller. `goal` undefined means "unknown, keep what you have"; null means "no goal is set".
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,
package/dist/jsonl.js ADDED
@@ -0,0 +1,113 @@
1
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
2
+ import { constants as bufferConstants } from "node:buffer";
3
+ import { TextDecoder } from "node:util";
4
+ export const JSONL_CHUNK_BYTES = 64 * 1024;
5
+ // UTF-8 can use up to three bytes per UTF-16 code unit. This ceiling therefore accepts any
6
+ // valid UTF-8 record whose decoded string is within Node's maximum supported string length.
7
+ export const JSONL_MAX_RECORD_BYTES = bufferConstants.MAX_STRING_LENGTH * 3;
8
+ export class JsonlRecordTooLargeError extends Error {
9
+ constructor(path, line, limit) {
10
+ const label = limit >= 1024 * 1024 ? `${Math.round(limit / 1024 / 1024)} MB` : `${limit} units`;
11
+ super(`JSONL record ${line} in ${path} exceeds the supported ${label} telemetry record limit`);
12
+ this.name = "JsonlRecordTooLargeError";
13
+ }
14
+ }
15
+ /** Decode failures are resource/input errors; only JSON syntax errors retain the historical skip behavior. */
16
+ export function parseJsonlRecord(bytes, path, line, decode = (input) => input.toString("utf8")) {
17
+ const text = decode(bytes);
18
+ let parsed;
19
+ try {
20
+ parsed = JSON.parse(text);
21
+ }
22
+ catch (error) {
23
+ if (error instanceof SyntaxError)
24
+ return null;
25
+ throw error;
26
+ }
27
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)
28
+ ? parsed
29
+ : null;
30
+ }
31
+ /**
32
+ * Parse JSONL with memory bounded by one record plus a fixed read chunk. A record larger than the
33
+ * platform limit is reported as unreadable rather than truncated or partially counted. Newline is
34
+ * an ASCII byte and cannot occur inside a UTF-8 code point, so decoding each joined record is safe
35
+ * even when the input chunk boundary splits a multi-byte character.
36
+ */
37
+ export function* readJsonlRecords(path, chunkBytes = JSONL_CHUNK_BYTES, maxRecordBytes = JSONL_MAX_RECORD_BYTES, maxDecodedStringLength = bufferConstants.MAX_STRING_LENGTH) {
38
+ const fd = openSync(path, "r");
39
+ try {
40
+ const size = fstatSync(fd).size;
41
+ const chunk = Buffer.allocUnsafe(chunkBytes);
42
+ let offset = 0;
43
+ let line = 0;
44
+ let parts = [];
45
+ let pendingBytes = 0;
46
+ let pendingStringLength = 0;
47
+ let decoder = new TextDecoder("utf-8", { ignoreBOM: true });
48
+ const account = (piece, final = false) => {
49
+ pendingStringLength += decoder.decode(piece, { stream: !final }).length;
50
+ if (pendingStringLength > maxDecodedStringLength) {
51
+ throw new JsonlRecordTooLargeError(path, line + 1, maxDecodedStringLength);
52
+ }
53
+ };
54
+ const record = (last) => {
55
+ const bytes = pendingBytes + last.length;
56
+ if (bytes > maxRecordBytes)
57
+ throw new JsonlRecordTooLargeError(path, line + 1, maxRecordBytes);
58
+ account(Buffer.alloc(0), true);
59
+ const joined = parts.length === 0 ? last : Buffer.concat([...parts, last], bytes);
60
+ parts = [];
61
+ pendingBytes = 0;
62
+ pendingStringLength = 0;
63
+ decoder = new TextDecoder("utf-8", { ignoreBOM: true });
64
+ line++;
65
+ if (joined.length === 0)
66
+ return null;
67
+ return parseJsonlRecord(joined, path, line);
68
+ };
69
+ while (offset < size) {
70
+ const wanted = Math.min(chunk.length, size - offset);
71
+ let got = 0;
72
+ while (got < wanted) {
73
+ const n = readSync(fd, chunk, got, wanted - got, offset + got);
74
+ if (n === 0)
75
+ break;
76
+ got += n;
77
+ }
78
+ if (got === 0)
79
+ break;
80
+ offset += got;
81
+ let start = 0;
82
+ for (let i = 0; i < got; i++) {
83
+ if (chunk[i] !== 0x0a)
84
+ continue;
85
+ const piece = chunk.subarray(start, i);
86
+ if (pendingBytes + piece.length > maxRecordBytes)
87
+ throw new JsonlRecordTooLargeError(path, line + 1, maxRecordBytes);
88
+ account(piece);
89
+ const parsed = record(piece);
90
+ if (parsed)
91
+ yield parsed;
92
+ start = i + 1;
93
+ }
94
+ const remainder = chunk.subarray(start, got);
95
+ if (pendingBytes + remainder.length > maxRecordBytes)
96
+ throw new JsonlRecordTooLargeError(path, line + 1, maxRecordBytes);
97
+ if (remainder.length) {
98
+ account(remainder);
99
+ parts.push(Buffer.from(remainder));
100
+ pendingBytes += remainder.length;
101
+ }
102
+ }
103
+ // The old full-file reader parsed a final valid record even when its writer had not appended a newline.
104
+ if (pendingBytes) {
105
+ const parsed = record(Buffer.alloc(0));
106
+ if (parsed)
107
+ yield parsed;
108
+ }
109
+ }
110
+ finally {
111
+ closeSync(fd);
112
+ }
113
+ }
@@ -1,4 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
+ import { X509Certificate } from "node:crypto";
2
3
  import { existsSync, statfsSync } from "node:fs";
3
4
  import { arch, homedir } from "node:os";
4
5
  import { dirname } from "node:path";
@@ -84,6 +85,131 @@ function runtimesFromJson(raw, devicesRaw, stat, floorPct) {
84
85
  });
85
86
  return { runtimes, error: devicesValid ? null : "simctl devices returned invalid JSON" };
86
87
  }
88
+ function subjectField(subject, key) {
89
+ for (const line of subject.split(/\r?\n/)) {
90
+ const idx = line.indexOf("=");
91
+ if (idx <= 0)
92
+ continue;
93
+ if (line.slice(0, idx).trim() === key) {
94
+ const value = line.slice(idx + 1).trim();
95
+ if (value)
96
+ return value;
97
+ }
98
+ }
99
+ return null;
100
+ }
101
+ const IDENTITY_PRIORITY = [
102
+ /^Developer ID Application:/i,
103
+ /^Apple Distribution:/i,
104
+ /^iPhone Distribution:/i,
105
+ /^Mac App Distribution:/i,
106
+ /^Apple Development:/i,
107
+ /^iPhone Developer:/i,
108
+ ];
109
+ function pickPreferredSigningIdentity(names) {
110
+ if (!names.length)
111
+ return null;
112
+ for (const pattern of IDENTITY_PRIORITY) {
113
+ const match = names.find((name) => pattern.test(name));
114
+ if (match)
115
+ return match;
116
+ }
117
+ return names[0] ?? null;
118
+ }
119
+ /** Read-only probe for macOS code-signing identity and X.509 certificate expiry; never accesses private keys. */
120
+ export function probeMacSigningIdentity(run) {
121
+ const identities = commandOutput(run, "security", ["find-identity", "-v", "-p", "codesigning"]);
122
+ if (!identities.ok) {
123
+ return {
124
+ status: "unavailable",
125
+ name: null,
126
+ team_id: null,
127
+ team_name: null,
128
+ expires_at: null,
129
+ reason: identities.error ?? "code-signing identity probe failed",
130
+ expiry_reason: null,
131
+ };
132
+ }
133
+ const validNames = [];
134
+ for (const line of identities.output.split(/\r?\n/)) {
135
+ const match = /^\s*\d+\)\s+[0-9A-Fa-f]{40}\s+"([^"]+)"(?:\s+\(([^)]+)\))?/.exec(line);
136
+ if (!match)
137
+ continue;
138
+ const statusNote = match[2] ?? "";
139
+ if (/CSSMERR|REVOKED|EXPIRED|NOT TRUSTED/i.test(statusNote))
140
+ continue;
141
+ if (match[1]?.trim())
142
+ validNames.push(match[1].trim());
143
+ }
144
+ const selected = pickPreferredSigningIdentity(validNames);
145
+ if (!selected) {
146
+ return {
147
+ status: "unavailable",
148
+ name: null,
149
+ team_id: null,
150
+ team_name: null,
151
+ expires_at: null,
152
+ reason: "no valid code-signing identity installed in keychain",
153
+ expiry_reason: null,
154
+ };
155
+ }
156
+ const trailingTeamMatch = /\(([A-Z0-9]{6,20})\)\s*$/.exec(selected);
157
+ const fallbackTeamId = trailingTeamMatch?.[1] ?? null;
158
+ // Query public certificates only (-p emits X.509 certificates, never private keys).
159
+ const certLookup = commandOutput(run, "security", ["find-certificate", "-a", "-c", selected, "-p"]);
160
+ if (!certLookup.ok) {
161
+ return {
162
+ status: "available",
163
+ name: selected,
164
+ team_id: fallbackTeamId,
165
+ team_name: null,
166
+ expires_at: null,
167
+ reason: null,
168
+ expiry_reason: certLookup.error ?? "certificate expiry lookup failed",
169
+ };
170
+ }
171
+ const pemBlocks = certLookup.output.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g) ?? [];
172
+ let bestCert = null;
173
+ for (const pem of pemBlocks) {
174
+ try {
175
+ const cert = new X509Certificate(pem);
176
+ const validToMs = Date.parse(cert.validTo);
177
+ if (!Number.isFinite(validToMs))
178
+ continue;
179
+ const cn = subjectField(cert.subject, "CN");
180
+ const ou = subjectField(cert.subject, "OU");
181
+ const org = subjectField(cert.subject, "O");
182
+ const exactMatch = cn === selected;
183
+ const bestExact = bestCert ? bestCert.cn === selected : false;
184
+ if (!bestCert || (exactMatch && !bestExact) || (exactMatch === bestExact && validToMs > bestCert.validToMs)) {
185
+ bestCert = { cn, ou, org, validToMs };
186
+ }
187
+ }
188
+ catch {
189
+ // Skip malformed certificate blocks safely without failing valid certificates.
190
+ }
191
+ }
192
+ if (!bestCert) {
193
+ return {
194
+ status: "available",
195
+ name: selected,
196
+ team_id: fallbackTeamId,
197
+ team_name: null,
198
+ expires_at: null,
199
+ reason: null,
200
+ expiry_reason: "certificate expiry could not be parsed from keychain certificate",
201
+ };
202
+ }
203
+ return {
204
+ status: "available",
205
+ name: selected,
206
+ team_id: bestCert.ou ?? fallbackTeamId,
207
+ team_name: bestCert.org,
208
+ expires_at: new Date(bestCert.validToMs).toISOString(),
209
+ reason: null,
210
+ expiry_reason: null,
211
+ };
212
+ }
87
213
  /** Read-only macOS/Xcode facts; probes never select Xcode, install runtimes, or accept licenses. */
88
214
  export function macReadiness(options = {}) {
89
215
  const run = options.run ?? runDefault(options.path);
@@ -127,6 +253,7 @@ export function macReadiness(options = {}) {
127
253
  return [];
128
254
  return [volumeRefusal(`${runtime.platform} ${runtime.version ?? runtime.identifier} simulator runtime`, runtime.disk)];
129
255
  })];
256
+ const signingIdentity = probeMacSigningIdentity(run);
130
257
  return {
131
258
  product_version: macVersion,
132
259
  product_build: build.ok ? firstLine(build.output) : null,
@@ -139,6 +266,7 @@ export function macReadiness(options = {}) {
139
266
  disk: { home: homeDisk, checkout_build: checkoutDisk },
140
267
  disk_policy: { floor_pct: floorPct, source: "machine cache floor" },
141
268
  readiness_refusals: { build: buildRefusals, simulators: simulatorRefusals },
269
+ signing_identity: signingIdentity,
142
270
  capabilities: {
143
271
  mac: { ok: !!macVersion, version: macVersion },
144
272
  architecture: { ok: !!machineArch, version: machineArch },
@@ -1,3 +1,5 @@
1
+ import { loadGateQuarantines } from "./gate-quarantines.js";
2
+ import { importFailingGateReports } from "./gate-test-reports.js";
1
3
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
4
  import { randomBytes } from "node:crypto";
3
5
  import { dirname, join } from "node:path";
@@ -12,10 +14,8 @@ export const CLI_VERSION_CONFLICT_FILES = [
12
14
  "packages/cli/package.json",
13
15
  "packages/cli/src/version.ts",
14
16
  ];
15
- export const PG_BASELINE_CONFLICT_FILE = "apps/api/pg-migrations/0001_baseline.sql";
16
17
  export const MECHANICALLY_RESOLVABLE_CONFLICT_FILES = [
17
18
  ...CLI_VERSION_CONFLICT_FILES,
18
- PG_BASELINE_CONFLICT_FILE,
19
19
  ];
20
20
  const MAX_RE_GATE_ATTEMPTS = 3;
21
21
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
@@ -28,7 +28,7 @@ export function shaMatches(left, right) {
28
28
  return false;
29
29
  return a.startsWith(b) || b.startsWith(a);
30
30
  }
31
- export const TRAIN_GATE_STAGES = ["typecheck", "api tests", "cli tests", "web tests", "web build", "cli build", "published CLI contract"];
31
+ 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
32
  export function supportedTrainGateStage(stage) {
33
33
  return TRAIN_GATE_STAGES.find(name => name === stage);
34
34
  }
@@ -352,25 +352,6 @@ async function tryResolveMechanicalMergeConflicts(worktreeDir, entry, conflictin
352
352
  return false;
353
353
  }
354
354
  }
355
- if (conflictingFiles.includes(PG_BASELINE_CONFLICT_FILE)) {
356
- // This file is generated from the complete SQLite migration set. Keep the current
357
- // accumulated baseline while merging each unit; the post-batch generator below writes
358
- // the authoritative baseline after every included migration has landed.
359
- const ours = await runner("git", ["-C", worktreeDir, "checkout", "--ours", "--", PG_BASELINE_CONFLICT_FILE], {
360
- cwd: worktreeDir,
361
- env,
362
- timeoutMs: 30_000,
363
- });
364
- if (ours.status !== 0)
365
- return false;
366
- const add = await runner("git", ["-C", worktreeDir, "add", "--", PG_BASELINE_CONFLICT_FILE], {
367
- cwd: worktreeDir,
368
- env,
369
- timeoutMs: 30_000,
370
- });
371
- if (add.status !== 0)
372
- return false;
373
- }
374
355
  const remaining = await runner("git", ["-C", worktreeDir, "diff", "--name-only", "--diff-filter=U"], {
375
356
  cwd: worktreeDir,
376
357
  env,
@@ -428,9 +409,6 @@ async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeC
428
409
  export function cliVersionBumpRequired(paths) {
429
410
  return paths.some((path) => path.startsWith("packages/cli/") || path.startsWith("packages/skill"));
430
411
  }
431
- export function pgBaselineRefreshRequired(paths) {
432
- return paths.some((path) => path.startsWith("apps/api/migrations/") && path.endsWith(".sql"));
433
- }
434
412
  /**
435
413
  * Executes a claimed merge-train gate job: merges queued approved heads onto origin/<target>
436
414
  * in order, leaves conflicting units out, runs the configured gate under complete-suite lock,
@@ -529,42 +507,6 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
529
507
  },
530
508
  };
531
509
  }
532
- // SQLite migrations from every included unit land together. Regenerate the PostgreSQL
533
- // baseline once from that complete merged tree before running the gate, then commit the
534
- // generated file into the exact candidate that the gate verifies.
535
- await h.runStep("refresh merged PostgreSQL baseline", async () => {
536
- const changed = await h.runner("git", ["-C", h.worktreeDir, "diff", "--name-only", baseSha, "HEAD"], {
537
- cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
538
- });
539
- if (changed.status !== 0)
540
- throw new Error(`could not inspect merged migration paths: ${(changed.stderr || changed.stdout).trim().slice(0, 300)}`);
541
- if (!pgBaselineRefreshRequired(changed.stdout.split(/\r?\n/).filter(Boolean)))
542
- return 0;
543
- const generate = await h.runner("npm", ["run", "pg:generate-baseline", "-w", "apps/api"], {
544
- cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
545
- });
546
- if (generate.status !== 0)
547
- throw new Error(`PostgreSQL baseline generation failed: ${(generate.stderr || generate.stdout).trim().slice(0, 500)}`);
548
- h.onLogLine(generate.stdout.trim());
549
- const pending = await h.runner("git", ["-C", h.worktreeDir, "diff", "--quiet", "--", "apps/api/pg-migrations/0001_baseline.sql"], {
550
- cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
551
- });
552
- if (pending.status === 1) {
553
- const add = await h.runner("git", ["-C", h.worktreeDir, "add", "--", "apps/api/pg-migrations/0001_baseline.sql"], {
554
- cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
555
- });
556
- if (add.status !== 0)
557
- throw new Error(`could not stage generated PostgreSQL baseline: ${(add.stderr || add.stdout).trim().slice(0, 300)}`);
558
- const commit = await h.runner("git", ["-C", h.worktreeDir, "commit", "-m", "chore(api): refresh PostgreSQL baseline after migration batch"], {
559
- cwd: h.worktreeDir, env: gitEnv, timeoutMs: 30_000,
560
- });
561
- if (commit.status !== 0)
562
- throw new Error(`could not commit generated PostgreSQL baseline: ${(commit.stderr || commit.stdout).trim().slice(0, 300)}`);
563
- }
564
- else if (pending.status !== 0)
565
- throw new Error(`could not check generated PostgreSQL baseline changes: ${(pending.stderr || pending.stdout).trim().slice(0, 300)}`);
566
- return 0;
567
- }, () => 0);
568
510
  // The published CLI version identifies an immutable source tree. When this train lands
569
511
  // CLI or skill changes, bump the version before calculating the candidate head and gate.
570
512
  await h.runStep("bump merged CLI version", async () => {
@@ -685,15 +627,33 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
685
627
  const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
686
628
  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
629
  };
630
+ const gateSpec = resolveTrainGateCommand(trainRun.gate_command, anchorUnit, candidateSha, h.worktreeDir);
631
+ const usesRepositoryGate = gateSpec?.execArgs[0] === "scripts/gate.sh";
632
+ let quarantineSnapshot;
688
633
  const runGateAtHead = async (stepName, unitForCmd, headSha, options = {}) => {
689
634
  throwIfHeartbeatFailed();
690
635
  const worktreeDir = options.worktreeDir ?? h.worktreeDir;
691
636
  const gateEnv = { ...(options.env ?? lockedEnv) };
692
637
  delete gateEnv.GATE_STAGE;
638
+ delete gateEnv.B9S_GATE_QUARANTINES;
639
+ delete gateEnv.B9S_GATE_TEST_ENGINE;
640
+ delete gateEnv.B9S_GATE_REPORT_DIR;
641
+ gateEnv.B9S_GATE_NODE_VERSION = process.versions.node;
642
+ if (quarantineSnapshot !== undefined)
643
+ gateEnv.B9S_GATE_QUARANTINES = quarantineSnapshot;
644
+ if (options.scanReceipt) {
645
+ const reportDir = join(gateArtifactDir, "test-reports");
646
+ rmSync(reportDir, { recursive: true, force: true });
647
+ mkdirSync(reportDir, { recursive: true });
648
+ gateEnv.B9S_GATE_REPORT_DIR = reportDir;
649
+ }
693
650
  const lockContextForGate = options.lockContext ?? lockContext;
694
651
  const spec = resolveTrainGateCommand(trainRun.gate_command, unitForCmd, headSha, worktreeDir, options.stage);
695
652
  if (!spec)
696
653
  return { status: 0, output: "" };
654
+ if (quarantineSnapshot && quarantineSnapshot !== "[]" && spec.execArgs[0] === "scripts/gate.sh" && !existsSync(join(worktreeDir, "scripts", "gate-quarantine-report.mjs"))) {
655
+ throw new CliError("quarantine_unsupported", `gate checkout ${headSha} cannot apply the active quarantine snapshot`);
656
+ }
697
657
  return h.runStep(stepName, async () => {
698
658
  let output = "";
699
659
  const res = await h.runner(spec.execCmd, spec.execArgs, {
@@ -788,6 +748,15 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
788
748
  BSCHAT_UX_JOB_ARTIFACT_DIR: artifactDir,
789
749
  };
790
750
  delete probeEnv.GATE_STAGE;
751
+ delete probeEnv.B9S_GATE_QUARANTINES;
752
+ delete probeEnv.B9S_GATE_REPORT_DIR;
753
+ delete probeEnv.B9S_GATE_TEST_ENGINE;
754
+ probeEnv.B9S_GATE_NODE_VERSION = process.versions.node;
755
+ if (quarantineSnapshot !== undefined)
756
+ probeEnv.B9S_GATE_QUARANTINES = quarantineSnapshot;
757
+ if (quarantineSnapshot && quarantineSnapshot !== "[]" && spec.execArgs[0] === "scripts/gate.sh" && !existsSync(join(probeWorktree, "scripts", "gate-quarantine-report.mjs"))) {
758
+ throw new CliError("quarantine_unsupported", `probe checkout ${probeSha} cannot apply the active quarantine snapshot`);
759
+ }
791
760
  if (probeLock?.jobId)
792
761
  probeEnv.B9S_LOCK_JOB_ID = probeLock.jobId;
793
762
  if (!Number.isSafeInteger(probeLock?.slot) || probeLock.slot < 1 || probeLock.slot > 3) {
@@ -915,7 +884,27 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
915
884
  };
916
885
  const scanner = createGateMarkerScanner();
917
886
  try {
887
+ if (usesRepositoryGate)
888
+ quarantineSnapshot = JSON.stringify(await loadGateQuarantines(h.agentClient, job.project, trainRun.target_branch));
889
+ const gateStartedAt = new Date().toISOString();
918
890
  const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha, { scanReceipt: true, keepSuccessfulResultOnHeartbeatError: true });
891
+ if (mainRun.status !== 0) {
892
+ try {
893
+ const imported = await importFailingGateReports({
894
+ dir: join(gateArtifactDir, "test-reports"), project: job.project, trainRunId: trainRun.id, branch: trainRun.target_branch,
895
+ candidate: candidateSha, base: baseSha, startedAt: gateStartedAt, endedAt: new Date().toISOString(),
896
+ creds: h.agentCreds, client: h.agentClient,
897
+ });
898
+ for (const report of imported)
899
+ h.onLogLine(`merge-train ${trainRun.id}: imported ${report.stage} report ${report.runId}`);
900
+ if (!imported.length)
901
+ h.onLogLine(`merge-train ${trainRun.id}: failure has no importable individual test report`);
902
+ }
903
+ catch (error) {
904
+ const detail = error instanceof Error ? error.message : String(error);
905
+ h.onLogLine(`merge-train ${trainRun.id}: failed to import failing gate reports; continuing with failure attribution: ${detail}`);
906
+ }
907
+ }
919
908
  scanner.push("", true);
920
909
  const scanResult = scanner.result();
921
910
  gateOutputText = mainRun.output;