@forkstage/verify 0.5.5 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,128 @@
1
+ import type { Event } from "@forkstage/proof";
2
+ import { type Recipe } from "@forkstage/recipe";
3
+ import { type Launched } from "./build-identity.js";
4
+ import { type SignedIn } from "./identities.js";
5
+ import { type Exec, type MailMessage } from "./index.js";
6
+ import type { ApiSurface, Intent, Plan, PlanRequest } from "./plan.js";
7
+ import { type Scenario, type ScenarioPlan, type ScenarioRun } from "./scenario.js";
8
+ import type { ChangeFiles } from "./scope.js";
9
+ export type Log = (line: string) => void;
10
+ export type Origin = "repo" | "change" | "forkstage";
11
+ /** One fork, as the plan needs it. */
12
+ export interface ForkPort {
13
+ id: string;
14
+ /** The service that runs the repository's code. */
15
+ appService?: string | undefined;
16
+ /** The app's public address, for requests from outside the fork. */
17
+ url?: string | undefined;
18
+ /** A command in a service; output and exit code, never a throw for a non-zero exit. */
19
+ exec(service: string, command: string, timeoutMs?: number): Promise<Exec>;
20
+ /** A command on the fork's machine, outside every service. Absent where there is none. */
21
+ guest?(command: string, timeoutSeconds?: number): Promise<{
22
+ exitCode: number;
23
+ output: string;
24
+ }>;
25
+ /** The tail of every service's log. */
26
+ logs(lines: number): Promise<string>;
27
+ /** Captured mail; null when this platform cannot read it. */
28
+ mail?(options: {
29
+ since?: string;
30
+ limit: number;
31
+ }): Promise<MailMessage[] | null>;
32
+ /** A line in the fork's timeline, which becomes the proof. */
33
+ record(event: Event): Promise<void>;
34
+ }
35
+ /** What the platform gives the plan besides the fork. */
36
+ export interface RunPorts {
37
+ fork: ForkPort;
38
+ /** A fresh fork of the build before the change; its owner strikes it. */
39
+ baseFork?(): Promise<{
40
+ fork: ForkPort;
41
+ done(): Promise<void>;
42
+ commit?: string | undefined;
43
+ }>;
44
+ /** The verification agent's scenarios for the intent (Forkstage's hosts). */
45
+ planScenarios?(request: AgentRequest): Promise<ScenarioOutcome>;
46
+ /** The older plan of checks, where scenarios cannot run. */
47
+ planChecks?(request: AgentRequest): Promise<PlanOutcome>;
48
+ /** Keep what the first fork of a build found running. */
49
+ recordLaunched?(launched: Launched[]): Promise<void>;
50
+ }
51
+ export interface AgentRequest {
52
+ intent: Intent;
53
+ recipe: Recipe;
54
+ api: ApiSurface | null;
55
+ identities: {
56
+ name: string;
57
+ role?: string;
58
+ }[];
59
+ replan: boolean;
60
+ }
61
+ /** The planner request for an agent request, the same from the CLI and the control plane. */
62
+ export declare function agentPlanRequest(req: AgentRequest, mode: "scenarios" | "checks"): PlanRequest;
63
+ export interface PlanOutcome {
64
+ plan?: Plan;
65
+ model?: string;
66
+ declined?: string;
67
+ error?: string;
68
+ ms: number;
69
+ reusedFrom?: string;
70
+ }
71
+ export interface ScenarioOutcome {
72
+ plan?: ScenarioPlan;
73
+ model?: string;
74
+ declined?: string;
75
+ error?: string;
76
+ ms: number;
77
+ reusedFrom?: string;
78
+ }
79
+ /** A frozen scenario as the proof keeps it. */
80
+ export interface FrozenScenario {
81
+ name: string;
82
+ requirement: string;
83
+ goal: "must" | "must_not";
84
+ hash: string;
85
+ code: string;
86
+ }
87
+ /** Who wrote a test run or a recipe check, from the recipe at the base and the changed files. */
88
+ export interface Provenance {
89
+ test: (name: string, command: string) => Origin | undefined;
90
+ check: (name: string, command?: string) => Origin | undefined;
91
+ }
92
+ /**
93
+ * "change" when the test or check is not in the recipe at the base, or runs a file the change
94
+ * touched; "repo" otherwise; unknown when the base's recipe could not be read (`baseRecipe`
95
+ * undefined). `baseRecipe` null means the base had no recipe at all.
96
+ */
97
+ export declare function provenanceOf(baseRecipe: string | null | undefined, changed: string[]): Provenance;
98
+ export interface RunInput {
99
+ recipe: Recipe;
100
+ intent?: Intent | undefined;
101
+ only?: string[] | undefined;
102
+ replan?: boolean | undefined;
103
+ /** The build the fork must be running, when it was forked from one. */
104
+ build?: {
105
+ key: string;
106
+ source: string;
107
+ recorded: Launched[] | null;
108
+ } | undefined;
109
+ /** What differs from the base, when it is known. */
110
+ files: ChangeFiles | null;
111
+ provenance: Provenance;
112
+ /** Routes read from the source, for an app with no OpenAPI document. */
113
+ sourceApi: ApiSurface | null;
114
+ }
115
+ export interface RunOutput {
116
+ launched: Launched[] | null;
117
+ scenarios: FrozenScenario[];
118
+ /** What the verification agent said it could not test. */
119
+ uncovered: string[];
120
+ /** The build check failed: nothing else ran. */
121
+ stopped: boolean;
122
+ }
123
+ /** The whole plan against one fork. */
124
+ export declare function runPlan(ports: RunPorts, input: RunInput, log: Log): Promise<RunOutput>;
125
+ /** Sign the recipe's identities in, once, and record how that went. */
126
+ export declare function identities(fork: ForkPort, recipe: Recipe, log: Log): Promise<SignedIn>;
127
+ /** Run frozen scenarios on a fork's machine, against the app on its own port. */
128
+ export declare function runScenariosIn(fork: ForkPort, recipe: Recipe, scenarios: Scenario[], identityHeaders: Record<string, Record<string, string>>): Promise<Map<string, ScenarioRun>>;
package/dist/runner.js ADDED
@@ -0,0 +1,500 @@
1
+ import { parseTestCounts } from "@forkstage/proof";
2
+ import { captureHosts, parseRecipe } from "@forkstage/recipe";
3
+ import { compareRuns } from "./baseline.js";
4
+ import { appServices, checkIdentity, IDENTITY_SCRIPT } from "./build-identity.js";
5
+ import { runFlow } from "./flow.js";
6
+ import { signIn } from "./identities.js";
7
+ import { changeScope, emailEvents, logScan, mailOutcome, NO_CAPTURE, NO_CHECKS, runCheck, apiSmoke as smoke, tailText, } from "./index.js";
8
+ import { migrationsProbe } from "./migrations.js";
9
+ import { toFlowStep } from "./plan.js";
10
+ import { routesFallback } from "./routes.js";
11
+ import { judge, parseRun, scenarioCommand, scenarioHash, stated, } from "./scenario.js";
12
+ import { smokeRoutes } from "./source-routes.js";
13
+ /** The planner request for an agent request, the same from the CLI and the control plane. */
14
+ export function agentPlanRequest(req, mode) {
15
+ const first = req.recipe.ready.find((r) => "http" in r);
16
+ return {
17
+ intent: req.intent,
18
+ stack: req.recipe.stack,
19
+ app: {
20
+ api: req.api,
21
+ mail_capture: captureHosts(req.recipe).length > 0,
22
+ readiness: first && "http" in first ? first.http.slice(first.http.indexOf("/")) : null,
23
+ recipe_checks: req.recipe.checks.map((x) => x.name),
24
+ identities: req.identities,
25
+ },
26
+ max_checks: 8,
27
+ // High by default: a false Broken costs more than the seconds medium saves.
28
+ effort: process.env.FORKSTAGE_PLANNER_EFFORT === "medium" ? "medium" : "high",
29
+ ...(mode === "scenarios" ? { mode: "scenarios" } : {}),
30
+ };
31
+ }
32
+ /**
33
+ * "change" when the test or check is not in the recipe at the base, or runs a file the change
34
+ * touched; "repo" otherwise; unknown when the base's recipe could not be read (`baseRecipe`
35
+ * undefined). `baseRecipe` null means the base had no recipe at all.
36
+ */
37
+ export function provenanceOf(baseRecipe, changed) {
38
+ const touches = (command) => Boolean(command) &&
39
+ changed.some((p) => {
40
+ const mod = p.replace(/\.py$/, "").replace(/\//g, ".");
41
+ return (command.includes(p) || (p.endsWith(".py") && command.includes(mod)));
42
+ });
43
+ let before = null;
44
+ if (baseRecipe !== undefined) {
45
+ const parsed = baseRecipe === null ? null : parseRecipe(baseRecipe);
46
+ before = parsed?.ok
47
+ ? {
48
+ tests: new Set(parsed.recipe.tests.map((t) => t.name)),
49
+ checks: new Set(parsed.recipe.checks.map((c) => c.name)),
50
+ }
51
+ : { tests: new Set(), checks: new Set() };
52
+ }
53
+ return {
54
+ test: (name, command) => !before ? undefined : !before.tests.has(name) || touches(command) ? "change" : "repo",
55
+ check: (name, command) => !before ? undefined : !before.checks.has(name) || touches(command) ? "change" : "repo",
56
+ };
57
+ }
58
+ const record = (fork, name, o, extra = {}) => fork.record({
59
+ kind: "check",
60
+ at: new Date().toISOString(),
61
+ name,
62
+ status: o.status,
63
+ ms: o.ms,
64
+ detail: o.detail,
65
+ ...(o.tail ? { tail: o.tail } : {}),
66
+ ...(o.evidence?.length ? { evidence: o.evidence } : {}),
67
+ ...(extra.source ? { source: extra.source } : {}),
68
+ ...(extra.goal ? { goal: extra.goal } : {}),
69
+ ...(extra.origin ? { origin: extra.origin } : {}),
70
+ });
71
+ const execOf = (fork) => (service, command) => fork.exec(service, command, 600_000);
72
+ const mailOf = (fork, recipe) => captureHosts(recipe).length && fork.mail
73
+ ? async (since) => (await fork.mail?.({ since, limit: 50 })) ?? []
74
+ : undefined;
75
+ const healthyNow = (fork, recipe) => async () => {
76
+ if (!fork.url)
77
+ return true;
78
+ const first = recipe.ready.find((c) => "http" in c);
79
+ const path = first && "http" in first ? first.http.slice(first.http.indexOf("/")) : "/";
80
+ for (let i = 0; i < 30; i++) {
81
+ const ok = await fetch(`${fork.url}${path}`, { signal: AbortSignal.timeout(5000) }).then((r) => r.ok, () => false);
82
+ if (ok)
83
+ return true;
84
+ await new Promise((r) => setTimeout(r, 1000));
85
+ }
86
+ return false;
87
+ };
88
+ /** The whole plan against one fork. */
89
+ export async function runPlan(ports, input, log) {
90
+ const { fork } = ports;
91
+ const { recipe } = input;
92
+ const out = { launched: null, scenarios: [], uncovered: [], stopped: false };
93
+ // Which code serves, before anything is trusted to the fork.
94
+ if (input.build) {
95
+ out.launched = await buildIdentity(ports, recipe, input.build, log);
96
+ if (!out.launched) {
97
+ out.stopped = true;
98
+ return out;
99
+ }
100
+ }
101
+ const signed = await identities(fork, recipe, log);
102
+ // The verification agent writes while the tests and the smoke run.
103
+ const api = await agentSurface(fork, input.sourceApi);
104
+ const agentRequest = input.intent
105
+ ? {
106
+ intent: input.intent,
107
+ recipe,
108
+ api,
109
+ identities: signed.available,
110
+ replan: input.replan === true,
111
+ }
112
+ : null;
113
+ const scenariosPlanned = agentRequest && ports.planScenarios ? ports.planScenarios(agentRequest) : null;
114
+ const checksPlanned = agentRequest && !scenariosPlanned && ports.planChecks ? ports.planChecks(agentRequest) : null;
115
+ await record(fork, "change scope", input.files
116
+ ? changeScope(input.files, recipe)
117
+ : {
118
+ status: "skipped",
119
+ detail: "the change could not be measured (not a git checkout)",
120
+ ms: 0,
121
+ });
122
+ const m = await migrationsProbe({
123
+ recipeMigrate: recipe.migrate,
124
+ appService: fork.appService,
125
+ exec: execOf(fork),
126
+ healthy: healthyNow(fork, recipe),
127
+ });
128
+ if (m.command)
129
+ log(`Migrations: ${m.tool} (${m.command})`);
130
+ await record(fork, "migrations", m);
131
+ const changed = input.files ? input.files.changed.length + input.files.deleted.length : 0;
132
+ await runTests(ports, recipe, log, input.only, input.provenance, changed > 0);
133
+ const port = fork.appService ? recipe.services[fork.appService]?.port : undefined;
134
+ await record(fork, "api smoke", await smoke(fork.url, log, async () => {
135
+ const table = await routesFallback(execOf(fork), fork.appService, port);
136
+ if (table && !(table.kind === "routes" && !table.routes.length))
137
+ return table;
138
+ return input.sourceApi
139
+ ? {
140
+ kind: "routes",
141
+ source: input.sourceApi.source,
142
+ routes: smokeRoutes(input.sourceApi),
143
+ }
144
+ : table;
145
+ }));
146
+ await changeChecks(fork, recipe, log, input.only, signed.headers, input.provenance);
147
+ if (input.intent && scenariosPlanned) {
148
+ const outcome = await scenariosPlanned;
149
+ out.uncovered = outcome.plan?.not_covered ?? [];
150
+ out.scenarios = await scenarioChecks(ports, recipe, input.intent, outcome, log, input.only, signed.headers);
151
+ }
152
+ else if (input.intent && checksPlanned) {
153
+ const outcome = await checksPlanned;
154
+ out.uncovered = outcome.plan?.not_covered ?? [];
155
+ await agentChecks(fork, recipe, input.intent, outcome, log, input.only, signed.headers);
156
+ }
157
+ await capturedMail(fork, recipe, log);
158
+ const started = Date.now();
159
+ try {
160
+ const text = await fork.logs(400);
161
+ const o = logScan(text, Date.now() - started);
162
+ log(`Service logs: ${o.detail}`);
163
+ await record(fork, "service logs", o);
164
+ }
165
+ catch (error) {
166
+ await record(fork, "service logs", {
167
+ status: "skipped",
168
+ detail: `could not read logs: ${error.message}`,
169
+ ms: Date.now() - started,
170
+ });
171
+ }
172
+ return out;
173
+ }
174
+ /** The surface the agent plans against: the app's OpenAPI document, else the source's routes. */
175
+ async function agentSurface(fork, sourceApi) {
176
+ const { fetchOpenApi } = await import("./index.js");
177
+ const { surfaceFromOpenApi } = await import("./plan.js");
178
+ const found = fork.url ? await fetchOpenApi(fork.url).catch(() => null) : null;
179
+ return found ? surfaceFromOpenApi(found.doc, found.path) : sourceApi;
180
+ }
181
+ async function buildIdentity(ports, recipe, expected, log) {
182
+ const { fork } = ports;
183
+ const started = Date.now();
184
+ const r = fork.guest
185
+ ? await fork
186
+ .guest(IDENTITY_SCRIPT, 60)
187
+ .catch((error) => ({ exitCode: 1, output: error.message }))
188
+ : { exitCode: 1, output: "" };
189
+ const res = checkIdentity(r.output, expected, appServices(recipe), expected.recorded);
190
+ const ms = Date.now() - started;
191
+ log(res.ok ? `Build checked: ${res.detail}` : `Build check failed: ${res.detail}`);
192
+ await record(fork, "build", res.ok
193
+ ? { status: "passed", detail: res.detail, ms }
194
+ : { status: "inconclusive", detail: `could not verify which code runs: ${res.detail}`, ms });
195
+ if (res.ok && !expected.recorded && ports.recordLaunched)
196
+ await ports.recordLaunched(res.launched).catch(() => { });
197
+ return res.ok ? res.launched : null;
198
+ }
199
+ /** Sign the recipe's identities in, once, and record how that went. */
200
+ export async function identities(fork, recipe, log) {
201
+ if (!Object.keys(recipe.identities ?? {}).length)
202
+ return { headers: {}, available: [], outcome: { status: "skipped", detail: "", ms: 0 } };
203
+ log(`Signing in as ${Object.keys(recipe.identities).join(", ")}`);
204
+ const signed = await signIn(recipe, {
205
+ base: fork.url,
206
+ appService: fork.appService,
207
+ exec: execOf(fork),
208
+ readMail: mailOf(fork, recipe),
209
+ });
210
+ await record(fork, "identities", signed.outcome);
211
+ return signed;
212
+ }
213
+ /**
214
+ * The recipe's test runs. A failing run is run again on the build before the change, in a fork
215
+ * of its own: failing the same way there makes it already failing, the repository's, not the
216
+ * change's.
217
+ */
218
+ async function runTests(ports, recipe, log, only, origin, hasChange) {
219
+ const { fork } = ports;
220
+ if (!recipe.tests.length) {
221
+ await record(fork, "tests", {
222
+ status: "skipped",
223
+ ms: 0,
224
+ detail: "no test runs under tests: in forkstage.yaml",
225
+ });
226
+ return;
227
+ }
228
+ const runs = [];
229
+ for (const t of recipe.tests) {
230
+ if (only && !only.includes(t.name))
231
+ continue;
232
+ const service = t.in ?? fork.appService;
233
+ if (!service)
234
+ continue;
235
+ log(`Test run ${t.name}: ${t.run} in ${service}`);
236
+ const r = await fork.exec(service, t.run, 600_000);
237
+ const counts = parseTestCounts(r.output);
238
+ log(` ${r.exitCode === 0 ? "passed" : `failed (exit ${r.exitCode})`}${counts.passed !== undefined ? ` · ${counts.passed} passed${counts.failed ? `, ${counts.failed} failed` : ""}` : ""}`);
239
+ runs.push({ t, r });
240
+ }
241
+ const failing = runs.filter((x) => x.r.exitCode !== 0).map((x) => x.t);
242
+ let earlier = null;
243
+ if (failing.length && hasChange && ports.baseFork) {
244
+ log(`Running ${failing.map((t) => t.name).join(", ")} again without the change, to see whether it was already failing`);
245
+ earlier = await (async () => {
246
+ const base = await ports.baseFork?.();
247
+ if (!base)
248
+ return null;
249
+ try {
250
+ const m = new Map();
251
+ for (const t of failing) {
252
+ const service = t.in ?? base.fork.appService;
253
+ if (!service)
254
+ continue;
255
+ const r = await base.fork.exec(service, t.run, 600_000);
256
+ m.set(t.name, {
257
+ exitCode: r.exitCode,
258
+ output: r.output,
259
+ ...parseTestCounts(r.output),
260
+ ...(base.commit ? { commit: base.commit } : {}),
261
+ });
262
+ }
263
+ return m;
264
+ }
265
+ finally {
266
+ await base.done().catch(() => { });
267
+ }
268
+ })().catch(() => null);
269
+ }
270
+ for (const { t, r } of runs) {
271
+ const counts = parseTestCounts(r.output);
272
+ const was = earlier?.get(t.name);
273
+ const cmp = was
274
+ ? compareRuns({ exitCode: r.exitCode, output: r.output, ...counts }, was)
275
+ : null;
276
+ if (was && cmp)
277
+ log(cmp.same
278
+ ? ` ${t.name} fails the same way without the change: already failing`
279
+ : ` ${t.name} without the change: ${was.exitCode === 0 ? "passes" : "fails differently"}`);
280
+ const who = origin.test(t.name, t.run);
281
+ await fork.record({
282
+ kind: "test",
283
+ at: new Date().toISOString(),
284
+ name: t.name,
285
+ command: t.run,
286
+ exitCode: r.exitCode,
287
+ ms: r.ms,
288
+ ...counts,
289
+ tail: tailText(r.output),
290
+ ...(who ? { origin: who } : {}),
291
+ ...(was && cmp
292
+ ? {
293
+ before: {
294
+ ...(was.commit ? { commit: was.commit } : {}),
295
+ exitCode: was.exitCode,
296
+ ...(was.passed !== undefined ? { passed: was.passed } : {}),
297
+ ...(was.failed !== undefined ? { failed: was.failed } : {}),
298
+ same: cmp.same,
299
+ ...(cmp.added.length ? { added: cmp.added } : {}),
300
+ },
301
+ }
302
+ : {}),
303
+ });
304
+ }
305
+ }
306
+ /** The change checks the recipe declares. */
307
+ async function changeChecks(fork, recipe, log, only, identityHeaders, origin) {
308
+ if (!recipe.checks.length) {
309
+ await record(fork, "change checks", NO_CHECKS);
310
+ return;
311
+ }
312
+ for (const c of recipe.checks) {
313
+ if (only && !only.includes(c.name))
314
+ continue;
315
+ log(`Check ${c.name}`);
316
+ const o = await runCheck(c, {
317
+ identities: identityHeaders,
318
+ base: fork.url,
319
+ appService: fork.appService,
320
+ exec: execOf(fork),
321
+ readMail: mailOf(fork, recipe),
322
+ });
323
+ await record(fork, c.name, o, {
324
+ source: "recipe",
325
+ origin: origin.check(c.name, c.run ?? c.steps?.map((st) => st.run ?? "").join(" ")),
326
+ });
327
+ }
328
+ }
329
+ /** The older plan of checks, run as flows against the fork. */
330
+ async function agentChecks(fork, recipe, intent, outcome, log, only, identityHeaders) {
331
+ const plan = outcome.plan;
332
+ if (!plan) {
333
+ await record(fork, "agent checks", {
334
+ status: "skipped",
335
+ detail: `the verification agent could not run: ${outcome.error ?? outcome.declined ?? "no plan"}`,
336
+ ms: outcome.ms,
337
+ });
338
+ return;
339
+ }
340
+ await fork.record({
341
+ kind: "note",
342
+ at: new Date().toISOString(),
343
+ text: plan.checks.length
344
+ ? `Verification agent (${outcome.model}) ${outcome.reusedFrom ? `reused its plan from ${outcome.reusedFrom.slice(11, 16)} UTC` : `planned ${plan.checks.length} check${plan.checks.length === 1 ? "" : "s"} in ${(outcome.ms / 1000).toFixed(1)} s`} for: ${intent.feature.slice(0, 200)}${plan.not_covered.length ? `. Not covered: ${plan.not_covered.join("; ")}` : ""}`
345
+ : `Verification agent planned no checks: ${outcome.declined ?? "nothing testable from the surface"}.`,
346
+ });
347
+ if (!plan.checks.length) {
348
+ await record(fork, "agent checks", {
349
+ status: "skipped",
350
+ detail: `no check from the verification agent: ${outcome.declined ?? "nothing testable from the surface"}`,
351
+ ms: outcome.ms,
352
+ });
353
+ return;
354
+ }
355
+ const chosen = only ? plan.checks.filter((c) => only.includes(c.name)) : plan.checks;
356
+ for (const c of chosen) {
357
+ log(`Agent check ${c.name} (${c.goal})`);
358
+ let steps;
359
+ try {
360
+ steps = c.steps.map(toFlowStep);
361
+ }
362
+ catch (error) {
363
+ await record(fork, c.name, {
364
+ status: "inconclusive",
365
+ detail: `${c.claim} — could not run: the planned steps are malformed (${error.message.slice(0, 120)})`,
366
+ ms: 0,
367
+ }, { source: "agent", goal: c.goal, origin: "forkstage" });
368
+ continue;
369
+ }
370
+ const o = await runFlow({ name: c.name, steps, browser: false }, {
371
+ base: fork.url,
372
+ appService: fork.appService,
373
+ exec: execOf(fork),
374
+ readMail: mailOf(fork, recipe),
375
+ identities: identityHeaders,
376
+ });
377
+ await record(fork, c.name, { ...o, detail: `${c.claim} — ${o.detail}` }, { source: "agent", goal: c.goal, origin: "forkstage" });
378
+ }
379
+ }
380
+ /** Run frozen scenarios on a fork's machine, against the app on its own port. */
381
+ export async function runScenariosIn(fork, recipe, scenarios, identityHeaders) {
382
+ const out = new Map();
383
+ const port = fork.appService ? recipe.services[fork.appService]?.port : undefined;
384
+ for (const s of scenarios) {
385
+ if (!port || !fork.guest) {
386
+ out.set(s.name, {
387
+ outcome: "prerequisite",
388
+ why: !port
389
+ ? "the app has no port in forkstage.yaml to send requests to"
390
+ : "this platform cannot run scenarios",
391
+ observations: [],
392
+ });
393
+ continue;
394
+ }
395
+ const cmd = scenarioCommand(s, {
396
+ base: `http://127.0.0.1:${port}`,
397
+ identities: identityHeaders,
398
+ });
399
+ const r = await fork.guest(cmd, 180).catch((error) => ({
400
+ exitCode: 3,
401
+ output: `FS ${JSON.stringify({ error: error.message })}`,
402
+ }));
403
+ out.set(s.name, parseRun(r.exitCode, r.output));
404
+ }
405
+ return out;
406
+ }
407
+ async function scenarioChecks(ports, recipe, intent, outcome, log, only, identityHeaders) {
408
+ const { fork } = ports;
409
+ const plan = outcome.plan;
410
+ if (!plan?.scenarios.length) {
411
+ await record(fork, "agent checks", {
412
+ status: "skipped",
413
+ detail: `no scenario from the verification agent: ${outcome.error ?? outcome.declined ?? "nothing testable from the routes"}${plan?.not_covered.length ? `; ${plan.not_covered.join("; ")}` : ""}`,
414
+ ms: outcome.ms,
415
+ });
416
+ return [];
417
+ }
418
+ const kind = intent.kind ?? "feature";
419
+ const chosen = only ? plan.scenarios.filter((s) => only.includes(s.name)) : plan.scenarios;
420
+ await fork.record({
421
+ kind: "note",
422
+ at: new Date().toISOString(),
423
+ text: `Verification agent (${outcome.model}) ${outcome.reusedFrom ? `reused its scenarios from ${outcome.reusedFrom.slice(11, 16)} UTC` : `wrote ${plan.scenarios.length} scenario${plan.scenarios.length === 1 ? "" : "s"} in ${(outcome.ms / 1000).toFixed(1)} s`} for a ${kind.replace("_", " ")}: ${intent.feature.slice(0, 200)}${plan.not_covered.length ? `. Not covered: ${plan.not_covered.join("; ")}` : ""}`,
424
+ });
425
+ const started = Date.now();
426
+ log(`Running ${chosen.length} scenario${chosen.length === 1 ? "" : "s"} on this build`);
427
+ const now = await runScenariosIn(fork, recipe, chosen, identityHeaders);
428
+ const needsBase = kind === "bug_fix" || kind === "refactor";
429
+ let earlier = null;
430
+ if (needsBase && ports.baseFork) {
431
+ log(`Running ${chosen.length} scenario${chosen.length === 1 ? "" : "s"} on the build before the change`);
432
+ earlier = await (async () => {
433
+ const base = await ports.baseFork?.();
434
+ if (!base)
435
+ return null;
436
+ try {
437
+ const signed = await identities(base.fork, recipe, () => { });
438
+ return await runScenariosIn(base.fork, recipe, chosen, signed.headers);
439
+ }
440
+ finally {
441
+ await base.done().catch(() => { });
442
+ }
443
+ })().catch(() => null);
444
+ }
445
+ // The stated requirements take the change's kind; the agent's own additions are guards.
446
+ const given = [...intent.must, ...intent.must_not];
447
+ for (const s of chosen) {
448
+ const run = now.get(s.name);
449
+ const as = given.length && !stated(s.requirement, given) ? "guard" : kind;
450
+ const j = judge(as, run, earlier?.get(s.name));
451
+ log(` ${s.name}: ${j.status}`);
452
+ await record(fork, s.name, {
453
+ status: j.status,
454
+ detail: `${s.requirement} — ${j.detail}`,
455
+ ms: Math.round((Date.now() - started) / chosen.length),
456
+ evidence: j.evidence,
457
+ }, { source: "agent", goal: s.goal, origin: "forkstage" });
458
+ }
459
+ return chosen.map((s) => ({
460
+ name: s.name,
461
+ requirement: s.requirement,
462
+ goal: s.goal,
463
+ hash: scenarioHash(s.code),
464
+ code: s.code,
465
+ }));
466
+ }
467
+ /** Captured mail: each message the stack tried to send becomes an email event. */
468
+ async function capturedMail(fork, recipe, log) {
469
+ const started = Date.now();
470
+ const hosts = captureHosts(recipe);
471
+ if (!hosts.length) {
472
+ await record(fork, "captured mail", NO_CAPTURE);
473
+ return;
474
+ }
475
+ let messages;
476
+ try {
477
+ messages = fork.mail ? await fork.mail({ limit: 100 }) : null;
478
+ }
479
+ catch (error) {
480
+ await record(fork, "captured mail", {
481
+ status: "warn",
482
+ detail: `could not read the mail service: ${error.message}`,
483
+ ms: Date.now() - started,
484
+ });
485
+ return;
486
+ }
487
+ if (messages === null) {
488
+ await record(fork, "captured mail", {
489
+ status: "skipped",
490
+ detail: "this platform does not read captured mail",
491
+ ms: 0,
492
+ });
493
+ return;
494
+ }
495
+ log(`Captured mail: ${messages.length} message${messages.length === 1 ? "" : "s"}`);
496
+ for (const e of emailEvents(messages))
497
+ await fork.record(e);
498
+ await record(fork, "captured mail", mailOutcome(messages, hosts, Date.now() - started));
499
+ }
500
+ //# sourceMappingURL=runner.js.map