@cnc-tools/storm 0.10.0 → 0.11.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 (198) hide show
  1. package/dist/bin/storm.js +17 -9
  2. package/dist/build-info.js +1 -1
  3. package/dist/chunks/{chunk-YF3ICDBY.js → chunk-3ZZVZPMG.js} +1 -1
  4. package/dist/chunks/{chunk-JQ2HK4RN.js → chunk-4EU4AH7E.js} +141 -6
  5. package/dist/chunks/{chunk-ZJ2USLAT.js → chunk-4PRAB24Y.js} +2 -22
  6. package/dist/chunks/chunk-AMTYHUYB.js +257 -0
  7. package/dist/chunks/{chunk-WF4KJ7YG.js → chunk-ETCZ6WP7.js} +1 -1
  8. package/dist/chunks/chunk-FVMQKYTT.js +10 -0
  9. package/dist/chunks/{chunk-XHJGHJBW.js → chunk-GRMD7G4J.js} +33 -275
  10. package/dist/chunks/chunk-ICB4BZJX.js +22 -0
  11. package/dist/chunks/{chunk-AGWW3HDT.js → chunk-KR7WIYLG.js} +1826 -2201
  12. package/dist/chunks/{chunk-OVXD7GES.js → chunk-L4ZPMSKQ.js} +4 -37
  13. package/dist/chunks/chunk-NPPJ57W7.js +569 -0
  14. package/dist/chunks/{chunk-VJQLMGOH.js → chunk-O4BUT7BE.js} +361 -1716
  15. package/dist/chunks/chunk-OJOKQRM6.js +1457 -0
  16. package/dist/chunks/chunk-SLNKW4ZM.js +40 -0
  17. package/dist/chunks/{chunk-AKKNF3WZ.js → chunk-TRFEAYNC.js} +277 -348
  18. package/dist/chunks/chunk-VZZTHCBW.js +93 -0
  19. package/dist/chunks/chunk-WNIQA5J6.js +19 -0
  20. package/dist/chunks/chunk-WSIF7SR6.js +10 -0
  21. package/dist/chunks/{live-app-RIJM3QFD.js → live-app-LOGYUBKB.js} +52 -7
  22. package/dist/commands/exec/cleanup.d.ts +3 -3
  23. package/dist/commands/exec/cleanup.js +6 -2
  24. package/dist/commands/exec/command.d.ts +3 -3
  25. package/dist/commands/exec/command.js +17 -10
  26. package/dist/commands/exec/job-summary.d.ts +1 -1
  27. package/dist/commands/exec/job-summary.js +1 -1
  28. package/dist/commands/exec/live-view.js +5 -5
  29. package/dist/commands/exec/mint-failed.js +1 -1
  30. package/dist/commands/exec/outcomes.d.ts +2 -2
  31. package/dist/commands/exec/outcomes.js +7 -8
  32. package/dist/commands/exec/plan-run.d.ts +3 -5
  33. package/dist/commands/exec/progress.d.ts +3 -3
  34. package/dist/commands/exec/progress.js +6 -6
  35. package/dist/commands/exec/resource-refusals.d.ts +1 -1
  36. package/dist/commands/exec/resource-refusals.js +1 -1
  37. package/dist/commands/exec/run-command.d.ts +14 -9
  38. package/dist/commands/exec/run-command.js +91 -202
  39. package/dist/commands/exec/run-metadata.d.ts +2 -2
  40. package/dist/commands/exec/run-metadata.js +3 -3
  41. package/dist/commands/exec/test-plan.d.ts +1 -35
  42. package/dist/commands/exec/test-plan.js +4 -24
  43. package/dist/commands/exec/view.js +3 -3
  44. package/dist/commands/exec/waterfall.d.ts +3 -1
  45. package/dist/commands/exec/waterfall.js +18 -1
  46. package/dist/commands/runs/facts.d.ts +2 -1
  47. package/dist/commands/runs/facts.js +1 -1
  48. package/dist/commands/runs/list/command.js +10 -9
  49. package/dist/commands/runs/logs/command.js +14 -12
  50. package/dist/commands/runs/past-run.d.ts +3 -27
  51. package/dist/commands/runs/past-run.js +3 -37
  52. package/dist/commands/runs/show/command.js +24 -21
  53. package/dist/commands/runs/show/outcomes.js +2 -2
  54. package/dist/commands/vitest/command.d.ts +3 -3
  55. package/dist/commands/vitest/command.js +24 -17
  56. package/dist/commands/vitest/outcomes.d.ts +1 -1
  57. package/dist/commands/vitest/outcomes.js +1 -1
  58. package/dist/config/credential-resolver.d.ts +6 -3
  59. package/dist/config/credential-resolver.js +6 -5
  60. package/dist/context.d.ts +27 -9
  61. package/dist/context.js +19 -8
  62. package/dist/core/before-run.d.ts +5 -4
  63. package/dist/core/before-run.js +6 -6
  64. package/dist/core/definition-lookup.d.ts +22 -0
  65. package/dist/core/definition-lookup.js +34 -0
  66. package/dist/core/events.d.ts +5 -19
  67. package/dist/core/gateways.d.ts +22 -162
  68. package/dist/core/index.d.ts +10 -11
  69. package/dist/core/index.js +9 -11
  70. package/dist/core/launcher-supplies.js +2 -2
  71. package/dist/core/live/terminal-command-gateway.d.ts +8 -0
  72. package/dist/core/live/terminal-command-gateway.js +49 -0
  73. package/dist/core/presentations.d.ts +4 -3
  74. package/dist/core/presentations.js +4 -5
  75. package/dist/core/resource-registry.d.ts +35 -51
  76. package/dist/core/resource-registry.js +27 -54
  77. package/dist/core/resource-reports.d.ts +37 -4
  78. package/dist/core/resource-reports.js +34 -5
  79. package/dist/core/resources.d.ts +4 -3
  80. package/dist/core/resources.js +2 -4
  81. package/dist/core/run-state.d.ts +1 -1
  82. package/dist/core/run-state.js +1 -1
  83. package/dist/core/run.d.ts +19 -37
  84. package/dist/core/run.js +59 -114
  85. package/dist/core/timeline.js +2 -1
  86. package/dist/credential/events.d.ts +20 -0
  87. package/dist/credential/events.js +4 -0
  88. package/dist/credential/index.d.ts +2 -1
  89. package/dist/credential/index.js +6 -5
  90. package/dist/credential/source.d.ts +38 -26
  91. package/dist/credential/source.js +25 -34
  92. package/dist/extension-commands.d.ts +12 -6
  93. package/dist/extension-commands.js +18 -11
  94. package/dist/extensions/story/command-tree.d.ts +6 -0
  95. package/dist/extensions/story/command-tree.js +21 -0
  96. package/dist/extensions/story/commands/app.d.ts +23 -0
  97. package/dist/extensions/story/commands/app.js +5 -0
  98. package/dist/extensions/story/commands/run/command.d.ts +211 -0
  99. package/dist/extensions/story/commands/run/command.js +259 -0
  100. package/dist/extensions/story/commands/run/metadata.d.ts +4 -0
  101. package/dist/extensions/story/commands/run/metadata.js +8 -0
  102. package/dist/extensions/story/commands/run/outcomes.d.ts +101 -0
  103. package/dist/extensions/story/commands/run/outcomes.js +73 -0
  104. package/dist/extensions/story/commands/tree.d.ts +2 -0
  105. package/dist/extensions/story/commands/tree.js +6 -0
  106. package/dist/extensions/story/extension.d.ts +2 -0
  107. package/dist/extensions/story/extension.js +8 -0
  108. package/dist/extensions/testserver/command-tree.d.ts +1 -1
  109. package/dist/extensions/testserver/command-tree.js +0 -1
  110. package/dist/extensions/testserver/commands/pool/create/command.js +14 -8
  111. package/dist/extensions/testserver/commands/pool/list/command.js +8 -4
  112. package/dist/extensions/testserver/vitest/config.d.ts +7 -5
  113. package/dist/extensions/testserver/vitest/config.js +7 -5
  114. package/dist/extensions/testserver/vitest/fixtures.d.ts +2 -0
  115. package/dist/extensions/testserver/vitest/fixtures.js +36 -5
  116. package/dist/extensions.d.ts +12 -21
  117. package/dist/extensions.js +22 -34
  118. package/dist/forward-sigterm.d.ts +8 -0
  119. package/dist/forward-sigterm.js +18 -0
  120. package/dist/launcher-resolvers/index.d.ts +1 -0
  121. package/dist/launcher-resolvers/index.js +2 -1
  122. package/dist/launcher-resolvers/local-services.d.ts +57 -0
  123. package/dist/launcher-resolvers/local-services.js +7 -0
  124. package/dist/live-app.js +2 -1
  125. package/dist/local-services.d.ts +19 -0
  126. package/dist/local-services.js +37 -0
  127. package/dist/run-directory/gateways.d.ts +167 -0
  128. package/dist/run-directory/gateways.js +2 -0
  129. package/dist/run-directory/index.d.ts +8 -0
  130. package/dist/run-directory/index.js +13 -0
  131. package/dist/run-directory/plan.d.ts +35 -0
  132. package/dist/run-directory/plan.js +24 -0
  133. package/dist/run-directory/reader.d.ts +70 -0
  134. package/dist/run-directory/reader.js +51 -0
  135. package/dist/run-directory/recording.d.ts +92 -0
  136. package/dist/run-directory/recording.js +85 -0
  137. package/dist/{commands/exec → run-directory}/run-collector.d.ts +9 -8
  138. package/dist/{commands/exec → run-directory}/run-collector.js +8 -10
  139. package/dist/{core → run-directory}/run-directory.d.ts +3 -3
  140. package/dist/{core → run-directory}/run-directory.js +2 -2
  141. package/dist/{commands/exec → run-directory}/run-record.d.ts +29 -7
  142. package/dist/{commands/exec → run-directory}/run-record.js +79 -5
  143. package/dist/{commands/exec → run-directory}/timeline-facts.d.ts +4 -8
  144. package/dist/{commands/exec → run-directory}/timeline-facts.js +8 -24
  145. package/dist/runner/events.d.ts +6 -5
  146. package/dist/runner/index.d.ts +13 -17
  147. package/dist/runner/index.js +10 -14
  148. package/dist/runner/prepare.d.ts +28 -6
  149. package/dist/runner/prepare.js +15 -9
  150. package/dist/runner/recipe.d.ts +14 -0
  151. package/dist/runner/recipe.js +12 -0
  152. package/dist/runner/scope.d.ts +18 -11
  153. package/dist/runner/scope.js +12 -10
  154. package/dist/runner/session.d.ts +100 -0
  155. package/dist/runner/session.js +109 -0
  156. package/dist/runner/snapshot-save.d.ts +3 -2
  157. package/dist/runner/snapshot-save.js +6 -5
  158. package/dist/sdk/extension/ci.d.ts +2 -0
  159. package/dist/sdk/extension/ci.js +6 -0
  160. package/dist/sdk/extension/commands.d.ts +11 -13
  161. package/dist/sdk/extension/commands.js +5 -5
  162. package/dist/sdk/extension/index.d.ts +1 -0
  163. package/dist/sdk/extension/index.js +1 -0
  164. package/dist/sdk/extension/lifecycle.d.ts +4 -3
  165. package/dist/sdk/extension/progress.js +2 -2
  166. package/dist/sdk/extension/resource.js +1 -1
  167. package/dist/story/align.d.ts +1 -1
  168. package/dist/story/align.js +1 -1
  169. package/dist/story/command-line.d.ts +6 -16
  170. package/dist/story/command-line.js +11 -23
  171. package/dist/story/errors.d.ts +1 -1
  172. package/dist/story/errors.js +1 -1
  173. package/dist/story/host.d.ts +1 -1
  174. package/dist/story/host.js +2 -2
  175. package/dist/story/index.d.ts +2 -2
  176. package/dist/story/index.js +4 -3
  177. package/dist/story/launch.d.ts +70 -0
  178. package/dist/story/launch.js +77 -0
  179. package/dist/story/report.d.ts +2 -2
  180. package/dist/story/report.js +3 -4
  181. package/dist/story/settle.d.ts +7 -7
  182. package/dist/story/settle.js +5 -5
  183. package/dist/story/start.d.ts +2 -2
  184. package/dist/vendor/testserver-sdk/container/container.d.ts +11 -6
  185. package/dist/vendor/testserver-sdk/container/container.js +38 -16
  186. package/dist/vendor/testserver-sdk/testserver/failure.d.ts +4 -3
  187. package/dist/vendor/testserver-sdk/testserver/failure.js +4 -3
  188. package/package.json +1 -1
  189. package/skills/overview.md +3 -0
  190. package/skills/read-run-output.md +2 -2
  191. package/dist/chunks/chunk-H2VCSNVU.js +0 -351
  192. package/dist/chunks/chunk-J6ZNYUDV.js +0 -21
  193. package/dist/core/mint.d.ts +0 -10
  194. package/dist/core/mint.js +0 -14
  195. package/dist/story/mode.d.ts +0 -17
  196. package/dist/story/mode.js +0 -21
  197. /package/dist/{core → run-directory}/live/run-directory-gateway.d.ts +0 -0
  198. /package/dist/{core → run-directory}/live/run-directory-gateway.js +0 -0
@@ -2,33 +2,15 @@ import {
2
2
  RUN_PAYLOAD_VARIABLE,
3
3
  SANDBOX_TEST_EVENTS_PATH,
4
4
  credentialSourceFor,
5
- keptMs,
6
5
  lineSplitter,
7
- mintSource,
8
- obtainedSource,
6
+ openRunnerSession,
9
7
  parseTestEvent,
10
- readyRunner,
11
- runCommandInSandbox,
12
- runnerSandboxScope,
13
- saveBranchSnapshot,
14
8
  systemClock,
15
9
  systemTimer,
16
- testserverPoolDefinition
17
- } from "./chunk-VJQLMGOH.js";
18
- import {
19
- booleanOption,
20
- defineResource,
21
- mustBe,
22
- resourceFactory
23
- } from "./chunk-XHJGHJBW.js";
24
- import {
25
- testserverExtensionCommands
26
- } from "./chunk-J6ZNYUDV.js";
27
- import {
28
- defineExtension
29
- } from "./chunk-ZJ2USLAT.js";
10
+ testEventLine
11
+ } from "./chunk-O4BUT7BE.js";
30
12
 
31
- // src/core/run-directory.ts
13
+ // src/run-directory/run-directory.ts
32
14
  import { join } from "node:path";
33
15
  var RUNS_SUBPATH = ["runs"];
34
16
  var RUN_DIRECTORIES_KEPT = 1e3;
@@ -69,6 +51,9 @@ function runDirectoryObserver(directory) {
69
51
  };
70
52
  }
71
53
 
54
+ // src/run-directory/run-record.ts
55
+ import { z as z3 } from "zod";
56
+
72
57
  // src/core/reports.ts
73
58
  var WARNINGS_HEADING = "Warnings";
74
59
  function warningTally(count) {
@@ -78,47 +63,9 @@ function warningRows(warnings) {
78
63
  return warnings.length === 0 ? [] : [[WARNINGS_HEADING, warnings.map(({ message }) => message)]];
79
64
  }
80
65
 
81
- // src/core/resource-registry.ts
82
- import { z } from "zod";
83
- function resourceRegistry(list2) {
84
- const named = (definition, key) => {
85
- const resource = list2.find((candidate) => candidate.name === definition);
86
- if (resource === void 0) throw new Error(`${key}'s definition, ${definition}, isn't in the registry`);
87
- return resource;
88
- };
89
- return {
90
- named,
91
- inRegistryOrder: (map) => {
92
- const entries = Object.entries(map).map(([key, record]) => ({
93
- key,
94
- record,
95
- resource: named(record.definition, key)
96
- }));
97
- return list2.flatMap((resource) => entries.filter((entry) => entry.resource === resource));
98
- }
99
- };
100
- }
101
- var warningSchema = z.object({
102
- /** Its snake_case reason. */
103
- reason: z.string(),
104
- message: z.string()
105
- });
106
- function instanceSchema(records) {
107
- const [first, ...rest] = records.map(
108
- ([name, facts]) => z.object({ definition: z.literal(name), facts, warnings: z.array(warningSchema) })
109
- );
110
- const record = first === void 0 ? z.never() : z.discriminatedUnion("definition", [first, ...rest]);
111
- return z.record(z.string(), record);
112
- }
113
- function cleanupInstanceSchema(names) {
114
- const [first, ...rest] = names;
115
- const record = first === void 0 ? z.never() : z.object({ definition: z.enum([first, ...rest]), warnings: z.array(warningSchema) });
116
- return z.record(z.string(), record);
117
- }
118
-
119
66
  // src/core/before-run.ts
120
- function bindLifecycles(resources, worlds) {
121
- const { named } = resourceRegistry(resources);
67
+ function bindLifecycles(lookup, worlds) {
68
+ const { definitions: resources, named } = lookup;
122
69
  const lifecycles = new Map(
123
70
  resources.map((resource) => [resource, resource.lifecycle(worlds[resource.name])])
124
71
  );
@@ -154,44 +101,29 @@ function bindLifecycles(resources, worlds) {
154
101
  };
155
102
  }
156
103
 
157
- // src/core/resource-reports.ts
158
- import { z as z2 } from "zod";
159
- function resourceReports(resources) {
160
- const { inRegistryOrder } = resourceRegistry(resources);
161
- const warningsOf = (facts) => inRegistryOrder(facts).flatMap(({ record }) => record.warnings.map(({ reason, message }) => ({ reason, message })));
104
+ // src/core/definition-lookup.ts
105
+ function definitionLookup(definitions) {
106
+ const byName = /* @__PURE__ */ new Map();
107
+ for (const definition of definitions) if (!byName.has(definition.name)) byName.set(definition.name, definition);
108
+ const named = (definition, key) => {
109
+ const resource = byName.get(definition);
110
+ if (resource === void 0) throw new Error(`${key}'s definition, ${definition}, isn't in the registry`);
111
+ return resource;
112
+ };
162
113
  return {
163
- cleanupSchema: cleanupInstanceSchema(resources.map(({ name }) => name)),
164
- // `{ definition, warnings }` for each instance, in registry order, then the records' order.
165
- cleanupFacts: (cleanup) => Object.fromEntries(
166
- inRegistryOrder(cleanup).map(({ key, record: { definition, warnings } }) => [key, { definition, warnings }])
167
- ),
168
- cleanupRows: (facts) => warningRows(warningsOf(facts)),
169
- cleanupWarnings: warningsOf,
170
- ranSchema: instanceSchema(resources.map(({ name }) => [name, z2.unknown()])),
171
- // `{ definition, facts, warnings }` for each instance, in registry order, then the records' order.
172
- ranFacts: (ran) => Object.fromEntries(
173
- inRegistryOrder(ran).map(({ key, record: { definition, facts, warnings } }) => [
114
+ definitions,
115
+ named,
116
+ inRegistryOrder: (map) => {
117
+ const entries = Object.entries(map).map(([key, record]) => ({
174
118
  key,
175
- { definition, facts, warnings }
176
- ])
177
- ),
178
- ranWarnings: warningsOf,
179
- ranRows: (ran) => inRegistryOrder(ran).flatMap(({ record }) => record.rows),
180
- // The run releases its instances in reverse order, so the cleanup records come in reverse order of the run's
181
- // instances; reversed, they come in the order the run took them.
182
- canceledLines: (cleanup) => inRegistryOrder(Object.fromEntries(Object.entries(cleanup).toReversed())).flatMap(({ record }) => [
183
- ...record.canceled,
184
- ...record.done,
185
- ...record.warnings.map(({ message }) => message)
186
- ])
119
+ record,
120
+ resource: named(record.definition, key)
121
+ }));
122
+ return definitions.flatMap((resource) => entries.filter((entry) => entry.resource === resource));
123
+ }
187
124
  };
188
125
  }
189
126
 
190
- // src/core/resources-of.ts
191
- function resourcesOf(extensions) {
192
- return extensions.flatMap(({ resources }) => resources);
193
- }
194
-
195
127
  // src/core/state-directory.ts
196
128
  import { isAbsolute, join as join2 } from "node:path";
197
129
  function stateDirectoryPattern(subpath) {
@@ -246,8 +178,8 @@ function commandExitStatus(outcome) {
246
178
  function seconds(ms) {
247
179
  return secondsText(secondsOf(ms));
248
180
  }
249
- function resourcePresentations(resources) {
250
- const { named } = resourceRegistry(resources);
181
+ function resourcePresentations(lookup) {
182
+ const { definitions: resources, named } = lookup;
251
183
  return {
252
184
  plain: (options) => {
253
185
  const renderers = new Map(
@@ -293,2210 +225,1933 @@ function resourcePresentations(resources) {
293
225
  };
294
226
  }
295
227
 
296
- // src/core/events.ts
297
- function timedProgress(clock, observer) {
298
- return { emit: (event) => observer.observe({ event, at: clock.now() }) };
228
+ // src/core/resource-reports.ts
229
+ import { z } from "zod";
230
+ var warningSchema = z.object({
231
+ /** Its snake_case reason. */
232
+ reason: z.string(),
233
+ message: z.string()
234
+ });
235
+ function instanceSchema(records) {
236
+ const [first, ...rest] = records.map(
237
+ ([name, facts]) => z.object({ definition: z.literal(name), facts, warnings: z.array(warningSchema) })
238
+ );
239
+ const record = first === void 0 ? z.never() : z.discriminatedUnion("definition", [first, ...rest]);
240
+ return z.record(z.string(), record);
299
241
  }
300
- function observeAll(...observers) {
242
+ function cleanupInstanceSchema(names) {
243
+ const [first, ...rest] = names;
244
+ const record = first === void 0 ? z.never() : z.object({ definition: z.enum([first, ...rest]), warnings: z.array(warningSchema) });
245
+ return z.record(z.string(), record);
246
+ }
247
+ function resourceReports(lookup) {
248
+ const { definitions: resources, inRegistryOrder } = lookup;
249
+ const warningsOf = (facts) => inRegistryOrder(facts).flatMap(({ record }) => record.warnings.map(({ reason, message }) => ({ reason, message })));
301
250
  return {
302
- observe: async (timed) => {
303
- for (const observer of observers) await observer.observe(timed);
304
- }
251
+ cleanupSchema: cleanupInstanceSchema(resources.map(({ name }) => name)),
252
+ // `{ definition, warnings }` for each instance, in registry order, then the records' order.
253
+ cleanupFacts: (cleanup) => Object.fromEntries(
254
+ inRegistryOrder(cleanup).map(({ key, record: { definition, warnings } }) => [key, { definition, warnings }])
255
+ ),
256
+ cleanupRows: (facts) => warningRows(warningsOf(facts)),
257
+ cleanupWarnings: warningsOf,
258
+ ranSchema: instanceSchema(resources.map(({ name }) => [name, z.unknown()])),
259
+ // `{ definition, facts, warnings }` for each instance, in registry order, then the records' order.
260
+ ranFacts: (ran) => Object.fromEntries(
261
+ inRegistryOrder(ran).map(({ key, record: { definition, facts, warnings } }) => [
262
+ key,
263
+ { definition, facts, warnings }
264
+ ])
265
+ ),
266
+ ranWarnings: warningsOf,
267
+ ranRows: (ran) => inRegistryOrder(ran).flatMap(({ record }) => record.rows),
268
+ // The run releases its instances in reverse order, so the cleanup records come in reverse order of the run's
269
+ // instances; reversed, they come in the order the run took them.
270
+ canceledLines: (cleanup) => inRegistryOrder(Object.fromEntries(Object.entries(cleanup).toReversed())).flatMap(({ record }) => [
271
+ ...record.canceled,
272
+ ...record.done,
273
+ ...record.warnings.map(({ message }) => message)
274
+ ])
305
275
  };
306
276
  }
307
277
 
308
- // src/core/live/command-gateway.ts
309
- import { spawn } from "node:child_process";
310
- import { StringDecoder } from "node:string_decoder";
311
- function liveCommandGateway() {
312
- return {
313
- run: (request) => runCommand(request)
314
- };
278
+ // src/core/run-state.ts
279
+ var RUNNER_STEPS = ["snapshot", "start", "upload", "apply", "install", "build"];
280
+ var EMPTY_RUN_STATE = {
281
+ origin: void 0,
282
+ lastAt: void 0,
283
+ version: void 0,
284
+ instances: void 0,
285
+ base: void 0,
286
+ mint: void 0,
287
+ lanesStartedAt: void 0,
288
+ resources: {},
289
+ runner: void 0,
290
+ command: void 0,
291
+ cleanup: void 0,
292
+ tests: void 0,
293
+ stopping: false
294
+ };
295
+ function applyRunEvent(resources, state, timed) {
296
+ const at = timed.at.getTime();
297
+ return applyEvent(resources, { ...state, origin: state.origin ?? at, lastAt: at }, timed.event, at);
315
298
  }
316
- var PIPE_DRAIN_MS = 2e3;
317
- function runCommand(request) {
318
- const [executable, ...args] = request.argv;
319
- if (executable === void 0) throw new Error("liveCommandGateway: the command's argv is empty");
320
- return new Promise((resolve) => {
321
- let started = false;
322
- let settled = false;
323
- let draining;
324
- const settle = (outcome) => {
325
- if (settled) return;
326
- settled = true;
327
- clearTimeout(draining);
328
- request.terminate.removeEventListener("abort", onTerminate);
329
- resolve(outcome);
330
- };
331
- const ended2 = (code2, signal) => signal !== null ? { kind: "signaled", signal } : { kind: "exited", code: code2 ?? 0 };
332
- const command = spawn(executable, args, {
333
- stdio: ["inherit", "pipe", "pipe"],
334
- shell: false,
335
- env: { ...request.env }
336
- });
337
- const onTerminate = () => {
338
- if (started) command.kill("SIGTERM");
339
- };
340
- for (const stream of ["stdout", "stderr"]) {
341
- const decoder = new StringDecoder("utf8");
342
- const pipe = command[stream];
343
- pipe.on("data", (chunk) => {
344
- const data = decoder.write(chunk);
345
- if (data !== "") request.onOutput({ stream, data });
346
- });
347
- pipe.on("end", () => {
348
- const data = decoder.end();
349
- if (data !== "") request.onOutput({ stream, data });
350
- });
351
- }
352
- command.once("spawn", () => {
353
- started = true;
354
- if (request.terminate.aborted) command.kill("SIGTERM");
355
- });
356
- command.once("error", (error) => {
357
- if (!started) settle({ kind: "spawn-failed", message: error.message });
358
- });
359
- command.once("close", (code2, signal) => settle(ended2(code2, signal)));
360
- command.once("exit", (code2, signal) => {
361
- draining = setTimeout(() => {
362
- command.stdout.destroy();
363
- command.stderr.destroy();
364
- settle(ended2(code2, signal));
365
- }, PIPE_DRAIN_MS);
366
- });
367
- request.terminate.addEventListener("abort", onTerminate, { once: true });
368
- });
299
+ function commandPassed(outcome) {
300
+ return outcome.kind === "exited" && outcome.code === 0;
369
301
  }
370
-
371
- // src/core/live/job-summary-gateway.ts
372
- import { appendFile } from "node:fs/promises";
373
- function liveJobSummaryGateway(options) {
374
- const { path } = options;
375
- return {
376
- appendJobSummary: async (markdown) => {
377
- if (path === void 0 || path === "") return { kind: "none" };
378
- try {
379
- await appendFile(path, markdown.endsWith("\n") ? markdown : `${markdown}
380
- `);
381
- return { kind: "appended" };
382
- } catch (error) {
383
- return { kind: "failed", failure: { path, message: error instanceof Error ? error.message : String(error) } };
384
- }
385
- }
386
- };
302
+ function cleanupProblems(cleanup) {
303
+ return cleanup.resourceWarnings + cleanup.notStopped + cleanup.notDeleted;
387
304
  }
388
-
389
- // src/core/live/progress-terminal.ts
390
- var LIVE_TICK_MS = 90;
391
- var CURSOR_HIDE = "\x1B[?25l";
392
- var CURSOR_SHOW = "\x1B[?25h";
393
- var AUTOWRAP_OFF = "\x1B[?7l";
394
- var AUTOWRAP_ON = "\x1B[?7h";
395
- var ERASE_DOWN = "\x1B[J";
396
- function liveProgressTerminal(options = {}) {
397
- const stdout = options.stdout ?? process.stdout;
398
- const stderr = options.stderr ?? process.stderr;
399
- let failed = false;
400
- let listening = false;
401
- let frame;
402
- let drawn = [];
403
- let lineEnded = true;
404
- let ticker;
405
- let redrawQueued = false;
406
- const write = (stream, text) => {
407
- if (failed || text === "") return;
408
- if (!listening) {
409
- stdout.on("error", fail);
410
- stderr.on("error", fail);
411
- listening = true;
412
- }
413
- try {
414
- stream.write(text);
415
- } catch {
416
- fail();
417
- }
418
- };
419
- const fail = () => {
420
- failed = true;
421
- stopTicking();
422
- };
423
- const terminalColumns = () => positive(stderr.columns) ?? 80;
424
- const columns = () => {
425
- const reported = positive(stderr.columns);
426
- return reported === void 0 ? 80 : Math.max(20, reported);
427
- };
428
- const occupied = () => {
429
- const width = terminalColumns();
430
- return drawn.reduce((rows, visible) => rows + Math.max(1, Math.ceil(visible / width)), 0);
431
- };
432
- const moveUp = () => {
433
- const rows = occupied();
434
- return rows > 0 ? `\x1B[${rows}F${ERASE_DOWN}` : "";
435
- };
436
- const erase = () => {
437
- write(stderr, moveUp());
438
- if (!failed) drawn = [];
439
- };
440
- const draw = () => {
441
- if (frame === void 0) return;
442
- const width = columns();
443
- const height = positive(stderr.rows);
444
- const shown = frame();
445
- const lines = (height === void 0 ? shown : shown.slice(0, Math.max(1, height - 1))).map(
446
- (line) => clip(line, width - 1)
447
- );
448
- if (lines.length === 0) {
449
- erase();
450
- return;
451
- }
452
- const lead = lineEnded ? "" : "\n";
453
- lineEnded = true;
454
- write(stderr, `${moveUp()}${lead}${AUTOWRAP_OFF}${lines.map((line) => `${line}
455
- `).join("")}${AUTOWRAP_ON}`);
456
- const edge = terminalColumns();
457
- drawn = lines.map((line) => Math.min(visibleWidth(line), edge));
458
- };
459
- const restore = () => write(stderr, CURSOR_SHOW);
460
- const stopTicking = () => {
461
- if (ticker !== void 0) clearInterval(ticker);
462
- ticker = void 0;
463
- };
464
- return {
465
- columns,
466
- show(next) {
467
- if (frame === void 0) {
468
- write(stderr, CURSOR_HIDE);
469
- process.once("exit", restore);
470
- }
471
- frame = next;
472
- draw();
473
- if (ticker === void 0 && !failed) {
474
- ticker = setInterval(draw, LIVE_TICK_MS);
475
- ticker.unref();
476
- }
477
- },
478
- print(stream, text) {
479
- if (text === "") return;
480
- erase();
481
- write(stream === "stdout" ? stdout : stderr, text);
482
- lineEnded = text.endsWith("\n");
483
- if (frame === void 0 || redrawQueued) return;
484
- redrawQueued = true;
485
- setImmediate(() => {
486
- redrawQueued = false;
487
- draw();
488
- });
489
- },
490
- settle() {
491
- if (frame === void 0) return;
492
- draw();
493
- frame = void 0;
494
- drawn = [];
495
- stopTicking();
496
- process.removeListener("exit", restore);
497
- restore();
498
- }
499
- };
500
- }
501
- function positive(value) {
502
- return value !== void 0 && Number.isInteger(value) && value > 0 ? value : void 0;
503
- }
504
- function visibleWidth(line) {
505
- let visible = 0;
506
- for (const part of line.split(/(\u001b\[[0-9;]*m)/)) {
507
- if (!part.startsWith("\x1B[")) visible += Array.from(part).length;
508
- }
509
- return visible;
510
- }
511
- function clip(line, width) {
512
- let visible = 0;
513
- let out = "";
514
- const parts = line.split(/(\u001b\[[0-9;]*m)/);
515
- for (const part of parts) {
516
- if (part.startsWith("\x1B[")) {
517
- out += part;
518
- continue;
519
- }
520
- for (const character of part) {
521
- if (visible >= width) return `${out}\x1B[0m`;
522
- out += character;
523
- visible += 1;
524
- }
525
- }
526
- return out;
527
- }
528
-
529
- // src/core/live/run-directory-gateway.ts
530
- import { randomBytes } from "node:crypto";
531
- import { createReadStream, createWriteStream } from "node:fs";
532
- import { mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
533
- import { hostname as osHostname } from "node:os";
534
- import { join as join3 } from "node:path";
535
- import { z as z3 } from "zod";
536
- var DIRECTORY_MODE = 448;
537
- var FILE_MODE = 384;
538
- var ACTIVE_MARKER_TRUST_MS = 24 * 60 * 60 * 1e3;
539
- var LIST_BATCH = 32;
540
- function liveRunDirectoryGateway(options) {
541
- const holders = {
542
- self: options.holder ?? { pid: process.pid, hostname: osHostname() },
543
- isAlive: options.isAlive ?? isAlive
544
- };
545
- return {
546
- open: (request) => open(options.directory, holders, request),
547
- list: (request) => list(options.directory, holders, request.now),
548
- read: (request) => read(options.directory, holders, request),
549
- readLog: (request) => readLog(options.directory, request)
550
- };
551
- }
552
- function unavailableRunDirectoryGateway(location, reason) {
553
- const failure = () => ({ path: location, message: reason });
554
- return {
555
- open: async () => ({ ok: false, failure: failure() }),
556
- list: async () => ({ ok: false, failure: failure() }),
557
- read: async () => ({ kind: "failed", failure: failure() }),
558
- readLog: async () => ({ kind: "failed", failure: failure() })
559
- };
560
- }
561
- var markerSchema = z3.object({
562
- pid: z3.number().int().positive(),
563
- hostname: z3.string().min(1),
564
- startedAt: z3.iso.datetime()
565
- });
566
- async function open(root, holders, request) {
567
- const id = `${runIdPrefix(request.startedAt)}-${randomBytes(2).toString("hex")}`;
568
- const path = join3(root, id);
569
- const opening = join3(root, `.opening-${id}-${randomBytes(4).toString("hex")}`);
570
- try {
571
- await mkdir(root, { recursive: true, mode: DIRECTORY_MODE });
572
- await mkdir(opening, { mode: DIRECTORY_MODE });
573
- const marker = { ...holders.self, startedAt: request.startedAt.toISOString() };
574
- await writeFile(join3(opening, ACTIVE_MARKER), `${JSON.stringify(marker)}
575
- `, { mode: FILE_MODE, flag: "wx" });
576
- await writeFile(join3(opening, RUN_FILE), `${request.run}
577
- `, { mode: FILE_MODE, flag: "wx" });
578
- await rename(opening, path);
579
- } catch (error) {
580
- await rm(opening, { recursive: true, force: true }).catch(() => void 0);
581
- return { ok: false, failure: { path, message: messageOf(error) } };
582
- }
583
- return {
584
- ok: true,
585
- directory: runDirectory(path, id),
586
- pruneFailures: await prune(root, request.keep, holders, request.startedAt)
587
- };
588
- }
589
- async function prune(root, keep, holders, now) {
590
- let names;
591
- try {
592
- names = (await readdir(root)).filter((name) => RUN_ID_PATTERN.test(name));
593
- } catch (error) {
594
- return [{ path: root, message: messageOf(error) }];
595
- }
596
- const completed = [];
597
- for (const name of names) if (!await isActive(join3(root, name), holders, now)) completed.push(name);
598
- const failures = [];
599
- const newestFirst = completed.toSorted().toReversed();
600
- for (const name of newestFirst.slice(keep)) {
601
- const path = join3(root, name);
602
- try {
603
- await rm(path, { recursive: true, force: true });
604
- } catch (error) {
605
- failures.push({ path, message: messageOf(error) });
606
- }
607
- }
608
- const kept = newestFirst.slice(0, keep);
609
- const leftovers = kept.flatMap(
610
- (name) => [TEST_EVENTS_STAGING_FILE, TESTS_PARTIAL_FILE].map((file) => join3(root, name, file))
611
- );
612
- for (let start = 0; start < leftovers.length; start += LIST_BATCH) {
613
- const removed = await Promise.all(
614
- leftovers.slice(start, start + LIST_BATCH).map(async (file) => {
615
- try {
616
- await rm(file, { force: true });
617
- return [];
618
- } catch (error) {
619
- return [{ path: file, message: messageOf(error) }];
620
- }
621
- })
622
- );
623
- failures.push(...removed.flat());
624
- }
625
- return failures;
626
- }
627
- async function list(root, holders, now) {
628
- let names;
629
- try {
630
- names = (await readdir(root)).filter((name) => RUN_ID_PATTERN.test(name));
631
- } catch (error) {
632
- if (errorCode(error) === "ENOENT") return { ok: true, runs: [] };
633
- return { ok: false, failure: { path: root, message: messageOf(error) } };
634
- }
635
- const ordered = names.toSorted().toReversed();
636
- const runs = [];
637
- for (let start = 0; start < ordered.length; start += LIST_BATCH) {
638
- runs.push(
639
- ...await Promise.all(
640
- ordered.slice(start, start + LIST_BATCH).map(async (id) => {
641
- const path = join3(root, id);
642
- const run = await readOptional(join3(path, RUN_FILE));
643
- return {
644
- id,
645
- path,
646
- active: await isActive(path, holders, now),
647
- run: run.kind === "found" ? run.text : void 0
648
- };
649
- })
650
- )
651
- );
652
- }
653
- return { ok: true, runs };
654
- }
655
- async function read(root, holders, request) {
656
- if (!RUN_ID_PATTERN.test(request.id)) return { kind: "not-found" };
657
- const path = join3(root, request.id);
658
- try {
659
- if (!(await stat(path)).isDirectory()) return { kind: "not-found" };
660
- } catch (error) {
661
- if (errorCode(error) === "ENOENT") return { kind: "not-found" };
662
- return { kind: "failed", failure: { path, message: messageOf(error) } };
663
- }
664
- const [run, tests, timeline2] = await Promise.all(
665
- [RUN_FILE, TESTS_FILE, TIMELINE_FILE].map((name) => readOptional(join3(path, name)))
666
- );
667
- for (const file of [run, tests, timeline2])
668
- if (file?.kind === "failed") return { kind: "failed", failure: file.failure };
669
- const text = (file) => file?.kind === "found" ? file.text : void 0;
670
- const testsText = text(tests);
671
- const held = await Promise.all(RUN_LOGS.map(async (log) => await exists(join3(path, runLogFile(log))) ? log : []));
672
- return {
673
- kind: "found",
674
- directory: {
675
- id: request.id,
676
- path,
677
- active: await isActive(path, holders, request.now),
678
- run: text(run),
679
- tests: testsText === void 0 ? void 0 : testsText.split("\n").filter((line) => line !== ""),
680
- timeline: text(timeline2),
681
- logs: held.flat()
682
- }
683
- };
684
- }
685
- async function exists(file) {
686
- try {
687
- await stat(file);
688
- return true;
689
- } catch {
690
- return false;
691
- }
692
- }
693
- async function readLog(root, request) {
694
- if (!RUN_ID_PATTERN.test(request.id)) return { kind: "not-found" };
695
- const file = join3(root, request.id, runLogFile(request.log));
696
- try {
697
- return { kind: "found", path: file, text: completeUtf8(await readFile(file)).toString("utf8") };
698
- } catch (error) {
699
- if (errorCode(error) === "ENOENT") return { kind: "not-found" };
700
- return { kind: "failed", failure: { path: file, message: messageOf(error) } };
701
- }
702
- }
703
- function completeUtf8(bytes) {
704
- for (let back = 1; back <= Math.min(3, bytes.length); back += 1) {
705
- const byte = bytes[bytes.length - back] ?? 0;
706
- if ((byte & 192) === 128) continue;
707
- const needs = byte >= 240 ? 4 : byte >= 224 ? 3 : byte >= 192 ? 2 : 1;
708
- return needs > back ? bytes.subarray(0, bytes.length - back) : bytes;
709
- }
710
- return bytes;
711
- }
712
- async function readOptional(file) {
713
- try {
714
- return { kind: "found", text: await readFile(file, "utf8") };
715
- } catch (error) {
716
- if (errorCode(error) === "ENOENT") return { kind: "missing" };
717
- return { kind: "failed", failure: { path: file, message: messageOf(error) } };
718
- }
719
- }
720
- async function isActive(path, holders, now) {
721
- const file = join3(path, ACTIVE_MARKER);
722
- let text;
723
- try {
724
- text = await readFile(file, "utf8");
725
- } catch (error) {
726
- if (errorCode(error) === "ENOENT") return false;
727
- return trustedSince(file, now);
728
- }
729
- const parsed = markerSchema.safeParse(parseJson(text));
730
- if (!parsed.success) return trustedSince(file, now);
731
- const { pid, hostname, startedAt } = parsed.data;
732
- if (hostname === holders.self.hostname) return holders.isAlive(pid);
733
- return now.getTime() - Date.parse(startedAt) < ACTIVE_MARKER_TRUST_MS;
734
- }
735
- async function trustedSince(file, now) {
736
- try {
737
- return now.getTime() - (await stat(file)).mtime.getTime() < ACTIVE_MARKER_TRUST_MS;
738
- } catch {
739
- return false;
740
- }
741
- }
742
- function parseJson(text) {
743
- try {
744
- return JSON.parse(text);
745
- } catch {
746
- return void 0;
747
- }
748
- }
749
- function isAlive(pid) {
750
- try {
751
- process.kill(pid, 0);
752
- return true;
753
- } catch (error) {
754
- return errorCode(error) !== "ESRCH";
755
- }
756
- }
757
- function errorCode(error) {
758
- return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
759
- }
760
- function runDirectory(path, id) {
761
- const streams = /* @__PURE__ */ new Map();
762
- let failure;
763
- let closed = false;
764
- let testsPublished = false;
765
- let changing = Promise.resolve();
766
- const inTurn = (file, change) => {
767
- if (failure !== void 0 || closed) return;
768
- changing = changing.then(async () => {
769
- if (failure !== void 0) return;
770
- try {
771
- await change();
772
- } catch (error) {
773
- failure ??= { path: file, message: messageOf(error) };
774
- }
775
- });
776
- };
777
- const replace = (name, text) => {
778
- const file = join3(path, name);
779
- inTurn(file, async () => {
780
- const temporary = join3(path, `.${name}.${randomBytes(4).toString("hex")}.tmp`);
781
- try {
782
- await writeFile(temporary, text, { mode: FILE_MODE, flag: "wx" });
783
- await rename(temporary, file);
784
- } catch (error) {
785
- await rm(temporary, { force: true }).catch(() => void 0);
786
- throw error;
787
- }
788
- });
789
- };
790
- const stream = (name) => {
791
- if (failure !== void 0 || closed) return void 0;
792
- let opened = streams.get(name);
793
- if (opened === void 0) {
794
- const file = join3(path, name);
795
- opened = createWriteStream(file, { flags: "a", mode: FILE_MODE });
796
- opened.on("error", (error) => {
797
- failure ??= { path: file, message: messageOf(error) };
798
- });
799
- streams.set(name, opened);
800
- }
801
- return opened;
802
- };
803
- const append = (name, text) => void stream(name)?.write(text);
804
- const endStream = async (name) => {
805
- const opened = streams.get(name);
806
- if (opened === void 0) return;
807
- streams.delete(name);
808
- await ended(opened);
809
- };
810
- return {
811
- path,
812
- id,
813
- writeRun: (text) => replace(RUN_FILE, `${text}
814
- `),
815
- appendEvent: (line) => append(EVENTS_FILE, `${line}
816
- `),
817
- appendStepOutput: (step, line) => append(runLogFile(step), `${line}
818
- `),
819
- appendCommandOutput: (text) => append(COMMAND_LOG, text),
820
- appendTestEvent: (line) => {
821
- if (!testsPublished) append(TESTS_PARTIAL_FILE, `${line}
822
- `);
823
- },
824
- publishTestEvents: () => {
825
- if (testsPublished) return;
826
- testsPublished = true;
827
- const partial = join3(path, TESTS_PARTIAL_FILE);
828
- inTurn(join3(path, TESTS_FILE), async () => {
829
- await endStream(TESTS_PARTIAL_FILE);
830
- if (failure !== void 0) return;
831
- await writeFile(partial, "", { mode: FILE_MODE, flag: "a" });
832
- await rename(partial, join3(path, TESTS_FILE));
833
- });
834
- },
835
- writeTimeline: (text) => replace(TIMELINE_FILE, `${text}
836
- `),
837
- readTestEvents: (onLine) => readStagedTestEvents(join3(path, TEST_EVENTS_STAGING_FILE), onLine),
838
- close: async () => {
839
- closed = true;
840
- await changing;
841
- await Promise.all([...streams.values()].map(ended));
842
- streams.clear();
843
- for (const name of [TEST_EVENTS_STAGING_FILE, TESTS_PARTIAL_FILE]) {
844
- const file = join3(path, name);
845
- try {
846
- await rm(file, { force: true });
847
- } catch (error) {
848
- failure ??= { path: file, message: messageOf(error) };
305
+ function applyEvent(resources, state, event, at) {
306
+ switch (event.kind) {
307
+ case "started":
308
+ return { ...state, version: { version: event.version, commit: event.commit }, instances: event.resources };
309
+ // A skipped resource takes nothing and has no lane: the progress says it, and the state keeps nothing of it.
310
+ case "resource-skipped":
311
+ return state;
312
+ case "runner-prepared":
313
+ return {
314
+ ...state,
315
+ base: { sha: event.base, ref: event.baseRef },
316
+ runner: {
317
+ status: "pending",
318
+ startedAt: at,
319
+ endedAt: void 0,
320
+ sandbox: void 0,
321
+ buildSandbox: void 0,
322
+ steps: RUNNER_STEPS.map((name) => ({
323
+ name,
324
+ status: "pending",
325
+ startedAt: void 0,
326
+ endedAt: void 0,
327
+ label: "",
328
+ latest: void 0
329
+ })),
330
+ snapshot: void 0,
331
+ uploadBytes: void 0,
332
+ activity: void 0,
333
+ kept: void 0,
334
+ save: void 0
849
335
  }
850
- }
851
- const marker = join3(path, ACTIVE_MARKER);
852
- try {
853
- await unlink(marker);
854
- } catch (error) {
855
- failure ??= { path: marker, message: messageOf(error) };
856
- }
857
- return failure;
336
+ };
337
+ case "minting":
338
+ return { ...state, mint: { status: "running", startedAt: at, endedAt: void 0, target: event.target } };
339
+ case "minted":
340
+ return state.mint === void 0 ? state : { ...state, mint: { ...state.mint, status: event.ok ? "done" : "failed", endedAt: at } };
341
+ // A GitHub Actions OIDC token request reports no end, so it has no span of its own.
342
+ case "requesting-token":
343
+ return state;
344
+ case "lanes-started":
345
+ return {
346
+ ...state,
347
+ lanesStartedAt: at,
348
+ runner: state.runner === void 0 ? void 0 : { ...state.runner, status: "running", startedAt: at }
349
+ };
350
+ case "lane-started": {
351
+ const startedAt = state.lanesStartedAt ?? state.origin ?? at;
352
+ if (event.resource === null) return state;
353
+ const { lane: name, resource: key } = event;
354
+ const owner = resources.find(({ progress }) => progress?.lane === name);
355
+ if (owner?.progress === void 0) return state;
356
+ return withState(state, key, owner.name, owner.progress.start(startedAt));
858
357
  }
859
- };
860
- }
861
- function ended(stream) {
862
- return new Promise((resolve) => {
863
- if (stream.closed || stream.destroyed) resolve();
864
- else {
865
- stream.once("close", () => resolve());
866
- stream.end();
358
+ case "lane-ended": {
359
+ if (event.resource === null) return runnerEnded(state, event.outcome, at);
360
+ const { outcome } = event;
361
+ return withOwnLane(
362
+ resources,
363
+ state,
364
+ event.resource,
365
+ void 0,
366
+ (progress, own) => progress.ended(own, outcome, at)
367
+ );
867
368
  }
868
- });
869
- }
870
- async function readStagedTestEvents(file, onLine) {
871
- let pending = "";
872
- try {
873
- for await (const chunk of createReadStream(file, { encoding: "utf8" })) {
874
- const lines = `${pending}${String(chunk)}`.split("\n");
875
- pending = lines.pop() ?? "";
876
- for (const line of lines) if (line !== "") onLine(line);
369
+ // The launcher's word that a resource is acquired changes no lane: its acquire's `announce` follows it, as one of
370
+ // its own events. A line or a warning a resource instance reported changes nothing either.
371
+ case "resource-acquired":
372
+ case "resource-notice":
373
+ case "resource-warning":
374
+ return state;
375
+ case "command-started":
376
+ return {
377
+ ...state,
378
+ command: { status: "running", startedAt: at, endedAt: void 0, argv: event.argv, outcome: void 0 }
379
+ };
380
+ case "command-ended": {
381
+ if (state.command === void 0) return state;
382
+ const endedAt = state.command.startedAt + event.ms;
383
+ const status = commandPassed(event.outcome) ? "done" : "failed";
384
+ return { ...state, command: { ...state.command, status, endedAt, outcome: event.outcome } };
877
385
  }
878
- if (pending !== "") onLine(pending);
879
- return { ok: true };
880
- } catch (error) {
881
- if (errorCode(error) === "ENOENT") return { ok: true };
882
- return { ok: false, failure: { path: file, message: messageOf(error) } };
386
+ case "cleanup-started":
387
+ return {
388
+ ...state,
389
+ cleanup: {
390
+ status: "running",
391
+ startedAt: at,
392
+ endedAt: void 0,
393
+ runnerSandbox: event.runnerSandbox,
394
+ resources: event.resources,
395
+ resourceWarnings: 0,
396
+ notStopped: 0,
397
+ notDeleted: 0,
398
+ waiting: false
399
+ }
400
+ };
401
+ case "cleanup-finished": {
402
+ if (state.cleanup === void 0) return state;
403
+ const cleanup = {
404
+ ...state.cleanup,
405
+ endedAt: at,
406
+ resourceWarnings: event.resourceWarnings,
407
+ notStopped: event.notStopped,
408
+ notDeleted: event.notDeleted,
409
+ waiting: false
410
+ };
411
+ return { ...state, cleanup: { ...cleanup, status: cleanupProblems(cleanup) === 0 ? "done" : "failed" } };
412
+ }
413
+ case "runner":
414
+ return applyRunnerEvent(state, event.event, at);
415
+ case "test":
416
+ return { ...state, tests: applyTestEvent(state.tests ?? EMPTY_TESTS, event.event, at) };
417
+ // The run's summary counts unreadable lines and says the results may be incomplete; no view shows either live.
418
+ case "test-event-unreadable":
419
+ case "test-events-incomplete":
420
+ return state;
421
+ // A resource's own events reach its progress, if it has its own. Its cleanup counts through `cleanup-finished`.
422
+ case "resource":
423
+ return withOwnLane(
424
+ resources,
425
+ state,
426
+ event.resource,
427
+ event.definition,
428
+ (progress, own) => progress.apply(own, event.event, at)
429
+ );
883
430
  }
884
431
  }
885
- function messageOf(error) {
886
- return error instanceof Error ? error.message : String(error);
887
- }
888
-
889
- // src/core/run.ts
890
- import { posix } from "node:path";
891
-
892
- // src/core/mint.ts
893
- async function mintReported(context, target, progress) {
894
- await progress.emit({ kind: "minting", target });
895
- const minted = await context.credentials.mint(target);
896
- await progress.emit({ kind: "minted", target, ok: minted.ok });
897
- return minted;
432
+ function withState(state, key, definition, own) {
433
+ return { ...state, resources: { ...state.resources, [key]: { definition, state: own } } };
898
434
  }
899
- function mintSourceReported(context, target, progress) {
900
- return mintSource(target, () => mintReported(context, target, progress));
435
+ function withOwnLane(resources, state, key, definition, change) {
436
+ const record = state.resources[key];
437
+ if (record === void 0 || definition !== void 0 && record.definition !== definition) return state;
438
+ const progress = resources.find((resource) => resource.name === record.definition)?.progress;
439
+ if (progress === void 0) return state;
440
+ return withState(state, key, record.definition, change(progress, record.state));
901
441
  }
902
-
903
- // src/core/payload.ts
904
- function runPayload(resources, options = {}) {
442
+ function runnerEnded(state, outcome, at) {
443
+ if (state.runner === void 0) return state;
444
+ const status = outcome === "ready" ? "done" : outcome;
905
445
  return {
906
- version: 3,
907
- resources,
908
- ...options.testEvents === void 0 ? {} : { testEvents: options.testEvents },
909
- ...options.verbose === true ? { verbose: true } : {}
446
+ ...state,
447
+ runner: {
448
+ ...state.runner,
449
+ status,
450
+ endedAt: at,
451
+ steps: state.runner.steps.map(
452
+ (step) => outcome === "ready" || step.status !== "running" ? step : { ...step, status, endedAt: at, latest: void 0 }
453
+ )
454
+ }
910
455
  };
911
456
  }
912
- function commandEnvironment(env, payload) {
913
- const kept = Object.entries(env).filter((pair) => pair[1] !== void 0);
914
- return { ...Object.fromEntries(kept), [RUN_PAYLOAD_VARIABLE]: JSON.stringify(payload) };
915
- }
916
- function colorEnvironment(env, color) {
917
- if (env["FORCE_COLOR"] !== void 0 || env["NO_COLOR"] !== void 0) return env;
918
- return { ...env, ...color ? { FORCE_COLOR: "1" } : { NO_COLOR: "1" } };
919
- }
920
-
921
- // src/core/resources.ts
922
- function resourceInstances(resources, worlds, requests) {
923
- const { named } = resourceRegistry(resources);
924
- return Object.entries(requests).map(
925
- ([key, request]) => instanceOf(named(request.definition, key), key, worlds, request)
926
- );
457
+ function applyRunnerEvent(state, event, at) {
458
+ switch (event.kind) {
459
+ case "snapshot-reused":
460
+ return withRunner(
461
+ withStep(state, "snapshot", () => ({ status: "done", startedAt: at, endedAt: at })),
462
+ () => ({
463
+ snapshot: { kind: "reused", id: event.snapshotId, base: event.base, branch: event.branch, head: event.head }
464
+ })
465
+ );
466
+ case "snapshot-build-started":
467
+ return withRunner(
468
+ withStep(state, "snapshot", () => ({ status: "running", startedAt: at })),
469
+ () => ({ snapshot: { kind: "building", summary: event.summary } })
470
+ );
471
+ case "snapshot-built":
472
+ return withRunner(
473
+ withStep(state, "snapshot", () => ({ status: "done", endedAt: at, latest: void 0 })),
474
+ () => ({
475
+ snapshot: { kind: "built", id: event.snapshotId, base: event.base, branch: null, head: null },
476
+ activity: void 0
477
+ })
478
+ );
479
+ case "snapshot-saving":
480
+ return withRunner(state, () => ({ activity: "saving-snapshot" }));
481
+ case "runner-sandbox-starting":
482
+ return withStep(state, "start", () => ({ status: "running", startedAt: at }));
483
+ case "sandbox-started":
484
+ if (event.role !== "runner") return withRunner(state, () => ({ buildSandbox: event.name }));
485
+ return withStep(
486
+ withRunner(state, () => ({ sandbox: { name: event.name, region: event.region, vcpus: event.vcpus } })),
487
+ "start",
488
+ () => ({ status: "done", endedAt: at })
489
+ );
490
+ case "uploading":
491
+ return withStep(state, "upload", () => ({ status: "running", startedAt: at }));
492
+ case "uploaded":
493
+ return withRunner(
494
+ withStep(state, "upload", () => ({ status: "done", endedAt: at })),
495
+ () => ({ uploadBytes: event.bytes })
496
+ );
497
+ case "step-started":
498
+ if (event.phase === "snapshot")
499
+ return withStep(state, "snapshot", () => ({ label: event.label, latest: void 0 }));
500
+ return withStep(state, event.phase, () => ({ status: "running", startedAt: at, label: event.label }));
501
+ case "step-output":
502
+ return withStep(state, event.phase, () => ({ latest: event.line }));
503
+ case "step-finished":
504
+ if (event.phase === "snapshot") return state;
505
+ return withStep(state, event.phase, () => ({ status: "done", endedAt: at, latest: void 0 }));
506
+ case "stopping":
507
+ return { ...state, stopping: true };
508
+ case "command-stopped":
509
+ return state.command === void 0 ? state : { ...state, command: { ...state.command, status: "stopped", endedAt: at, outcome: "stopped" } };
510
+ case "waiting-for-snapshot":
511
+ return withRunner(
512
+ state.cleanup === void 0 ? state : { ...state, cleanup: { ...state.cleanup, waiting: true } },
513
+ () => ({ activity: "waiting-for-snapshot" })
514
+ );
515
+ case "sandbox-kept":
516
+ return withRunner(state, () => ({ kept: { name: event.name, stopsAt: event.stopsAt } }));
517
+ case "branch-snapshot-saving":
518
+ return withRunner(state, () => ({ save: { kind: "saving", branch: event.branch } }));
519
+ case "branch-snapshot-saved":
520
+ return withRunner(state, () => ({
521
+ save: { kind: "saved", id: event.snapshotId, branch: event.branch, head: event.head }
522
+ }));
523
+ case "branch-snapshot-not-saved":
524
+ return withRunner(state, () => ({ save: { kind: "not-saved" } }));
525
+ // A step's outcome comes from its lane's end, not from the end of its output.
526
+ case "output-started":
527
+ case "output-ended":
528
+ case "snapshot-entry-not-written":
529
+ case "command-output-started":
530
+ case "branch-snapshots-dropped":
531
+ case "branch-snapshots-not-dropped":
532
+ return state;
533
+ }
927
534
  }
928
- function instanceOf(resource, key, worlds, request) {
929
- const { name } = resource;
930
- const lifecycle = resource.lifecycle(worlds[name]);
931
- const taken = [];
932
- let result;
933
- let canceled = [];
934
- const acquireWarnings = [];
935
- const releaseWarnings = [];
936
- const report = (progress, lane2, kept) => ({
937
- run: (text) => progress.emit({ kind: "resource-notice", resource: key, definition: name, lane: "run", text }),
938
- cleanup: (text) => progress.emit({ kind: "resource-notice", resource: key, definition: name, lane: "cleanup", text }),
939
- warning: (reason, message) => {
940
- kept.push({ reason, message });
941
- return progress.emit({ kind: "resource-warning", resource: key, definition: name, lane: lane2, reason, message });
942
- },
943
- progress: (event) => progress.emit({ kind: "resource", resource: key, definition: name, event })
535
+ var EMPTY_TESTS = { workers: [], filesDone: 0, passed: 0, failed: 0 };
536
+ function applyTestEvent(tests, event, at) {
537
+ if (event.kind === "test-result")
538
+ return {
539
+ ...tests,
540
+ passed: tests.passed + (event.state === "pass" ? 1 : 0),
541
+ failed: tests.failed + (event.state === "fail" ? 1 : 0)
542
+ };
543
+ const existing = tests.workers.find((candidate) => candidate.worker === event.worker);
544
+ const worker = existing ?? {
545
+ worker: event.worker,
546
+ file: void 0,
547
+ fileStartedAt: void 0,
548
+ containerSince: void 0
549
+ };
550
+ const put = (changed, rest = {}) => ({
551
+ ...tests,
552
+ ...rest,
553
+ workers: [...tests.workers.filter((candidate) => candidate.worker !== changed.worker), changed].toSorted(
554
+ (a, b) => a.worker - b.worker
555
+ )
944
556
  });
945
- const acquired = () => result !== void 0 && "acquired" in result ? result.acquired : void 0;
946
- const laneName = resource.progress?.lane;
947
- const lane = laneName === void 0 ? void 0 : { lane: laneName, resource: key };
948
- return {
949
- listing: { resource: key, definition: name, lane: laneName ?? null },
950
- lane,
951
- startLane: async (progress) => {
952
- if (lane !== void 0) await progress.emit({ kind: "lane-started", ...lane });
953
- },
954
- acquire: async ({ signal, credential, progress, finishLane }) => {
955
- const answered = await finishLane(
956
- lane,
957
- lifecycle.acquireForRun({
958
- options: request.options,
959
- secrets: request.secrets,
960
- credential,
961
- take: (one) => void taken.push(one),
962
- report: report(progress, "run", acquireWarnings),
963
- signal
964
- }),
965
- resourceLaneOutcome
557
+ switch (event.kind) {
558
+ case "file-started":
559
+ return put({ ...worker, file: event.file, fileStartedAt: at, containerSince: void 0 });
560
+ case "test-started":
561
+ return put({ ...worker, file: event.file, fileStartedAt: worker.fileStartedAt ?? at });
562
+ case "test-attempt-finished":
563
+ return put(worker);
564
+ case "file-finished":
565
+ return put(
566
+ { ...worker, file: void 0, fileStartedAt: void 0, containerSince: void 0 },
567
+ { filesDone: tests.filesDone + 1 }
966
568
  );
967
- if ("refused" in answered) {
968
- const outcome = {
969
- kind: "resource-refused",
970
- resource: key,
971
- definition: name,
972
- refusal: answered
973
- };
974
- return { kind: "refused", outcome };
975
- }
976
- if ("mintFailed" in answered) {
977
- const { failure, target } = answered.mintFailed;
978
- return { kind: "refused", outcome: { kind: "mint-failed", failure, target, runner: false } };
979
- }
980
- result = answered;
981
- canceled = "acquired" in answered ? answered.acquired.canceled ?? [] : answered.canceled;
982
- return { kind: "acquired" in answered ? "acquired" : "canceled" };
983
- },
984
- acquired: () => {
985
- const one = acquired();
986
- if (one === void 0) return [];
987
- const said = { kind: "resource-acquired", resource: key, definition: name };
988
- return one.announce === void 0 ? [said] : [said, { kind: "resource", resource: key, definition: name, event: one.announce }];
989
- },
990
- payload: () => {
991
- const one = acquired();
992
- return one === void 0 ? {} : { [key]: { definition: name, payload: one.payload } };
993
- },
994
- ran: () => {
995
- const one = acquired();
996
- if (one === void 0 || one.result === void 0 && acquireWarnings.length === 0) return {};
997
- const facts = one.result === void 0 ? null : one.result.facts;
998
- const rows = one.result === void 0 ? [] : one.result.rows;
999
- return { [key]: { definition: name, facts, rows, warnings: [...acquireWarnings] } };
1000
- },
1001
- took: () => taken.length > 0,
1002
- release: async (progress) => {
1003
- const released = await lifecycle.releaseAfterRun({
1004
- taken,
1005
- report: report(progress, "cleanup", releaseWarnings)
1006
- });
1007
- if ("nothingTaken" in released) return {};
1008
- return { [key]: { definition: name, warnings: [...releaseWarnings], done: released.done, canceled } };
1009
- }
1010
- };
569
+ case "container-starting":
570
+ return put({ ...worker, containerSince: at });
571
+ case "container-started":
572
+ return put({ ...worker, containerSince: void 0 });
573
+ }
1011
574
  }
1012
- async function acquireResources(instances, input) {
1013
- const { progress, beside } = input;
1014
- const internal = new AbortController();
1015
- const signal = AbortSignal.any([input.signal, internal.signal]);
1016
- const finishLane = async (lane, task, outcomeOf2) => {
1017
- let value;
1018
- let outcome;
1019
- try {
1020
- value = await task;
1021
- outcome = outcomeOf2(value);
1022
- if (lane !== void 0) await progress.emit({ kind: "lane-ended", ...lane, outcome });
1023
- } catch (error) {
1024
- if (lane !== void 0 && outcome === void 0)
1025
- await progress.emit({ kind: "lane-ended", ...lane, outcome: "failed" }).catch(() => void 0);
1026
- internal.abort();
1027
- throw error;
575
+ function withRunner(state, change) {
576
+ return state.runner === void 0 ? state : { ...state, runner: { ...state.runner, ...change() } };
577
+ }
578
+ function withStep(state, name, change) {
579
+ if (state.runner === void 0) return state;
580
+ return {
581
+ ...state,
582
+ runner: {
583
+ ...state.runner,
584
+ steps: state.runner.steps.map((step) => step.name === name ? { ...step, ...change() } : step)
1028
585
  }
1029
- if (outcome !== "ready") internal.abort();
1030
- return value;
1031
586
  };
1032
- for (const instance of instances) await instance.startLane(progress);
1033
- const instanceTasks = instances.map(
1034
- (instance) => instance.acquire({ signal, credential: input.credential, progress, finishLane })
1035
- );
1036
- const besideTask = beside === void 0 ? Promise.resolve(void 0) : finishLane(beside.lane, beside.start(signal), beside.outcomeOf);
1037
- const [[besideEnded], instancesEnded] = await Promise.all([
1038
- Promise.allSettled([besideTask]),
1039
- Promise.allSettled(instanceTasks)
1040
- ]);
1041
- if (besideEnded.status === "rejected") throw besideEnded.reason;
1042
- const outcomes = [];
1043
- for (const one of instancesEnded) {
1044
- if (one.status === "rejected") throw one.reason;
1045
- outcomes.push(one.value);
1046
- }
1047
- if (input.signal.aborted) return { kind: "stopped", outcome: canceledStop() };
1048
- const besideValue = besideEnded.value;
1049
- const besideStopped = besideValue === void 0 ? void 0 : beside?.stopped(besideValue);
1050
- if (besideStopped !== void 0) return { kind: "stopped", outcome: besideStopped };
1051
- for (const outcome of outcomes) if (outcome?.kind === "refused") return { kind: "stopped", outcome: outcome.outcome };
1052
- if (outcomes.some((outcome) => outcome?.kind === "canceled")) return { kind: "stopped", outcome: canceledStop() };
1053
- return { kind: "acquired", beside: besideValue };
1054
587
  }
1055
- function resourceLaneOutcome(result) {
1056
- if ("acquired" in result) return "ready";
1057
- return "canceled" in result ? "stopped" : "failed";
588
+
589
+ // src/core/timeline.ts
590
+ function timeline(resources, state) {
591
+ const { origin } = state;
592
+ if (origin === void 0) return { startedAt: (/* @__PURE__ */ new Date(0)).toISOString(), totalMs: 0, rows: [], criticalPath: [] };
593
+ const totalMs = (state.lastAt ?? origin) - origin;
594
+ const span = (from) => ({
595
+ startMs: from.startedAt - origin,
596
+ endMs: from.endedAt === void 0 || from.status === "running" ? totalMs : from.endedAt - origin,
597
+ outcome: outcomeOf(from.status)
598
+ });
599
+ const row = (ref, from, extra = {}) => ({
600
+ name: ref.name,
601
+ resource: ref.resource,
602
+ ...span(from),
603
+ steps: extra.steps ?? [],
604
+ idleMs: 0,
605
+ snapshot: extra.snapshot,
606
+ sandboxes: extra.sandboxes
607
+ });
608
+ const rows = [];
609
+ const { mint, runner, command, cleanup } = state;
610
+ if (mint !== void 0) rows.push(row(MINT, mint));
611
+ const started = [];
612
+ for (const [key, record] of Object.entries(state.resources)) {
613
+ const projected = laneRow(resources, key, record, span);
614
+ if (projected === void 0) continue;
615
+ started.push({ ref: projected.ref, span: projected.state });
616
+ rows.push(
617
+ row(projected.ref, projected.state, {
618
+ steps: projected.steps,
619
+ sandboxes: projected.sandboxes
620
+ })
621
+ );
622
+ }
623
+ const runnerStarted = runner !== void 0 && runner.status !== "pending";
624
+ if (runnerStarted) {
625
+ const steps = runner.steps.filter((step) => step.status !== "pending" && !(step.name === "snapshot" && runner.snapshot?.kind === "reused")).flatMap(
626
+ (step) => step.startedAt === void 0 ? [] : [{ name: step.name, ...span({ status: step.status, startedAt: step.startedAt, endedAt: step.endedAt }) }]
627
+ ).toSorted((a, b) => a.startMs - b.startMs);
628
+ const snapshot = runner.snapshot?.kind === "building" ? void 0 : runner.snapshot?.kind;
629
+ rows.push(row(RUNNER, runner, { steps, snapshot }));
630
+ }
631
+ const ready = [...started, ...runner === void 0 ? [] : [{ ref: RUNNER, span: runner }]].flatMap(
632
+ ({ ref, span: from }) => from.status === "done" && from.endedAt !== void 0 ? [{ ref, readyAt: from.endedAt }] : []
633
+ );
634
+ const last = ready.length < 2 ? void 0 : ready.reduce((later, lane) => lane.readyAt >= later.readyAt ? lane : later);
635
+ if (last !== void 0)
636
+ for (const lane of ready) {
637
+ if (lane === last) continue;
638
+ const index = rows.findIndex((candidate) => sameRow(candidate, lane.ref));
639
+ const waited = rows[index];
640
+ if (waited !== void 0) rows[index] = { ...waited, idleMs: last.readyAt - lane.readyAt };
641
+ }
642
+ if (command !== void 0) rows.push(row(TESTS, command));
643
+ if (cleanup !== void 0) rows.push(row(CLEANUP, cleanup));
644
+ const waitedOn = last?.ref ?? started[0]?.ref ?? (runnerStarted ? RUNNER : void 0);
645
+ return {
646
+ startedAt: new Date(origin).toISOString(),
647
+ totalMs,
648
+ rows,
649
+ criticalPath: command === void 0 ? [] : waitedOn === void 0 ? [TESTS] : [waitedOn, TESTS]
650
+ };
1058
651
  }
1059
- function canceledStop() {
1060
- return { kind: "canceled" };
652
+ var MINT = { name: "mint", resource: null };
653
+ var RUNNER = { name: "runner", resource: null };
654
+ var TESTS = { name: "tests", resource: null };
655
+ var CLEANUP = { name: "cleanup", resource: null };
656
+ function sameRow(a, b) {
657
+ return a.resource === null ? b.resource === null && a.name === b.name : a.resource === b.resource;
1061
658
  }
1062
- async function announceAcquired(instances, progress) {
1063
- for (const instance of instances) for (const event of instance.acquired()) await progress.emit(event);
659
+ function laneRow(resources, key, record, span) {
660
+ const progress = resources.find((resource) => resource.name === record.definition)?.progress;
661
+ if (progress === void 0) return void 0;
662
+ const { state } = record;
663
+ const { steps, sandboxes } = progress.row(state);
664
+ return {
665
+ ref: { name: progress.lane, resource: key },
666
+ state,
667
+ steps: steps.map(({ name: step, span: from }) => ({ name: step, ...span(from) })),
668
+ sandboxes
669
+ };
1064
670
  }
1065
- function resourcesPayload(instances) {
1066
- let resources = {};
1067
- for (const instance of instances) resources = { ...resources, ...instance.payload() };
1068
- return resources;
671
+ function outcomeOf(status) {
672
+ return status === "running" || status === "pending" ? "unfinished" : status;
1069
673
  }
1070
- function resourcesRan(instances) {
1071
- let ran = {};
1072
- for (const instance of instances) ran = { ...ran, ...instance.ran() };
1073
- return ran;
674
+
675
+ // src/core/resource-registry.ts
676
+ var LOOKUP = /* @__PURE__ */ Symbol("definition lookup");
677
+ function resourceRegistry(definitions) {
678
+ const lookup = definitionLookup(definitions);
679
+ return {
680
+ definitions,
681
+ reports: resourceReports(lookup),
682
+ presentations: resourcePresentations(lookup),
683
+ applyEvent: (state, timed) => applyRunEvent(definitions, state, timed),
684
+ timeline: (state) => timeline(definitions, state),
685
+ lifecycles: (worlds) => bindLifecycles(lookup, worlds),
686
+ worlds: (env) => worldsOf(definitions, env),
687
+ [LOOKUP]: lookup
688
+ };
1074
689
  }
1075
- function runInstances(instances) {
1076
- return instances.map((instance) => instance.listing);
690
+
691
+ // src/core/resources-of.ts
692
+ function resourcesOf(extensions) {
693
+ return extensions.flatMap(({ resources }) => resources);
1077
694
  }
1078
- function releasedResources(instances) {
1079
- return instances.filter((instance) => instance.took()).map((instance) => instance.listing.resource);
695
+
696
+ // src/core/events.ts
697
+ function timedProgress(clock, observer) {
698
+ return { emit: (event) => observer.observe({ event, at: clock.now() }) };
1080
699
  }
1081
- async function releaseResources(instances, progress) {
1082
- let releaseFacts = {};
1083
- const thrown = [];
1084
- for (const instance of instances.toReversed()) {
1085
- try {
1086
- releaseFacts = { ...releaseFacts, ...await instance.release(progress) };
1087
- } catch (error) {
1088
- thrown.push(error);
700
+ function observeAll(...observers) {
701
+ return {
702
+ observe: async (timed) => {
703
+ for (const observer of observers) await observer.observe(timed);
1089
704
  }
1090
- }
1091
- if (thrown.length > 0) throw thrown[0];
1092
- return releaseFacts;
1093
- }
1094
- function resourceWarnings(cleanup) {
1095
- return Object.values(cleanup).reduce((sum, { warnings }) => sum + warnings.length, 0);
705
+ };
1096
706
  }
1097
707
 
1098
- // src/core/run.ts
1099
- async function executeRun(resources, context, worlds, request, control, progress) {
1100
- const instances = resourceInstances(resources, worlds, request.resources);
1101
- await progress.emit({
1102
- kind: "started",
1103
- version: request.version,
1104
- commit: request.commit,
1105
- configFile: request.configFile,
1106
- resources: runInstances(instances)
1107
- });
1108
- for (const skip of request.skipped ?? []) await progress.emit({ kind: "resource-skipped", ...skip });
1109
- if (request.runner !== void 0) {
1110
- const { prepared } = request.runner;
1111
- await progress.emit({
1112
- kind: "runner-prepared",
1113
- base: prepared.base,
1114
- baseRef: prepared.baseRef,
1115
- nestedRepositories: prepared.upload.nestedRepositories,
1116
- notes: prepared.notes,
1117
- saveSkipped: prepared.save?.kind === "skipped"
1118
- });
1119
- }
1120
- let cleanupStarted = false;
1121
- const startCleanup = async (runnerSandbox) => {
1122
- if (cleanupStarted) return;
1123
- cleanupStarted = true;
1124
- await progress.emit({ kind: "cleanup-started", runnerSandbox, resources: releasedResources(instances) });
1125
- };
1126
- let resourceCleanup = {};
1127
- let releasing;
1128
- const release = (runnerSandbox) => releasing ??= (async () => {
1129
- try {
1130
- await startCleanup(runnerSandbox);
1131
- } finally {
1132
- resourceCleanup = await releaseResources(instances, progress);
1133
- }
1134
- })();
1135
- const unsaved = request.runner === void 0 ? null : { kind: "keep", ms: keptMs(request.runner.sandbox) };
1136
- let ended2;
1137
- let runnerCleanup = null;
1138
- try {
1139
- ({ ended: ended2, runnerCleanup } = request.runner === void 0 ? { ended: await runUnsandboxed(context, request, instances, control, progress), runnerCleanup: null } : await runSandboxed(context, request, instances, control, progress, { startCleanup, release }));
1140
- } finally {
1141
- await release(unsaved);
1142
- }
1143
- await progress.emit({
1144
- kind: "cleanup-finished",
1145
- resourceWarnings: resourceWarnings(resourceCleanup),
1146
- notStopped: runnerCleanup?.notStopped.length ?? 0,
1147
- notDeleted: runnerCleanup?.notDeleted.length ?? 0
1148
- });
1149
- if (ended2.kind !== "command-ended") return { ...ended2, runnerCleanup, resourceCleanup };
1150
- const { kind: _kind, ...ran } = ended2;
708
+ // src/core/live/command-gateway.ts
709
+ import { spawn } from "node:child_process";
710
+ import { StringDecoder } from "node:string_decoder";
711
+ function liveCommandGateway() {
1151
712
  return {
1152
- kind: "ran",
1153
- ...ran,
1154
- runnerCleanup,
1155
- resourceCleanup
713
+ run: (request) => runCommand(request)
1156
714
  };
1157
715
  }
1158
- async function runUnsandboxed(context, request, instances, control, progress) {
1159
- const acquisition = await acquireResources(instances, {
1160
- credential: request.credential === void 0 ? void 0 : unsandboxedSource(context, request.credential, progress),
1161
- signal: control.signal,
1162
- progress
716
+ var PIPE_DRAIN_MS = 2e3;
717
+ function runCommand(request) {
718
+ const [executable, ...args] = request.argv;
719
+ if (executable === void 0) throw new Error("liveCommandGateway: the command's argv is empty");
720
+ return new Promise((resolve) => {
721
+ let started = false;
722
+ let settled = false;
723
+ let draining;
724
+ const settle = (outcome) => {
725
+ if (settled) return;
726
+ settled = true;
727
+ clearTimeout(draining);
728
+ request.terminate.removeEventListener("abort", onTerminate);
729
+ resolve(outcome);
730
+ };
731
+ const ended2 = (code, signal) => signal !== null ? { kind: "signaled", signal } : { kind: "exited", code: code ?? 0 };
732
+ const command = spawn(executable, args, {
733
+ stdio: ["inherit", "pipe", "pipe"],
734
+ shell: false,
735
+ env: { ...request.env }
736
+ });
737
+ const onTerminate = () => {
738
+ if (started) command.kill("SIGTERM");
739
+ };
740
+ for (const stream of ["stdout", "stderr"]) {
741
+ const decoder = new StringDecoder("utf8");
742
+ const pipe = command[stream];
743
+ pipe.on("data", (chunk) => {
744
+ const data = decoder.write(chunk);
745
+ if (data !== "") request.onOutput({ stream, data });
746
+ });
747
+ pipe.on("end", () => {
748
+ const data = decoder.end();
749
+ if (data !== "") request.onOutput({ stream, data });
750
+ });
751
+ }
752
+ command.once("spawn", () => {
753
+ started = true;
754
+ if (request.terminate.aborted) command.kill("SIGTERM");
755
+ });
756
+ command.once("error", (error) => {
757
+ if (!started) settle({ kind: "spawn-failed", message: error.message });
758
+ });
759
+ command.once("close", (code, signal) => settle(ended2(code, signal)));
760
+ command.once("exit", (code, signal) => {
761
+ draining = setTimeout(() => {
762
+ command.stdout.destroy();
763
+ command.stderr.destroy();
764
+ settle(ended2(code, signal));
765
+ }, PIPE_DRAIN_MS);
766
+ });
767
+ request.terminate.addEventListener("abort", onTerminate, { once: true });
1163
768
  });
1164
- if (acquisition.kind === "stopped") return acquisition.outcome;
1165
- await announceAcquired(instances, progress);
1166
- const terminal = context.runnerTerminal;
1167
- const env = commandEnvironment(
1168
- colorEnvironment(request.env, terminal.color),
1169
- runPayload(resourcesPayload(instances), {
1170
- ...request.testEvents === void 0 ? {} : { testEvents: request.testEvents },
1171
- ...request.verbose === void 0 ? {} : { verbose: request.verbose }
1172
- })
1173
- );
1174
- await progress.emit({ kind: "command-started", argv: request.argv });
1175
- if (control.signal.aborted) return canceledStop();
1176
- const commandStartedAt = context.clock.now();
1177
- const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
1178
- const write = (stream, text) => {
1179
- if (text === "") return;
1180
- if (stream === "stdout") terminal.writeStdout(text);
1181
- else terminal.writeStderr(text);
769
+ }
770
+
771
+ // src/core/live/terminal-command-gateway.ts
772
+ import { spawn as spawn2 } from "node:child_process";
773
+ function liveTerminalCommandGateway() {
774
+ return {
775
+ run: (request) => runInTerminal(request)
1182
776
  };
1183
- const command = await context.commands.run({
1184
- argv: request.argv,
1185
- env,
1186
- terminate: control.terminate,
1187
- onOutput: ({ stream, data }) => write(stream, splitters[stream].push(data))
1188
- });
1189
- const commandEndedAt = context.clock.now();
1190
- write("stdout", splitters.stdout.flush());
1191
- write("stderr", splitters.stderr.flush());
1192
- if (command.kind === "spawn-failed")
1193
- return { kind: "spawn-failed", executable: request.argv[0] ?? "", message: command.message };
1194
- await progress.emit({
1195
- kind: "command-ended",
1196
- command: posix.basename(request.argv[0] ?? ""),
1197
- outcome: command,
1198
- ms: commandEndedAt.getTime() - commandStartedAt.getTime()
1199
- });
1200
- return { kind: "command-ended", resources: resourcesRan(instances), command, runner: void 0 };
1201
777
  }
1202
- function unsandboxedSource(context, choice, progress) {
1203
- if (choice.source === "mint") return mintSourceReported(context, choice.target, progress);
1204
- return credentialSourceFor(choice, context, {
1205
- onMint: (target) => progress.emit({ kind: "minting", target }),
1206
- onRequest: () => progress.emit({ kind: "requesting-token" })
778
+ function runInTerminal(request) {
779
+ const [executable, ...args] = request.argv;
780
+ if (executable === void 0) throw new Error("liveTerminalCommandGateway: the command's argv is empty");
781
+ return new Promise((resolve) => {
782
+ let started = false;
783
+ let settled = false;
784
+ const settle = (outcome) => {
785
+ if (settled) return;
786
+ settled = true;
787
+ request.terminate.removeEventListener("abort", onTerminate);
788
+ resolve(outcome);
789
+ };
790
+ const command = spawn2(executable, args, {
791
+ cwd: request.cwd,
792
+ stdio: "inherit",
793
+ shell: false,
794
+ env: { ...request.env }
795
+ });
796
+ const onTerminate = () => {
797
+ if (started) command.kill("SIGTERM");
798
+ };
799
+ command.once("spawn", () => {
800
+ started = true;
801
+ if (request.terminate.aborted) command.kill("SIGTERM");
802
+ });
803
+ command.once("error", (error) => {
804
+ if (!started) settle({ kind: "spawn-failed", message: error.message });
805
+ });
806
+ command.once(
807
+ "exit",
808
+ (code, signal) => settle(signal !== null ? { kind: "signaled", signal } : { kind: "exited", code: code ?? 0 })
809
+ );
810
+ request.terminate.addEventListener("abort", onTerminate, { once: true });
1207
811
  });
1208
812
  }
1209
- function runnerLaneOutcome(outcome) {
1210
- if (outcome.kind === "ready") return "ready";
1211
- return outcome.kind === "aborted" ? "stopped" : "failed";
1212
- }
1213
- function runnerStopped(outcome) {
1214
- if (outcome.kind === "failed") return { kind: "runner-failed", failure: outcome.failure };
1215
- if (outcome.kind === "snapshot-gone")
1216
- return { kind: "snapshot-gone", entry: outcome.entry, removal: outcome.removal };
1217
- return void 0;
813
+
814
+ // src/core/live/job-summary-gateway.ts
815
+ import { appendFile } from "node:fs/promises";
816
+ function liveJobSummaryGateway(options) {
817
+ const { path } = options;
818
+ return {
819
+ appendJobSummary: async (markdown) => {
820
+ if (path === void 0 || path === "") return { kind: "none" };
821
+ try {
822
+ await appendFile(path, markdown.endsWith("\n") ? markdown : `${markdown}
823
+ `);
824
+ return { kind: "appended" };
825
+ } catch (error) {
826
+ return { kind: "failed", failure: { path, message: error instanceof Error ? error.message : String(error) } };
827
+ }
828
+ }
829
+ };
1218
830
  }
1219
- async function runSandboxed(context, request, instances, control, progress, cleanup) {
1220
- const runnerProgress = { emit: (event) => progress.emit({ kind: "runner", event }) };
1221
- const plan = request.runner.sandbox;
1222
- const keepMs = keptMs(plan);
1223
- const scope = runnerSandboxScope(context, runnerProgress, { keepMs });
1224
- let commandRunning = false;
1225
- const stop = () => {
1226
- void progress.emit({ kind: "runner", event: { kind: "stopping", commandRunning, keepMs } }).catch(() => void 0);
1227
- void scope.close().catch(() => void 0);
831
+
832
+ // src/core/live/progress-terminal.ts
833
+ var LIVE_TICK_MS = 90;
834
+ var CURSOR_HIDE = "\x1B[?25l";
835
+ var CURSOR_SHOW = "\x1B[?25h";
836
+ var AUTOWRAP_OFF = "\x1B[?7l";
837
+ var AUTOWRAP_ON = "\x1B[?7h";
838
+ var ERASE_DOWN = "\x1B[J";
839
+ function liveProgressTerminal(options = {}) {
840
+ const stdout = options.stdout ?? process.stdout;
841
+ const stderr = options.stderr ?? process.stderr;
842
+ let failed = false;
843
+ let listening = false;
844
+ let frame;
845
+ let drawn = [];
846
+ let lineEnded = true;
847
+ let ticker;
848
+ let redrawQueued = false;
849
+ const write = (stream, text) => {
850
+ if (failed || text === "") return;
851
+ if (!listening) {
852
+ stdout.on("error", fail);
853
+ stderr.on("error", fail);
854
+ listening = true;
855
+ }
856
+ try {
857
+ stream.write(text);
858
+ } catch {
859
+ fail();
860
+ }
1228
861
  };
1229
- if (control.signal.aborted) stop();
1230
- else control.signal.addEventListener("abort", stop, { once: true });
1231
- try {
1232
- const ended2 = await runInSandbox(
1233
- context,
1234
- request,
1235
- instances,
1236
- {
1237
- ...control,
1238
- scope,
1239
- commandStarted: () => {
1240
- commandRunning = true;
1241
- }
1242
- },
1243
- progress,
1244
- runnerProgress
862
+ const fail = () => {
863
+ failed = true;
864
+ stopTicking();
865
+ };
866
+ const terminalColumns = () => positive(stderr.columns) ?? 80;
867
+ const columns = () => {
868
+ const reported = positive(stderr.columns);
869
+ return reported === void 0 ? 80 : Math.max(20, reported);
870
+ };
871
+ const occupied = () => {
872
+ const width = terminalColumns();
873
+ return drawn.reduce((rows, visible) => rows + Math.max(1, Math.ceil(visible / width)), 0);
874
+ };
875
+ const moveUp = () => {
876
+ const rows = occupied();
877
+ return rows > 0 ? `\x1B[${rows}F${ERASE_DOWN}` : "";
878
+ };
879
+ const erase = () => {
880
+ write(stderr, moveUp());
881
+ if (!failed) drawn = [];
882
+ };
883
+ const draw = () => {
884
+ if (frame === void 0) return;
885
+ const width = columns();
886
+ const height = positive(stderr.rows);
887
+ const shown = frame();
888
+ const lines = (height === void 0 ? shown : shown.slice(0, Math.max(1, height - 1))).map(
889
+ (line) => clip(line, width - 1)
1245
890
  );
1246
- commandRunning = false;
1247
- const unsaved = { kind: "keep", ms: keepMs };
1248
- if (ended2.kind !== "command-ended") {
1249
- await cleanup.startCleanup(unsaved);
1250
- return { ended: ended2, runnerCleanup: { ...await scope.close(), target: request.runner.target } };
891
+ if (lines.length === 0) {
892
+ erase();
893
+ return;
1251
894
  }
1252
- const { ready, ...rest } = ended2;
1253
- const { prepared } = request.runner;
1254
- let save = prepared.save?.kind === "skipped" ? prepared.save : null;
1255
- const action = plan.kind === "save" && !control.signal.aborted ? plan : unsaved;
1256
- if (action.kind === "save") {
1257
- const saving = saveBranchSnapshot(
1258
- context,
1259
- { ready, branch: action.branch, head: prepared.head.commit },
1260
- { scope, signal: control.signal },
1261
- runnerProgress
1262
- );
1263
- try {
1264
- await cleanup.release(action);
1265
- } finally {
1266
- save = await saving;
895
+ const lead = lineEnded ? "" : "\n";
896
+ lineEnded = true;
897
+ write(stderr, `${moveUp()}${lead}${AUTOWRAP_OFF}${lines.map((line) => `${line}
898
+ `).join("")}${AUTOWRAP_ON}`);
899
+ const edge = terminalColumns();
900
+ drawn = lines.map((line) => Math.min(visibleWidth(line), edge));
901
+ };
902
+ const restore = () => write(stderr, CURSOR_SHOW);
903
+ const stopTicking = () => {
904
+ if (ticker !== void 0) clearInterval(ticker);
905
+ ticker = void 0;
906
+ };
907
+ return {
908
+ columns,
909
+ show(next) {
910
+ if (frame === void 0) {
911
+ write(stderr, CURSOR_HIDE);
912
+ process.once("exit", restore);
1267
913
  }
1268
- }
1269
- await cleanup.startCleanup(action);
1270
- const runnerCleanup = { ...await scope.close(), target: request.runner.target };
1271
- return { ended: { ...rest, runner: { ...rest.runner, save } }, runnerCleanup };
1272
- } finally {
1273
- control.signal.removeEventListener("abort", stop);
1274
- await scope.close();
1275
- }
1276
- }
1277
- async function runInSandbox(context, request, instances, control, progress, runnerProgress) {
1278
- const { runner } = request;
1279
- const canceled = () => ({ ...canceledStop(), commandStopped: false });
1280
- if (control.signal.aborted) return canceled();
1281
- const minted = await mintReported(context, runner.target, progress);
1282
- if (!minted.ok) return { kind: "mint-failed", failure: minted.failure, target: runner.target, runner: true };
1283
- const project = minted.credential.vercelProject();
1284
- if (project === void 0)
1285
- return { kind: "runner-failed", failure: { kind: "credential-claims-missing", target: runner.target } };
1286
- if (control.signal.aborted) return canceled();
1287
- const acquisition = await readyBoth(
1288
- context,
1289
- {
1290
- request,
1291
- instances,
1292
- credential: obtainedSource(runner.target, minted.credential),
1293
- access: { credential: minted.credential, ...project }
1294
- },
1295
- control,
1296
- progress,
1297
- runnerProgress
1298
- );
1299
- if (acquisition.kind === "stopped") {
1300
- const { outcome } = acquisition;
1301
- return outcome.kind === "canceled" ? { ...outcome, commandStopped: false } : outcome;
1302
- }
1303
- const { beside: readied } = acquisition;
1304
- if (readied?.kind !== "ready") return canceled();
1305
- const ready = readied.runner;
1306
- await announceAcquired(instances, progress);
1307
- await progress.emit({ kind: "command-started", argv: request.argv });
1308
- if (control.signal.aborted) return canceled();
1309
- control.commandStarted();
1310
- let testEvents = Promise.resolve();
1311
- const sandboxed = await runCommandInSandbox(
1312
- context,
1313
- {
1314
- runner: ready,
1315
- argv: request.argv,
1316
- runPayload: JSON.stringify(
1317
- runPayload(resourcesPayload(instances), {
1318
- testEvents: SANDBOX_TEST_EVENTS_PATH,
1319
- ...request.verbose === void 0 ? {} : { verbose: request.verbose }
1320
- })
1321
- ),
1322
- testEvents: {
1323
- onLine: (line) => {
1324
- const event = parseTestEvent(line);
1325
- testEvents = testEvents.then(
1326
- () => progress.emit(event === void 0 ? { kind: "test-event-unreadable" } : { kind: "test", event })
1327
- );
1328
- },
1329
- onIncomplete: (message) => {
1330
- testEvents = testEvents.then(() => progress.emit({ kind: "test-events-incomplete", message }));
1331
- }
914
+ frame = next;
915
+ draw();
916
+ if (ticker === void 0 && !failed) {
917
+ ticker = setInterval(draw, LIVE_TICK_MS);
918
+ ticker.unref();
1332
919
  }
1333
920
  },
1334
- { kill: control.signal },
1335
- runnerProgress
1336
- );
1337
- await testEvents;
1338
- if (sandboxed.kind === "killed" || sandboxed.kind === "failed" && control.signal.aborted)
1339
- return { ...canceledStop(), commandStopped: true };
1340
- if (sandboxed.kind === "failed") return { kind: "runner-failed", failure: sandboxed.failure };
1341
- const command = sandboxed.exitCode === null ? { kind: "no-exit-code" } : { kind: "exited", code: sandboxed.exitCode };
1342
- await progress.emit({
1343
- kind: "command-ended",
1344
- command: posix.basename(request.argv[0] ?? ""),
1345
- outcome: command,
1346
- ms: sandboxed.ms
1347
- });
1348
- return {
1349
- kind: "command-ended",
1350
- resources: resourcesRan(instances),
1351
- command,
1352
- runner: {
1353
- snapshotId: ready.startedFrom.snapshotId,
1354
- base: ready.startedFrom.base,
1355
- snapshotBranch: ready.startedFrom.branch ?? null,
1356
- snapshotHead: ready.startedFrom.head ?? null,
1357
- built: ready.built,
1358
- vcpus: ready.vcpus,
1359
- region: ready.region,
1360
- runtime: ready.runtime,
1361
- buildMs: ready.buildMs,
1362
- save: null
1363
- },
1364
- ready
921
+ print(stream, text) {
922
+ if (text === "") return;
923
+ erase();
924
+ write(stream === "stdout" ? stdout : stderr, text);
925
+ lineEnded = text.endsWith("\n");
926
+ if (frame === void 0 || redrawQueued) return;
927
+ redrawQueued = true;
928
+ setImmediate(() => {
929
+ redrawQueued = false;
930
+ draw();
931
+ });
932
+ },
933
+ settle() {
934
+ if (frame === void 0) return;
935
+ draw();
936
+ frame = void 0;
937
+ drawn = [];
938
+ stopTicking();
939
+ process.removeListener("exit", restore);
940
+ restore();
941
+ }
1365
942
  };
1366
943
  }
1367
- async function readyBoth(context, request, control, progress, runnerProgress) {
1368
- const { runner } = request.request;
1369
- await progress.emit({ kind: "lanes-started" });
1370
- return await acquireResources(request.instances, {
1371
- credential: request.credential,
1372
- signal: control.signal,
1373
- progress,
1374
- beside: {
1375
- lane: { lane: "runner", resource: null },
1376
- start: (signal) => readyRunner(
1377
- context,
1378
- { prepared: runner.prepared, access: request.access, user: runner.user, secrets: runner.secrets },
1379
- { scope: control.scope, signal },
1380
- runnerProgress
1381
- ),
1382
- outcomeOf: runnerLaneOutcome,
1383
- stopped: runnerStopped
944
+ function positive(value) {
945
+ return value !== void 0 && Number.isInteger(value) && value > 0 ? value : void 0;
946
+ }
947
+ function visibleWidth(line) {
948
+ let visible = 0;
949
+ for (const part of line.split(/(\u001b\[[0-9;]*m)/)) {
950
+ if (!part.startsWith("\x1B[")) visible += Array.from(part).length;
951
+ }
952
+ return visible;
953
+ }
954
+ function clip(line, width) {
955
+ let visible = 0;
956
+ let out = "";
957
+ const parts = line.split(/(\u001b\[[0-9;]*m)/);
958
+ for (const part of parts) {
959
+ if (part.startsWith("\x1B[")) {
960
+ out += part;
961
+ continue;
1384
962
  }
1385
- });
963
+ for (const character of part) {
964
+ if (visible >= width) return `${out}\x1B[0m`;
965
+ out += character;
966
+ visible += 1;
967
+ }
968
+ }
969
+ return out;
1386
970
  }
1387
971
 
1388
- // src/core/run-state.ts
1389
- var RUNNER_STEPS = ["snapshot", "start", "upload", "apply", "install", "build"];
1390
- var EMPTY_RUN_STATE = {
1391
- origin: void 0,
1392
- lastAt: void 0,
1393
- version: void 0,
1394
- instances: void 0,
1395
- base: void 0,
1396
- mint: void 0,
1397
- lanesStartedAt: void 0,
1398
- resources: {},
1399
- runner: void 0,
1400
- command: void 0,
1401
- cleanup: void 0,
1402
- tests: void 0,
1403
- stopping: false
1404
- };
1405
- function applyRunEvent(resources, state, timed) {
1406
- const at = timed.at.getTime();
1407
- return applyEvent(resources, { ...state, origin: state.origin ?? at, lastAt: at }, timed.event, at);
972
+ // src/core/run.ts
973
+ import { posix } from "node:path";
974
+
975
+ // src/core/payload.ts
976
+ function runPayload(resources, options = {}) {
977
+ return {
978
+ version: 3,
979
+ resources,
980
+ ...options.testEvents === void 0 ? {} : { testEvents: options.testEvents },
981
+ ...options.verbose === true ? { verbose: true } : {}
982
+ };
1408
983
  }
1409
- function commandPassed(outcome) {
1410
- return outcome.kind === "exited" && outcome.code === 0;
984
+ function commandEnvironment(env, payload) {
985
+ const kept = Object.entries(env).filter((pair) => pair[1] !== void 0);
986
+ return { ...Object.fromEntries(kept), [RUN_PAYLOAD_VARIABLE]: JSON.stringify(payload) };
1411
987
  }
1412
- function cleanupProblems(cleanup) {
1413
- return cleanup.resourceWarnings + cleanup.notStopped + cleanup.notDeleted;
988
+ function colorEnvironment(env, color) {
989
+ if (env["FORCE_COLOR"] !== void 0 || env["NO_COLOR"] !== void 0) return env;
990
+ return { ...env, ...color ? { FORCE_COLOR: "1" } : { NO_COLOR: "1" } };
1414
991
  }
1415
- function applyEvent(resources, state, event, at) {
1416
- switch (event.kind) {
1417
- case "started":
1418
- return { ...state, version: { version: event.version, commit: event.commit }, instances: event.resources };
1419
- // A skipped resource takes nothing and has no lane: the progress says it, and the state keeps nothing of it.
1420
- case "resource-skipped":
1421
- return state;
1422
- case "runner-prepared":
1423
- return {
1424
- ...state,
1425
- base: { sha: event.base, ref: event.baseRef },
1426
- runner: {
1427
- status: "pending",
1428
- startedAt: at,
1429
- endedAt: void 0,
1430
- sandbox: void 0,
1431
- buildSandbox: void 0,
1432
- steps: RUNNER_STEPS.map((name) => ({
1433
- name,
1434
- status: "pending",
1435
- startedAt: void 0,
1436
- endedAt: void 0,
1437
- label: "",
1438
- latest: void 0
1439
- })),
1440
- snapshot: void 0,
1441
- uploadBytes: void 0,
1442
- activity: void 0,
1443
- kept: void 0,
1444
- save: void 0
1445
- }
1446
- };
1447
- case "minting":
1448
- return { ...state, mint: { status: "running", startedAt: at, endedAt: void 0, target: event.target } };
1449
- case "minted":
1450
- return state.mint === void 0 ? state : { ...state, mint: { ...state.mint, status: event.ok ? "done" : "failed", endedAt: at } };
1451
- // A GitHub Actions OIDC token request reports no end, so it has no span of its own.
1452
- case "requesting-token":
1453
- return state;
1454
- case "lanes-started":
1455
- return {
1456
- ...state,
1457
- lanesStartedAt: at,
1458
- runner: state.runner === void 0 ? void 0 : { ...state.runner, status: "running", startedAt: at }
1459
- };
1460
- case "lane-started": {
1461
- const startedAt = state.lanesStartedAt ?? state.origin ?? at;
1462
- if (event.resource === null) return state;
1463
- const { lane: name, resource: key } = event;
1464
- const owner = resources.find(({ progress }) => progress?.lane === name);
1465
- if (owner?.progress === void 0) return state;
1466
- return withState(state, key, owner.name, owner.progress.start(startedAt));
1467
- }
1468
- case "lane-ended": {
1469
- if (event.resource === null) return runnerEnded(state, event.outcome, at);
1470
- const { outcome } = event;
1471
- return withOwnLane(
1472
- resources,
1473
- state,
1474
- event.resource,
1475
- void 0,
1476
- (progress, own) => progress.ended(own, outcome, at)
992
+
993
+ // src/core/resources.ts
994
+ function resourceInstances({ named }, worlds, requests) {
995
+ return Object.entries(requests).map(
996
+ ([key, request]) => instanceOf(named(request.definition, key), key, worlds, request)
997
+ );
998
+ }
999
+ function instanceOf(resource, key, worlds, request) {
1000
+ const { name } = resource;
1001
+ const lifecycle = resource.lifecycle(worlds[name]);
1002
+ const taken = [];
1003
+ let result;
1004
+ let canceled = [];
1005
+ const acquireWarnings = [];
1006
+ const releaseWarnings = [];
1007
+ const report = (progress, lane2, kept) => ({
1008
+ run: (text) => progress.emit({ kind: "resource-notice", resource: key, definition: name, lane: "run", text }),
1009
+ cleanup: (text) => progress.emit({ kind: "resource-notice", resource: key, definition: name, lane: "cleanup", text }),
1010
+ warning: (reason, message) => {
1011
+ kept.push({ reason, message });
1012
+ return progress.emit({ kind: "resource-warning", resource: key, definition: name, lane: lane2, reason, message });
1013
+ },
1014
+ progress: (event) => progress.emit({ kind: "resource", resource: key, definition: name, event })
1015
+ });
1016
+ const acquired = () => result !== void 0 && "acquired" in result ? result.acquired : void 0;
1017
+ const laneName = resource.progress?.lane;
1018
+ const lane = laneName === void 0 ? void 0 : { lane: laneName, resource: key };
1019
+ return {
1020
+ listing: { resource: key, definition: name, lane: laneName ?? null },
1021
+ lane,
1022
+ startLane: async (progress) => {
1023
+ if (lane !== void 0) await progress.emit({ kind: "lane-started", ...lane });
1024
+ },
1025
+ acquire: async ({ signal, credential, progress, finishLane }) => {
1026
+ const answered = await finishLane(
1027
+ lane,
1028
+ lifecycle.acquireForRun({
1029
+ options: request.options,
1030
+ secrets: request.secrets,
1031
+ credential,
1032
+ take: (one) => void taken.push(one),
1033
+ report: report(progress, "run", acquireWarnings),
1034
+ signal
1035
+ }),
1036
+ resourceLaneOutcome
1477
1037
  );
1038
+ if ("refused" in answered) {
1039
+ const outcome = {
1040
+ kind: "resource-refused",
1041
+ resource: key,
1042
+ definition: name,
1043
+ refusal: answered
1044
+ };
1045
+ return { kind: "refused", outcome };
1046
+ }
1047
+ if ("mintFailed" in answered) {
1048
+ const { failure, target } = answered.mintFailed;
1049
+ return { kind: "refused", outcome: { kind: "mint-failed", failure, target, runner: false } };
1050
+ }
1051
+ result = answered;
1052
+ canceled = "acquired" in answered ? answered.acquired.canceled ?? [] : answered.canceled;
1053
+ return { kind: "acquired" in answered ? "acquired" : "canceled" };
1054
+ },
1055
+ acquired: () => {
1056
+ const one = acquired();
1057
+ if (one === void 0) return [];
1058
+ const said = { kind: "resource-acquired", resource: key, definition: name };
1059
+ return one.announce === void 0 ? [said] : [said, { kind: "resource", resource: key, definition: name, event: one.announce }];
1060
+ },
1061
+ payload: () => {
1062
+ const one = acquired();
1063
+ return one === void 0 ? {} : { [key]: { definition: name, payload: one.payload } };
1064
+ },
1065
+ ran: () => {
1066
+ const one = acquired();
1067
+ if (one === void 0 || one.result === void 0 && acquireWarnings.length === 0) return {};
1068
+ const facts = one.result === void 0 ? null : one.result.facts;
1069
+ const rows = one.result === void 0 ? [] : one.result.rows;
1070
+ return { [key]: { definition: name, facts, rows, warnings: [...acquireWarnings] } };
1071
+ },
1072
+ took: () => taken.length > 0,
1073
+ release: async (progress) => {
1074
+ const released = await lifecycle.releaseAfterRun({
1075
+ taken,
1076
+ report: report(progress, "cleanup", releaseWarnings)
1077
+ });
1078
+ if ("nothingTaken" in released) return {};
1079
+ return { [key]: { definition: name, warnings: [...releaseWarnings], done: released.done, canceled } };
1478
1080
  }
1479
- // The launcher's word that a resource is acquired changes no lane: its acquire's `announce` follows it, as one of
1480
- // its own events. A line or a warning a resource instance reported changes nothing either.
1481
- case "resource-acquired":
1482
- case "resource-notice":
1483
- case "resource-warning":
1484
- return state;
1485
- case "command-started":
1486
- return {
1487
- ...state,
1488
- command: { status: "running", startedAt: at, endedAt: void 0, argv: event.argv, outcome: void 0 }
1489
- };
1490
- case "command-ended": {
1491
- if (state.command === void 0) return state;
1492
- const endedAt = state.command.startedAt + event.ms;
1493
- const status = commandPassed(event.outcome) ? "done" : "failed";
1494
- return { ...state, command: { ...state.command, status, endedAt, outcome: event.outcome } };
1495
- }
1496
- case "cleanup-started":
1497
- return {
1498
- ...state,
1499
- cleanup: {
1500
- status: "running",
1501
- startedAt: at,
1502
- endedAt: void 0,
1503
- runnerSandbox: event.runnerSandbox,
1504
- resources: event.resources,
1505
- resourceWarnings: 0,
1506
- notStopped: 0,
1507
- notDeleted: 0,
1508
- waiting: false
1509
- }
1510
- };
1511
- case "cleanup-finished": {
1512
- if (state.cleanup === void 0) return state;
1513
- const cleanup = {
1514
- ...state.cleanup,
1515
- endedAt: at,
1516
- resourceWarnings: event.resourceWarnings,
1517
- notStopped: event.notStopped,
1518
- notDeleted: event.notDeleted,
1519
- waiting: false
1520
- };
1521
- return { ...state, cleanup: { ...cleanup, status: cleanupProblems(cleanup) === 0 ? "done" : "failed" } };
1081
+ };
1082
+ }
1083
+ async function acquireResources(instances, input) {
1084
+ const { progress, beside } = input;
1085
+ const internal = new AbortController();
1086
+ const signal = AbortSignal.any([input.signal, internal.signal]);
1087
+ const finishLane = async (lane, task, outcomeOf2) => {
1088
+ let value;
1089
+ let outcome;
1090
+ try {
1091
+ value = await task;
1092
+ outcome = outcomeOf2(value);
1093
+ if (lane !== void 0) await progress.emit({ kind: "lane-ended", ...lane, outcome });
1094
+ } catch (error) {
1095
+ if (lane !== void 0 && outcome === void 0)
1096
+ await progress.emit({ kind: "lane-ended", ...lane, outcome: "failed" }).catch(() => void 0);
1097
+ internal.abort();
1098
+ throw error;
1522
1099
  }
1523
- case "runner":
1524
- return applyRunnerEvent(state, event.event, at);
1525
- case "test":
1526
- return { ...state, tests: applyTestEvent(state.tests ?? EMPTY_TESTS, event.event, at) };
1527
- // The run's summary counts unreadable lines and says the results may be incomplete; no view shows either live.
1528
- case "test-event-unreadable":
1529
- case "test-events-incomplete":
1530
- return state;
1531
- // A resource's own events reach its progress, if it has its own. Its cleanup counts through `cleanup-finished`.
1532
- case "resource":
1533
- return withOwnLane(
1534
- resources,
1535
- state,
1536
- event.resource,
1537
- event.definition,
1538
- (progress, own) => progress.apply(own, event.event, at)
1539
- );
1100
+ if (outcome !== "ready") internal.abort();
1101
+ return value;
1102
+ };
1103
+ for (const instance of instances) await instance.startLane(progress);
1104
+ const instanceTasks = instances.map(
1105
+ (instance) => instance.acquire({ signal, credential: input.credential, progress, finishLane })
1106
+ );
1107
+ const besideTask = beside === void 0 ? Promise.resolve(void 0) : finishLane(beside.lane, beside.start(signal), beside.outcomeOf);
1108
+ const [[besideEnded], instancesEnded] = await Promise.all([
1109
+ Promise.allSettled([besideTask]),
1110
+ Promise.allSettled(instanceTasks)
1111
+ ]);
1112
+ if (besideEnded.status === "rejected") throw besideEnded.reason;
1113
+ const outcomes = [];
1114
+ for (const one of instancesEnded) {
1115
+ if (one.status === "rejected") throw one.reason;
1116
+ outcomes.push(one.value);
1540
1117
  }
1118
+ if (input.signal.aborted) return { kind: "stopped", outcome: canceledStop() };
1119
+ const besideValue = besideEnded.value;
1120
+ const besideStopped = besideValue === void 0 ? void 0 : beside?.stopped(besideValue);
1121
+ if (besideStopped !== void 0) return { kind: "stopped", outcome: besideStopped };
1122
+ for (const outcome of outcomes) if (outcome?.kind === "refused") return { kind: "stopped", outcome: outcome.outcome };
1123
+ if (outcomes.some((outcome) => outcome?.kind === "canceled")) return { kind: "stopped", outcome: canceledStop() };
1124
+ return { kind: "acquired", beside: besideValue };
1541
1125
  }
1542
- function withState(state, key, definition, own) {
1543
- return { ...state, resources: { ...state.resources, [key]: { definition, state: own } } };
1126
+ function resourceLaneOutcome(result) {
1127
+ if ("acquired" in result) return "ready";
1128
+ return "canceled" in result ? "stopped" : "failed";
1544
1129
  }
1545
- function withOwnLane(resources, state, key, definition, change) {
1546
- const record = state.resources[key];
1547
- if (record === void 0 || definition !== void 0 && record.definition !== definition) return state;
1548
- const progress = resources.find((resource) => resource.name === record.definition)?.progress;
1549
- if (progress === void 0) return state;
1550
- return withState(state, key, record.definition, change(progress, record.state));
1130
+ function canceledStop() {
1131
+ return { kind: "canceled" };
1551
1132
  }
1552
- function runnerEnded(state, outcome, at) {
1553
- if (state.runner === void 0) return state;
1554
- const status = outcome === "ready" ? "done" : outcome;
1555
- return {
1556
- ...state,
1557
- runner: {
1558
- ...state.runner,
1559
- status,
1560
- endedAt: at,
1561
- steps: state.runner.steps.map(
1562
- (step) => outcome === "ready" || step.status !== "running" ? step : { ...step, status, endedAt: at, latest: void 0 }
1563
- )
1133
+ async function announceAcquired(instances, progress) {
1134
+ for (const instance of instances) for (const event of instance.acquired()) await progress.emit(event);
1135
+ }
1136
+ function resourcesPayload(instances) {
1137
+ let resources = {};
1138
+ for (const instance of instances) resources = { ...resources, ...instance.payload() };
1139
+ return resources;
1140
+ }
1141
+ function resourcesRan(instances) {
1142
+ let ran = {};
1143
+ for (const instance of instances) ran = { ...ran, ...instance.ran() };
1144
+ return ran;
1145
+ }
1146
+ function runInstances(instances) {
1147
+ return instances.map((instance) => instance.listing);
1148
+ }
1149
+ function releasedResources(instances) {
1150
+ return instances.filter((instance) => instance.took()).map((instance) => instance.listing.resource);
1151
+ }
1152
+ async function releaseResources(instances, progress) {
1153
+ let releaseFacts = {};
1154
+ const thrown = [];
1155
+ for (const instance of instances.toReversed()) {
1156
+ try {
1157
+ releaseFacts = { ...releaseFacts, ...await instance.release(progress) };
1158
+ } catch (error) {
1159
+ thrown.push(error);
1564
1160
  }
1565
- };
1161
+ }
1162
+ if (thrown.length > 0) throw thrown[0];
1163
+ return releaseFacts;
1566
1164
  }
1567
- function applyRunnerEvent(state, event, at) {
1568
- switch (event.kind) {
1569
- case "snapshot-reused":
1570
- return withRunner(
1571
- withStep(state, "snapshot", () => ({ status: "done", startedAt: at, endedAt: at })),
1572
- () => ({
1573
- snapshot: { kind: "reused", id: event.snapshotId, base: event.base, branch: event.branch, head: event.head }
1574
- })
1575
- );
1576
- case "snapshot-build-started":
1577
- return withRunner(
1578
- withStep(state, "snapshot", () => ({ status: "running", startedAt: at })),
1579
- () => ({ snapshot: { kind: "building", summary: event.summary } })
1580
- );
1581
- case "snapshot-built":
1582
- return withRunner(
1583
- withStep(state, "snapshot", () => ({ status: "done", endedAt: at, latest: void 0 })),
1584
- () => ({
1585
- snapshot: { kind: "built", id: event.snapshotId, base: event.base, branch: null, head: null },
1586
- activity: void 0
1587
- })
1588
- );
1589
- case "snapshot-saving":
1590
- return withRunner(state, () => ({ activity: "saving-snapshot" }));
1591
- case "runner-sandbox-starting":
1592
- return withStep(state, "start", () => ({ status: "running", startedAt: at }));
1593
- case "sandbox-started":
1594
- if (event.role !== "runner") return withRunner(state, () => ({ buildSandbox: event.name }));
1595
- return withStep(
1596
- withRunner(state, () => ({ sandbox: { name: event.name, region: event.region, vcpus: event.vcpus } })),
1597
- "start",
1598
- () => ({ status: "done", endedAt: at })
1599
- );
1600
- case "uploading":
1601
- return withStep(state, "upload", () => ({ status: "running", startedAt: at }));
1602
- case "uploaded":
1603
- return withRunner(
1604
- withStep(state, "upload", () => ({ status: "done", endedAt: at })),
1605
- () => ({ uploadBytes: event.bytes })
1606
- );
1607
- case "step-started":
1608
- if (event.phase === "snapshot")
1609
- return withStep(state, "snapshot", () => ({ label: event.label, latest: void 0 }));
1610
- return withStep(state, event.phase, () => ({ status: "running", startedAt: at, label: event.label }));
1611
- case "step-output":
1612
- return withStep(state, event.phase, () => ({ latest: event.line }));
1613
- case "step-finished":
1614
- if (event.phase === "snapshot") return state;
1615
- return withStep(state, event.phase, () => ({ status: "done", endedAt: at, latest: void 0 }));
1616
- case "stopping":
1617
- return { ...state, stopping: true };
1618
- case "command-stopped":
1619
- return state.command === void 0 ? state : { ...state, command: { ...state.command, status: "stopped", endedAt: at, outcome: "stopped" } };
1620
- case "waiting-for-snapshot":
1621
- return withRunner(
1622
- state.cleanup === void 0 ? state : { ...state, cleanup: { ...state.cleanup, waiting: true } },
1623
- () => ({ activity: "waiting-for-snapshot" })
1624
- );
1625
- case "sandbox-kept":
1626
- return withRunner(state, () => ({ kept: { name: event.name, stopsAt: event.stopsAt } }));
1627
- case "branch-snapshot-saving":
1628
- return withRunner(state, () => ({ save: { kind: "saving", branch: event.branch } }));
1629
- case "branch-snapshot-saved":
1630
- return withRunner(state, () => ({
1631
- save: { kind: "saved", id: event.snapshotId, branch: event.branch, head: event.head }
1632
- }));
1633
- case "branch-snapshot-not-saved":
1634
- return withRunner(state, () => ({ save: { kind: "not-saved" } }));
1635
- // A step's outcome comes from its lane's end, not from the end of its output.
1636
- case "output-started":
1637
- case "output-ended":
1638
- case "snapshot-entry-not-written":
1639
- case "command-output-started":
1640
- case "branch-snapshots-dropped":
1641
- case "branch-snapshots-not-dropped":
1642
- return state;
1165
+ function resourceWarnings(cleanup) {
1166
+ return Object.values(cleanup).reduce((sum, { warnings }) => sum + warnings.length, 0);
1167
+ }
1168
+
1169
+ // src/core/run.ts
1170
+ async function executeRun(registry, context, worlds, request, control, progress) {
1171
+ const instances = resourceInstances(registry[LOOKUP], worlds, request.resources);
1172
+ await progress.emit({
1173
+ kind: "started",
1174
+ version: request.version,
1175
+ commit: request.commit,
1176
+ configFile: request.configFile,
1177
+ resources: runInstances(instances)
1178
+ });
1179
+ for (const skip of request.skipped ?? []) await progress.emit({ kind: "resource-skipped", ...skip });
1180
+ if (request.runner !== void 0) {
1181
+ const { prepared } = request.runner;
1182
+ await progress.emit({
1183
+ kind: "runner-prepared",
1184
+ base: prepared.base,
1185
+ baseRef: prepared.baseRef,
1186
+ nestedRepositories: prepared.upload.nestedRepositories,
1187
+ notes: prepared.notes,
1188
+ saveSkipped: prepared.save?.kind === "skipped"
1189
+ });
1190
+ }
1191
+ let cleanupStarted = false;
1192
+ const startCleanup = async (runnerSandbox) => {
1193
+ if (cleanupStarted) return;
1194
+ cleanupStarted = true;
1195
+ await progress.emit({ kind: "cleanup-started", runnerSandbox, resources: releasedResources(instances) });
1196
+ };
1197
+ let resourceCleanup = {};
1198
+ let releasing;
1199
+ const release = (runnerSandbox) => releasing ??= (async () => {
1200
+ try {
1201
+ await startCleanup(runnerSandbox);
1202
+ } finally {
1203
+ resourceCleanup = await releaseResources(instances, progress);
1204
+ }
1205
+ })();
1206
+ let ended2;
1207
+ let runnerCleanup = null;
1208
+ try {
1209
+ ({ ended: ended2, runnerCleanup } = request.runner === void 0 ? { ended: await runUnsandboxed(context, request, instances, control, progress), runnerCleanup: null } : await runSandboxed(context, request, instances, control, progress, { startCleanup, release }));
1210
+ } finally {
1211
+ await release(null);
1643
1212
  }
1213
+ await progress.emit({
1214
+ kind: "cleanup-finished",
1215
+ resourceWarnings: resourceWarnings(resourceCleanup),
1216
+ notStopped: runnerCleanup?.notStopped.length ?? 0,
1217
+ notDeleted: runnerCleanup?.notDeleted.length ?? 0
1218
+ });
1219
+ if (ended2.kind !== "command-ended") return { ...ended2, runnerCleanup, resourceCleanup };
1220
+ const { kind: _kind, ...ran } = ended2;
1221
+ return {
1222
+ kind: "ran",
1223
+ ...ran,
1224
+ runnerCleanup,
1225
+ resourceCleanup
1226
+ };
1644
1227
  }
1645
- var EMPTY_TESTS = { workers: [], filesDone: 0, passed: 0, failed: 0 };
1646
- function applyTestEvent(tests, event, at) {
1647
- if (event.kind === "test-result")
1648
- return {
1649
- ...tests,
1650
- passed: tests.passed + (event.state === "pass" ? 1 : 0),
1651
- failed: tests.failed + (event.state === "fail" ? 1 : 0)
1652
- };
1653
- const existing = tests.workers.find((candidate) => candidate.worker === event.worker);
1654
- const worker = existing ?? {
1655
- worker: event.worker,
1656
- file: void 0,
1657
- fileStartedAt: void 0,
1658
- containerSince: void 0
1228
+ async function runUnsandboxed(context, request, instances, control, progress) {
1229
+ const acquisition = await acquireResources(instances, {
1230
+ credential: request.credential === void 0 ? void 0 : credentialSourceFor(request.credential, context, progress),
1231
+ signal: control.signal,
1232
+ progress
1233
+ });
1234
+ if (acquisition.kind === "stopped") return acquisition.outcome;
1235
+ await announceAcquired(instances, progress);
1236
+ const terminal = context.runnerTerminal;
1237
+ const env = commandEnvironment(
1238
+ colorEnvironment(request.env, terminal.color),
1239
+ runPayload(resourcesPayload(instances), {
1240
+ ...request.testEvents === void 0 ? {} : { testEvents: request.testEvents },
1241
+ ...request.verbose === void 0 ? {} : { verbose: request.verbose }
1242
+ })
1243
+ );
1244
+ await progress.emit({ kind: "command-started", argv: request.argv });
1245
+ if (control.signal.aborted) return canceledStop();
1246
+ const commandStartedAt = context.clock.now();
1247
+ const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
1248
+ const write = (stream, text) => {
1249
+ if (text === "") return;
1250
+ if (stream === "stdout") terminal.writeStdout(text);
1251
+ else terminal.writeStderr(text);
1659
1252
  };
1660
- const put = (changed, rest = {}) => ({
1661
- ...tests,
1662
- ...rest,
1663
- workers: [...tests.workers.filter((candidate) => candidate.worker !== changed.worker), changed].toSorted(
1664
- (a, b) => a.worker - b.worker
1665
- )
1253
+ const command = await context.commands.run({
1254
+ argv: request.argv,
1255
+ env,
1256
+ terminate: control.terminate,
1257
+ onOutput: ({ stream, data }) => write(stream, splitters[stream].push(data))
1666
1258
  });
1667
- switch (event.kind) {
1668
- case "file-started":
1669
- return put({ ...worker, file: event.file, fileStartedAt: at, containerSince: void 0 });
1670
- case "test-started":
1671
- return put({ ...worker, file: event.file, fileStartedAt: worker.fileStartedAt ?? at });
1672
- case "test-attempt-finished":
1673
- return put(worker);
1674
- case "file-finished":
1675
- return put(
1676
- { ...worker, file: void 0, fileStartedAt: void 0, containerSince: void 0 },
1677
- { filesDone: tests.filesDone + 1 }
1678
- );
1679
- case "container-starting":
1680
- return put({ ...worker, containerSince: at });
1681
- case "container-started":
1682
- return put({ ...worker, containerSince: void 0 });
1683
- }
1259
+ const commandEndedAt = context.clock.now();
1260
+ write("stdout", splitters.stdout.flush());
1261
+ write("stderr", splitters.stderr.flush());
1262
+ if (command.kind === "spawn-failed")
1263
+ return { kind: "spawn-failed", executable: request.argv[0] ?? "", message: command.message };
1264
+ await progress.emit({
1265
+ kind: "command-ended",
1266
+ command: posix.basename(request.argv[0] ?? ""),
1267
+ outcome: command,
1268
+ ms: commandEndedAt.getTime() - commandStartedAt.getTime()
1269
+ });
1270
+ return { kind: "command-ended", resources: resourcesRan(instances), command, runner: void 0 };
1684
1271
  }
1685
- function withRunner(state, change) {
1686
- return state.runner === void 0 ? state : { ...state, runner: { ...state.runner, ...change() } };
1272
+ function runnerLaneOutcome(outcome) {
1273
+ if (outcome.kind === "ready") return "ready";
1274
+ return outcome.kind === "aborted" ? "stopped" : "failed";
1687
1275
  }
1688
- function withStep(state, name, change) {
1689
- if (state.runner === void 0) return state;
1276
+ function runnerStopped(outcome) {
1277
+ if (outcome.kind === "failed") return { kind: "runner-failed", failure: outcome.failure };
1278
+ if (outcome.kind === "snapshot-gone")
1279
+ return { kind: "snapshot-gone", entry: outcome.entry, removal: outcome.removal };
1280
+ return void 0;
1281
+ }
1282
+ async function runSandboxed(context, request, instances, control, progress, cleanup) {
1283
+ const runnerProgress = { emit: (event) => progress.emit({ kind: "runner", event }) };
1284
+ const session = openRunnerSession(context, request.runner, { signal: control.signal, cleanup }, runnerProgress);
1285
+ try {
1286
+ const ended2 = await runInSandbox(context, request, instances, session, control, progress);
1287
+ const finished = await session.finish();
1288
+ return {
1289
+ ended: ended2.kind === "command-ended" ? { ...ended2, runner: { ...ended2.runner, save: finished.save } } : ended2,
1290
+ runnerCleanup: finished.cleanup
1291
+ };
1292
+ } finally {
1293
+ await session.close();
1294
+ }
1295
+ }
1296
+ async function runInSandbox(context, request, instances, session, control, progress) {
1297
+ const { runner } = request;
1298
+ const canceled = () => ({ ...canceledStop(), commandStopped: false });
1299
+ if (control.signal.aborted) return canceled();
1300
+ const mint = credentialSourceFor({ source: "mint", target: runner.target }, context, progress);
1301
+ const minted = await mint.obtain();
1302
+ if (!minted.ok) return { kind: "mint-failed", failure: minted.failure.failure, target: runner.target, runner: true };
1303
+ const project = minted.credential.vercelProject();
1304
+ if (project === void 0)
1305
+ return { kind: "runner-failed", failure: { kind: "credential-claims-missing", target: runner.target } };
1306
+ if (control.signal.aborted) return canceled();
1307
+ const acquisition = await readyBoth(
1308
+ {
1309
+ instances,
1310
+ credential: mint,
1311
+ ready: (signal) => session.ready({ credential: minted.credential, ...project }, signal)
1312
+ },
1313
+ control,
1314
+ progress
1315
+ );
1316
+ if (acquisition.kind === "stopped") {
1317
+ const { outcome } = acquisition;
1318
+ return outcome.kind === "canceled" ? { ...outcome, commandStopped: false } : outcome;
1319
+ }
1320
+ const { beside: readied } = acquisition;
1321
+ if (readied?.kind !== "ready") return canceled();
1322
+ const ready = readied.runner;
1323
+ await announceAcquired(instances, progress);
1324
+ await progress.emit({ kind: "command-started", argv: request.argv });
1325
+ if (control.signal.aborted) return canceled();
1326
+ let testEvents = Promise.resolve();
1327
+ const sandboxed = await session.runCommand({
1328
+ argv: request.argv,
1329
+ runPayload: JSON.stringify(
1330
+ runPayload(resourcesPayload(instances), {
1331
+ testEvents: SANDBOX_TEST_EVENTS_PATH,
1332
+ ...request.verbose === void 0 ? {} : { verbose: request.verbose }
1333
+ })
1334
+ ),
1335
+ testEvents: {
1336
+ onLine: (line) => {
1337
+ const event = parseTestEvent(line);
1338
+ testEvents = testEvents.then(
1339
+ () => progress.emit(event === void 0 ? { kind: "test-event-unreadable" } : { kind: "test", event })
1340
+ );
1341
+ },
1342
+ onIncomplete: (message) => {
1343
+ testEvents = testEvents.then(() => progress.emit({ kind: "test-events-incomplete", message }));
1344
+ }
1345
+ }
1346
+ });
1347
+ await testEvents;
1348
+ if (sandboxed.kind === "killed" || sandboxed.kind === "failed" && control.signal.aborted)
1349
+ return { ...canceledStop(), commandStopped: true };
1350
+ if (sandboxed.kind === "failed") return { kind: "runner-failed", failure: sandboxed.failure };
1351
+ const command = sandboxed.exitCode === null ? { kind: "no-exit-code" } : { kind: "exited", code: sandboxed.exitCode };
1352
+ await progress.emit({
1353
+ kind: "command-ended",
1354
+ command: posix.basename(request.argv[0] ?? ""),
1355
+ outcome: command,
1356
+ ms: sandboxed.ms
1357
+ });
1690
1358
  return {
1691
- ...state,
1359
+ kind: "command-ended",
1360
+ resources: resourcesRan(instances),
1361
+ command,
1692
1362
  runner: {
1693
- ...state.runner,
1694
- steps: state.runner.steps.map((step) => step.name === name ? { ...step, ...change() } : step)
1363
+ snapshotId: ready.startedFrom.snapshotId,
1364
+ base: ready.startedFrom.base,
1365
+ snapshotBranch: ready.startedFrom.branch ?? null,
1366
+ snapshotHead: ready.startedFrom.head ?? null,
1367
+ built: ready.built,
1368
+ vcpus: ready.vcpus,
1369
+ region: ready.region,
1370
+ runtime: ready.runtime,
1371
+ buildMs: ready.buildMs,
1372
+ save: null
1695
1373
  }
1696
1374
  };
1697
1375
  }
1698
-
1699
- // src/core/timeline.ts
1700
- function timeline(resources, state) {
1701
- const { origin } = state;
1702
- if (origin === void 0) return { startedAt: (/* @__PURE__ */ new Date(0)).toISOString(), totalMs: 0, rows: [], criticalPath: [] };
1703
- const totalMs = (state.lastAt ?? origin) - origin;
1704
- const span = (from) => ({
1705
- startMs: from.startedAt - origin,
1706
- endMs: from.endedAt === void 0 || from.status === "running" ? totalMs : from.endedAt - origin,
1707
- outcome: outcomeOf(from.status)
1708
- });
1709
- const row = (ref, from, extra = {}) => ({
1710
- name: ref.name,
1711
- resource: ref.resource,
1712
- ...span(from),
1713
- steps: extra.steps ?? [],
1714
- idleMs: 0,
1715
- snapshot: extra.snapshot,
1716
- sandboxes: extra.sandboxes
1717
- });
1718
- const rows = [];
1719
- const { mint, runner, command, cleanup } = state;
1720
- if (mint !== void 0) rows.push(row(MINT, mint));
1721
- const started = [];
1722
- for (const [key, record] of Object.entries(state.resources)) {
1723
- const projected = laneRow(resources, key, record, span);
1724
- if (projected === void 0) continue;
1725
- started.push({ ref: projected.ref, span: projected.state });
1726
- rows.push(
1727
- row(projected.ref, projected.state, {
1728
- steps: projected.steps,
1729
- sandboxes: projected.sandboxes
1730
- })
1731
- );
1732
- }
1733
- const runnerStarted = runner !== void 0 && runner.status !== "pending";
1734
- if (runnerStarted) {
1735
- const steps = runner.steps.filter((step) => step.status !== "pending" && !(step.name === "snapshot" && runner.snapshot?.kind === "reused")).flatMap(
1736
- (step) => step.startedAt === void 0 ? [] : [{ name: step.name, ...span({ status: step.status, startedAt: step.startedAt, endedAt: step.endedAt }) }]
1737
- ).toSorted((a, b) => a.startMs - b.startMs);
1738
- const snapshot = runner.snapshot?.kind === "building" ? void 0 : runner.snapshot?.kind;
1739
- rows.push(row(RUNNER, runner, { steps, snapshot }));
1740
- }
1741
- const ready = [...started, ...runner === void 0 ? [] : [{ ref: RUNNER, span: runner }]].flatMap(
1742
- ({ ref, span: from }) => from.status === "done" && from.endedAt !== void 0 ? [{ ref, readyAt: from.endedAt }] : []
1743
- );
1744
- const last = ready.length < 2 ? void 0 : ready.reduce((later, lane) => lane.readyAt >= later.readyAt ? lane : later);
1745
- if (last !== void 0)
1746
- for (const lane of ready) {
1747
- if (lane === last) continue;
1748
- const index = rows.findIndex((candidate) => sameRow(candidate, lane.ref));
1749
- const waited = rows[index];
1750
- if (waited !== void 0) rows[index] = { ...waited, idleMs: last.readyAt - lane.readyAt };
1376
+ async function readyBoth(request, control, progress) {
1377
+ await progress.emit({ kind: "lanes-started" });
1378
+ return await acquireResources(request.instances, {
1379
+ credential: request.credential,
1380
+ signal: control.signal,
1381
+ progress,
1382
+ beside: {
1383
+ lane: { lane: "runner", resource: null },
1384
+ start: request.ready,
1385
+ outcomeOf: runnerLaneOutcome,
1386
+ stopped: runnerStopped
1751
1387
  }
1752
- if (command !== void 0) rows.push(row(TESTS, command));
1753
- if (cleanup !== void 0) rows.push(row(CLEANUP, cleanup));
1754
- const waitedOn = last?.ref ?? started[0]?.ref ?? (runnerStarted ? RUNNER : void 0);
1388
+ });
1389
+ }
1390
+
1391
+ // src/run-directory/plan.ts
1392
+ import { z as z2 } from "zod";
1393
+ var planOptionSchema = z2.object({
1394
+ /** The option's key path, `resources.<key>.<option>`, under its resource key. */
1395
+ path: z2.string(),
1396
+ /** Its value. */
1397
+ value: z2.union([z2.string(), z2.number(), z2.boolean()]),
1398
+ /** Where the value came from: its flag (`flag`), storm.config.ts (`file`), or its default, given the test plan (`default`). */
1399
+ from: z2.enum(["flag", "file", "default"])
1400
+ });
1401
+ var planSchema = z2.object({
1402
+ /** How many tests `vitest list --json <args>` counted. */
1403
+ tests: z2.number().int().nonnegative(),
1404
+ /** How many distinct test files they are in. */
1405
+ files: z2.number().int().nonnegative(),
1406
+ /**
1407
+ * Each resource option whose default is a function of the test plan, with its value and where that came from; empty
1408
+ * when the run has none.
1409
+ */
1410
+ options: z2.array(planOptionSchema)
1411
+ });
1412
+
1413
+ // src/run-directory/run-record.ts
1414
+ var testTotalsSchema = z3.object({
1415
+ passed: z3.number().int().nonnegative(),
1416
+ failed: z3.number().int().nonnegative(),
1417
+ skipped: z3.number().int().nonnegative()
1418
+ });
1419
+ var endedSchema = z3.object({
1420
+ outcome: z3.string(),
1421
+ exitCode: z3.number().int().nullable(),
1422
+ signal: z3.string().nullable(),
1423
+ ms: z3.number().nonnegative().nullable(),
1424
+ tests: testTotalsSchema.nullable(),
1425
+ testsIncomplete: z3.string().nullable(),
1426
+ resources: z3.record(z3.string(), z3.object({ definition: z3.string(), facts: z3.unknown() })).nullable(),
1427
+ resourceRows: z3.array(z3.tuple([z3.string(), z3.union([z3.string(), z3.array(z3.string())])]))
1428
+ });
1429
+ var snapshotSchema = z3.object({
1430
+ id: z3.string(),
1431
+ base: z3.string(),
1432
+ built: z3.boolean(),
1433
+ branch: z3.string().nullable(),
1434
+ head: z3.string().nullable()
1435
+ });
1436
+ var saveSchema = z3.discriminatedUnion("kind", [
1437
+ z3.object({
1438
+ /** It saved the runner sandbox as a branch snapshot. */
1439
+ kind: z3.literal("saved"),
1440
+ /** The runner snapshot it saved. */
1441
+ snapshotId: z3.string(),
1442
+ /** The base it is of: the base of the runner snapshot the run started from, a full SHA. */
1443
+ base: z3.string(),
1444
+ /** The local branch it is for. */
1445
+ branch: z3.string(),
1446
+ /** HEAD's commit as the run started, a full SHA. */
1447
+ head: z3.string(),
1448
+ /** How long the save took, in milliseconds, from the scrub's start until the snapshot was saved. */
1449
+ ms: z3.number(),
1450
+ /** The snapshot's size in bytes. */
1451
+ sizeBytes: z3.number(),
1452
+ /** Whether the runner snapshot cache recorded it; a later run on the branch starts from it only when it did. */
1453
+ entryWritten: z3.boolean()
1454
+ }),
1455
+ z3.object({
1456
+ /** It didn't save: HEAD was detached, so there is no branch to save for. */
1457
+ kind: z3.literal("skipped"),
1458
+ reason: z3.literal("detached-head")
1459
+ }),
1460
+ z3.object({
1461
+ /** It didn't save: the scrub or the save failed. */
1462
+ kind: z3.literal("failed"),
1463
+ step: z3.enum(["scrub", "save-snapshot"]),
1464
+ message: z3.string()
1465
+ }),
1466
+ z3.object({
1467
+ /** It didn't save, or recorded nothing: a signal stopped it. */
1468
+ kind: z3.literal("stopped")
1469
+ })
1470
+ ]);
1471
+ var whereSchema = z3.discriminatedUnion("kind", [
1472
+ z3.object({ kind: z3.literal("unsandboxed") }),
1473
+ z3.object({
1474
+ kind: z3.literal("runner"),
1475
+ team: z3.string(),
1476
+ project: z3.string(),
1477
+ region: z3.string(),
1478
+ runtime: z3.string(),
1479
+ vcpus: z3.number().int().positive(),
1480
+ base: z3.string(),
1481
+ baseRef: z3.string(),
1482
+ sandbox: z3.string().nullable(),
1483
+ snapshot: snapshotSchema.nullable(),
1484
+ keptUntil: z3.string().nullable(),
1485
+ save: saveSchema.nullable()
1486
+ })
1487
+ ]);
1488
+ var gitSchema = z3.object({ branch: z3.string().nullable(), commit: z3.string(), dirty: z3.boolean() });
1489
+ var runRecordSchema = z3.object({
1490
+ version: z3.literal(3),
1491
+ startedAt: z3.string(),
1492
+ cwd: z3.string(),
1493
+ configFile: z3.string().nullable(),
1494
+ argv: z3.array(z3.string()).readonly(),
1495
+ // Only a `storm vitest` run has one.
1496
+ plan: planSchema.exactOptional(),
1497
+ where: whereSchema,
1498
+ git: gitSchema.nullable(),
1499
+ ended: endedSchema.exactOptional()
1500
+ });
1501
+ function runRecordText(record) {
1502
+ return JSON.stringify(record);
1503
+ }
1504
+ function parseRunRecord(text) {
1505
+ if (text === void 0) return void 0;
1506
+ let json;
1507
+ try {
1508
+ json = JSON.parse(text);
1509
+ } catch {
1510
+ return void 0;
1511
+ }
1512
+ const parsed = runRecordSchema.safeParse(json);
1513
+ return parsed.success ? parsed.data : void 0;
1514
+ }
1515
+ function testTotals(events) {
1516
+ let passed = 0;
1517
+ let failed = 0;
1518
+ let skipped = 0;
1519
+ let any = false;
1520
+ for (const event of events) {
1521
+ if (event.kind !== "test-result") continue;
1522
+ any = true;
1523
+ if (event.state === "pass") passed += 1;
1524
+ else if (event.state === "fail") failed += 1;
1525
+ else skipped += 1;
1526
+ }
1527
+ return any ? { passed, failed, skipped } : null;
1528
+ }
1529
+ function runEnd(outcome, ran, tests, reports) {
1530
+ const command = outcome.kind === "ran" ? outcome.command : void 0;
1531
+ const ranRecords = outcome.kind === "ran" ? outcome.resources : void 0;
1532
+ const ms = ran?.outcome === void 0 || ran.outcome === "stopped" || ran.endedAt === void 0 ? null : ran.endedAt - ran.startedAt;
1755
1533
  return {
1756
- startedAt: new Date(origin).toISOString(),
1757
- totalMs,
1758
- rows,
1759
- criticalPath: command === void 0 ? [] : waitedOn === void 0 ? [TESTS] : [waitedOn, TESTS]
1534
+ outcome: outcome.kind,
1535
+ exitCode: command === void 0 ? null : commandExitStatus(command),
1536
+ signal: command?.kind === "signaled" ? command.signal : null,
1537
+ ms,
1538
+ tests: testTotals(tests.events),
1539
+ testsIncomplete: tests.incomplete ?? null,
1540
+ resources: ranRecords === void 0 ? null : reports.ranFacts(ranRecords),
1541
+ resourceRows: ranRecords === void 0 ? [] : reports.ranRows(ranRecords)
1760
1542
  };
1761
1543
  }
1762
- var MINT = { name: "mint", resource: null };
1763
- var RUNNER = { name: "runner", resource: null };
1764
- var TESTS = { name: "tests", resource: null };
1765
- var CLEANUP = { name: "cleanup", resource: null };
1766
- function sameRow(a, b) {
1767
- return a.resource === null ? b.resource === null && a.name === b.name : a.resource === b.resource;
1768
- }
1769
- function laneRow(resources, key, record, span) {
1770
- const progress = resources.find((resource) => resource.name === record.definition)?.progress;
1771
- if (progress === void 0) return void 0;
1772
- const { state } = record;
1773
- const { steps, sandboxes } = progress.row(state);
1544
+ function startedWhere(run) {
1545
+ if (run.runner === void 0) return { kind: "unsandboxed" };
1546
+ const { prepared, target } = run.runner;
1774
1547
  return {
1775
- ref: { name: progress.lane, resource: key },
1776
- state,
1777
- steps: steps.map(({ name: step, span: from }) => ({ name: step, ...span(from) })),
1778
- sandboxes
1548
+ kind: "runner",
1549
+ team: target.team,
1550
+ project: target.project,
1551
+ region: prepared.recipe.region,
1552
+ runtime: prepared.recipe.runtime,
1553
+ vcpus: prepared.vcpus,
1554
+ base: prepared.base,
1555
+ baseRef: prepared.baseRef,
1556
+ sandbox: null,
1557
+ snapshot: null,
1558
+ keptUntil: null,
1559
+ save: null
1779
1560
  };
1780
1561
  }
1781
- function outcomeOf(status) {
1782
- return status === "running" || status === "pending" ? "unfinished" : status;
1562
+ function endedWhere(where, runner, save) {
1563
+ if (where.kind === "unsandboxed") return where;
1564
+ const snapshot = runner?.snapshot;
1565
+ return {
1566
+ ...where,
1567
+ sandbox: runner?.sandbox?.name ?? null,
1568
+ snapshot: snapshot === void 0 || snapshot.kind === "building" ? null : {
1569
+ id: snapshot.id,
1570
+ base: snapshot.base,
1571
+ built: snapshot.kind === "built",
1572
+ branch: snapshot.branch,
1573
+ head: snapshot.head
1574
+ },
1575
+ keptUntil: runner?.kept?.stopsAt ?? null,
1576
+ save
1577
+ };
1783
1578
  }
1784
1579
 
1785
- // src/vitest/list-output.ts
1580
+ // src/run-directory/timeline-facts.ts
1786
1581
  import { z as z4 } from "zod";
1787
- var VITEST_LIST = z4.array(z4.looseObject({ name: z4.string(), file: z4.string() }));
1788
- function readVitestList(stdout) {
1789
- let document;
1582
+ var rowRefShape = {
1583
+ /** The row's name: `mint`, a resource lane's name, `runner`, `tests` or `cleanup`. */
1584
+ name: z4.string(),
1585
+ /** For a resource instance's lane, the resource key; null for every other row. */
1586
+ resource: z4.string().nullable()
1587
+ };
1588
+ var timelineOutcomeSchema = z4.enum(["done", "failed", "stopped", "unfinished"]);
1589
+ var timelineSchema = z4.object({
1590
+ /** When the run started, as an ISO time. */
1591
+ startedAt: z4.string(),
1592
+ /** From the run's start to its last event. */
1593
+ totalMs: z4.number(),
1594
+ /**
1595
+ * The lanes in order: mint, each resource instance's lane, runner, tests, cleanup; each only when the run got that
1596
+ * far.
1597
+ */
1598
+ rows: z4.array(
1599
+ z4.object({
1600
+ ...rowRefShape,
1601
+ /** The row's label, as the waterfall named it when the run ended, such as `credential` or `runner-setup`. */
1602
+ label: z4.string(),
1603
+ startMs: z4.number(),
1604
+ endMs: z4.number(),
1605
+ outcome: timelineOutcomeSchema,
1606
+ /** The lane's steps: a resource lane's, as its presentation named them, and the runner's snapshot, start, upload, apply, install and build. */
1607
+ steps: z4.array(
1608
+ z4.object({
1609
+ name: z4.string(),
1610
+ startMs: z4.number(),
1611
+ endMs: z4.number(),
1612
+ outcome: timelineOutcomeSchema
1613
+ })
1614
+ ),
1615
+ /** How long the lane, once ready, waited for the other before the command started. */
1616
+ idleMs: z4.number(),
1617
+ /** The runner lane's: whether it reused or built its runner snapshot. */
1618
+ snapshot: z4.enum(["reused", "built"]).optional(),
1619
+ /** A resource lane's that counts them: how many of the things it holds it reused, and how many it created. */
1620
+ sandboxes: z4.object({ reused: z4.number(), created: z4.number() }).optional()
1621
+ })
1622
+ ),
1623
+ /** The lanes the command waited on, then the command, each by its row; empty when the command didn't start. */
1624
+ criticalPath: z4.array(z4.object(rowRefShape))
1625
+ });
1626
+ function timelineFacts(timeline2, laneKinds) {
1627
+ return {
1628
+ startedAt: timeline2.startedAt,
1629
+ totalMs: timeline2.totalMs,
1630
+ rows: timeline2.rows.map((row) => ({
1631
+ ...row,
1632
+ label: laneLabel(row.name, laneKinds),
1633
+ steps: row.steps.map((step) => ({ ...step }))
1634
+ })),
1635
+ criticalPath: timeline2.criticalPath.map((step) => ({ ...step }))
1636
+ };
1637
+ }
1638
+ function laneLabel(name, laneKinds) {
1639
+ if (name === "mint") return "credential";
1640
+ if (name === "runner") return "runner-setup";
1641
+ return laneKinds.find(({ lane }) => lane === name)?.label ?? name;
1642
+ }
1643
+
1644
+ // src/run-directory/reader.ts
1645
+ function pastRuns(gateway) {
1646
+ return {
1647
+ list: async (request) => {
1648
+ const listed = await gateway.list(request);
1649
+ return listed.ok ? { ok: true, runs: listed.runs.map(listedRun) } : listed;
1650
+ },
1651
+ read: async (request) => {
1652
+ const read2 = await gateway.read(request);
1653
+ return read2.kind === "found" ? { kind: "found", run: pastRun(read2.directory) } : read2;
1654
+ },
1655
+ readLog: async (request) => await gateway.readLog(request)
1656
+ };
1657
+ }
1658
+ function listedRun({ id, path, active, run }) {
1659
+ return { id, path, active, record: parseRunRecord(run) };
1660
+ }
1661
+ function pastRun(directory) {
1662
+ const parsed = (directory.tests ?? []).map(parseTestEvent);
1663
+ return {
1664
+ ...listedRun(directory),
1665
+ finished: directory.tests !== void 0,
1666
+ events: parsed.filter((event) => event !== void 0),
1667
+ unreadableTestLines: parsed.filter((event) => event === void 0).length,
1668
+ timeline: parseTimeline(directory.timeline),
1669
+ logs: directory.logs.map((log) => ({ log, path: `${directory.path}/${runLogFile(log)}` }))
1670
+ };
1671
+ }
1672
+ function parseTimeline(text) {
1673
+ if (text === void 0) return void 0;
1674
+ let json;
1790
1675
  try {
1791
- document = JSON.parse(stdout);
1676
+ json = JSON.parse(text);
1792
1677
  } catch {
1793
- throw new Error("`vitest list --json` did not print JSON");
1678
+ return void 0;
1794
1679
  }
1795
- const parsed = VITEST_LIST.safeParse(document);
1796
- if (!parsed.success) throw new Error("`vitest list --json` did not print a list of tests");
1797
- return parsed.data.map(({ name, file }) => ({ name, file }));
1680
+ const parsed = timelineSchema.safeParse(json);
1681
+ return parsed.success ? parsed.data : void 0;
1798
1682
  }
1799
1683
 
1800
- // src/vitest/live/list-gateway.ts
1801
- import { spawn as spawn2 } from "node:child_process";
1802
- import { constants as constants2 } from "node:fs";
1803
- import { access } from "node:fs/promises";
1804
- import { join as join5 } from "node:path";
1805
-
1806
- // src/vitest/find-vitest.ts
1807
- import { dirname, join as join4, relative, isAbsolute as isAbsolute2 } from "node:path";
1808
- var VITEST_BIN = join4("node_modules", ".bin", "vitest");
1809
- function vitestSearchDirectories(from, root) {
1810
- const inside = from === root || isInside(root, from);
1811
- const directories = [];
1812
- let directory = from;
1813
- for (; ; ) {
1814
- directories.push(directory);
1815
- if (inside && directory === root) return directories;
1816
- const parent = dirname(directory);
1817
- if (parent === directory) return directories;
1818
- directory = parent;
1819
- }
1684
+ // src/run-directory/live/run-directory-gateway.ts
1685
+ import { randomBytes } from "node:crypto";
1686
+ import { createReadStream, createWriteStream } from "node:fs";
1687
+ import { mkdir, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
1688
+ import { hostname as osHostname } from "node:os";
1689
+ import { join as join3 } from "node:path";
1690
+ import { z as z5 } from "zod";
1691
+ var DIRECTORY_MODE = 448;
1692
+ var FILE_MODE = 384;
1693
+ var ACTIVE_MARKER_TRUST_MS = 24 * 60 * 60 * 1e3;
1694
+ var LIST_BATCH = 32;
1695
+ function liveRunDirectoryGateway(options) {
1696
+ const holders = {
1697
+ self: options.holder ?? { pid: process.pid, hostname: osHostname() },
1698
+ isAlive: options.isAlive ?? isAlive
1699
+ };
1700
+ return {
1701
+ open: (request) => open(options.directory, holders, request),
1702
+ list: (request) => list(options.directory, holders, request.now),
1703
+ read: (request) => read(options.directory, holders, request),
1704
+ readLog: (request) => readLog(options.directory, request)
1705
+ };
1820
1706
  }
1821
- function isInside(directory, path) {
1822
- const between = relative(directory, path);
1823
- return between !== "" && !between.startsWith("..") && !isAbsolute2(between);
1707
+ function unavailableRunDirectoryGateway(location, reason) {
1708
+ const failure = () => ({ path: location, message: reason });
1709
+ return {
1710
+ open: async () => ({ ok: false, failure: failure() }),
1711
+ list: async () => ({ ok: false, failure: failure() }),
1712
+ read: async () => ({ kind: "failed", failure: failure() }),
1713
+ readLog: async () => ({ kind: "failed", failure: failure() })
1714
+ };
1824
1715
  }
1825
-
1826
- // src/vitest/live/list-gateway.ts
1827
- var liveVitestListGateway = {
1828
- async findVitest({ from, root }) {
1829
- const searched = vitestSearchDirectories(from, root);
1830
- for (const directory of searched) {
1831
- const path = join5(directory, VITEST_BIN);
1832
- try {
1833
- await access(path, constants2.X_OK);
1834
- return { ok: true, path };
1835
- } catch {
1836
- }
1716
+ var markerSchema = z5.object({
1717
+ pid: z5.number().int().positive(),
1718
+ hostname: z5.string().min(1),
1719
+ startedAt: z5.iso.datetime()
1720
+ });
1721
+ async function open(root, holders, request) {
1722
+ const id = `${runIdPrefix(request.startedAt)}-${randomBytes(2).toString("hex")}`;
1723
+ const path = join3(root, id);
1724
+ const opening = join3(root, `.opening-${id}-${randomBytes(4).toString("hex")}`);
1725
+ try {
1726
+ await mkdir(root, { recursive: true, mode: DIRECTORY_MODE });
1727
+ await mkdir(opening, { mode: DIRECTORY_MODE });
1728
+ const marker = { ...holders.self, startedAt: request.startedAt.toISOString() };
1729
+ await writeFile(join3(opening, ACTIVE_MARKER), `${JSON.stringify(marker)}
1730
+ `, { mode: FILE_MODE, flag: "wx" });
1731
+ await writeFile(join3(opening, RUN_FILE), `${request.run}
1732
+ `, { mode: FILE_MODE, flag: "wx" });
1733
+ await rename(opening, path);
1734
+ } catch (error) {
1735
+ await rm(opening, { recursive: true, force: true }).catch(() => void 0);
1736
+ return { ok: false, failure: { path, message: messageOf(error) } };
1737
+ }
1738
+ return {
1739
+ ok: true,
1740
+ directory: runDirectory(path, id),
1741
+ pruneFailures: await prune(root, request.keep, holders, request.startedAt)
1742
+ };
1743
+ }
1744
+ async function prune(root, keep, holders, now) {
1745
+ let names;
1746
+ try {
1747
+ names = (await readdir(root)).filter((name) => RUN_ID_PATTERN.test(name));
1748
+ } catch (error) {
1749
+ return [{ path: root, message: messageOf(error) }];
1750
+ }
1751
+ const completed = [];
1752
+ for (const name of names) if (!await isActive(join3(root, name), holders, now)) completed.push(name);
1753
+ const failures = [];
1754
+ const newestFirst = completed.toSorted().toReversed();
1755
+ for (const name of newestFirst.slice(keep)) {
1756
+ const path = join3(root, name);
1757
+ try {
1758
+ await rm(path, { recursive: true, force: true });
1759
+ } catch (error) {
1760
+ failures.push({ path, message: messageOf(error) });
1837
1761
  }
1838
- return { ok: false, searched };
1839
- },
1840
- listTests(request) {
1841
- return new Promise((resolve) => {
1842
- let settled = false;
1843
- const settle = (result) => {
1844
- if (settled) return;
1845
- settled = true;
1846
- resolve(result);
1847
- };
1848
- const timeout = AbortSignal.timeout(request.timeoutMs);
1849
- const child = spawn2(request.executable ?? "vitest", listArgv(request.args), {
1850
- ...request.cwd === void 0 ? {} : { cwd: request.cwd },
1851
- stdio: ["ignore", "pipe", "pipe"],
1852
- signal: request.signal === void 0 ? timeout : AbortSignal.any([timeout, request.signal])
1853
- });
1854
- let stopped;
1855
- let stdout = "";
1856
- let stderr = "";
1857
- child.stdout.setEncoding("utf8").on("data", (chunk) => {
1858
- stdout += chunk;
1859
- });
1860
- child.stderr.setEncoding("utf8").on("data", (chunk) => {
1861
- stderr += chunk;
1862
- });
1863
- child.on("error", (error) => {
1864
- if (error.name !== "AbortError") {
1865
- settle({ ok: false, failure: { kind: "start-failed", message: error.message } });
1866
- return;
1867
- }
1868
- stopped = request.signal?.aborted === true ? { kind: "canceled" } : { kind: "timed-out", timeoutMs: request.timeoutMs };
1869
- if (child.exitCode !== null || child.signalCode !== null) settle({ ok: false, failure: stopped });
1870
- });
1871
- child.on("exit", () => {
1872
- if (stopped !== void 0) settle({ ok: false, failure: stopped });
1873
- });
1874
- child.on("close", (exitCode, signal) => {
1875
- if (stopped !== void 0) {
1876
- settle({ ok: false, failure: stopped });
1877
- return;
1878
- }
1879
- if (exitCode !== 0) {
1880
- settle({ ok: false, failure: { kind: "exited", exitCode, signal, lastStderrLine: lastLine(stderr) } });
1881
- return;
1882
- }
1762
+ }
1763
+ const kept = newestFirst.slice(0, keep);
1764
+ const leftovers = kept.flatMap(
1765
+ (name) => [TEST_EVENTS_STAGING_FILE, TESTS_PARTIAL_FILE].map((file) => join3(root, name, file))
1766
+ );
1767
+ for (let start = 0; start < leftovers.length; start += LIST_BATCH) {
1768
+ const removed = await Promise.all(
1769
+ leftovers.slice(start, start + LIST_BATCH).map(async (file) => {
1883
1770
  try {
1884
- settle({ ok: true, tests: readVitestList(stdout) });
1771
+ await rm(file, { force: true });
1772
+ return [];
1885
1773
  } catch (error) {
1886
- settle({ ok: false, failure: { kind: "unreadable-output", message: error.message } });
1774
+ return [{ path: file, message: messageOf(error) }];
1887
1775
  }
1888
- });
1889
- });
1776
+ })
1777
+ );
1778
+ failures.push(...removed.flat());
1890
1779
  }
1891
- };
1892
- function lastLine(text) {
1893
- return text.split(/\r?\n/).map((line) => line.trim()).findLast((line) => line !== "" && !/^at\s/.test(line)) ?? "";
1894
- }
1895
- function listArgv(args) {
1896
- const end = args.indexOf("--");
1897
- return end === -1 ? ["list", ...args, "--json"] : ["list", ...args.slice(0, end), "--json", ...args.slice(end)];
1780
+ return failures;
1898
1781
  }
1899
-
1900
- // src/vitest/plan.ts
1901
- var LIST_TIMEOUT_MS = 6e4;
1902
- async function planVitestRun(options, gateway = liveVitestListGateway) {
1903
- const timeoutMs = options.timeoutMs ?? LIST_TIMEOUT_MS;
1904
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
1905
- throw new TypeError(`planVitestRun: timeoutMs is ${String(timeoutMs)}, not a positive number`);
1782
+ async function list(root, holders, now) {
1783
+ let names;
1784
+ try {
1785
+ names = (await readdir(root)).filter((name) => RUN_ID_PATTERN.test(name));
1786
+ } catch (error) {
1787
+ if (errorCode(error) === "ENOENT") return { ok: true, runs: [] };
1788
+ return { ok: false, failure: { path: root, message: messageOf(error) } };
1906
1789
  }
1907
- const listed = await gateway.listTests({
1908
- args: options.args,
1909
- ...options.cwd === void 0 ? {} : { cwd: options.cwd },
1910
- ...options.executable === void 0 ? {} : { executable: options.executable },
1911
- timeoutMs,
1912
- ...options.signal === void 0 ? {} : { signal: options.signal }
1913
- });
1914
- return listed.ok ? { ok: true, plan: planOf(listed.tests) } : { ok: false, failure: listed.failure };
1915
- }
1916
- function vitestRunArgv(executable, args) {
1917
- return [executable, "run", ...args];
1918
- }
1919
- function formatPlan(plan) {
1920
- return `${plan.tests} ${plan.tests === 1 ? "test" : "tests"} in ${plan.files} ${plan.files === 1 ? "file" : "files"}`;
1921
- }
1922
- function planOf(tests) {
1923
- return { tests: tests.length, files: new Set(tests.map((test) => test.file)).size };
1924
- }
1925
- function describeVitestListFailure(failure) {
1926
- switch (failure.kind) {
1927
- case "start-failed":
1928
- return `\`vitest list\` failed to start: ${failure.message}`;
1929
- case "timed-out":
1930
- return `\`vitest list\` did not finish in ${failure.timeoutMs / 1e3}s`;
1931
- case "exited": {
1932
- const how = failure.exitCode === null ? `was ended by ${failure.signal ?? "a signal"}` : `exited ${failure.exitCode}`;
1933
- return `\`vitest list\` ${how}${failure.lastStderrLine === "" ? "" : `: ${failure.lastStderrLine}`}`;
1934
- }
1935
- case "unreadable-output":
1936
- return failure.message;
1937
- case "canceled":
1938
- return "`vitest list` was canceled";
1790
+ const ordered = names.toSorted().toReversed();
1791
+ const runs = [];
1792
+ for (let start = 0; start < ordered.length; start += LIST_BATCH) {
1793
+ runs.push(
1794
+ ...await Promise.all(
1795
+ ordered.slice(start, start + LIST_BATCH).map(async (id) => {
1796
+ const path = join3(root, id);
1797
+ const run = await readOptional(join3(path, RUN_FILE));
1798
+ return {
1799
+ id,
1800
+ path,
1801
+ active: await isActive(path, holders, now),
1802
+ run: run.kind === "found" ? run.text : void 0
1803
+ };
1804
+ })
1805
+ )
1806
+ );
1939
1807
  }
1808
+ return { ok: true, runs };
1940
1809
  }
1941
-
1942
- // src/commands/exec/cleanup.ts
1943
- import { z as z5 } from "zod";
1944
-
1945
- // src/commands/dashboard.ts
1946
- function projectPage({ team, project }) {
1947
- return `https://vercel.com/${encodeURIComponent(team)}/${encodeURIComponent(project)}`;
1948
- }
1949
- function sandboxPage(where, name) {
1950
- return `${projectPage(where)}/sandboxes/${encodeURIComponent(name)}`;
1951
- }
1952
- function sandboxConnectPage(where, name) {
1953
- return `${sandboxPage(where, name)}/connect`;
1954
- }
1955
- function snapshotPage(where, id) {
1956
- return `${projectPage(where)}/sandboxes/snapshots/${encodeURIComponent(id)}`;
1957
- }
1958
-
1959
- // src/commands/exec/text.ts
1960
- function seconds2(ms) {
1961
- return secondsText(secondsOf(ms));
1962
- }
1963
- function keepTimeText(ms) {
1964
- const minutes = Math.round(ms / 6e4);
1965
- return minutes >= 60 && minutes % 60 === 0 ? `${minutes / 60}h` : `${minutes}m`;
1966
- }
1967
- function releaseText(resources, done) {
1968
- return resources.length === 0 ? void 0 : `${done ? "released" : "releasing"} ${resources.join(", ")}`;
1969
- }
1970
- function isoSecondsText(iso) {
1971
- return iso.replace(/\.\d+Z$/, "Z");
1972
- }
1973
- function short(sha) {
1974
- return sha.slice(0, 12);
1810
+ async function read(root, holders, request) {
1811
+ if (!RUN_ID_PATTERN.test(request.id)) return { kind: "not-found" };
1812
+ const path = join3(root, request.id);
1813
+ try {
1814
+ if (!(await stat(path)).isDirectory()) return { kind: "not-found" };
1815
+ } catch (error) {
1816
+ if (errorCode(error) === "ENOENT") return { kind: "not-found" };
1817
+ return { kind: "failed", failure: { path, message: messageOf(error) } };
1818
+ }
1819
+ const [run, tests, timeline2] = await Promise.all(
1820
+ [RUN_FILE, TESTS_FILE, TIMELINE_FILE].map((name) => readOptional(join3(path, name)))
1821
+ );
1822
+ for (const file of [run, tests, timeline2])
1823
+ if (file?.kind === "failed") return { kind: "failed", failure: file.failure };
1824
+ const text = (file) => file?.kind === "found" ? file.text : void 0;
1825
+ const testsText = text(tests);
1826
+ const held = await Promise.all(RUN_LOGS.map(async (log) => await exists(join3(path, runLogFile(log))) ? log : []));
1827
+ return {
1828
+ kind: "found",
1829
+ directory: {
1830
+ id: request.id,
1831
+ path,
1832
+ active: await isActive(path, holders, request.now),
1833
+ run: text(run),
1834
+ tests: testsText === void 0 ? void 0 : testsText.split("\n").filter((line) => line !== ""),
1835
+ timeline: text(timeline2),
1836
+ logs: held.flat()
1837
+ }
1838
+ };
1975
1839
  }
1976
- function shortFile(file) {
1977
- const parts = file.split("/").filter((part) => part !== "");
1978
- return parts.slice(-2).join("/").replace(/\.(test|spec)\.[cm]?[jt]sx?$/, "").replace(/\.[cm]?[jt]sx?$/, "");
1840
+ async function exists(file) {
1841
+ try {
1842
+ await stat(file);
1843
+ return true;
1844
+ } catch {
1845
+ return false;
1846
+ }
1979
1847
  }
1980
- function median(values) {
1981
- const sorted = [...values].toSorted((a, b) => a - b);
1982
- if (sorted.length === 0) return void 0;
1983
- const middle = Math.floor(sorted.length / 2);
1984
- return sorted.length % 2 === 1 ? sorted[middle] : ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;
1848
+ async function readLog(root, request) {
1849
+ if (!RUN_ID_PATTERN.test(request.id)) return { kind: "not-found" };
1850
+ const file = join3(root, request.id, runLogFile(request.log));
1851
+ try {
1852
+ return { kind: "found", path: file, text: completeUtf8(await readFile(file)).toString("utf8") };
1853
+ } catch (error) {
1854
+ if (errorCode(error) === "ENOENT") return { kind: "not-found" };
1855
+ return { kind: "failed", failure: { path: file, message: messageOf(error) } };
1856
+ }
1985
1857
  }
1986
- var code = (open2, close) => (text) => text === "" ? text : `\x1B[${open2}m${text}\x1B[${close}m`;
1987
- function paint(color) {
1988
- if (!color) {
1989
- const none = (text) => text;
1990
- return { done: none, failed: none, stopped: none, active: none, faint: none, strong: none };
1858
+ function completeUtf8(bytes) {
1859
+ for (let back = 1; back <= Math.min(3, bytes.length); back += 1) {
1860
+ const byte = bytes[bytes.length - back] ?? 0;
1861
+ if ((byte & 192) === 128) continue;
1862
+ const needs = byte >= 240 ? 4 : byte >= 224 ? 3 : byte >= 192 ? 2 : 1;
1863
+ return needs > back ? bytes.subarray(0, bytes.length - back) : bytes;
1991
1864
  }
1992
- return {
1993
- done: code(32, 39),
1994
- failed: code(31, 39),
1995
- stopped: code(33, 39),
1996
- active: code(36, 39),
1997
- faint: code(2, 22),
1998
- strong: code(1, 22)
1999
- };
2000
- }
2001
- var COLOR_CODE = /\u001b\[[0-9;]*m/g;
2002
- function visibleLength(text) {
2003
- return Array.from(text.replace(COLOR_CODE, "")).length;
2004
- }
2005
- function truncate(text, width) {
2006
- if (visibleLength(text) <= width) return text;
2007
- const plain = Array.from(text.replace(COLOR_CODE, ""));
2008
- return width <= 0 ? "" : `${plain.slice(0, width - 1).join("")}\u2026`;
2009
- }
2010
- function spread(left, right, width) {
2011
- if (right === "") return truncate(left, width);
2012
- const room = width - visibleLength(right) - 1;
2013
- const fitted = truncate(left, Math.max(0, room));
2014
- return `${fitted}${" ".repeat(Math.max(1, width - visibleLength(fitted) - visibleLength(right)))}${right}`;
1865
+ return bytes;
2015
1866
  }
2016
-
2017
- // src/commands/exec/cleanup.ts
2018
- var notStoppedSchema = z5.object({
2019
- name: z5.string(),
2020
- role: z5.enum(["runner", "snapshot-build"]),
2021
- /** The sandbox's own timeout, in minutes, within which it stops. */
2022
- timeoutMinutes: z5.number(),
2023
- message: z5.string()
2024
- });
2025
- var notDeletedSchema = z5.object({
2026
- name: z5.string(),
2027
- role: z5.enum(["runner", "snapshot-build"]),
2028
- message: z5.string()
2029
- });
2030
- var keptSchema = z5.object({
2031
- name: z5.string(),
2032
- /** When its timeout stops it, as an ISO time: the keep time from when the run ended, or later. */
2033
- stopsAt: z5.string(),
2034
- /** Its Connect page in the Vercel dashboard, which says how to open a shell in it. */
2035
- url: z5.string()
2036
- });
2037
- var notKeptSchema = z5.object({ name: z5.string(), message: z5.string() });
2038
- var runnerCleanupSchema = z5.object({
2039
- kept: keptSchema.nullable(),
2040
- notKept: notKeptSchema.nullable(),
2041
- notStopped: z5.array(notStoppedSchema),
2042
- notDeleted: z5.array(notDeletedSchema)
2043
- });
2044
- function sandboxRole(role) {
2045
- return role === "runner" ? "runner sandbox" : "build sandbox";
2046
- }
2047
- function notStoppedText(sandbox) {
2048
- return `Couldn't stop the ${sandboxRole(sandbox.role)} ${sandbox.name}: ${sandbox.message}. Its own timeout stops it within ${sandbox.timeoutMinutes} minutes.`;
2049
- }
2050
- function notDeletedText(sandbox) {
2051
- return `Stopped the ${sandboxRole(sandbox.role)} ${sandbox.name}, but couldn't delete it: ${sandbox.message}. It stays listed in the Vercel project.`;
2052
- }
2053
- function keptText(kept) {
2054
- return `Kept the runner sandbox ${kept.name} running until ${isoSecondsText(kept.stopsAt)}, so you can connect to it: ${kept.url}`;
2055
- }
2056
- function notKeptText(sandbox) {
2057
- return `Couldn't keep the runner sandbox ${sandbox.name} running: ${sandbox.message}. Stopped and deleted it instead.`;
2058
- }
2059
- function runnerCleanupRows(cleanup) {
2060
- if (cleanup === null) return [];
2061
- const { kept, notKept } = cleanup;
2062
- return [
2063
- ...kept === null ? [] : [["Sandbox kept", [`${kept.name}, running until ${isoSecondsText(kept.stopsAt)}`, kept.url]]],
2064
- ...notKept === null ? [] : [["Sandbox not kept", notKeptText(notKept)]],
2065
- ...cleanup.notStopped.length === 0 ? [] : [["Sandboxes not stopped", cleanup.notStopped.map(notStoppedText)]],
2066
- ...cleanup.notDeleted.length === 0 ? [] : [["Sandboxes not deleted", cleanup.notDeleted.map(notDeletedText)]]
2067
- ];
2068
- }
2069
- function runnerCleanupWarnings(cleanup) {
2070
- if (cleanup === null) return [];
2071
- return [
2072
- ...cleanup.notKept === null ? [] : [{ reason: "runner_sandbox_not_kept", message: notKeptText(cleanup.notKept) }],
2073
- ...cleanup.notStopped.map((sandbox) => ({
2074
- reason: "runner_sandbox_not_stopped",
2075
- message: notStoppedText(sandbox)
2076
- })),
2077
- ...cleanup.notDeleted.map((sandbox) => ({
2078
- reason: "runner_sandbox_not_deleted",
2079
- message: notDeletedText(sandbox)
2080
- }))
2081
- ];
2082
- }
2083
- function runCleanupOf(reports) {
2084
- const schema = z5.object({ runner: runnerCleanupSchema.nullable(), resources: reports.cleanupSchema });
2085
- const rows = (cleanup) => [
2086
- ...runnerCleanupRows(cleanup.runner),
2087
- ...reports.cleanupRows(cleanup.resources)
2088
- ];
2089
- return {
2090
- schema,
2091
- facts: ({ runnerCleanup, resourceCleanup }) => ({
2092
- runner: runnerCleanupOf(runnerCleanup),
2093
- resources: reports.cleanupFacts(resourceCleanup)
2094
- }),
2095
- rows
2096
- };
1867
+ async function readOptional(file) {
1868
+ try {
1869
+ return { kind: "found", text: await readFile(file, "utf8") };
1870
+ } catch (error) {
1871
+ if (errorCode(error) === "ENOENT") return { kind: "missing" };
1872
+ return { kind: "failed", failure: { path: file, message: messageOf(error) } };
1873
+ }
2097
1874
  }
2098
- function runnerCleanupOf(report) {
2099
- if (report === null) return null;
2100
- const { kept, target } = report;
2101
- return {
2102
- kept: kept === null ? null : { name: kept.name, stopsAt: kept.stopsAt, url: sandboxConnectPage(target, kept.name) },
2103
- notKept: report.notKept === null ? null : { ...report.notKept },
2104
- notStopped: report.notStopped.map(({ name, role, timeoutMinutes, message }) => ({
2105
- name,
2106
- role,
2107
- timeoutMinutes,
2108
- message
2109
- })),
2110
- notDeleted: report.notDeleted.map(({ name, role, message }) => ({ name, role, message }))
2111
- };
1875
+ async function isActive(path, holders, now) {
1876
+ const file = join3(path, ACTIVE_MARKER);
1877
+ let text;
1878
+ try {
1879
+ text = await readFile(file, "utf8");
1880
+ } catch (error) {
1881
+ if (errorCode(error) === "ENOENT") return false;
1882
+ return trustedSince(file, now);
1883
+ }
1884
+ const parsed = markerSchema.safeParse(parseJson(text));
1885
+ if (!parsed.success) return trustedSince(file, now);
1886
+ const { pid, hostname, startedAt } = parsed.data;
1887
+ if (hostname === holders.self.hostname) return holders.isAlive(pid);
1888
+ return now.getTime() - Date.parse(startedAt) < ACTIVE_MARKER_TRUST_MS;
2112
1889
  }
2113
-
2114
- // src/extensions/github/release.ts
2115
- function fixtureRepoCleanupFailureText(cleanup, failure) {
2116
- return failure.branch === null ? `Couldn't list the branches under ${cleanup.runPrefix}/ in ${cleanup.repo}: ${failure.message}. Any there are left behind.` : `Couldn't delete branch ${failure.branch} in ${cleanup.repo}: ${failure.message}. It is left behind.`;
1890
+ async function trustedSince(file, now) {
1891
+ try {
1892
+ return now.getTime() - (await stat(file)).mtime.getTime() < ACTIVE_MARKER_TRUST_MS;
1893
+ } catch {
1894
+ return false;
1895
+ }
2117
1896
  }
2118
- function fixtureRepoCleanedText(nameWithOwner, cleaned) {
2119
- const { runPrefix, deleted } = cleaned;
2120
- const branches = deleted.length === 1 ? "1 branch" : `${deleted.length} branches`;
2121
- return `deleted ${branches} under ${runPrefix}/ in ${nameWithOwner}`;
1897
+ function parseJson(text) {
1898
+ try {
1899
+ return JSON.parse(text);
1900
+ } catch {
1901
+ return void 0;
1902
+ }
2122
1903
  }
2123
- function fixtureRepoCleanupWarnings(cleaned) {
2124
- return cleaned.failures.map((failure) => ({
2125
- reason: failure.branch === null ? "github_branches_not_listed" : "github_branch_not_deleted",
2126
- message: fixtureRepoCleanupFailureText(cleaned, failure)
2127
- }));
1904
+ function isAlive(pid) {
1905
+ try {
1906
+ process.kill(pid, 0);
1907
+ return true;
1908
+ } catch (error) {
1909
+ return errorCode(error) !== "ESRCH";
1910
+ }
2128
1911
  }
2129
- function githubFixtureRepoReleased(cleaned) {
2130
- const { repo, runPrefix, failures } = cleaned;
2131
- return { done: failures.length === 0 ? [`Every branch under ${runPrefix}/ in ${repo} is deleted.`] : [] };
1912
+ function errorCode(error) {
1913
+ return error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : void 0;
2132
1914
  }
2133
-
2134
- // src/extensions/github/refusals.ts
2135
- function githubTokenMissing(data) {
2136
- const { tokenEnv, repo, requiredBy } = data;
2137
- return {
2138
- refused: "github_token_missing",
2139
- data: { ...data },
2140
- message: `${tokenEnv} is not set: resources.githubFixtureRepo needs a token for ${repo} from it. The run didn't start.`,
2141
- next: [
2142
- {
2143
- type: "text",
2144
- text: requiredBy === "flag" ? `Set ${tokenEnv} to a token limited to ${repo}: --github-optional=false makes the repository required for this run.` : `Set ${tokenEnv} to a token limited to ${repo}, or let runs go on without the repository with githubFixtureRepo({ \u2026, optional: true }) or --github-optional.`
1915
+ function runDirectory(path, id) {
1916
+ const streams = /* @__PURE__ */ new Map();
1917
+ let failure;
1918
+ let closed = false;
1919
+ let testsPublished = false;
1920
+ let changing = Promise.resolve();
1921
+ const inTurn = (file, change) => {
1922
+ if (failure !== void 0 || closed) return;
1923
+ changing = changing.then(async () => {
1924
+ if (failure !== void 0) return;
1925
+ try {
1926
+ await change();
1927
+ } catch (error) {
1928
+ failure ??= { path: file, message: messageOf(error) };
2145
1929
  }
2146
- ]
1930
+ });
2147
1931
  };
2148
- }
2149
- function githubFixtureRepoUnavailable(data) {
2150
- const { repo, status, message } = data;
2151
- return {
2152
- refused: "github_fixture_repo_unavailable",
2153
- data: { ...data },
2154
- message: `Couldn't read the GitHub fixture repository ${repo}: ${status === null ? message : `HTTP ${status}: ${message}`}. The command didn't run.`,
2155
- next: [
2156
- {
2157
- type: "text",
2158
- text: `Check that the token in resources.githubFixtureRepo's tokenEnv can read ${repo}, then retry.`
1932
+ const replace = (name, text) => {
1933
+ const file = join3(path, name);
1934
+ inTurn(file, async () => {
1935
+ const temporary = join3(path, `.${name}.${randomBytes(4).toString("hex")}.tmp`);
1936
+ try {
1937
+ await writeFile(temporary, text, { mode: FILE_MODE, flag: "wx" });
1938
+ await rename(temporary, file);
1939
+ } catch (error) {
1940
+ await rm(temporary, { force: true }).catch(() => void 0);
1941
+ throw error;
2159
1942
  }
2160
- ]
1943
+ });
2161
1944
  };
2162
- }
2163
-
2164
- // src/extensions/github/fixture-repo.ts
2165
- var FIXTURE_RUN_PREFIX_ROOT = "run/";
2166
- function fixtureRunPrefix(startedAt, suffix) {
2167
- const stamp = startedAt.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
2168
- return `${FIXTURE_RUN_PREFIX_ROOT}${stamp}-${suffix}`;
2169
- }
2170
- function fixtureRepoPayload(opened) {
2171
- return { url: opened.url, nameWithOwner: opened.nameWithOwner, token: opened.token, runPrefix: opened.runPrefix };
2172
- }
2173
- async function openFixtureRepo(context, request, prefix) {
2174
- const read2 = await context.githubFixtureRepos.readRepo(request);
2175
- if (!read2.ok) return { kind: "unavailable", repo: request.repo, failure: read2.failure };
2176
- return {
2177
- kind: "opened",
2178
- repo: {
2179
- repo: request.repo,
2180
- nameWithOwner: read2.repo.nameWithOwner,
2181
- url: read2.repo.cloneUrl,
2182
- token: request.token,
2183
- runPrefix: fixtureRunPrefix(prefix.startedAt, prefix.suffix)
1945
+ const stream = (name) => {
1946
+ if (failure !== void 0 || closed) return void 0;
1947
+ let opened = streams.get(name);
1948
+ if (opened === void 0) {
1949
+ const file = join3(path, name);
1950
+ opened = createWriteStream(file, { flags: "a", mode: FILE_MODE });
1951
+ opened.on("error", (error) => {
1952
+ failure ??= { path: file, message: messageOf(error) };
1953
+ });
1954
+ streams.set(name, opened);
2184
1955
  }
1956
+ return opened;
2185
1957
  };
2186
- }
2187
- async function cleanupFixtureRepo(context, opened) {
2188
- const { repo, token, runPrefix } = opened;
2189
- const listed = await context.githubFixtureRepos.listBranches({ repo, token, prefix: `${runPrefix}/` });
2190
- if (!listed.ok)
2191
- return { repo, runPrefix, deleted: [], failures: [{ branch: null, message: failureText(listed.failure) }] };
2192
- const deleted = [];
2193
- const failures = [];
2194
- for (const branch of listed.branches) {
2195
- const removed = await context.githubFixtureRepos.deleteBranch({ repo, token, branch });
2196
- if (removed.ok) deleted.push(branch);
2197
- else failures.push({ branch, message: failureText(removed.failure) });
2198
- }
2199
- return { repo, runPrefix, deleted, failures };
2200
- }
2201
- function failureText(failure) {
2202
- return failure.status === null ? failure.message : `HTTP ${failure.status}: ${failure.message}`;
2203
- }
2204
-
2205
- // src/extensions/github/lifecycle.ts
2206
- function tokenIn(world, tokenEnv) {
2207
- const token = world.env[tokenEnv];
2208
- return token === void 0 || token === "" ? void 0 : token;
2209
- }
2210
- function githubFixtureRepoLifecycle(world) {
2211
- return {
2212
- // No I/O: the token, when the launcher has it, for a refusal that comes before `beforeRun`.
2213
- secrets: ({ options }) => {
2214
- const token = tokenIn(world, options.tokenEnv);
2215
- return token === void 0 ? [] : [token];
2216
- },
2217
- beforeRun: async ({
2218
- options,
2219
- sources
2220
- }) => {
2221
- const { repo, tokenEnv, optional } = options;
2222
- const token = tokenIn(world, tokenEnv);
2223
- if (token !== void 0)
2224
- return { use: { secrets: { token }, needsVercelCredential: false, hiddenVariables: [] } };
2225
- if (optional)
2226
- return {
2227
- skip: `${tokenEnv} is unset and resources.githubFixtureRepo is optional, so the run goes on without ${repo}`
2228
- };
2229
- return githubTokenMissing({ tokenEnv, repo, requiredBy: sources.optional === "flag" ? "flag" : "config" });
2230
- },
2231
- acquireForRun: async ({
2232
- options,
2233
- secrets,
2234
- take,
2235
- report
2236
- }) => {
2237
- const opened = await openFixtureRepo(
2238
- world,
2239
- { repo: options.repo, token: secrets.token },
2240
- { startedAt: world.clock.now(), suffix: world.randomSuffix() }
2241
- );
2242
- if (opened.kind === "unavailable")
2243
- return githubFixtureRepoUnavailable({
2244
- repo: opened.repo,
2245
- status: opened.failure.status,
2246
- message: opened.failure.message
2247
- });
2248
- take(opened.repo);
2249
- const { nameWithOwner, runPrefix } = opened.repo;
2250
- await report.run(`GitHub fixture repository ${nameWithOwner}, the run's branches under ${runPrefix}/`);
2251
- return { acquired: { payload: fixtureRepoPayload(opened.repo) } };
2252
- },
2253
- releaseAfterRun: async ({
2254
- taken: [repo],
2255
- report
2256
- }) => {
2257
- if (repo === void 0) return { nothingTaken: true };
2258
- const cleaned = await cleanupFixtureRepo(world, repo);
2259
- await report.cleanup(fixtureRepoCleanedText(repo.nameWithOwner, cleaned));
2260
- for (const { reason, message } of fixtureRepoCleanupWarnings(cleaned)) await report.warning(reason, message);
2261
- return githubFixtureRepoReleased(cleaned);
2262
- }
1958
+ const append = (name, text) => void stream(name)?.write(text);
1959
+ const endStream = async (name) => {
1960
+ const opened = streams.get(name);
1961
+ if (opened === void 0) return;
1962
+ streams.delete(name);
1963
+ await ended(opened);
2263
1964
  };
2264
- }
2265
-
2266
- // src/extensions/github/live/world.ts
2267
- import { randomBytes as randomBytes2 } from "node:crypto";
2268
-
2269
- // src/extensions/github/live/fixture-repo-gateway.ts
2270
- import { z as z6 } from "zod";
2271
- var repoSchema = z6.object({ full_name: z6.string().min(1), clone_url: z6.string().min(1) });
2272
- var refsSchema = z6.array(z6.object({ ref: z6.string() }));
2273
- var errorSchema = z6.object({ message: z6.string() });
2274
- function liveGitHubFixtureRepoGateway(options) {
2275
1965
  return {
2276
- readRepo: async ({ repo, token }) => {
2277
- const answered = await call(options, token, "GET", `repos/${repoPath(repo)}`);
2278
- if (!answered.ok) return answered;
2279
- const parsed = repoSchema.safeParse(answered.body);
2280
- if (!parsed.success) return { ok: false, failure: { status: answered.status, message: "unexpected answer" } };
2281
- return { ok: true, repo: { nameWithOwner: parsed.data.full_name, cloneUrl: parsed.data.clone_url } };
1966
+ path,
1967
+ id,
1968
+ writeRun: (text) => replace(RUN_FILE, `${text}
1969
+ `),
1970
+ appendEvent: (line) => append(EVENTS_FILE, `${line}
1971
+ `),
1972
+ appendStepOutput: (step, line) => append(runLogFile(step), `${line}
1973
+ `),
1974
+ appendCommandOutput: (text) => append(COMMAND_LOG, text),
1975
+ appendTestEvent: (line) => {
1976
+ if (!testsPublished) append(TESTS_PARTIAL_FILE, `${line}
1977
+ `);
2282
1978
  },
2283
- listBranches: async ({ repo, token, prefix }) => {
2284
- const answered = await call(
2285
- options,
2286
- token,
2287
- "GET",
2288
- `repos/${repoPath(repo)}/git/matching-refs/heads/${refPath(prefix)}`
2289
- );
2290
- if (!answered.ok) return answered;
2291
- const parsed = refsSchema.safeParse(answered.body);
2292
- if (!parsed.success) return { ok: false, failure: { status: answered.status, message: "unexpected answer" } };
2293
- const branches = parsed.data.map(({ ref }) => ref).filter((ref) => ref.startsWith("refs/heads/")).map((ref) => ref.slice("refs/heads/".length)).filter((branch) => branch.startsWith(prefix));
2294
- return { ok: true, branches };
1979
+ publishTestEvents: () => {
1980
+ if (testsPublished) return;
1981
+ testsPublished = true;
1982
+ const partial = join3(path, TESTS_PARTIAL_FILE);
1983
+ inTurn(join3(path, TESTS_FILE), async () => {
1984
+ await endStream(TESTS_PARTIAL_FILE);
1985
+ if (failure !== void 0) return;
1986
+ await writeFile(partial, "", { mode: FILE_MODE, flag: "a" });
1987
+ await rename(partial, join3(path, TESTS_FILE));
1988
+ });
2295
1989
  },
2296
- deleteBranch: async ({ repo, token, branch }) => {
2297
- const answered = await call(
2298
- options,
2299
- token,
2300
- "DELETE",
2301
- `repos/${repoPath(repo)}/git/refs/heads/${refPath(branch)}`
2302
- );
2303
- return answered.ok ? { ok: true } : answered;
1990
+ writeTimeline: (text) => replace(TIMELINE_FILE, `${text}
1991
+ `),
1992
+ readTestEvents: (onLine) => readStagedTestEvents(join3(path, TEST_EVENTS_STAGING_FILE), onLine),
1993
+ close: async () => {
1994
+ closed = true;
1995
+ await changing;
1996
+ await Promise.all([...streams.values()].map(ended));
1997
+ streams.clear();
1998
+ for (const name of [TEST_EVENTS_STAGING_FILE, TESTS_PARTIAL_FILE]) {
1999
+ const file = join3(path, name);
2000
+ try {
2001
+ await rm(file, { force: true });
2002
+ } catch (error) {
2003
+ failure ??= { path: file, message: messageOf(error) };
2004
+ }
2005
+ }
2006
+ const marker = join3(path, ACTIVE_MARKER);
2007
+ try {
2008
+ await unlink(marker);
2009
+ } catch (error) {
2010
+ failure ??= { path: marker, message: messageOf(error) };
2011
+ }
2012
+ return failure;
2304
2013
  }
2305
2014
  };
2306
2015
  }
2307
- function repoPath(repo) {
2308
- return repo.split("/").map(encodeURIComponent).join("/");
2309
- }
2310
- function refPath(ref) {
2311
- return ref.split("/").map(encodeURIComponent).join("/");
2016
+ function ended(stream) {
2017
+ return new Promise((resolve) => {
2018
+ if (stream.closed || stream.destroyed) resolve();
2019
+ else {
2020
+ stream.once("close", () => resolve());
2021
+ stream.end();
2022
+ }
2023
+ });
2312
2024
  }
2313
- async function call(options, token, method, path) {
2314
- const signal = AbortSignal.timeout(options.timeoutMs);
2315
- const hide = (text) => token === "" ? text : text.replaceAll(token, "<token>");
2025
+ async function readStagedTestEvents(file, onLine) {
2026
+ let pending = "";
2316
2027
  try {
2317
- const response = await fetch(`${options.origin}/${path}`, {
2318
- method,
2319
- headers: {
2320
- accept: "application/vnd.github+json",
2321
- authorization: `Bearer ${token}`,
2322
- "x-github-api-version": "2022-11-28",
2323
- "user-agent": "storm"
2324
- },
2325
- redirect: "manual",
2326
- signal
2327
- });
2328
- const text = await response.text();
2329
- if (response.status < 200 || response.status >= 300) {
2330
- let message = `HTTP ${response.status}`;
2331
- try {
2332
- const parsed = errorSchema.safeParse(JSON.parse(text));
2333
- if (parsed.success) message = parsed.data.message;
2334
- } catch {
2335
- }
2336
- return { ok: false, failure: { status: response.status, message: hide(message) } };
2028
+ for await (const chunk of createReadStream(file, { encoding: "utf8" })) {
2029
+ const lines = `${pending}${String(chunk)}`.split("\n");
2030
+ pending = lines.pop() ?? "";
2031
+ for (const line of lines) if (line !== "") onLine(line);
2337
2032
  }
2338
- return { ok: true, status: response.status, body: text === "" ? null : JSON.parse(text) };
2033
+ if (pending !== "") onLine(pending);
2034
+ return { ok: true };
2339
2035
  } catch (error) {
2340
- const message = signal.aborted ? `no answer within ${options.timeoutMs / 1e3}s` : error instanceof Error ? error.message : String(error);
2341
- return { ok: false, failure: { status: null, message: hide(message) } };
2036
+ if (errorCode(error) === "ENOENT") return { ok: true };
2037
+ return { ok: false, failure: { path: file, message: messageOf(error) } };
2342
2038
  }
2343
2039
  }
2040
+ function messageOf(error) {
2041
+ return error instanceof Error ? error.message : String(error);
2042
+ }
2344
2043
 
2345
- // src/extensions/github/live/world.ts
2346
- var GITHUB_API_ORIGIN = "https://api.github.com";
2347
- function liveGitHubWorld(supplies) {
2044
+ // src/run-directory/run-collector.ts
2045
+ function runCollector(registry, directory) {
2046
+ let state = EMPTY_RUN_STATE;
2047
+ const events = [];
2048
+ let unreadable = 0;
2049
+ let incomplete;
2050
+ let workerOffsetMs = Infinity;
2051
+ const collect = (event) => {
2052
+ directory?.appendTestEvent(testEventLine(event));
2053
+ events.push(summaryEvent(event));
2054
+ };
2348
2055
  return {
2349
- env: supplies.env,
2350
- githubFixtureRepos: liveGitHubFixtureRepoGateway({ origin: GITHUB_API_ORIGIN, timeoutMs: 1e4 }),
2351
- randomSuffix: () => randomBytes2(4).toString("hex"),
2352
- clock: supplies.clock
2056
+ observer: {
2057
+ observe: async (timed) => {
2058
+ const { event } = timed;
2059
+ if (event.kind === "runner" && event.event.kind === "step-output") return;
2060
+ state = registry.applyEvent(state, timed);
2061
+ if (event.kind === "test") {
2062
+ collect(event.event);
2063
+ if (event.event.kind !== "test-result")
2064
+ workerOffsetMs = Math.min(workerOffsetMs, timed.at.getTime() - event.event.at);
2065
+ } else if (event.kind === "test-event-unreadable") unreadable += 1;
2066
+ else if (event.kind === "test-events-incomplete") incomplete ??= event.message;
2067
+ }
2068
+ },
2069
+ readStaged: async (runDirectory2, redact) => {
2070
+ const read2 = await runDirectory2.readTestEvents((line) => {
2071
+ const event = parseTestEvent(line);
2072
+ if (event === void 0) unreadable += 1;
2073
+ else collect(redact(event));
2074
+ });
2075
+ if (!read2.ok) incomplete ??= read2.failure.message;
2076
+ },
2077
+ finish: () => ({
2078
+ state,
2079
+ tests: { events, unreadable, incomplete },
2080
+ workerOffsetMs: workerOffsetMs === Infinity ? 0 : workerOffsetMs
2081
+ })
2082
+ };
2083
+ }
2084
+ function summaryEvent(event) {
2085
+ if (event.kind !== "test-result") return event;
2086
+ return {
2087
+ kind: event.kind,
2088
+ id: event.id,
2089
+ file: event.file,
2090
+ test: event.test,
2091
+ state: event.state,
2092
+ retryCount: event.retryCount,
2093
+ flaky: event.flaky,
2094
+ at: event.at
2353
2095
  };
2354
2096
  }
2355
2097
 
2356
- // src/extensions/github/options.ts
2357
- import { z as z7 } from "zod";
2358
- var REPO_NAME = /^[\w.-]+\/[\w.-]+$/;
2359
- var ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
2360
- var REPO = "a repository as owner/name";
2361
- var repoName = z7.string(mustBe(REPO)).regex(REPO_NAME, mustBe(REPO));
2362
- var ENV = "an environment variable's name";
2363
- var envName = z7.string(mustBe(ENV)).regex(ENV_NAME, mustBe(ENV));
2364
- var githubFixtureRepoRules = {
2365
- /** The repository, as `owner/name`. storm creates no repository; this one must exist. */
2366
- repo: { schema: repoName, required: true },
2367
- /**
2368
- * The launcher environment variable that holds the token for `repo`, such as `CNC_GITHUB_FIXTURE_TOKEN`. Use a
2369
- * token limited to this one repository: the command gets it in its run payload.
2370
- */
2371
- tokenEnv: { schema: envName, required: true },
2372
- /**
2373
- * What a run does when `tokenEnv` is unset or empty: `false`, the default, refuses the run; `true` runs without the
2374
- * resource and says so in one line.
2375
- */
2376
- optional: {
2377
- schema: booleanOption,
2378
- default: false,
2379
- flag: {
2380
- description: "Whether the run goes on without the GitHub fixture repository when the launcher environment variable its tokenEnv names is unset, overriding resources.githubFixtureRepo.optional in storm.config.ts; default false. --github-optional=false makes the repository required for this run, so a run without its token is refused with github_token_missing before anything starts. Gives the run the GitHub fixture repository resource, whose repo and tokenEnv only storm.config.ts gives."
2381
- }
2382
- }
2383
- };
2384
-
2385
- // src/extensions/github/run/payload.ts
2386
- var GITHUB_FIXTURE_REPO_NAME = "githubFixtureRepo";
2387
- function checkGitHubFixtureRepoPayload(section) {
2388
- if (!isObject(section)) return { ok: false, at: [], problem: "must be an object" };
2389
- const { url, nameWithOwner, token, runPrefix } = section;
2390
- if (!filled(url)) return refused("url");
2391
- if (!filled(nameWithOwner)) return refused("nameWithOwner");
2392
- if (!filled(token)) return refused("token");
2393
- if (!filled(runPrefix)) return refused("runPrefix");
2394
- return { ok: true, value: { url, nameWithOwner, token, runPrefix } };
2395
- }
2396
- function isObject(value) {
2397
- return typeof value === "object" && value !== null && !Array.isArray(value);
2398
- }
2399
- function filled(value) {
2400
- return typeof value === "string" && value !== "";
2401
- }
2402
- function refused(field) {
2403
- return { ok: false, at: [field], problem: "must be a non-empty string" };
2404
- }
2405
- var githubFixtureRepoPayload = Object.freeze({ name: GITHUB_FIXTURE_REPO_NAME, payload: checkGitHubFixtureRepoPayload });
2406
-
2407
- // src/extensions/github/definition.ts
2408
- var githubFixtureRepoDefinition = defineResource({
2409
- name: GITHUB_FIXTURE_REPO_NAME,
2410
- flagPrefix: "github",
2411
- options: githubFixtureRepoRules,
2412
- payload: githubFixtureRepoPayload,
2413
- world: liveGitHubWorld,
2414
- lifecycle: githubFixtureRepoLifecycle
2415
- });
2416
-
2417
- // src/extensions/github/extension.ts
2418
- var githubExtension = defineExtension({ name: "github", resources: [githubFixtureRepoDefinition] });
2419
-
2420
- // src/extensions/github/resource.ts
2421
- var githubFixtureRepo = resourceFactory(githubFixtureRepoDefinition);
2422
-
2423
- // src/extensions/testserver/extension.ts
2424
- var testserverExtension = defineExtension({
2425
- name: "testserver",
2426
- resources: [testserverPoolDefinition],
2427
- commands: testserverExtensionCommands,
2428
- examples: {
2429
- exec: [
2430
- {
2431
- argv: "--testserver-sandboxes 4 -- pnpm test:testserver",
2432
- description: "Run a script in a runner sandbox against 4 Testserver sandboxes."
2433
- },
2434
- {
2435
- argv: "--unsandboxed --testserver-sandboxes 4 --scope vercel --project vercel -- pnpm test",
2436
- description: "Run the tests on this machine against 4 Testserver sandboxes on the stable build channel."
2437
- },
2438
- {
2439
- argv: "--unsandboxed --testserver-ttl 30m --testserver-min-time-left 25m -- pnpm test",
2440
- description: "Create Testserver sandboxes that live 30 minutes, with team and project from storm.config.ts."
2441
- },
2442
- {
2443
- argv: "--unsandboxed --testserver-build pr:104196 -- pnpm test",
2444
- description: "Run the tests on this machine against the Testserver build of vercel/api pull request 104196's head commit."
2445
- },
2446
- {
2447
- argv: "--unsandboxed --testserver-create=false --testserver-sandboxes 4 -- pnpm test",
2448
- description: "Run only on Testserver sandboxes already in the pool, never minting."
2449
- },
2450
- {
2451
- argv: "--unsandboxed --verbose --testserver-sandboxes 2 -- pnpm test",
2452
- description: "Run the tests, printing each create's progress and, through the Vitest adapter, each test as it ends."
2453
- },
2454
- {
2455
- argv: "--unsandboxed --credential github-actions --testserver-ttl 30m --testserver-min-time-left 25m -- pnpm test",
2456
- description: "In a GitHub Actions job, create Testserver sandboxes with a GitHub Actions OIDC token."
2457
- },
2458
- {
2459
- argv: "--unsandboxed --testserver-build latest_main --testserver-min-time-left 75m --scope vercel --project vercel -- pnpm test",
2460
- description: "Run them on the newest main build, with Testserver sandboxes that live at least 75 more minutes."
2461
- }
2462
- ],
2463
- vitest: [
2464
- {
2465
- argv: "--testserver-build pr:104196",
2466
- description: "Run every test against the Testserver build of vercel/api pull request 104196's head commit."
2467
- },
2468
- {
2469
- argv: "--unsandboxed --testserver-create=false",
2470
- description: "Run on this machine, on Testserver sandboxes already in the pool, never minting."
2098
+ // src/run-directory/recording.ts
2099
+ async function recordRun(gateway, start) {
2100
+ const { registry } = start;
2101
+ const record = start.redact({
2102
+ version: 3,
2103
+ startedAt: start.startedAt.toISOString(),
2104
+ cwd: start.cwd,
2105
+ configFile: start.configFile,
2106
+ argv: start.argv,
2107
+ ...start.plan === void 0 ? {} : { plan: start.plan },
2108
+ where: startedWhere(start.run),
2109
+ git: start.git
2110
+ });
2111
+ const result = await gateway.open({
2112
+ startedAt: start.startedAt,
2113
+ keep: RUN_DIRECTORIES_KEPT,
2114
+ run: runRecordText(record)
2115
+ });
2116
+ const directory = result.ok ? result.directory : void 0;
2117
+ const opened = result.ok ? { ok: true, id: result.directory.id, path: result.directory.path, pruneFailures: result.pruneFailures } : { ok: false, failure: result.failure };
2118
+ const collector = runCollector(registry, directory);
2119
+ return {
2120
+ opened,
2121
+ testEvents: directory === void 0 ? void 0 : testEventsPath(directory.path),
2122
+ observer: (beside) => directory === void 0 ? observeAll(collector.observer, beside) : observeAll(collector.observer, beside, runDirectoryObserver(directory)),
2123
+ terminal: (terminal) => directory === void 0 ? terminal : {
2124
+ color: terminal.color,
2125
+ writeStdout: (text) => {
2126
+ directory.appendCommandOutput(text);
2127
+ terminal.writeStdout(text);
2471
2128
  },
2472
- {
2473
- argv: "--testserver-sandboxes 6 -- --project testserver",
2474
- description: "Run vitest's testserver project against 6 Testserver sandboxes, whatever the test count."
2129
+ writeStderr: (text) => {
2130
+ directory.appendCommandOutput(text);
2131
+ terminal.writeStderr(text);
2475
2132
  }
2476
- ]
2477
- }
2478
- });
2479
-
2480
- // src/extensions/testserver/resource.ts
2481
- var testserverPool = resourceFactory(testserverPoolDefinition);
2482
-
2483
- // src/extensions.ts
2484
- var EXTENSIONS = [githubExtension, testserverExtension];
2485
- var RESOURCES = resourcesOf(EXTENSIONS);
2486
- var RESOURCE_REPORTS = resourceReports(RESOURCES);
2487
- var RESOURCE_PRESENTATIONS = resourcePresentations(RESOURCES);
2488
- var RUN_CLEANUP = runCleanupOf(RESOURCE_REPORTS);
2489
- function resourceLifecycles(worlds) {
2490
- return bindLifecycles(RESOURCES, worlds);
2491
- }
2492
- function liveWorlds(env) {
2493
- return worldsOf(RESOURCES, env);
2494
- }
2495
- function applyStormEvent(state, timed) {
2496
- return applyRunEvent(RESOURCES, state, timed);
2497
- }
2498
- function stormTimeline(state) {
2499
- return timeline(RESOURCES, state);
2133
+ },
2134
+ stepLog: (step) => directory === void 0 ? void 0 : stepLog(directory.path, step),
2135
+ end: async (outcome) => {
2136
+ if (directory !== void 0) await collector.readStaged(directory, start.redact);
2137
+ const { state, tests, workerOffsetMs } = collector.finish();
2138
+ const timeline2 = timelineFacts(registry.timeline(state), registry.presentations.laneKinds);
2139
+ directory?.publishTestEvents();
2140
+ directory?.writeTimeline(JSON.stringify(timeline2, null, 2));
2141
+ directory?.writeRun(
2142
+ runRecordText({
2143
+ ...record,
2144
+ where: endedWhere(record.where, state.runner, outcome.kind === "ran" ? outcome.runner?.save ?? null : null),
2145
+ ended: runEnd(outcome, state.command, tests, registry.reports)
2146
+ })
2147
+ );
2148
+ const writeFailure = await directory?.close();
2149
+ return { state, timeline: timeline2, tests, workerOffsetMs, writeFailure };
2150
+ },
2151
+ abandon: async () => {
2152
+ await directory?.close();
2153
+ }
2154
+ };
2500
2155
  }
2501
2156
 
2502
2157
  export {
@@ -2507,53 +2162,23 @@ export {
2507
2162
  secondsText,
2508
2163
  megabytesText,
2509
2164
  commandExitStatus,
2165
+ EMPTY_RUN_STATE,
2166
+ cleanupProblems,
2167
+ sameRow,
2168
+ resourceRegistry,
2169
+ resourcesOf,
2510
2170
  timedProgress,
2511
- observeAll,
2512
2171
  liveCommandGateway,
2172
+ liveTerminalCommandGateway,
2513
2173
  liveJobSummaryGateway,
2514
2174
  liveProgressTerminal,
2175
+ executeRun,
2515
2176
  RUNS_SUBPATH,
2516
- RUN_DIRECTORIES_KEPT,
2517
- runLogFile,
2518
- testEventsPath,
2519
- stepLog,
2520
- runDirectoryObserver,
2521
2177
  liveRunDirectoryGateway,
2522
2178
  unavailableRunDirectoryGateway,
2523
- executeRun,
2524
- EMPTY_RUN_STATE,
2525
- cleanupProblems,
2526
- sameRow,
2527
- liveVitestListGateway,
2528
- planVitestRun,
2529
- vitestRunArgv,
2530
- formatPlan,
2531
- describeVitestListFailure,
2532
- sandboxPage,
2533
- snapshotPage,
2534
- seconds2 as seconds,
2535
- keepTimeText,
2536
- releaseText,
2537
- isoSecondsText,
2538
- short,
2539
- shortFile,
2540
- median,
2541
- paint,
2542
- visibleLength,
2543
- truncate,
2544
- spread,
2545
- notStoppedText,
2546
- notDeletedText,
2547
- keptText,
2548
- notKeptText,
2549
- runnerCleanupWarnings,
2550
- EXTENSIONS,
2551
- RESOURCES,
2552
- RESOURCE_REPORTS,
2553
- RESOURCE_PRESENTATIONS,
2554
- RUN_CLEANUP,
2555
- resourceLifecycles,
2556
- liveWorlds,
2557
- applyStormEvent,
2558
- stormTimeline
2179
+ planSchema,
2180
+ saveSchema,
2181
+ timelineSchema,
2182
+ recordRun,
2183
+ pastRuns
2559
2184
  };