@cnc-tools/storm 0.5.0 → 0.7.0

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.
Files changed (171) hide show
  1. package/dist/build-info.js +1 -1
  2. package/dist/combine-errors.js +2 -2
  3. package/dist/commands/dashboard.js +1 -1
  4. package/dist/commands/{run → exec}/cleanup.d.ts +1 -1
  5. package/dist/commands/{run → exec}/cleanup.js +1 -1
  6. package/dist/commands/{run/outcomes.d.ts → exec/command.d.ts} +103 -112
  7. package/dist/commands/exec/command.js +23 -0
  8. package/dist/commands/{run → exec}/job-summary.d.ts +5 -1
  9. package/dist/commands/{run → exec}/job-summary.js +5 -2
  10. package/dist/commands/{run → exec}/live-view.js +29 -13
  11. package/dist/commands/exec/metadata.d.ts +69 -0
  12. package/dist/commands/exec/metadata.js +55 -0
  13. package/dist/commands/{run → exec}/mint-failed.js +4 -4
  14. package/dist/commands/exec/outcomes.d.ts +664 -0
  15. package/dist/commands/exec/outcomes.js +347 -0
  16. package/dist/commands/{run → exec}/progress.d.ts +14 -2
  17. package/dist/commands/{run → exec}/progress.js +54 -9
  18. package/dist/commands/exec/run-command.d.ts +227 -0
  19. package/dist/commands/exec/run-command.js +696 -0
  20. package/dist/commands/exec/run-metadata.d.ts +59 -0
  21. package/dist/commands/exec/run-metadata.js +61 -0
  22. package/dist/commands/{run → exec}/run-record.d.ts +110 -5
  23. package/dist/commands/{run → exec}/run-record.js +57 -1
  24. package/dist/commands/exec/testserver-flags.d.ts +48 -0
  25. package/dist/commands/exec/testserver-flags.js +80 -0
  26. package/dist/commands/{run → exec}/view.js +36 -4
  27. package/dist/commands/runs/facts.d.ts +25 -0
  28. package/dist/commands/runs/facts.js +38 -5
  29. package/dist/commands/runs/list/command.d.ts +25 -0
  30. package/dist/commands/runs/list/outcomes.d.ts +25 -0
  31. package/dist/commands/runs/logs/metadata.js +1 -1
  32. package/dist/commands/runs/logs/outcomes.js +4 -1
  33. package/dist/commands/runs/past-run.d.ts +2 -2
  34. package/dist/commands/runs/past-run.js +2 -2
  35. package/dist/commands/runs/show/command.d.ts +25 -0
  36. package/dist/commands/runs/show/metadata.js +2 -2
  37. package/dist/commands/runs/show/outcomes.d.ts +25 -0
  38. package/dist/commands/runs/show/outcomes.js +37 -5
  39. package/dist/commands/vitest/command.d.ts +325 -0
  40. package/dist/commands/vitest/command.js +138 -0
  41. package/dist/commands/vitest/metadata.d.ts +69 -0
  42. package/dist/commands/vitest/metadata.js +35 -0
  43. package/dist/commands/vitest/outcomes.d.ts +298 -0
  44. package/dist/commands/vitest/outcomes.js +77 -0
  45. package/dist/config/index.d.ts +2 -1
  46. package/dist/config/index.js +1 -0
  47. package/dist/config/resolve.d.ts +3 -3
  48. package/dist/config/resolve.js +3 -3
  49. package/dist/config/resource-config.d.ts +2 -2
  50. package/dist/config/schema.d.ts +1 -1
  51. package/dist/config/set.d.ts +15 -4
  52. package/dist/config/set.js +28 -12
  53. package/dist/config-file/define.d.ts +8 -6
  54. package/dist/context.d.ts +6 -3
  55. package/dist/context.js +4 -2
  56. package/dist/core/command-provider.d.ts +1 -1
  57. package/dist/core/events.d.ts +9 -7
  58. package/dist/core/presentation.js +1 -1
  59. package/dist/core/presentations.js +1 -1
  60. package/dist/core/run-state.d.ts +30 -6
  61. package/dist/core/run-state.js +19 -4
  62. package/dist/core/run.d.ts +17 -4
  63. package/dist/core/run.js +61 -25
  64. package/dist/resources/testserver/command.d.ts +1 -1
  65. package/dist/resources/testserver/command.js +1 -1
  66. package/dist/resources/testserver/config.d.ts +1 -1
  67. package/dist/resources/testserver/config.js +3 -2
  68. package/dist/resources/testserver/credential-facts.js +1 -1
  69. package/dist/resources/testserver/resource.d.ts +2 -2
  70. package/dist/resources/testserver/sandbox/create.d.ts +2 -2
  71. package/dist/resources/testserver/sandbox/create.js +2 -2
  72. package/dist/resources.d.ts +9 -6
  73. package/dist/resources.js +3 -3
  74. package/dist/runner/events.d.ts +64 -1
  75. package/dist/runner/gateways.d.ts +17 -6
  76. package/dist/runner/index.d.ts +5 -4
  77. package/dist/runner/index.js +4 -3
  78. package/dist/runner/live/snapshot-records.js +18 -4
  79. package/dist/runner/prepare.d.ts +23 -4
  80. package/dist/runner/prepare.js +13 -3
  81. package/dist/runner/ready.d.ts +7 -3
  82. package/dist/runner/ready.js +11 -5
  83. package/dist/runner/scope.d.ts +17 -1
  84. package/dist/runner/scope.js +4 -0
  85. package/dist/runner/snapshot-build.d.ts +3 -1
  86. package/dist/runner/snapshot-build.js +12 -2
  87. package/dist/runner/snapshot-cache.d.ts +46 -8
  88. package/dist/runner/snapshot-cache.js +60 -11
  89. package/dist/runner/snapshot-key.d.ts +12 -1
  90. package/dist/runner/snapshot-key.js +17 -1
  91. package/dist/runner/snapshot-save.d.ts +53 -0
  92. package/dist/runner/snapshot-save.js +148 -0
  93. package/dist/sdk/index.js +1 -1
  94. package/dist/sdk/payload/payload.d.ts +2 -2
  95. package/dist/sdk/payload/payload.js +2 -2
  96. package/dist/story/align.d.ts +1 -1
  97. package/dist/story/align.js +1 -1
  98. package/dist/story/definition.d.ts +22 -15
  99. package/dist/story/definition.js +2 -2
  100. package/dist/story/errors.js +1 -1
  101. package/dist/story/gateways.d.ts +45 -25
  102. package/dist/story/gateways.js +2 -2
  103. package/dist/story/host.d.ts +11 -8
  104. package/dist/story/host.js +37 -37
  105. package/dist/story/index.d.ts +1 -1
  106. package/dist/story/index.js +4 -4
  107. package/dist/story/json.d.ts +1 -1
  108. package/dist/story/json.js +2 -2
  109. package/dist/story/live/recording-gateway.d.ts +2 -0
  110. package/dist/story/live/{artifact-gateway.js → recording-gateway.js} +33 -12
  111. package/dist/story/mode.d.ts +2 -2
  112. package/dist/story/mode.js +1 -1
  113. package/dist/story/orphans.d.ts +23 -5
  114. package/dist/story/orphans.js +44 -8
  115. package/dist/story/recording.d.ts +62 -0
  116. package/dist/story/{artifact.js → recording.js} +31 -27
  117. package/dist/story/report.d.ts +21 -9
  118. package/dist/story/report.js +37 -25
  119. package/dist/story/settle.d.ts +23 -21
  120. package/dist/story/settle.js +17 -16
  121. package/dist/story/{run.d.ts → start.d.ts} +18 -17
  122. package/dist/story/{run.js → start.js} +66 -43
  123. package/dist/vercel-cli/driver.d.ts +1 -1
  124. package/dist/vercel-cli/entry.d.ts +1 -1
  125. package/dist/vercel-cli/entry.js +1 -1
  126. package/dist/vercel-cli/verbose.d.ts +2 -2
  127. package/dist/vercel-cli/verbose.js +2 -2
  128. package/dist/vitest/config.d.ts +5 -5
  129. package/dist/vitest/config.js +5 -5
  130. package/dist/vitest/find-vitest.d.ts +7 -0
  131. package/dist/vitest/find-vitest.js +28 -0
  132. package/dist/vitest/fixtures.d.ts +2 -2
  133. package/dist/vitest/fixtures.js +3 -3
  134. package/dist/vitest/gateways.d.ts +37 -6
  135. package/dist/vitest/gateways.js +3 -2
  136. package/dist/vitest/live/list-gateway.d.ts +7 -3
  137. package/dist/vitest/live/list-gateway.js +55 -8
  138. package/dist/vitest/plan.d.ts +41 -8
  139. package/dist/vitest/plan.js +47 -16
  140. package/dist/vitest/sandbox.d.ts +1 -1
  141. package/dist/vitest/sandbox.js +1 -1
  142. package/dist/vitest/test-events.d.ts +2 -2
  143. package/dist/vitest/test-events.js +3 -3
  144. package/dist/vitest/test-results.d.ts +1 -1
  145. package/dist/vitest/test-results.js +1 -1
  146. package/dist/vitest/types.d.ts +1 -1
  147. package/package.json +2 -2
  148. package/skills/overview.md +5 -4
  149. package/skills/read-run-output.md +1 -1
  150. package/dist/commands/run/command.d.ts +0 -327
  151. package/dist/commands/run/command.js +0 -620
  152. package/dist/commands/run/metadata.d.ts +0 -47
  153. package/dist/commands/run/metadata.js +0 -83
  154. package/dist/commands/run/outcomes.js +0 -332
  155. package/dist/story/artifact.d.ts +0 -60
  156. package/dist/story/live/artifact-gateway.d.ts +0 -2
  157. /package/dist/commands/{run → exec}/live-view.d.ts +0 -0
  158. /package/dist/commands/{run → exec}/mint-failed.d.ts +0 -0
  159. /package/dist/commands/{run → exec}/redaction.d.ts +0 -0
  160. /package/dist/commands/{run → exec}/redaction.js +0 -0
  161. /package/dist/commands/{run → exec}/run-collector.d.ts +0 -0
  162. /package/dist/commands/{run → exec}/run-collector.js +0 -0
  163. /package/dist/commands/{run → exec}/tests-summary.d.ts +0 -0
  164. /package/dist/commands/{run → exec}/tests-summary.js +0 -0
  165. /package/dist/commands/{run → exec}/text.d.ts +0 -0
  166. /package/dist/commands/{run → exec}/text.js +0 -0
  167. /package/dist/commands/{run → exec}/view.d.ts +0 -0
  168. /package/dist/commands/{run → exec}/waterfall.d.ts +0 -0
  169. /package/dist/commands/{run → exec}/waterfall.js +0 -0
  170. /package/dist/commands/{run → exec}/worker-chart.d.ts +0 -0
  171. /package/dist/commands/{run → exec}/worker-chart.js +0 -0
@@ -0,0 +1,696 @@
1
+ // What `exec` and `vitest` share: the request fields and checks every run takes, settling the run, and running it.
2
+ // The two commands differ only in the command's argv and in what `vitest` does once the run is settled and before
3
+ // anything is minted, leased or started (`RunCommandSpec.prepare`).
4
+ import { refused, } from "@vercel/clinkr";
5
+ import { NodeSignalCancellation } from "@vercel/clinkr/node";
6
+ import { z } from "zod";
7
+ import { describeMintFailure, requireTarget, settleCredential, } from "../../credential/index.js";
8
+ import { prepareRunner, } from "../../runner/index.js";
9
+ import { fileSettings, invalidConfig, loadSettingsFile, parseSetFlags, settleResourceOptions, } from "../../config/index.js";
10
+ import { commandExitStatus, executeRun, observeAll, RUN_DIRECTORIES_KEPT, runDirectoryObserver, stepLog, testEventsPath, timedProgress, } from "../../core/index.js";
11
+ import { RESOURCE_COMMANDS, RESOURCE_CONFIGS, RESOURCE_REPORTS, RESOURCES, RUN_CLEANUP, stormTimeline, } from "../../resources.js";
12
+ import { parseKeepTime } from "../../time/index.js";
13
+ import { jobSummaryMarkdown } from "./job-summary.js";
14
+ import { testsSummaryLines } from "./tests-summary.js";
15
+ import { TESTSERVER_OWN_FLAGS, testserverFlagProblems, withTestserverFlags } from "./testserver-flags.js";
16
+ import { runView } from "./view.js";
17
+ import { waterfallLines } from "./waterfall.js";
18
+ import { testsChart } from "./worker-chart.js";
19
+ import { runCollector } from "./run-collector.js";
20
+ import { mintFailedErrors } from "./mint-failed.js";
21
+ import { outcomes, runErrors } from "./outcomes.js";
22
+ import { keptText, notDeletedText, notKeptText, notStoppedText, } from "./cleanup.js";
23
+ import { redactingObserver, redactingTerminal, redactor, redactStrings } from "./redaction.js";
24
+ import { runRecordText, testTotals, } from "./run-record.js";
25
+ /** The request fields every run takes, `exec`'s and `vitest`'s: each command adds the fields for its command. */
26
+ export const RUN_REQUEST_FIELDS = {
27
+ set: z.array(z.string()).default([]),
28
+ testserverSandboxes: z.number().optional(),
29
+ testserverBuild: z.string().optional(),
30
+ testserverMinTimeLeft: z.string().optional(),
31
+ testserverTtl: z.string().optional(),
32
+ testserverNoCreate: z.boolean().optional(),
33
+ scope: z.string().min(1).optional(),
34
+ project: z.string().min(1).optional(),
35
+ credential: z.enum(["mint", "github-actions"]).optional(),
36
+ local: z.boolean().default(false),
37
+ rebuildSnapshot: z.boolean().default(false),
38
+ saveSnapshot: z.boolean().default(false),
39
+ showOutput: z.boolean().default(false),
40
+ keepSandbox: z.string().optional(),
41
+ verbose: z.boolean().default(false),
42
+ };
43
+ /** The CLI spellings of the fields every run takes. */
44
+ export const RUN_CLI_OPTIONS = { project: { short: "p" } };
45
+ const runRequestSchema = z.object(RUN_REQUEST_FIELDS);
46
+ /**
47
+ * Runs a run's command, the argv `spec.prepare` gives once the run is settled (`exec`'s command after `--`, or the
48
+ * `vitest run` argv `vitest` builds), with the run payload in `STORM_RUN` and the host variables each resource
49
+ * names removed (`TESTSERVER_BASES`/`TESTSERVER_BASE` for the Testserver pool), waits for it, and prints a waterfall.
50
+ * With a Testserver side it first leases usable Testserver sandboxes from the pool, creates the rest, and prints the
51
+ * sandbox list, and releases the leases once the command ends. The process exits with the command's code, or `128 + n`
52
+ * when signal `n` ended it: `bin/storm.ts` applies the status this records in `app.exit`, which Clinkr's 0 or 1
53
+ * can't carry.
54
+ *
55
+ * A run holds a resource when `storm.config.ts` has it under `resources` or the command line gives one of its
56
+ * options: a `--set resources.<name>.<option>=<value>`, or for the Testserver pool resource one of its own flags
57
+ * (`--testserver-sandboxes`, `--testserver-build`, `--testserver-min-time-left`, `--testserver-ttl`,
58
+ * `--testserver-no-create`; `testserver-flags.ts`). A run has a Testserver side when it holds the Testserver pool
59
+ * resource; without one, the run payload names no Testserver sandbox.
60
+ *
61
+ * Signals: before the command starts, the first signal stops the run at its next step, lets creates in flight settle,
62
+ * releases its leases, and cancels (exit `128 + n`). A signal while `spec.prepare` runs, such as while `vitest` counts
63
+ * the tests, stops it and cancels the run before anything is minted, leased or started (`canceledBeforeStart`). While
64
+ * the command runs, Ctrl+C and a closed terminal reach it directly through its process group, so only SIGTERM is
65
+ * passed on; either way the run waits for the command. A second signal makes Clinkr's host exit at once with
66
+ * `128 + n`, leaving the leases for the next run to reclaim, since their holder is gone.
67
+ *
68
+ * `scope` and `project` come from `--scope` and `--project`, else `storm.config.ts` (found from the working
69
+ * directory and checked whole); they have no default, so one of the two must give them when the run mints. Each
70
+ * resource's options come from the command line, else the file's section, else the option's default (the registry's
71
+ * resource configs, `src/resources.ts`). On the command line, each Testserver pool option has its own
72
+ * `--testserver-<option>` flag, and any other option comes from `--set resources.<name>.<option>=<value>`, which may
73
+ * repeat. An unknown key path, a key path given twice, a key path with its own flag, or a value its option's rule
74
+ * refuses is a usage error. Options that don't fit together once merged, such as a TTL not longer than `minTimeLeft`,
75
+ * or a `--testserver-ttl` with `noCreate`, are `invalid_resource_options`, which names each value's source.
76
+ *
77
+ * By default the command runs in a runner sandbox, from the `runner` recipe of `storm.config.ts`, which only a
78
+ * runner run reads: `missing_runner` without one. `--local` (no config key) runs it on this machine instead. The
79
+ * runner's local checks (`prepareRunner`) run before anything is minted, leased or created. A runner run always mints,
80
+ * for the runner sandbox, so it needs `scope` and `project` whatever resources it holds. In a runner run, the first
81
+ * SIGINT, SIGTERM or SIGHUP stops the run in any phase: the remote command is killed, every sandbox the run started is
82
+ * stopped and deleted, the leases are released, and the run cancels. `--rebuild-snapshot` (no config key, not with
83
+ * `--local`) builds a runner snapshot whatever the cache holds, and drops HEAD's branch's branch snapshots from it.
84
+ * `--save-snapshot` (no config key, not with `--local` or a `--keep-sandbox` above 0) saves the runner sandbox as a
85
+ * branch snapshot once the command ended on its own, while the leases are released, so the next run on the branch
86
+ * starts from it; a run with it on a branch keeps no runner sandbox, however it ends, and one on a detached HEAD says
87
+ * so as it starts and keeps its runner sandbox as without the flag.
88
+ *
89
+ * `--credential` (no config key) picks the credential source: `mint`, the default, or `github-actions`, which requests
90
+ * a GitHub Actions OIDC token instead and so needs no `--scope` or `--project`; any given are unused. A runner run
91
+ * needs the mint, so `--credential github-actions` without `--local` is a usage error. The registry says whether a held
92
+ * resource takes the credential (`RESOURCE_COMMANDS.takesCredential`): the Testserver pool does unless `noCreate`. A
93
+ * `--credential` given to a run where none does is `credential_unused`.
94
+ *
95
+ * Progress shows by the app's presentation (`presentation.ts`): a live view on a terminal a person watches, plain lines
96
+ * elsewhere, folded for GitHub Actions, nothing under `--json`. `--show-output` (no config key, not with `--local`)
97
+ * prints the runner's step output above the live view. `--verbose` (no config key) prints each create's progress
98
+ * messages and the runner's step output, and sets `verbose` in the run payload. Every run, `--json` included, writes a
99
+ * run directory (`core/run-directory.ts`), and a run that can't make one goes on without it; the waterfall names it and
100
+ * the `storm runs show` command that reads the run back by its run id, which a ran outcome carries as `runId`, and
101
+ * in a GitHub Actions step with a job summary the run appends a Markdown summary there.
102
+ *
103
+ * Each resource is a provider (the registry, `src/resources.ts`, lists them), whose folder under `src/resources/` says
104
+ * what the run does with it, and whose command half settles it (`RESOURCE_COMMANDS.settle`). The run refuses in this
105
+ * order: `invalid_config`, `invalid_resource_options`, `credential_unused`; in a runner run `missing_runner`, then
106
+ * `missing_target`; in a local run where a resource takes the credential, `missing_target` for the mint; then each
107
+ * resource's settle, in provider order; then `spec.prepare`'s refusal, if any. A resource's secrets, such as a token,
108
+ * are hidden as `<token>` in the run's progress, its run directory, its job summary, its outcome, `spec.prepare`'s
109
+ * refusal, and its command's output, in either kind of run.
110
+ */
111
+ export async function runCommand({ app, ui, signal }, request, spec) {
112
+ const sets = parseSetFlags(request.set, RESOURCE_CONFIGS, TESTSERVER_OWN_FLAGS);
113
+ // `validate` refused every `--set` this can't read, so it always reads.
114
+ if (!sets.ok)
115
+ throw new Error(`--set should have been refused: ${sets.problems.join("; ")}`);
116
+ const settled = await settleRun(app, { ...request, given: withTestserverFlags(sets.values, request) });
117
+ if (!settled.ok)
118
+ return settled.refusal;
119
+ // The resources' secrets: every event, the command's output and a preparation's refusal pass through `redact`
120
+ // before any view, the run directory or the summary sees them. A refusal can quote what preparation ran with this
121
+ // machine's environment, such as the last line of `vitest list`'s stderr.
122
+ const { secrets } = settled.settlement;
123
+ const redact = redactor(secrets);
124
+ const ready = await spec.prepare(settled, signal);
125
+ if (signal.aborted)
126
+ return canceledBeforeStart();
127
+ if (!ready.ok)
128
+ return secrets.length === 0 ? ready.refusal : redactStrings(ready.refusal, redact);
129
+ const { argv, plan } = ready;
130
+ const { configFile, options, where, settlement } = ready.settled;
131
+ if (settlement.secrets !== secrets)
132
+ throw new Error("spec.prepare changed the run's secrets");
133
+ const base = {
134
+ argv,
135
+ // A resource can name host variables that could point the command at something else than the run payload
136
+ // names, so the command never sees one.
137
+ env: Object.fromEntries(Object.entries(app.env).filter(([name]) => !RESOURCE_REPORTS.hostVariablesToDrop.includes(name))),
138
+ version: app.version,
139
+ commit: app.commit,
140
+ configFile,
141
+ verbose: request.verbose,
142
+ };
143
+ // Both kinds of run take the same requests. A local run carries the credential choice it settled, if any, whose
144
+ // source the core builds; a runner run's resources share its one mint.
145
+ let run;
146
+ if (where.kind === "local")
147
+ run = {
148
+ ...base,
149
+ resources: settlement.requests,
150
+ ...(where.credential === undefined ? {} : { credential: where.credential }),
151
+ };
152
+ else {
153
+ const prepared = await prepareRunner(app.context, {
154
+ cwd: app.cwd,
155
+ recipe: where.recipe,
156
+ resources: RESOURCE_REPORTS.runnerResources(options),
157
+ rebuild: request.rebuildSnapshot,
158
+ saveSnapshot: request.saveSnapshot,
159
+ });
160
+ if (prepared.kind !== "ok")
161
+ return prepareRefusal(prepared, configFile);
162
+ const { save } = prepared.prepared;
163
+ run = {
164
+ ...base,
165
+ resources: settlement.requests,
166
+ runner: {
167
+ prepared: prepared.prepared,
168
+ target: where.target,
169
+ user: app.user,
170
+ sandbox: save?.kind === "branch"
171
+ ? { kind: "save", branch: save.branch }
172
+ : { kind: "keep", ms: keepSandboxMinutes(request.keepSandbox, where.recipe, app.env) * 60_000 },
173
+ },
174
+ };
175
+ }
176
+ // With --local, only SIGTERM is passed on to the local command, which Ctrl+C and a closed terminal reach
177
+ // directly. In a runner run, `executeRun` stops on any signal itself.
178
+ const terminate = new AbortController();
179
+ const forward = () => {
180
+ const reason = signal.reason;
181
+ if (reason instanceof NodeSignalCancellation && reason.signal === "SIGTERM")
182
+ terminate.abort(reason);
183
+ };
184
+ if (run.runner === undefined) {
185
+ if (signal.aborted)
186
+ forward();
187
+ else
188
+ signal.addEventListener("abort", forward, { once: true });
189
+ }
190
+ const view = runView({
191
+ presentation: app.presentation,
192
+ progress: ui.progress,
193
+ context: app.context,
194
+ showOutput: request.showOutput,
195
+ verbose: request.verbose,
196
+ });
197
+ const git = await checkoutGit(app.context.checkout, app.cwd);
198
+ const startedAt = app.context.clock.now();
199
+ const record = redactStrings({
200
+ version: 1,
201
+ startedAt: startedAt.toISOString(),
202
+ cwd: app.cwd,
203
+ configFile,
204
+ argv,
205
+ ...(plan === undefined ? {} : { plan }),
206
+ where: run.runner === undefined ? { kind: "local" } : startedWhere(run.runner),
207
+ git,
208
+ }, redact);
209
+ const opened = await app.context.runDirectories.open({
210
+ startedAt,
211
+ keep: RUN_DIRECTORIES_KEPT,
212
+ run: runRecordText(record),
213
+ });
214
+ const directory = opened.ok ? opened.directory : undefined;
215
+ const collector = runCollector(directory);
216
+ const observers = [collector.observer, view.observer];
217
+ if (directory !== undefined)
218
+ observers.push(runDirectoryObserver(directory));
219
+ const observer = observeAll(...observers);
220
+ const terminal = teeTerminal(view.runnerTerminal, directory);
221
+ let outcome;
222
+ try {
223
+ const ended = await executeRun(RESOURCES, { ...app.context, runnerTerminal: secrets.length === 0 ? terminal : redactingTerminal(terminal, redact) }, run.runner === undefined && directory !== undefined
224
+ ? { ...run, testEvents: testEventsPath(directory.path) }
225
+ : run, { signal, terminate: terminate.signal }, timedProgress(app.context.clock, secrets.length === 0 ? observer : redactingObserver(observer, redact)));
226
+ // An outcome's facts, such as a failed Sandbox call's message, can quote what the run handed its command.
227
+ outcome = secrets.length === 0 ? ended : redactStrings(ended, redact);
228
+ }
229
+ catch (error) {
230
+ // A live region must not outlive the run, however it ends, and closing the run directory completes it and
231
+ // removes the test events a local command staged there, unredacted. They are never saved: the run didn't end.
232
+ await view.finish([]);
233
+ await directory?.close();
234
+ throw error;
235
+ }
236
+ signal.removeEventListener("abort", forward);
237
+ const ran = await summarize(app, {
238
+ command: spec.name,
239
+ view,
240
+ collector,
241
+ opened,
242
+ local: run.runner === undefined,
243
+ redact,
244
+ record,
245
+ outcome,
246
+ requests: run.resources,
247
+ });
248
+ switch (outcome.kind) {
249
+ case "ran": {
250
+ app.exit.status = commandExitStatus(outcome.command);
251
+ const { command } = outcome;
252
+ return spec.ran({
253
+ version: app.version,
254
+ commit: app.commit,
255
+ configFile,
256
+ resources: RESOURCE_REPORTS.ranFacts(outcome.resources, run.resources),
257
+ cleanup: RUN_CLEANUP.facts(outcome),
258
+ command: command.kind === "exited"
259
+ ? { exitCode: command.code, signal: null }
260
+ : command.kind === "signaled"
261
+ ? { exitCode: null, signal: command.signal }
262
+ : { exitCode: null, signal: null },
263
+ runner: outcome.runner === undefined
264
+ ? null
265
+ : {
266
+ snapshotId: outcome.runner.snapshotId,
267
+ base: outcome.runner.base,
268
+ snapshotBranch: outcome.runner.snapshotBranch,
269
+ snapshotHead: outcome.runner.snapshotHead,
270
+ built: outcome.runner.built,
271
+ vcpus: outcome.runner.vcpus,
272
+ region: outcome.runner.region,
273
+ runtime: outcome.runner.runtime,
274
+ buildMs: outcome.runner.buildMs,
275
+ save: outcome.runner.save,
276
+ },
277
+ timeline: timelineFacts(ran),
278
+ runId: directory?.id ?? null,
279
+ }, plan);
280
+ }
281
+ case "resource-unprepared":
282
+ return RESOURCE_COMMANDS.unpreparedError(outcome);
283
+ case "resource-refused":
284
+ return RESOURCE_COMMANDS.refusedError(outcome, RUN_CLEANUP.facts(outcome));
285
+ // The run's mint: in a runner run for the runner sandbox, in a local run for a resource that needed it.
286
+ case "mint-failed":
287
+ return mintFailedErrors.mintFailed({
288
+ ...outcome.target,
289
+ ...describeMintFailure(outcome.failure, outcome.target),
290
+ runner: outcome.runner,
291
+ cleanup: RUN_CLEANUP.facts(outcome),
292
+ });
293
+ case "spawn-failed":
294
+ return runErrors.spawnFailed({
295
+ executable: outcome.executable,
296
+ message: outcome.message,
297
+ // Only a local run spawns its command on this machine, so it holds no runner sandbox.
298
+ cleanup: RUN_CLEANUP.facts({ runnerCleanup: null, resourceCleanup: outcome.resourceCleanup }),
299
+ });
300
+ case "canceled":
301
+ return outcomes.canceled({ changed: canceledChanges(outcome) });
302
+ case "runner-failed":
303
+ return runErrors.runnerFailed({
304
+ failure: runnerFailureFacts(outcome.failure),
305
+ cleanup: RUN_CLEANUP.facts(outcome),
306
+ });
307
+ case "snapshot-gone":
308
+ return runErrors.snapshotGone({
309
+ snapshotId: outcome.entry.snapshotId,
310
+ base: outcome.entry.base,
311
+ removal: outcome.removal === undefined ? null : { ...outcome.removal },
312
+ cleanup: RUN_CLEANUP.facts(outcome),
313
+ });
314
+ }
315
+ }
316
+ /** What is wrong with a run's request that its schema can't say, as `validate` reports it. */
317
+ export function runProblems({ set, credential, local, rebuildSnapshot, saveSnapshot, showOutput, keepSandbox, ...rest }) {
318
+ return [
319
+ ...setProblems(set).map((problem) => ({ field: "set", message: `${problem}.` })),
320
+ ...testserverFlagProblems(rest),
321
+ ...(rebuildSnapshot && local
322
+ ? [{ field: "rebuildSnapshot", message: "--rebuild-snapshot builds a runner snapshot; drop it or --local." }]
323
+ : []),
324
+ ...(!local && credential === "github-actions"
325
+ ? [
326
+ {
327
+ field: "credential",
328
+ message: "A runner run needs the mint: the runner sandbox uses a minted Vercel token. Add --local, or drop --credential github-actions.",
329
+ },
330
+ ]
331
+ : []),
332
+ ...(showOutput && local
333
+ ? [{ field: "showOutput", message: "--show-output prints a runner run's step output; drop it or --local." }]
334
+ : []),
335
+ ...(keepSandbox !== undefined && parseKeepTime(keepSandbox) === undefined
336
+ ? [
337
+ {
338
+ field: "keepSandbox",
339
+ message: `--keep-sandbox takes 0, or a whole number of minutes or hours up to 5h, such as 30m or 2h, not ${JSON.stringify(keepSandbox)}.`,
340
+ },
341
+ ]
342
+ : []),
343
+ ...(keepSandbox !== undefined && local
344
+ ? [{ field: "keepSandbox", message: "--keep-sandbox keeps a runner run's runner sandbox; drop it or --local." }]
345
+ : []),
346
+ ...(saveSnapshot && local
347
+ ? [{ field: "saveSnapshot", message: "--save-snapshot saves a runner run's runner sandbox; drop it or --local." }]
348
+ : []),
349
+ ...(saveSnapshot && keepSandbox !== undefined && (parseKeepTime(keepSandbox) ?? 0) > 0
350
+ ? [
351
+ {
352
+ field: "saveSnapshot",
353
+ message: "--save-snapshot saves the runner sandbox instead of keeping it; drop --keep-sandbox or set it to 0.",
354
+ },
355
+ ]
356
+ : []),
357
+ ];
358
+ }
359
+ /**
360
+ * The refusal for a runner whose local checks failed: no base, submodules, a recipe storm can't use at the run's
361
+ * base or for its sandbox count (`invalid_config`, naming the key inside `runner`), or git or tar failing.
362
+ */
363
+ function prepareRefusal(prepared, configFile) {
364
+ switch (prepared.kind) {
365
+ case "no-base-ref":
366
+ return runErrors.noBaseRef({ refs: prepared.refs.map(({ ref, reason }) => ({ ref, reason })) });
367
+ case "submodules":
368
+ return runErrors.submodulesRefused({ paths: [...prepared.paths] });
369
+ case "invalid-recipe":
370
+ return invalidConfig(configFile ?? "", [
371
+ { key: ["runner", ...prepared.path].join("."), location: null, problem: prepared.problem },
372
+ ]);
373
+ case "checkout-failed":
374
+ return checkoutFailedRefusal(prepared.failure);
375
+ }
376
+ }
377
+ /**
378
+ * A run canceled before it started, while it was settled or prepared: nothing was minted, leased or started, and the
379
+ * command didn't run.
380
+ */
381
+ export function canceledBeforeStart() {
382
+ return outcomes.canceled({ changed: "The command didn't run.\nNothing was minted, leased or started." });
383
+ }
384
+ /**
385
+ * The refusal for a runner run whose checkout git couldn't read before anything was minted, leased or started:
386
+ * `runner_failed` with `checkout-failed`, holding nothing.
387
+ */
388
+ export function checkoutFailedRefusal(failure) {
389
+ return runErrors.runnerFailed({
390
+ failure: runnerFailureFacts({ kind: "checkout-failed", failure }),
391
+ cleanup: RUN_CLEANUP.facts(NOTHING_HELD),
392
+ });
393
+ }
394
+ /**
395
+ * Once the run is done: reads a `--local` run's staged test events through `collector`, which redacts and streams each
396
+ * one to the private test events file, then publishes the redacted test events as `tests.jsonl`, writes the timeline
397
+ * and how the run ended (`record` with `ended`, its runner sandbox and runner snapshot from the final state, and a ran
398
+ * outcome's acquired resources' ran facts, from their `requests`) to the run directory, in that order, and closes it,
399
+ * which removes the staged test events and an unpublished partial file. Then it appends the job summary, and has the
400
+ * view print the waterfall, with the worker chart under its tests lane, the tests' summary, the logs of failed steps,
401
+ * and what went wrong with either file. The job summary leaves the worker chart out. It answers the timeline, which a
402
+ * ran outcome carries.
403
+ */
404
+ async function summarize(app, run) {
405
+ const { view, opened } = run;
406
+ const directory = opened.ok ? opened.directory : undefined;
407
+ if (run.local && directory !== undefined)
408
+ await run.collector.readLocal(directory, run.redact);
409
+ const collected = run.collector.finish();
410
+ const { state, tests } = collected;
411
+ const ran = stormTimeline(state);
412
+ directory?.publishTestEvents();
413
+ directory?.writeTimeline(JSON.stringify(ran, null, 2));
414
+ directory?.writeRun(runRecordText({
415
+ ...run.record,
416
+ where: endedWhere(run.record.where, state.runner, run.outcome.kind === "ran" ? (run.outcome.runner?.save ?? null) : null),
417
+ ended: runEnd(run.outcome, state.command, tests, run.requests),
418
+ }));
419
+ const writeFailure = await directory?.close();
420
+ const failed = tests.events.some((event) => event.kind === "test-result" && event.state === "fail");
421
+ const testsLines = testsSummaryLines(tests.events, tests.unreadable, tests.incomplete);
422
+ const stepLogs = failedStepLogs(ran, directory?.path, app.env);
423
+ const clock = workerClock(ran, collected, run.local);
424
+ const charted = clock === undefined ? undefined : testsChart(tests.events, tests.unreadable, clock, tests.incomplete);
425
+ const summarized = await app.context.jobSummary.appendJobSummary(jobSummaryMarkdown(ran, { command: run.command, logs: directory?.path, details: [...testsLines, ...stepLogs] }));
426
+ await view.finish(waterfallLines(ran, {
427
+ width: view.width,
428
+ paint: view.paint,
429
+ logs: logsText(opened, writeFailure, app.env, failed),
430
+ ...(charted === undefined ? {} : { workers: charted.lanes }),
431
+ details: [
432
+ ...(charted?.notes ?? testsLines),
433
+ ...stepLogs,
434
+ ...(summarized.kind === "failed"
435
+ ? [` couldn't append to the job summary at ${summarized.failure.path}: ${summarized.failure.message}`]
436
+ : []),
437
+ ],
438
+ }));
439
+ return ran;
440
+ }
441
+ /**
442
+ * How the workers' clock maps to the run's, for the worker chart under the tests lane; undefined without one. A local
443
+ * command's workers share the run's clock. In a runner run they run in the runner sandbox, so the offset comes from
444
+ * when the run heard each worker test event.
445
+ */
446
+ function workerClock(ran, collected, local) {
447
+ const tests = ran.rows.find((row) => row.name === "tests");
448
+ if (tests === undefined)
449
+ return undefined;
450
+ return { runStartedAt: Date.parse(ran.startedAt), offsetMs: local ? 0 : collected.workerOffsetMs, tests };
451
+ }
452
+ /** The command's output, in either kind of run, to `terminal` and to the run directory's `command.log`. */
453
+ function teeTerminal(terminal, directory) {
454
+ if (directory === undefined)
455
+ return terminal;
456
+ return {
457
+ color: terminal.color,
458
+ writeStdout: (text) => {
459
+ directory.appendCommandOutput(text);
460
+ terminal.writeStdout(text);
461
+ },
462
+ writeStderr: (text) => {
463
+ directory.appendCommandOutput(text);
464
+ terminal.writeStderr(text);
465
+ },
466
+ };
467
+ }
468
+ /** A path as a person reads it: under `HOME`, starting `~/`. */
469
+ function displayPath(path, env) {
470
+ const home = env["HOME"];
471
+ if (home === undefined || home === "" || !path.startsWith(`${home}/`))
472
+ return path;
473
+ return `~${path.slice(home.length)}`;
474
+ }
475
+ /**
476
+ * Where the run directory is, for the summary's logs line, and what went wrong with it: it couldn't be made, a write
477
+ * failed, or pruning couldn't remove an older one or the staged test events left in one. The run goes on whichever it
478
+ * was. Then the command that reads the run back by its run id, with `--failed` when a test `failed`.
479
+ */
480
+ function logsText(opened, writeFailure, env, failed) {
481
+ if (!opened.ok)
482
+ return `none: couldn't make ${opened.failure.path}: ${opened.failure.message}`;
483
+ const path = `${displayPath(opened.directory.path, env)}/`;
484
+ const problems = [
485
+ ...(writeFailure === undefined ? [] : [`couldn't write ${writeFailure.path}: ${writeFailure.message}`]),
486
+ ...opened.pruneFailures.slice(0, 1).map((failure) => `couldn't remove ${failure.path}: ${failure.message}`),
487
+ ];
488
+ const show = `storm runs show ${opened.directory.id}${failed ? " --failed" : ""}`;
489
+ return `${problems.length === 0 ? path : `${path} (${problems.join("; ")})`} · ${show}`;
490
+ }
491
+ /**
492
+ * How the run ended, for `run.json`: its outcome's kind; for a run whose command ran, the status storm exits with
493
+ * and the signal that ended the command; how long the command took, from the command's state once it ended on its own
494
+ * (a command the run stopped has none); the totals of its tests' final results, and why they may be incomplete; and a
495
+ * ran outcome's acquired resources' ran facts, from their `requests`.
496
+ */
497
+ function runEnd(outcome, ran, tests, requests) {
498
+ const command = outcome.kind === "ran" ? outcome.command : undefined;
499
+ const ms = ran?.outcome === undefined || ran.outcome === "stopped" || ran.endedAt === undefined
500
+ ? null
501
+ : ran.endedAt - ran.startedAt;
502
+ return {
503
+ outcome: outcome.kind,
504
+ exitCode: command === undefined ? null : commandExitStatus(command),
505
+ signal: command?.kind === "signaled" ? command.signal : null,
506
+ ms,
507
+ tests: testTotals(tests.events),
508
+ testsIncomplete: tests.incomplete ?? null,
509
+ resources: outcome.kind === "ran" ? RESOURCE_REPORTS.ranFacts(outcome.resources, requests) : null,
510
+ };
511
+ }
512
+ /**
513
+ * Where the checkout `cwd` is in was as the run starts, for `run.json`; null outside a Git checkout, or when git
514
+ * can't say. The run goes on either way.
515
+ */
516
+ async function checkoutGit(checkout, cwd) {
517
+ const root = await checkout.repositoryRoot({ cwd });
518
+ if (!root.ok)
519
+ return null;
520
+ const head = await checkout.head({ repoRoot: root.value });
521
+ return head.ok ? { ...head.value } : null;
522
+ }
523
+ /** How long a runner sandbox keeps running once its run ends, when neither the flag nor the recipe says. */
524
+ export const DEFAULT_KEEP_SANDBOX_MINUTES = 30;
525
+ /**
526
+ * How long the runner sandbox keeps running once the run ends, in minutes: `--keep-sandbox`, else the recipe's
527
+ * `keepSandbox`, else `DEFAULT_KEEP_SANDBOX_MINUTES`, or 0 when `CI` is set, where nobody connects to it.
528
+ */
529
+ function keepSandboxMinutes(flag, recipe, env) {
530
+ // `validate` refused a flag this can't read.
531
+ const fromFlag = flag === undefined ? undefined : parseKeepTime(flag);
532
+ return fromFlag ?? recipe.keepSandboxMinutes ?? (isCi(env) ? 0 : DEFAULT_KEEP_SANDBOX_MINUTES);
533
+ }
534
+ /** Whether `CI` is set, as CI services set it: to anything but empty, `0` or `false`. */
535
+ function isCi(env) {
536
+ const ci = env["CI"];
537
+ return ci !== undefined && ci !== "" && ci !== "0" && ci.toLowerCase() !== "false";
538
+ }
539
+ /** Where a runner run's command runs, as `run.json` records it as the run starts: no sandbox or snapshot yet. */
540
+ function startedWhere(runner) {
541
+ const { prepared, target } = runner;
542
+ return {
543
+ kind: "runner",
544
+ team: target.team,
545
+ project: target.project,
546
+ region: prepared.recipe.region,
547
+ runtime: prepared.recipe.runtime,
548
+ vcpus: prepared.vcpus,
549
+ base: prepared.base,
550
+ baseRef: prepared.baseRef,
551
+ sandbox: null,
552
+ snapshot: null,
553
+ keptUntil: null,
554
+ save: null,
555
+ };
556
+ }
557
+ /**
558
+ * `where` once the run is over, from the runner's final state: for a runner run, the runner sandbox the run started,
559
+ * the runner snapshot it started from, which the run reused or built, when its timeout stops the runner sandbox it
560
+ * kept running, and how saving it as a branch snapshot ended (`save`). Each is null when the run stopped before it,
561
+ * kept no runner sandbox, or saved none.
562
+ */
563
+ function endedWhere(where, runner, save) {
564
+ if (where.kind === "local")
565
+ return where;
566
+ const snapshot = runner?.snapshot;
567
+ return {
568
+ ...where,
569
+ sandbox: runner?.sandbox?.name ?? null,
570
+ snapshot: snapshot === undefined || snapshot.kind === "building"
571
+ ? null
572
+ : {
573
+ id: snapshot.id,
574
+ base: snapshot.base,
575
+ built: snapshot.kind === "built",
576
+ branch: snapshot.branch,
577
+ head: snapshot.head,
578
+ },
579
+ keptUntil: runner?.kept?.stopsAt ?? null,
580
+ save,
581
+ };
582
+ }
583
+ /** For each runner step that failed, where its whole output is: the summary's lines after the critical path. */
584
+ function failedStepLogs(ran, directory, env) {
585
+ if (directory === undefined)
586
+ return [];
587
+ const runner = ran.rows.find((row) => row.name === "runner");
588
+ return (runner?.steps ?? [])
589
+ .filter((step) => step.outcome === "failed")
590
+ .flatMap((step) => {
591
+ const log = stepLog(directory, step.name);
592
+ return log === undefined ? [] : [` failed ${step.name}, whole output: ${displayPath(log, env)}`];
593
+ });
594
+ }
595
+ /** The run's timeline as the ran outcome reports it. */
596
+ function timelineFacts(ran) {
597
+ return {
598
+ ...ran,
599
+ rows: ran.rows.map((row) => ({ ...row, steps: row.steps.map((step) => ({ ...step })) })),
600
+ criticalPath: [...ran.criticalPath],
601
+ };
602
+ }
603
+ /** A runner failure as outcomes report it. */
604
+ function runnerFailureFacts(failure) {
605
+ switch (failure.kind) {
606
+ case "snapshot-build-step-failed":
607
+ case "apply-failed":
608
+ case "install-failed":
609
+ case "build-failed":
610
+ return { kind: failure.kind, label: failure.label, exitCode: failure.exitCode, tail: [...failure.tail] };
611
+ case "sandbox-api-failed":
612
+ return { kind: failure.kind, operation: failure.operation, status: failure.status, message: failure.message };
613
+ case "checkout-failed":
614
+ return { kind: failure.kind, message: failure.failure.message, command: failure.failure.displayCommand ?? null };
615
+ case "credential-claims-missing":
616
+ return { kind: failure.kind, ...failure.target };
617
+ }
618
+ }
619
+ /** The cleanup of a run that never started a runner sandbox or held a resource. */
620
+ const NOTHING_HELD = { runnerCleanup: null, resourceCleanup: {} };
621
+ /** What is wrong with the `--set` flags, for a person: each one `parseSetFlags` can't use. */
622
+ function setProblems(texts) {
623
+ const parsed = parseSetFlags(texts, RESOURCE_CONFIGS, TESTSERVER_OWN_FLAGS);
624
+ return parsed.ok ? [] : parsed.problems;
625
+ }
626
+ /**
627
+ * Settles a run before it starts, refusing in this order: the config file (`invalid_config`); each held resource's
628
+ * merged options (`invalid_resource_options`); a `--credential` no held resource takes (`credential_unused`); in a
629
+ * runner run, the runner recipe (`missing_runner`) and the team and project its mint needs (`missing_target`); in a
630
+ * local run where a held resource takes the credential, the credential source (`missing_target` for the mint); then
631
+ * each held resource's own settle, in provider order.
632
+ */
633
+ async function settleRun(app, request) {
634
+ const file = await loadSettingsFile(app.context.config, app.cwd, RESOURCE_CONFIGS);
635
+ if (!file.ok)
636
+ return file;
637
+ const configFile = file.path;
638
+ const resolved = settleResourceOptions(file, request.given);
639
+ if (!resolved.ok)
640
+ return resolved;
641
+ const { options } = resolved;
642
+ const takesCredential = RESOURCE_COMMANDS.takesCredential(options);
643
+ if (request.credential !== undefined && !takesCredential)
644
+ return refused(runErrors.credentialUnused({ flags: ["--credential"], configFile }));
645
+ const settings = fileSettings(file, request);
646
+ let where;
647
+ if (!request.local) {
648
+ if (settings.runner === undefined)
649
+ return refused(runErrors.missingRunner({ configFile }));
650
+ const required = requireTarget(settings.scope, settings.project);
651
+ if (!required.ok)
652
+ return required;
653
+ where = { kind: "runner", recipe: settings.runner.value, target: required.target };
654
+ }
655
+ else if (takesCredential) {
656
+ const chosen = settleCredential(request.credential ?? "mint", settings.scope, settings.project);
657
+ if (!chosen.ok)
658
+ return chosen;
659
+ where = { kind: "local", credential: chosen.credential };
660
+ }
661
+ else
662
+ where = { kind: "local", credential: undefined };
663
+ const settlement = RESOURCE_COMMANDS.settle(options, app.env, configFile);
664
+ if (!settlement.ok)
665
+ return settlement;
666
+ return { ok: true, configFile, file, options, where, settlement };
667
+ }
668
+ /**
669
+ * What a canceled run changed, for a person: whether its command ran, what happened to a runner run's sandboxes, and
670
+ * what each resource it held says of what it changed (`RESOURCE_COMMANDS.canceledLines`).
671
+ */
672
+ function canceledChanges(outcome) {
673
+ const { commandStopped } = outcome;
674
+ const lines = [
675
+ commandStopped === true ? "The command was stopped in the runner sandbox." : "The command didn't run.",
676
+ ];
677
+ const cleanup = RUN_CLEANUP.facts(outcome).runner;
678
+ if (cleanup !== null)
679
+ lines.push(...runnerCleanupLines(cleanup));
680
+ lines.push(...RESOURCE_COMMANDS.canceledLines(outcome.resources, outcome.resourceCleanup));
681
+ return lines.join("\n");
682
+ }
683
+ /** What happened to a canceled runner run's sandboxes, for a person: the one it kept running, and the rest. */
684
+ function runnerCleanupLines({ kept, notKept, notStopped, notDeleted }) {
685
+ const problems = [
686
+ ...(notKept === null ? [] : [notKeptText(notKept)]),
687
+ ...notStopped.map(notStoppedText),
688
+ ...notDeleted.map(notDeletedText),
689
+ ];
690
+ if (kept === null)
691
+ return problems.length === 0 ? ["Every sandbox the runner started is stopped and deleted."] : problems;
692
+ return [
693
+ keptText(kept),
694
+ ...(problems.length === 0 ? ["Every other sandbox the runner started is stopped and deleted."] : problems),
695
+ ];
696
+ }