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.
@@ -1,13 +1,17 @@
1
1
  import { str } from "../args.js";
2
2
  import { Client } from "../client.js";
3
3
  import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
4
+ import { consoleLink } from "../console-links.js";
4
5
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
5
6
  import { projectOf } from "./agent.js";
6
7
  import { evidence } from "./evidence.js";
7
8
  export async function mock(p, out) {
8
- const [, sub, study, variant, file] = p.positionals;
9
+ const [, sub, ...args] = p.positionals;
10
+ if (sub === "review")
11
+ return platformReview(args, p, out);
12
+ const [study, variant, file] = args;
9
13
  if (sub !== "upload" && sub !== "gaps")
10
- throw new CliError("usage", "mock upload <studyId> <variantId> <file.html> [--summary text] | mock gaps <studyId> --json <gapsJson> | --clear");
14
+ throw new CliError("usage", "mock upload <studyId> <variantId> <file.html> [--summary text] | mock gaps <studyId> --json <gapsJson> | --clear | mock review show --group <id> | --study <id> | mock review gaps|propose <reviewId> --json <array> | mock review revise <reviewId>");
11
15
  if (!study)
12
16
  throw new CliError("usage", "studyId is required");
13
17
  if (sub === "upload" && (!variant || !file || p.positionals.length !== 5))
@@ -62,3 +66,112 @@ export async function mock(p, out) {
62
66
  throw new CliError("attach_failed", `Mock evidence:${id} was uploaded, but attachment failed: ${error.message}`);
63
67
  }
64
68
  }
69
+ function jsonArray(raw, flag) {
70
+ if (!raw)
71
+ throw new CliError("usage", `--json must be a JSON array of ${flag}`);
72
+ let value;
73
+ try {
74
+ value = JSON.parse(raw);
75
+ }
76
+ catch {
77
+ throw new CliError("usage", `--json must be a JSON array of ${flag}`);
78
+ }
79
+ if (!Array.isArray(value))
80
+ throw new CliError("usage", `--json must be a JSON array of ${flag}`);
81
+ return value;
82
+ }
83
+ function assertUniqueGapTitles(gaps) {
84
+ const titles = new Set();
85
+ for (const gap of gaps) {
86
+ if (!gap || typeof gap !== "object" || typeof gap.title !== "string")
87
+ throw new CliError("usage", "each gap needs a title and description");
88
+ const title = gap.title.trim().toLocaleLowerCase().replace(/\s+/g, " ");
89
+ if (!title)
90
+ throw new CliError("usage", "each gap needs a title and description");
91
+ if (titles.has(title))
92
+ throw new CliError("usage", `duplicate platform gap title: ${gap.title}`);
93
+ titles.add(title);
94
+ }
95
+ }
96
+ async function platformReview(args, p, out) {
97
+ const [action, reviewId] = args;
98
+ const usage = "mock review show --group <groupId> | --study <studyId> | mock review gaps <reviewId> --json <gapsArray> | mock review propose <reviewId> --json <proposalsArray> | mock review revise <reviewId>";
99
+ if (!action)
100
+ throw new CliError("usage", usage);
101
+ const name = resolveAgentName(str(p.flags, "as"));
102
+ const creds = loadAgent(name);
103
+ const client = Client.forAgent(creds, resolveModel(str(p.flags, "model"), process.env, process.cwd(), name));
104
+ const project = projectOf(p, creds);
105
+ const reviews = `/projects/${encodeURIComponent(project)}/design-platform-reviews`;
106
+ if (action === "show") {
107
+ if (args.length !== 1)
108
+ throw new CliError("usage", usage);
109
+ const groupId = str(p.flags, "group"), studyId = str(p.flags, "study");
110
+ if ((groupId === undefined) === (studyId === undefined))
111
+ throw new CliError("usage", "choose exactly one of --group <groupId> or --study <studyId>");
112
+ const query = groupId !== undefined ? `group_id=${encodeURIComponent(groupId)}` : `study_id=${encodeURIComponent(studyId)}`;
113
+ const result = await client.call("GET", `${reviews}?${query}`);
114
+ const review = result.review;
115
+ if (!review) {
116
+ out.print("No platform review exists for this scope.", result);
117
+ return;
118
+ }
119
+ const studiesResult = await client.call("GET", `/projects/${encodeURIComponent(project)}/design-studies`);
120
+ if (!Array.isArray(studiesResult.studies))
121
+ throw new CliError("bad_response", "design study list response omitted studies");
122
+ const variants = studiesResult.studies.flatMap(study => (study.rounds ?? []).flatMap(round => (round.variants ?? []).map(variant => ({ ...variant, study_id: study.id, study_title: study.title }))));
123
+ const selected = review.shortlist.map(id => {
124
+ const variant = variants.find(item => item.id === id);
125
+ return variant ? { variant_id: id, study_id: variant.study_id, study_title: variant.study_title, label: variant.label, status: variant.status, summary: variant.summary } : { variant_id: id, unavailable: true };
126
+ });
127
+ const lines = [`Platform review ${review.id} [${review.status}]`, ...selected.map(item => "unavailable" in item ? `Shortlisted ${item.variant_id}: mock details unavailable` : `${item.study_title} · ${item.label} [${item.status}]${item.summary ? `\n ${item.summary}` : ""}\n ${consoleLink("mock", project, item.study_id)}`), ...review.gaps.map(gap => `Gap: ${gap.title} — ${gap.description}${gap.direction ? `\n Direction: ${gap.direction}` : ""}`), ...review.proposals.map(proposal => `Proposed WU${proposal.work_unit_number ? ` #${proposal.work_unit_number}` : " (draft)"}: ${proposal.title} [${proposal.tags.join(", ")}]`), ...(review.direction ? [`Operator direction: ${review.direction}`] : [])];
128
+ out.print(lines.join("\n") || `Platform review ${review.id} [${review.status}]`, { ...result, shortlisted_mocks: selected });
129
+ return;
130
+ }
131
+ if (action === "gaps" || action === "propose") {
132
+ if (args.length !== 2 || !reviewId)
133
+ throw new CliError("usage", usage);
134
+ const values = jsonArray(str(p.flags, "json"), action === "gaps" ? "gaps" : "proposals");
135
+ if (action === "gaps")
136
+ assertUniqueGapTitles(values);
137
+ const body = action === "gaps" ? { gaps: values } : { proposals: values };
138
+ const result = await client.call("POST", `${reviews}/${encodeURIComponent(reviewId)}/${action === "propose" ? "proposals" : "gaps"}`, body);
139
+ out.print(action === "gaps" ? "Platform review gaps submitted." : "Platform unit proposals submitted as drafts.", result);
140
+ return;
141
+ }
142
+ if (action === "revise") {
143
+ if (args.length !== 2 || !reviewId)
144
+ throw new CliError("usage", usage);
145
+ const result = await client.call("GET", `${reviews}/${encodeURIComponent(reviewId)}`);
146
+ const review = result.review;
147
+ if (review.status !== "revision")
148
+ throw new CliError("conflict", `mock revisions can start only after operator confirmation and direction (review status is ${review.status})`);
149
+ const studiesResult = await client.call("GET", `/projects/${encodeURIComponent(project)}/design-studies`);
150
+ if (!Array.isArray(studiesResult.studies))
151
+ throw new CliError("bad_response", "design study list response omitted studies");
152
+ const byVariant = new Map();
153
+ for (const study of studiesResult.studies) {
154
+ const sourceVariantIds = new Set((study.rounds ?? []).flatMap(round => (round.variants ?? []).flatMap(variant => variant.source_variant_id ? [variant.source_variant_id] : [])));
155
+ for (const round of study.rounds ?? [])
156
+ for (const variant of round.variants ?? [])
157
+ byVariant.set(variant.id, { studyId: study.id, title: study.title, sourceVariantIds });
158
+ }
159
+ if (!review.shortlist.length)
160
+ throw new CliError("bad_response", "confirmed platform review has no shortlisted mocks");
161
+ const started = [];
162
+ for (const variantId of review.shortlist) {
163
+ const source = byVariant.get(variantId);
164
+ if (!source)
165
+ throw new CliError("bad_response", `shortlisted variant ${variantId} is missing from project studies`);
166
+ if (source.sourceVariantIds.has(variantId)) {
167
+ started.push({ study_id: source.studyId, study_title: source.title, source_variant_id: variantId, already_started: true });
168
+ continue;
169
+ }
170
+ const iteration = await client.call("POST", `/projects/${encodeURIComponent(project)}/design-studies/${encodeURIComponent(source.studyId)}/iterate`, { variant_id: variantId });
171
+ started.push({ study_id: source.studyId, study_title: source.title, source_variant_id: variantId, study: iteration.study });
172
+ }
173
+ out.print(started.map(item => `${"already_started" in item ? "Revision already started" : "Revision started"}: ${item.study_title}\n ${consoleLink("mock", project, item.study_id)}`).join("\n"), { review_id: reviewId, revisions: started });
174
+ return;
175
+ }
176
+ throw new CliError("usage", usage);
177
+ }
@@ -327,7 +327,7 @@ export async function needsAdmin(p, out, project) {
327
327
  return out.print(project ? `Nothing waiting in ${r.project?.name ?? project}.` : "Nothing is waiting on you.", r);
328
328
  const ind = (t) => t.replace(/\n/g, "\n ");
329
329
  out.print(r.needs.map((n, i) => [
330
- `${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : n.kind === "platform_fault" ? (n.key.startsWith("remote-job-health:") ? "remote job health" : "platform fault") : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
330
+ `${i + 1}. [${n.project || "Account"}] ${n.display_id ?? (n.kind === "unit_question" ? `WU #${n.unit} question` : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : "decision id unavailable")} · ${n.kind === "unit_question" ? "unit question" : n.kind === "wake_broken" || n.kind === "wake_unresponsive" ? "wake path" : n.kind === "sendback_reviewer_gap" ? "send-back reviewer gap" : n.kind === "flow_agent_budget" ? "Flow Agent budget" : n.kind === "notifier" ? "your alerts" : n.kind === "machine_report_refused" ? "machine report refused" : n.kind === "machine_session" ? "machine" : n.kind === "lock_silent" ? "silent lock job" : n.kind === "platform_fault" ? (n.key.startsWith("remote-job-health:") ? "remote job health" : "platform fault") : "decision"} · ${n.asked_by} · since ${n.since.slice(0, 16).replace("T", " ")} UTC`,
331
331
  ` Console: ${consoleLink("decision", n.project, n.key)}`,
332
332
  n.plain ? ` In plain words: ${ind(n.plain)}` : n.unexplained ? ` In plain words: (${n.asked_by} did not explain this; b9s-admin explain ${n.key})` : null,
333
333
  n.blocks ? ` What's stuck: ${ind(n.blocks)}` : null,
@@ -35,10 +35,19 @@ async function printJob(job, res, p, out, creds, client, project) {
35
35
  throw new CliError("checksum_mismatch", `full-log bytes hash to ${actual} but server says ${expected || "no checksum"}`);
36
36
  process.stdout.write(bytes);
37
37
  }
38
+ function jobUnitTarget(job) {
39
+ return job.work_unit_number !== null && job.work_unit_number !== undefined
40
+ ? `WU #${job.work_unit_number}`
41
+ : `branch ${job.target_branch ?? job.branch}`;
42
+ }
38
43
  function formatJob(job) {
39
44
  const isGate = job.job_kind === "gate";
40
45
  const what = isGate
41
- ? (job.train_run_id ? "merge train gate" : "complete-suite gate (scripts/gate.sh)")
46
+ ? (job.train_run_id
47
+ ? "merge train gate"
48
+ : job.trigger_source === "direct_push" || job.target_branch
49
+ ? `direct push gate (${job.target_branch ?? job.branch})`
50
+ : "complete-suite gate (scripts/gate.sh)")
42
51
  : [job.task ? `ux:task ${job.task}` : null, job.compare_screen ? `ux:compare ${job.compare_screen}` : null].filter(Boolean).join(" + ");
43
52
  const headText = job.resolved_head ? job.resolved_head.slice(0, 9) : job.head ? job.head.slice(0, 9) : "branch tip";
44
53
  const evidenceLine = Array.isArray(job.evidence_ids) && job.evidence_ids.length
@@ -71,7 +80,7 @@ function formatJob(job) {
71
80
  }
72
81
  else if (job.checkout_retention_note)
73
82
  checkoutLine = `\nCheckout: ${job.checkout_retention_note}`;
74
- return `${kindLabel} job ${job.id} [${job.status}] on ${job.machine} for WU #${job.work_unit_number}\nTask: ${what}\nBranch: ${job.branch} @ ${headText}${steps}${failedTail}${fingerprint}${checkoutLine}${evidenceLine}${fullLogLine}${errorLine}`;
83
+ return `${kindLabel} job ${job.id} [${job.status}] on ${job.machine} for ${jobUnitTarget(job)}\nTask: ${what}\nBranch: ${job.branch} @ ${headText}${steps}${failedTail}${fingerprint}${checkoutLine}${evidenceLine}${fullLogLine}${errorLine}`;
75
84
  }
76
85
  export async function ux(p, out) {
77
86
  const sub = p.positionals[1];
@@ -147,7 +156,7 @@ export async function ux(p, out) {
147
156
  id: job.id,
148
157
  kind: job.job_kind ?? "ux",
149
158
  status: job.status,
150
- unit: `#${job.work_unit_number}`,
159
+ unit: job.work_unit_number !== null && job.work_unit_number !== undefined ? `#${job.work_unit_number}` : (job.target_branch ?? job.branch),
151
160
  machine: job.machine,
152
161
  task: job.job_kind === "gate" ? "gate.sh" : (job.task ?? job.compare_screen ?? "-"),
153
162
  head: (job.resolved_head ?? job.head ?? "-").slice(0, 9),
@@ -219,7 +228,7 @@ export async function gate(p, out) {
219
228
  const rows = res.jobs.map((job) => ({
220
229
  id: job.id,
221
230
  status: job.status,
222
- unit: `#${job.work_unit_number}`,
231
+ unit: job.work_unit_number !== null && job.work_unit_number !== undefined ? `#${job.work_unit_number}` : (job.target_branch ?? job.branch),
223
232
  machine: job.machine,
224
233
  head: (job.resolved_head ?? job.head ?? "-").slice(0, 9),
225
234
  evidence: Array.isArray(job.evidence_ids) ? job.evidence_ids.length : 0,
@@ -11,7 +11,8 @@ import { readState, updateState } from "../state.js";
11
11
  import { codexRollout, sessionsOf } from "../sessions.js";
12
12
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
13
13
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
14
- import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, hasRemote, inspectRemoteBranch, isAncestor, isShaBranchName, pushBranchToOrigin, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
14
+ import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, hasRemote, inspectRemoteBranch, isAncestor, isShaBranchName, machineIdentityForAgent, pushBranchToOrigin, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
15
+ import { executeScopedGateForSubmit, scopedGatePlan } from "../scoped-gate.js";
15
16
  import { join, resolve } from "node:path";
16
17
  import { formatStepRules, table } from "../output.js";
17
18
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
@@ -644,8 +645,8 @@ function reportSubmitScopeChecklist(scope) {
644
645
  }
645
646
  process.stderr.write(`b9s: pre-submit scope checklist (verify each item and its evidence):\n${numbered.map((line) => ` [ ] ${line}`).join("\n")}\n`);
646
647
  }
647
- export function submitPayload(fields, hasReviewRules, target, cwd = process.cwd()) {
648
- const paths = changedPathsAgainstTarget(target, cwd);
648
+ export function submitPayload(fields, includeChangedPaths, target, cwd = process.cwd(), precomputedPaths) {
649
+ const paths = precomputedPaths ?? changedPathsAgainstTarget(target, cwd);
649
650
  const directories = {}, fileKinds = {};
650
651
  for (const path of paths) {
651
652
  const slash = path.lastIndexOf("/");
@@ -655,7 +656,7 @@ export function submitPayload(fields, hasReviewRules, target, cwd = process.cwd(
655
656
  directories[directory] = (directories[directory] ?? 0) + 1;
656
657
  fileKinds[kind] = (fileKinds[kind] ?? 0) + 1;
657
658
  }
658
- return { ...fields, changed_paths: hasReviewRules ? paths : [], changed_path_summary: { total: paths.length, by_directory: directories, by_file_kind: fileKinds, paths: paths.slice(0, 200), truncated: paths.length > 200 } };
659
+ return { ...fields, changed_paths: includeChangedPaths ? paths : [], changed_path_summary: { total: paths.length, by_directory: directories, by_file_kind: fileKinds, paths: paths.slice(0, 200), truncated: paths.length > 200 } };
659
660
  }
660
661
  export function branchValueIdsAtHead(values, head) {
661
662
  if (!head)
@@ -753,7 +754,7 @@ export async function wu(p, out) {
753
754
  const createdReceiptLine = (u) => `WU #${u.number} created: ${u.title}`;
754
755
  const fmt = (u) => {
755
756
  const waitList = Array.isArray(u.waits_on) ? u.waits_on : u.waiting_on ? [u.waiting_on] : [];
756
- const flags = [u.priority === "urgent" ? "URGENT" : null, u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
757
+ const flags = [u.held_for_review ? "HELD FOR REVIEW" : null, u.priority === "urgent" ? "URGENT" : null, u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held for busy owner" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
757
758
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
758
759
  const approvals = u.approvals.map((a) => a.name).join(", ");
759
760
  return [
@@ -831,7 +832,8 @@ export async function wu(p, out) {
831
832
  const priority = str(p.flags, "priority");
832
833
  if (priority !== undefined && priority !== "normal" && priority !== "urgent")
833
834
  throw new CliError("usage", "--priority must be urgent or normal");
834
- const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
835
+ const reviewHold = bool(p.flags, "review-hold");
836
+ const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), held_for_review: reviewHold, ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
835
837
  const n = r.unit.number;
836
838
  const created = createdReceipt(r.unit, r);
837
839
  if (r.unit.waiting_on != null) {
@@ -841,6 +843,10 @@ export async function wu(p, out) {
841
843
  // Report the irreversible create before any local worktree or start step can fail. JSON
842
844
  // callers receive this compact, stable receipt instead of the later start envelope.
843
845
  out.print(withRuleText(createdReceiptLine(r.unit), r, "cut"), created);
846
+ if (reviewHold) {
847
+ out.print(`${fmt(r.unit)}\nHeld for review; no worker or automation can take it until an assigner or operator releases it with b9s wu release-for-review ${n}.`, created);
848
+ return;
849
+ }
844
850
  const contextDecision = await contextDecisionForStart(client, base, r.unit, name, p);
845
851
  const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
846
852
  const where = symbolicBranchAndHead(path);
@@ -865,6 +871,12 @@ export async function wu(p, out) {
865
871
  }
866
872
  const to = str(p.flags, "to");
867
873
  const reason = str(p.flags, "reason");
874
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
875
+ const overrideReason = str(p.flags, "override-reason");
876
+ if (overrideWakeability && !overrideReason?.trim())
877
+ throw new CliError("usage", '--override-unwakeable requires --override-reason "why this unavailable target must receive work"');
878
+ if (overrideReason !== undefined && !overrideWakeability)
879
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
868
880
  const priority = str(p.flags, "priority");
869
881
  if (priority !== undefined && priority !== "normal" && priority !== "urgent")
870
882
  throw new CliError("usage", "--priority must be urgent or normal");
@@ -876,7 +888,7 @@ export async function wu(p, out) {
876
888
  throw new CliError("usage", "amend an existing unit session requirement with wu scope before assigning it");
877
889
  if (p.flags.after !== undefined)
878
890
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
879
- const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
891
+ const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}) });
880
892
  out.print(withRuleText(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}`, r, "cut"), r);
881
893
  return;
882
894
  }
@@ -892,7 +904,7 @@ export async function wu(p, out) {
892
904
  const scope = await scopeText();
893
905
  const replay = str(p.flags, "replay-of");
894
906
  const clientId = randomUUID();
895
- const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
907
+ const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, held_for_review: bool(p.flags, "review-hold"), force: bool(p.flags, "force"), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
896
908
  const clientWarnings = [];
897
909
  if (explicitBranch && baseFlag === undefined && repoName() && hasRemote("origin")) {
898
910
  const remoteState = inspectRemoteBranch(explicitBranch);
@@ -908,6 +920,22 @@ export async function wu(p, out) {
908
920
  out.print(withRuleText(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput([...(r.warnings ?? []), ...clientWarnings])}`, r, "cut"), createdReceipt(r.unit, r));
909
921
  return;
910
922
  }
923
+ case "release-for-review": {
924
+ const raw = p.positionals.slice(2).join(",");
925
+ const numbers = [...new Set(raw.split(",").map((value) => {
926
+ const trimmed = value.trim().replace(/^#/, "");
927
+ if (!/^\d+$/.test(trimmed) || Number(trimmed) < 1)
928
+ throw new CliError("usage", "wu release-for-review expects one or more comma-separated unit numbers");
929
+ return Number(trimmed);
930
+ }))];
931
+ if (!numbers.length)
932
+ throw new CliError("usage", "wu release-for-review <n>[,<n>...]");
933
+ const released = [];
934
+ for (const number of numbers)
935
+ released.push((await client.call("POST", `${base}/${number}/review-hold/release`, {})).unit);
936
+ out.print(released.map((unit) => `${fmt(unit)}\nReview hold released; normal dispatch resumed.`).join("\n"), { units: released });
937
+ return;
938
+ }
911
939
  case "park": {
912
940
  const note = str(p.flags, "note");
913
941
  if (!note?.trim())
@@ -942,9 +970,15 @@ export async function wu(p, out) {
942
970
  // Pull a queued unit: for yourself (qualified by works or trial), or for someone with --to (assigners).
943
971
  const to = str(p.flags, "to") ?? null;
944
972
  const reason = str(p.flags, "reason");
973
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
974
+ const overrideReason = str(p.flags, "override-reason");
975
+ if (overrideWakeability && (!to || !overrideReason?.trim()))
976
+ throw new CliError("usage", '--override-unwakeable requires --to <agent> and --override-reason "why this unavailable target must receive work"');
977
+ if (overrideReason !== undefined && !overrideWakeability)
978
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
945
979
  if (reason !== undefined && !to)
946
980
  throw new CliError("usage", 'wu take <n> --to <agent> --reason "why" is only for an assigner handing work to a named agent');
947
- const r = await client.call("POST", `${base}/${num()}/take`, { to, ...(reason === undefined ? {} : { reason }) });
981
+ const r = await client.call("POST", `${base}/${num()}/take`, { to, ...(reason === undefined ? {} : { reason }), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}) });
948
982
  out.print(`${fmt(r.unit)}\n${to ? `Handed to ${r.unit.owner_name}.` : `Yours. Start it: b9s wu start ${r.unit.number}`}`, r);
949
983
  return;
950
984
  }
@@ -1079,6 +1113,44 @@ export async function wu(p, out) {
1079
1113
  throw new CliError("rebase_required", `WU #${num()} needs rebase onto ${unitTarget}; run b9s wu submit ${num()} from the unit worktree after rebasing`);
1080
1114
  }
1081
1115
  const pr = str(p.flags, "pr") ?? null;
1116
+ const changedPaths = where.head ? changedPathsAgainstTarget(unitTarget) : [];
1117
+ const fullUnitHead = where.head ? fullSha("HEAD") : null;
1118
+ let scopedReceipt = null;
1119
+ if (fullUnitHead && def.merge?.require_gate_receipt) {
1120
+ const plan = scopedGatePlan(changedPaths, def.merge);
1121
+ if (plan.required && plan.stages.length > 0) {
1122
+ const originTargetSha = fullSha(`refs/remotes/origin/${unitTarget}^{commit}`);
1123
+ const existing = submitRecord.scoped_gate_status?.receipt;
1124
+ const matchesExisting = Boolean(existing
1125
+ && existing.exit_code === 0
1126
+ && existing.unit_head === fullUnitHead
1127
+ && existing.target_branch === unitTarget
1128
+ && originTargetSha
1129
+ && existing.target_sha === originTargetSha
1130
+ && (rebased === true || existing.merged_sha !== fullUnitHead)
1131
+ && Array.isArray(existing.stages)
1132
+ && plan.stages.every((stage) => existing.stages.includes(stage)));
1133
+ if (matchesExisting) {
1134
+ process.stderr.write(`b9s: reusing passing scoped gate receipt for ${fullUnitHead.slice(0, 9)} merged with origin/${unitTarget} (${originTargetSha.slice(0, 9)})\n`);
1135
+ }
1136
+ else {
1137
+ process.stderr.write(`b9s: running local scoped submit gate stages [${plan.stages.join(", ")}] for ${fullUnitHead.slice(0, 9)} merged with current origin/${unitTarget}\n`);
1138
+ scopedReceipt = await executeScopedGateForSubmit({
1139
+ unitNumber: num(),
1140
+ unitHead: fullUnitHead,
1141
+ targetBranch: unitTarget,
1142
+ changedPaths,
1143
+ machine: machineIdentityForAgent(creds.machine),
1144
+ merge: def.merge,
1145
+ });
1146
+ if (scopedReceipt) {
1147
+ rebased = scopedReceipt.rebased ?? rebased;
1148
+ await client.call("POST", `${base}/${num()}/scoped-gate-receipts`, scopedReceipt);
1149
+ process.stderr.write(`b9s: recorded self-attested scoped gate receipt for merged head ${scopedReceipt.merged_sha.slice(0, 9)} (unit ${scopedReceipt.unit_head.slice(0, 9)} + origin/${unitTarget} ${scopedReceipt.target_sha.slice(0, 9)})\n`);
1150
+ }
1151
+ }
1152
+ }
1153
+ }
1082
1154
  const telemetry = await roundTelemetry(client, base, num(), name, project);
1083
1155
  let branchValueIds = [];
1084
1156
  if (where.head) {
@@ -1091,7 +1163,7 @@ export async function wu(p, out) {
1091
1163
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
1092
1164
  }
1093
1165
  }
1094
- const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, ...(rebaseComparison ? { rebase_comparison: rebaseComparison } : {}), usage: telemetry.usage, context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
1166
+ const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, ...(rebaseComparison ? { rebase_comparison: rebaseComparison } : {}), usage: telemetry.usage, context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, Boolean(def.review_rules?.length || def.merge?.require_gate_receipt), unitTarget, process.cwd(), where.head ? changedPaths : []);
1095
1167
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
1096
1168
  const u = r.unit;
1097
1169
  const submitLine = u.status === "classifying"
@@ -1253,11 +1325,17 @@ export async function wu(p, out) {
1253
1325
  const replace = str(p.flags, "replace");
1254
1326
  const withName = str(p.flags, "with");
1255
1327
  const note = str(p.flags, "note");
1328
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
1329
+ const overrideReason = str(p.flags, "override-reason");
1330
+ if (overrideWakeability && (!withName || !overrideReason?.trim()))
1331
+ throw new CliError("usage", '--override-unwakeable requires --with <agent> and --override-reason "why this unavailable reviewer must review"');
1332
+ if (overrideReason !== undefined && !overrideWakeability)
1333
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
1256
1334
  if (!replace?.trim() || !note?.trim()) {
1257
1335
  throw new CliError("usage", 'wu reviewer <n> --replace <agent> [--with <agent>] --note "why this reviewer is being replaced"');
1258
1336
  }
1259
1337
  const r = await client.call("POST", `${base}/${num()}/reviewer`, {
1260
- replace: replace.trim(), ...(withName?.trim() ? { with: withName.trim() } : {}), note: note.trim(),
1338
+ replace: replace.trim(), ...(withName?.trim() ? { with: withName.trim() } : {}), note: note.trim(), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}),
1261
1339
  });
1262
1340
  out.print(withRuleText(fmt(r.unit), r, "submit"), r);
1263
1341
  return;
@@ -2562,8 +2640,14 @@ export async function askOperator(p, out) {
2562
2640
  if (value !== undefined)
2563
2641
  body[field] = value;
2564
2642
  }
2643
+ const decision = str(p.flags, "decision");
2644
+ if (decision !== undefined)
2645
+ body.decision = decision;
2646
+ const kind = str(p.flags, "kind");
2647
+ if (kind !== undefined)
2648
+ body.kind = kind;
2565
2649
  if (!Object.keys(body).length)
2566
- throw new CliError("usage", "ask-operator --amend <id> [new question] [--plain ...] [--blocks ...] [--if-yes ...] [--if-no ...] [--propose ...]");
2650
+ throw new CliError("usage", "ask-operator --amend <id> [new question] [--decision ...] [--kind ...] [--plain ...] [--blocks ...] [--if-yes ...] [--if-no ...] [--propose ...]");
2567
2651
  const result = await client.call("POST", "/projects/" + project + "/asks/" + amend + "/amend", body);
2568
2652
  out.print("Amended your open ask " + amend + "; the operator was told.", result);
2569
2653
  return;
@@ -2574,11 +2658,22 @@ export async function askOperator(p, out) {
2574
2658
  if (!text || missing.length)
2575
2659
  throw new CliError("usage", `ask-operator "exactly what you need the operator to do or decide" --plain "one or two plain sentences for someone who has not read the thread: what this is about (no unit numbers or jargon unexplained)" --blocks "what's stuck until they answer" --if-yes "what happens then" --if-no "what happens then" [--propose "your recommended answer, approvable as written"]${missing.length ? `\nmissing: ${missing.join(", ")}` : ""}`);
2576
2660
  const proposal = str(p.flags, "propose") ?? "";
2661
+ const decision = str(p.flags, "decision");
2662
+ const kind = str(p.flags, "kind");
2663
+ const askKinds = ["ci_rerun", "ci_log", "ci_artifact", "pr_label", "git_push", "decision", "approval", "scope_change", "access", "milestone_close", "other"];
2664
+ if (decision !== undefined && (!decision.trim() || decision.trim().length > 120 || /[\r\n]/.test(decision.trim())))
2665
+ throw new CliError("usage", "--decision must be a non-empty one-line headline of at most 120 characters");
2666
+ if (kind !== undefined && !askKinds.includes(kind))
2667
+ throw new CliError("usage", `--kind must be one of: ${askKinds.join(", ")}`);
2668
+ const headline = decision?.trim() ?? (() => {
2669
+ const firstLine = text.split(/[\r\n]/, 1)[0].trim();
2670
+ return firstLine.length <= 120 ? firstLine : `${firstLine.slice(0, 117).trimEnd()}...`;
2671
+ })();
2577
2672
  const milestone = str(p.flags, "milestone");
2578
2673
  const rawUnit = str(p.flags, "unit");
2579
2674
  if (rawUnit !== undefined && !/^[1-9]\d*$/.test(rawUnit))
2580
2675
  throw new CliError("usage", "--unit must be a positive work unit number");
2581
- const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal, ...(milestone !== undefined ? { milestone } : {}), ...(rawUnit !== undefined ? { unit: Number(rawUnit) } : {}) });
2676
+ const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal, decision: headline, ...(kind !== undefined ? { kind } : {}), ...(milestone !== undefined ? { milestone } : {}), ...(rawUnit !== undefined ? { unit: Number(rawUnit) } : {}) });
2582
2677
  out.print(`Asked the operator${proposal ? " with your proposal (they can approve it as written)" : ""}; it is on their console banner and reported to them. You will be @mentioned with the decision. Carry on with what does not depend on it.`, r);
2583
2678
  }
2584
2679
  async function reviewUsage(client, project, name) {
package/dist/config.js CHANGED
@@ -7,7 +7,6 @@ import { writeFileAtomic } from "./shared-file.js";
7
7
  import { readState, updateState } from "./state.js";
8
8
  import { detectVendor } from "./vendor.js";
9
9
  import { configDirectory } from "./directories.js";
10
- import { CLI_VERSION } from "./version.js";
11
10
  export const DEFAULT_URL = "https://api.benignswarm.org";
12
11
  export function configRoot(env = process.env) {
13
12
  return configDirectory(env);
@@ -168,7 +167,7 @@ export function resolveAgentName(asFlag, env = process.env, cwd = process.cwd())
168
167
  const saved = listSaved("agents", env);
169
168
  throw new CliError("no_identity", `BSCHAT_AGENT is not set and --as was not given; b9s cannot tell which agent you are${identityWalkStoppedAt() ? ` (it looked for this checkout's identity file up to ${identityWalkStoppedAt()}, where it is not permitted to look)` : ""}`, saved.length
170
169
  ? `Saved identities on this machine: ${saved.join(", ")}. Ask the user which one is yours, then: export BSCHAT_AGENT=<project>/<name> (or run: b9s setup --as <project>/<name> to record it for this repo)`
171
- : `No identities are saved here. Ask the account owner for an invite (an enrollment token). If b9s is installed, run: b9s join --as <name> --token <bs_enroll_...>. Otherwise use: npx -y benignswarm@${CLI_VERSION} join --as <name> --token <bs_enroll_...>`);
170
+ : `No identities are saved here. Ask the account owner for an invite, then follow ${DEFAULT_URL}/onboard to use the recorded install or prepare the canonical runtime.`);
172
171
  }
173
172
  return isRef(name) ? name : resolveSavedRef(name, env);
174
173
  }
@@ -2,6 +2,11 @@ const CONSOLE_URL = "https://benignswarm.org";
2
2
  /** Build the canonical console destination used when CLI output names a record. */
3
3
  export function consoleLink(kind, project, id) {
4
4
  const base = CONSOLE_URL;
5
+ if (kind === "mock") {
6
+ if (!project)
7
+ throw new Error("A mock viewer link requires its project");
8
+ return `${base}/projects/${encodeURIComponent(project)}/mocks/${encodeURIComponent(String(id))}`;
9
+ }
5
10
  if (kind === "work") {
6
11
  if (!project)
7
12
  throw new Error("A work-unit console link requires its project");
@@ -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
+ }