@cnc-tools/storm 0.12.0 → 0.14.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 (188) hide show
  1. package/dist/application.js +5 -1
  2. package/dist/bin/storm.js +6 -2
  3. package/dist/build-info.js +1 -1
  4. package/dist/chunks/{chunk-FK4RLDEK.js → chunk-27P2QSIM.js} +1 -1
  5. package/dist/chunks/{chunk-ODQHQJLE.js → chunk-5ED3IDUJ.js} +749 -1121
  6. package/dist/chunks/{chunk-FSP3SJ35.js → chunk-5TMHYH7G.js} +16 -46
  7. package/dist/chunks/{chunk-Y3BUNNRG.js → chunk-BFLYGMG3.js} +12 -7
  8. package/dist/chunks/{chunk-LQKNI3EG.js → chunk-BRUIATTR.js} +6 -6
  9. package/dist/chunks/{chunk-RYRJNHL7.js → chunk-HOKDKP5A.js} +3 -9
  10. package/dist/chunks/{chunk-SXW6XN4R.js → chunk-IVRRGGCD.js} +60 -20
  11. package/dist/chunks/{chunk-TMQQYHUX.js → chunk-QBR5VHJ7.js} +1 -1
  12. package/dist/chunks/{chunk-YT5OROR7.js → chunk-RA4L2ACU.js} +12 -2
  13. package/dist/chunks/{chunk-TEEZL3GA.js → chunk-RKONDLPS.js} +17 -71
  14. package/dist/chunks/{chunk-IYM44FUX.js → chunk-UC6DULWY.js} +2 -2
  15. package/dist/chunks/{chunk-4XT5RC5T.js → chunk-XPCUINWS.js} +6 -42
  16. package/dist/chunks/{chunk-U7M3ZB3Z.js → chunk-YBPTMJUM.js} +123 -180
  17. package/dist/chunks/{chunk-ISGQJIQM.js → chunk-Z5OXOZD3.js} +125 -83
  18. package/dist/chunks/{chunk-7D6LC5JY.js → chunk-ZH5R7W4A.js} +7 -39
  19. package/dist/chunks/{live-app-AZ5N5HBD.js → live-app-FBVWUUMT.js} +7 -7
  20. package/dist/commands/exec/command.d.ts +4 -90
  21. package/dist/commands/exec/command.js +15 -41
  22. package/dist/commands/exec/define-run-command.d.ts +19 -100
  23. package/dist/commands/exec/define-run-command.js +48 -15
  24. package/dist/commands/exec/driver-plan.d.ts +24 -16
  25. package/dist/commands/exec/driver-plan.js +34 -15
  26. package/dist/commands/exec/driver-refusals.js +7 -6
  27. package/dist/commands/exec/exec-words.d.ts +1 -1
  28. package/dist/commands/exec/exec-words.js +8 -2
  29. package/dist/commands/exec/final-results.d.ts +39 -0
  30. package/dist/commands/exec/final-results.js +29 -0
  31. package/dist/commands/exec/live-view.js +18 -22
  32. package/dist/commands/exec/metadata.js +1 -1
  33. package/dist/commands/exec/outcomes.d.ts +15 -109
  34. package/dist/commands/exec/outcomes.js +25 -39
  35. package/dist/commands/exec/plan-run.d.ts +11 -3
  36. package/dist/commands/exec/plan-run.js +3 -2
  37. package/dist/commands/exec/progress.d.ts +3 -19
  38. package/dist/commands/exec/progress.js +16 -60
  39. package/dist/commands/exec/run-command.d.ts +5 -24
  40. package/dist/commands/exec/run-command.js +32 -84
  41. package/dist/commands/exec/run-metadata.d.ts +0 -6
  42. package/dist/commands/exec/run-metadata.js +2 -8
  43. package/dist/commands/exec/snapshot-text.d.ts +7 -16
  44. package/dist/commands/exec/snapshot-text.js +9 -49
  45. package/dist/commands/exec/test-plan.d.ts +2 -1
  46. package/dist/commands/exec/test-plan.js +13 -4
  47. package/dist/commands/exec/tests-summary.d.ts +2 -2
  48. package/dist/commands/exec/view.js +2 -12
  49. package/dist/commands/exec/worker-chart.d.ts +1 -1
  50. package/dist/commands/playwright/command.d.ts +12 -97
  51. package/dist/commands/playwright/command.js +14 -14
  52. package/dist/commands/playwright/metadata.js +2 -2
  53. package/dist/commands/runs/facts.d.ts +1 -37
  54. package/dist/commands/runs/facts.js +4 -36
  55. package/dist/commands/runs/list/command.d.ts +0 -72
  56. package/dist/commands/runs/list/command.js +6 -6
  57. package/dist/commands/runs/list/outcomes.d.ts +0 -36
  58. package/dist/commands/runs/logs/command.js +6 -6
  59. package/dist/commands/runs/show/command.d.ts +2 -74
  60. package/dist/commands/runs/show/command.js +16 -43
  61. package/dist/commands/runs/show/metadata.js +1 -1
  62. package/dist/commands/runs/show/outcomes.d.ts +1 -37
  63. package/dist/commands/runs/show/outcomes.js +8 -42
  64. package/dist/commands/snapshots/build/command.d.ts +14 -411
  65. package/dist/commands/snapshots/build/command.js +59 -234
  66. package/dist/commands/snapshots/build/metadata.js +10 -7
  67. package/dist/commands/snapshots/build/outcomes.d.ts +11 -241
  68. package/dist/commands/snapshots/build/outcomes.js +29 -196
  69. package/dist/commands/snapshots/list/command.d.ts +2 -36
  70. package/dist/commands/snapshots/list/command.js +20 -56
  71. package/dist/commands/snapshots/list/metadata.js +1 -1
  72. package/dist/commands/snapshots/list/outcomes.d.ts +2 -37
  73. package/dist/commands/snapshots/list/outcomes.js +13 -53
  74. package/dist/commands/vitest/command.d.ts +14 -98
  75. package/dist/commands/vitest/command.js +14 -14
  76. package/dist/commands/vitest/metadata.js +2 -2
  77. package/dist/config/resolve.d.ts +1 -1
  78. package/dist/config/resolve.js +2 -1
  79. package/dist/config/schema.d.ts +8 -0
  80. package/dist/config/schema.js +5 -4
  81. package/dist/core/events.d.ts +5 -6
  82. package/dist/core/run-state.d.ts +7 -29
  83. package/dist/core/run-state.js +3 -26
  84. package/dist/core/run.d.ts +6 -14
  85. package/dist/core/run.js +17 -28
  86. package/dist/extensions/playwright/driver.js +17 -10
  87. package/dist/extensions/testserver/commands/pool/create/command.js +4 -4
  88. package/dist/extensions/testserver/commands/pool/list/command.js +2 -2
  89. package/dist/extensions/testserver/definition.d.ts +1 -1
  90. package/dist/extensions/testserver/extension.d.ts +1 -1
  91. package/dist/extensions/testserver/options/rules.d.ts +3 -3
  92. package/dist/extensions/testserver/options/rules.js +5 -5
  93. package/dist/extensions/testserver/resource.d.ts +1 -1
  94. package/dist/extensions/testserver/vercel-cli/index.d.ts +1 -0
  95. package/dist/extensions/testserver/vercel-cli/index.js +1 -0
  96. package/dist/extensions/testserver/vercel-cli/report.js +5 -2
  97. package/dist/extensions/testserver/vercel-cli/session-id.d.ts +8 -0
  98. package/dist/extensions/testserver/vercel-cli/session-id.js +16 -0
  99. package/dist/extensions/testserver/vitest/config.d.ts +2 -2
  100. package/dist/extensions/testserver/vitest/config.js +2 -2
  101. package/dist/extensions/testserver/vitest/container-scope.d.ts +25 -16
  102. package/dist/extensions/testserver/vitest/container-scope.js +32 -13
  103. package/dist/extensions/testserver/vitest/diagnostics.d.ts +5 -4
  104. package/dist/extensions/testserver/vitest/diagnostics.js +15 -8
  105. package/dist/extensions/testserver/vitest/fixtures.d.ts +10 -1
  106. package/dist/extensions/testserver/vitest/fixtures.js +36 -10
  107. package/dist/extensions/testserver/vitest/types.d.ts +9 -0
  108. package/dist/extensions/vitest/driver.js +28 -14
  109. package/dist/extensions/vitest/plan/gateways.d.ts +28 -5
  110. package/dist/extensions/vitest/plan/gateways.js +2 -2
  111. package/dist/extensions/vitest/plan/list-output.d.ts +5 -0
  112. package/dist/extensions/vitest/plan/list-output.js +23 -9
  113. package/dist/extensions/vitest/plan/live/list-gateway.d.ts +3 -2
  114. package/dist/extensions/vitest/plan/live/list-gateway.js +77 -64
  115. package/dist/extensions/vitest/plan/plan-over.d.ts +19 -7
  116. package/dist/extensions/vitest/plan/plan-over.js +18 -7
  117. package/dist/extensions/vitest/plan/plan.d.ts +14 -5
  118. package/dist/extensions/vitest/plan/plan.js +23 -9
  119. package/dist/extensions.d.ts +2 -2
  120. package/dist/run-directory/index.d.ts +1 -1
  121. package/dist/run-directory/index.js +0 -1
  122. package/dist/run-directory/plan.d.ts +3 -2
  123. package/dist/run-directory/plan.js +6 -3
  124. package/dist/run-directory/recording.js +2 -2
  125. package/dist/run-directory/run-record.d.ts +18 -135
  126. package/dist/run-directory/run-record.js +8 -68
  127. package/dist/runner/build-snapshots.d.ts +50 -114
  128. package/dist/runner/build-snapshots.js +70 -159
  129. package/dist/runner/events.d.ts +4 -88
  130. package/dist/runner/gateways.d.ts +5 -23
  131. package/dist/runner/index.d.ts +5 -6
  132. package/dist/runner/index.js +1 -1
  133. package/dist/runner/live/snapshot-records.js +7 -18
  134. package/dist/runner/prepare.d.ts +11 -22
  135. package/dist/runner/prepare.js +6 -17
  136. package/dist/runner/ready.d.ts +16 -45
  137. package/dist/runner/ready.js +34 -59
  138. package/dist/runner/recipe.d.ts +5 -45
  139. package/dist/runner/recipe.js +0 -41
  140. package/dist/runner/sandboxed-command.d.ts +5 -3
  141. package/dist/runner/sandboxed-command.js +10 -4
  142. package/dist/runner/scope.d.ts +8 -25
  143. package/dist/runner/scope.js +4 -8
  144. package/dist/runner/session.d.ts +18 -65
  145. package/dist/runner/session.js +15 -83
  146. package/dist/runner/snapshot-build.d.ts +2 -2
  147. package/dist/runner/snapshot-cache.d.ts +22 -74
  148. package/dist/runner/snapshot-cache.js +15 -107
  149. package/dist/runner/snapshot-inspect.d.ts +9 -13
  150. package/dist/runner/snapshot-inspect.js +48 -57
  151. package/dist/runner/snapshot-key.d.ts +9 -14
  152. package/dist/runner/snapshot-key.js +15 -22
  153. package/dist/sdk/extension/driver.d.ts +32 -6
  154. package/dist/sdk/extension/driver.js +12 -2
  155. package/dist/sdk/extension/index.d.ts +1 -1
  156. package/dist/sdk/extension/index.js +2 -1
  157. package/dist/sdk/extension/resource-definition.d.ts +6 -5
  158. package/dist/vendor/testserver-sdk/container/api-request.d.ts +2 -3
  159. package/dist/vendor/testserver-sdk/container/api-request.js +2 -3
  160. package/dist/vendor/testserver-sdk/container/container.d.ts +12 -2
  161. package/dist/vendor/testserver-sdk/container/container.js +10 -7
  162. package/dist/vendor/testserver-sdk/container/recorder.d.ts +29 -7
  163. package/dist/vendor/testserver-sdk/container/recorder.js +26 -14
  164. package/dist/vendor/testserver-sdk/index.d.ts +1 -1
  165. package/dist/vendor/testserver-sdk/index.js +1 -1
  166. package/dist/vendor/testserver-sdk/proxy/exchange.d.ts +24 -5
  167. package/dist/vendor/testserver-sdk/proxy/exchange.js +43 -25
  168. package/dist/vendor/testserver-sdk/proxy/faulted-exchange.js +15 -10
  169. package/dist/vendor/testserver-sdk/proxy/faults.d.ts +6 -5
  170. package/dist/vendor/testserver-sdk/proxy/proxy.d.ts +10 -1
  171. package/dist/vendor/testserver-sdk/proxy/proxy.js +5 -3
  172. package/dist/vendor/testserver-sdk/proxy/records.d.ts +17 -17
  173. package/dist/vendor/testserver-sdk/proxy/records.js +18 -17
  174. package/dist/vendor/testserver-sdk/records/body.d.ts +7 -9
  175. package/dist/vendor/testserver-sdk/records/body.js +10 -15
  176. package/dist/vendor/testserver-sdk/records/headers.d.ts +79 -0
  177. package/dist/vendor/testserver-sdk/records/headers.js +162 -0
  178. package/dist/vendor/testserver-sdk/records/index.d.ts +2 -1
  179. package/dist/vendor/testserver-sdk/records/index.js +4 -2
  180. package/dist/vendor/testserver-sdk/records/records.d.ts +19 -10
  181. package/package.json +5 -4
  182. package/skills/overview.md +5 -5
  183. package/skills/read-run-output.md +8 -9
  184. package/dist/runner/snapshot-save.d.ts +0 -70
  185. package/dist/runner/snapshot-save.js +0 -160
  186. package/dist/runner/snapshot-start.d.ts +0 -25
  187. package/dist/runner/snapshot-start.js +0 -16
  188. package/skills/testserver-builds.md +0 -82
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  Credential,
3
3
  NOT_COUNTED,
4
+ booleanOption,
4
5
  defaultResourceKey,
5
6
  describeMintFailure,
6
7
  describeValue,
@@ -9,7 +10,7 @@ import {
9
10
  resourceCall,
10
11
  tokenRequestFailureFacts,
11
12
  tokenRequestFailureShape
12
- } from "./chunk-YT5OROR7.js";
13
+ } from "./chunk-RA4L2ACU.js";
13
14
  import {
14
15
  defineErrors,
15
16
  refused
@@ -125,6 +126,201 @@ function baseStepContext(checkout, request2) {
125
126
  };
126
127
  }
127
128
 
129
+ // src/runner/scope.ts
130
+ var CREATE_SETTLE_MS = 2e4;
131
+ var SNAPSHOT_SETTLE_MS = 2 * 6e4;
132
+ function runnerSandboxScope(context, progress, keep) {
133
+ const { runnerSandboxes: sandboxes, timer, clock } = context;
134
+ const live = /* @__PURE__ */ new Set();
135
+ const creating = /* @__PURE__ */ new Set();
136
+ const saving = /* @__PURE__ */ new Set();
137
+ const notStopped = [];
138
+ const notDeleted = [];
139
+ let kept = null;
140
+ let notKept = null;
141
+ let closing;
142
+ const track = (set, task) => {
143
+ set.add(task);
144
+ const forget = () => set.delete(task);
145
+ void task.then(forget, forget);
146
+ return task;
147
+ };
148
+ const remove = async (sandbox) => {
149
+ const deleted = await sandboxes.delete(sandbox);
150
+ if (!deleted.ok)
151
+ notDeleted.push({ name: sandbox.name, role: sandbox.role, message: failureMessage(deleted.failure) });
152
+ };
153
+ const stopAndRemove = async (sandbox) => {
154
+ const stopped = await sandboxes.stop(sandbox);
155
+ if (!stopped.ok) {
156
+ notStopped.push({
157
+ name: sandbox.name,
158
+ role: sandbox.role,
159
+ timeoutMinutes: Math.round(sandbox.timeoutMs / 6e4),
160
+ message: failureMessage(stopped.failure)
161
+ });
162
+ return;
163
+ }
164
+ await remove(sandbox);
165
+ };
166
+ const keepOrRemove = async (sandbox) => {
167
+ const keepMs = sandbox.role === "runner" ? keep.keepMs : 0;
168
+ if (keepMs <= 0) return await stopAndRemove(sandbox);
169
+ const keeping = await sandboxes.keepRunning(sandbox, { until: new Date(clock.now().getTime() + keepMs) });
170
+ if (!keeping.ok) {
171
+ notKept = { name: sandbox.name, message: failureMessage(keeping.failure) };
172
+ return await stopAndRemove(sandbox);
173
+ }
174
+ kept = { name: sandbox.name, stopsAt: keeping.value.stopsAt.toISOString() };
175
+ await progress.emit({ kind: "sandbox-kept", ...kept });
176
+ };
177
+ const owned = (start) => {
178
+ if (closing !== void 0) return Promise.resolve({ ok: false, failure: { kind: "aborted" } });
179
+ return track(
180
+ creating,
181
+ (async () => {
182
+ const started = await start();
183
+ if (!started.ok) return started;
184
+ if (closing !== void 0) {
185
+ await stopAndRemove(started.value);
186
+ return { ok: false, failure: { kind: "aborted" } };
187
+ }
188
+ live.add(started.value);
189
+ return started;
190
+ })()
191
+ );
192
+ };
193
+ return {
194
+ startBuildSandbox: (access, request2) => owned(() => sandboxes.startBuildSandbox(access, request2)),
195
+ startRunnerSandbox: (access, request2) => owned(() => sandboxes.startRunnerSandbox(access, request2)),
196
+ saveSnapshot: (sandbox, request2) => track(
197
+ saving,
198
+ (async () => {
199
+ const saved = await sandboxes.saveSnapshot(sandbox, request2);
200
+ if (saved.ok && live.delete(sandbox)) await remove(sandbox);
201
+ return saved;
202
+ })()
203
+ ),
204
+ close() {
205
+ closing ??= (async () => {
206
+ if (saving.size > 0) await progress.emit({ kind: "waiting-for-snapshot", settleMs: SNAPSHOT_SETTLE_MS });
207
+ await Promise.all([
208
+ settleWithin(timer, creating, CREATE_SETTLE_MS),
209
+ settleWithin(timer, saving, SNAPSHOT_SETTLE_MS)
210
+ ]);
211
+ const held = [...live];
212
+ live.clear();
213
+ await Promise.all(held.map(keepOrRemove));
214
+ return { kept, notKept, notStopped: [...notStopped], notDeleted: [...notDeleted] };
215
+ })();
216
+ return closing;
217
+ }
218
+ };
219
+ }
220
+ async function settleWithin(timer, tasks, ms) {
221
+ if (tasks.size === 0) return;
222
+ const done = new AbortController();
223
+ await Promise.race([Promise.allSettled(tasks), timer.sleep(ms, done.signal)]);
224
+ done.abort();
225
+ }
226
+ function failureMessage(failure) {
227
+ return failure.message ?? failure.kind;
228
+ }
229
+
230
+ // src/runner/context.ts
231
+ function runnerPurpose(recipeName) {
232
+ return `storm-runner-${recipeName}`;
233
+ }
234
+ function runnerTags(recipeName, role, user) {
235
+ return { purpose: runnerPurpose(recipeName), user, role };
236
+ }
237
+
238
+ // src/runner/snapshot-cache.ts
239
+ import { createHash } from "node:crypto";
240
+ var RUNNER_SNAPSHOTS_SUBPATH = ["runner", "snapshots"];
241
+ var SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1e3;
242
+ var SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1e3;
243
+ function snapshotEntryIdentity(entry) {
244
+ return createHash("sha256").update(
245
+ [
246
+ entry.teamId,
247
+ entry.projectId,
248
+ entry.region,
249
+ entry.runtime,
250
+ entry.recipeName,
251
+ entry.snapshotKey,
252
+ entry.base
253
+ ].join("\0")
254
+ ).digest("hex").slice(0, 32);
255
+ }
256
+ function snapshotEntryFileName(entry) {
257
+ return `${snapshotEntryIdentity(entry)}.json`;
258
+ }
259
+ function isExpiredEntry(entry, now) {
260
+ return Date.parse(entry.expiresAt) <= now.getTime();
261
+ }
262
+ function hasTimeLeft(entry, now) {
263
+ return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
264
+ }
265
+ async function removeExpiredEntries(context) {
266
+ const { runnerSnapshots } = context;
267
+ const listed = await runnerSnapshots.listEntries();
268
+ if (!listed.ok) return { entries: [], notes: [{ kind: "cache-unreadable", failure: listed.failure }] };
269
+ const now = context.clock.now();
270
+ const entries = [];
271
+ const notes = [];
272
+ for (const entry of listed.value.entries) {
273
+ if (!isExpiredEntry(entry, now)) {
274
+ entries.push(entry);
275
+ continue;
276
+ }
277
+ const removed = await runnerSnapshots.removeEntry(entry);
278
+ if (!removed.ok) notes.push({ kind: "expired-entry-not-removed", entry, failure: removed.failure });
279
+ }
280
+ return { entries, notes };
281
+ }
282
+ function classifySnapshotEntries(context, request2) {
283
+ const { entries, recipe, base, snapshotKey: snapshotKey2, commitsAfterBase } = request2;
284
+ const now = context.clock.now();
285
+ const candidates = [];
286
+ const rejected = [];
287
+ const verdicts = [];
288
+ const reject = (entry, reason) => {
289
+ const rejection = { entry, reason };
290
+ rejected.push(rejection);
291
+ verdicts.push({ kind: "rejected", entry, rejection });
292
+ };
293
+ for (const entry of entries) {
294
+ if (entry.region !== recipe.region || entry.runtime !== recipe.runtime || entry.recipeName !== recipe.name) {
295
+ verdicts.push({ kind: "other-recipe", entry });
296
+ continue;
297
+ }
298
+ if (isExpiredEntry(entry, now)) reject(entry, "expired");
299
+ else if (!hasTimeLeft(entry, now)) reject(entry, "expires-soon");
300
+ else if (entry.base !== base) reject(entry, "other-base");
301
+ else if (entry.snapshotKey !== snapshotKey2) reject(entry, "steps-changed");
302
+ else {
303
+ const candidate = { entry, builtBehind: commitsAfterBase };
304
+ candidates.push(candidate);
305
+ verdicts.push({ kind: "candidate", entry, candidate });
306
+ }
307
+ }
308
+ return { candidates, rejected, verdicts };
309
+ }
310
+ function snapshotRejections(read, owner) {
311
+ const owned = (entry) => entry.teamId === owner.teamId && entry.projectId === owner.projectId;
312
+ return [
313
+ ...read.candidates.map(({ entry }) => ({ entry, reason: "other-owner" })),
314
+ ...read.rejected.map(({ entry, reason }) => ({ entry, reason: owned(entry) ? reason : "other-owner" }))
315
+ ];
316
+ }
317
+ function pickSnapshot(candidates, owner) {
318
+ return candidates.find(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId);
319
+ }
320
+
321
+ // src/runner/snapshot-key.ts
322
+ import { createHash as createHash2 } from "node:crypto";
323
+
128
324
  // src/time/duration.ts
129
325
  var MIN_TTL_MINUTES = 10;
130
326
  var MAX_TTL_MINUTES = 300;
@@ -342,16 +538,6 @@ function sandboxStop(operation, failure) {
342
538
  }
343
539
 
344
540
  // src/runner/recipe.ts
345
- function runStepTakesSecret(recipe) {
346
- return recipe.run.install.secrets.length > 0 || recipe.run.build.secrets.length > 0;
347
- }
348
- function devSnapshotsTrusted(recipe) {
349
- return recipe.trustDevSnapshots || !runStepTakesSecret(recipe);
350
- }
351
- function devSnapshotReuse(recipe, runReuses) {
352
- if (!devSnapshotsTrusted(recipe)) return "not-trusted";
353
- return runReuses ? "reuse" : "reuse-off";
354
- }
355
541
  var RECIPE_DEFAULTS = {
356
542
  cwd: ".",
357
543
  timeout: "60m",
@@ -369,9 +555,6 @@ var RECIPE_KEYS = /* @__PURE__ */ new Set([
369
555
  "secrets",
370
556
  "timeout",
371
557
  "keepSandbox",
372
- "saveDevSnapshot",
373
- "reuseDevSnapshot",
374
- "trustDevSnapshots",
375
558
  "baseRefs",
376
559
  "region",
377
560
  "runtime"
@@ -434,20 +617,6 @@ function checkRecipe(value) {
434
617
  ["keepSandbox"],
435
618
  `must be 0, or a whole number of minutes or hours up to 5h, not ${describeRecipeValue(keepSandbox)}`
436
619
  );
437
- const saveDevSnapshot2 = value["saveDevSnapshot"];
438
- if (saveDevSnapshot2 !== void 0 && typeof saveDevSnapshot2 !== "boolean")
439
- report(["saveDevSnapshot"], `must be true or false, not ${describeRecipeValue(saveDevSnapshot2)}`);
440
- const reuseDevSnapshot = orDefault(value["reuseDevSnapshot"], true);
441
- if (typeof reuseDevSnapshot !== "boolean")
442
- report(["reuseDevSnapshot"], `must be true or false, not ${describeRecipeValue(reuseDevSnapshot)}`);
443
- const trustDevSnapshots = orDefault(value["trustDevSnapshots"], false);
444
- if (typeof trustDevSnapshots !== "boolean")
445
- report(["trustDevSnapshots"], `must be true or false, not ${describeRecipeValue(trustDevSnapshots)}`);
446
- if (saveDevSnapshot2 === true && trustDevSnapshots === false && run !== void 0 && runStepTakesSecret({ run }))
447
- report(
448
- ["saveDevSnapshot"],
449
- "must not be true while run.install or run.build names a runner secret, unless trustDevSnapshots is true"
450
- );
451
620
  const baseRefs = checkBaseRefs(value["baseRefs"], report);
452
621
  const region = orDefault(value["region"], RECIPE_DEFAULTS.region);
453
622
  if (!isNonEmptyString(region)) report(["region"], `must be a non-empty string, not ${describeRecipeValue(region)}`);
@@ -469,9 +638,6 @@ function checkRecipe(value) {
469
638
  timeout,
470
639
  timeoutMinutes,
471
640
  keepSandboxMinutes,
472
- ...typeof saveDevSnapshot2 === "boolean" ? { saveDevSnapshot: saveDevSnapshot2 } : {},
473
- reuseDevSnapshot,
474
- trustDevSnapshots,
475
641
  baseRefs,
476
642
  region,
477
643
  runtime
@@ -689,900 +855,269 @@ function resolveVcpus(recipe, { run, resourceKeys }) {
689
855
  let returned;
690
856
  try {
691
857
  returned = recipe.vcpus(run);
692
- } catch (error) {
693
- return { ok: false, problem: `threw for ${describeResourceKeys(resourceKeys)}: ${errorMessage(error)}` };
694
- }
695
- return isPositiveInteger(returned) ? { ok: true, vcpus: returned } : {
696
- ok: false,
697
- problem: `must return a positive whole number, not ${describeRecipeValue(returned)} for ${describeResourceKeys(resourceKeys)}`
698
- };
699
- }
700
- function describeResourceKeys(names) {
701
- const last = names.at(-1);
702
- if (last === void 0) return "a run with no resource";
703
- return `a run with ${names.length === 1 ? last : `${names.slice(0, -1).join(", ")} and ${last}`}`;
704
- }
705
- function describeRecipeValue(value) {
706
- if (typeof value === "string") return JSON.stringify(value);
707
- if (typeof value === "number" || typeof value === "boolean") return String(value);
708
- if (value === null) return "null";
709
- if (value === void 0) return "undefined";
710
- if (typeof value === "function") return "a function";
711
- if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array";
712
- if (typeof value === "object") return "an object";
713
- return `a ${typeof value}`;
714
- }
715
- function errorMessage(error) {
716
- return error instanceof Error ? error.message : String(error);
717
- }
718
- function orDefault(value, fallback) {
719
- return value === void 0 ? fallback : value;
720
- }
721
- function isRecord(value) {
722
- return typeof value === "object" && value !== null && !Array.isArray(value);
723
- }
724
- function isNonEmptyString(value) {
725
- return typeof value === "string" && value.length > 0;
726
- }
727
- function isPositiveInteger(value) {
728
- return typeof value === "number" && Number.isInteger(value) && value > 0;
729
- }
730
- function isRelativePath(value) {
731
- return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split(/[/\\]/).includes("..");
732
- }
733
-
734
- // src/runner/snapshot-cache.ts
735
- import { createHash } from "node:crypto";
736
- var RUNNER_SNAPSHOTS_SUBPATH = ["runner", "snapshots"];
737
- var SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1e3;
738
- var SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1e3;
739
- function snapshotEntryIdentity(entry) {
740
- return createHash("sha256").update(
741
- [
742
- entry.teamId,
743
- entry.projectId,
744
- entry.region,
745
- entry.runtime,
746
- entry.recipeName,
747
- entry.snapshotKey,
748
- ...isDevEntry(entry) ? [entry.repoRoot, entry.head] : [entry.base]
749
- ].join("\0")
750
- ).digest("hex").slice(0, 32);
751
- }
752
- function isDevEntry(entry) {
753
- return entry.head !== void 0 && entry.repoRoot !== void 0;
754
- }
755
- function builtAtCommit(entry) {
756
- return isDevEntry(entry) ? entry.head : entry.base;
757
- }
758
- function snapshotEntryFileName(entry) {
759
- return `${snapshotEntryIdentity(entry)}.json`;
760
- }
761
- function isExpiredEntry(entry, now) {
762
- return Date.parse(entry.expiresAt) <= now.getTime();
763
- }
764
- function hasTimeLeft(entry, now) {
765
- return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
766
- }
767
- async function removeExpiredEntries(context) {
768
- const { runnerSnapshots } = context;
769
- const listed = await runnerSnapshots.listEntries();
770
- if (!listed.ok) return { entries: [], notes: [{ kind: "cache-unreadable", failure: listed.failure }] };
771
- const now = context.clock.now();
772
- const entries = [];
773
- const notes = [];
774
- for (const entry of listed.value.entries) {
775
- if (!isExpiredEntry(entry, now)) {
776
- entries.push(entry);
777
- continue;
778
- }
779
- const removed = await runnerSnapshots.removeEntry(entry);
780
- if (!removed.ok) notes.push({ kind: "expired-entry-not-removed", entry, failure: removed.failure });
781
- }
782
- return { entries, notes };
783
- }
784
- async function classifySnapshotEntries(context, request2) {
785
- const { checkout } = context;
786
- const { entries, repoRoot, recipe, base, snapshotKey: snapshotKey2, commitsAfterBase, devSnapshots } = request2;
787
- const now = context.clock.now();
788
- const candidates = [];
789
- const rejected = [];
790
- const verdicts = [];
791
- const reject = (entry, reason) => {
792
- const rejection = { entry, reason };
793
- rejected.push(rejection);
794
- verdicts.push({ kind: "rejected", entry, rejection });
795
- };
796
- const inHistory = /* @__PURE__ */ new Map();
797
- const behind = /* @__PURE__ */ new Map();
798
- for (const entry of entries) {
799
- if (entry.region !== recipe.region || entry.runtime !== recipe.runtime || entry.recipeName !== recipe.name) {
800
- verdicts.push({ kind: "other-recipe", entry });
801
- continue;
802
- }
803
- const dev = isDevEntry(entry);
804
- if (isExpiredEntry(entry, now)) reject(entry, "expired");
805
- else if (!hasTimeLeft(entry, now)) reject(entry, "expires-soon");
806
- else if (dev && entry.repoRoot !== repoRoot) reject(entry, "other-checkout");
807
- else if (dev && devSnapshots !== "reuse") reject(entry, devSnapshots);
808
- else if (entry.base !== base) reject(entry, "other-base");
809
- else if (entry.snapshotKey !== snapshotKey2) reject(entry, "steps-changed");
810
- else if (!dev) {
811
- const candidate = { entry, builtAt: entry.base, builtBehind: commitsAfterBase };
812
- candidates.push(candidate);
813
- verdicts.push({ kind: "candidate", entry, candidate });
814
- } else {
815
- const builtAt = entry.head;
816
- let contained = inHistory.get(builtAt);
817
- if (contained === void 0) {
818
- const asked = await checkout.contains({ repoRoot, ancestor: builtAt, descendant: "HEAD" });
819
- if (!asked.ok) return asked;
820
- contained = asked.value;
821
- inHistory.set(builtAt, contained);
822
- }
823
- if (!contained) {
824
- reject(entry, "not-in-history");
825
- continue;
826
- }
827
- let builtBehind = behind.get(builtAt);
828
- if (builtBehind === void 0) {
829
- const counted = await checkout.commitCount({ repoRoot, from: builtAt, to: "HEAD" });
830
- if (!counted.ok) return counted;
831
- builtBehind = counted.value;
832
- behind.set(builtAt, builtBehind);
833
- }
834
- const candidate = { entry, builtAt, builtBehind };
835
- candidates.push(candidate);
836
- verdicts.push({ kind: "candidate", entry, candidate });
837
- }
838
- }
839
- return { ok: true, value: { candidates, rejected, verdicts } };
840
- }
841
- function snapshotRejections(read, owner) {
842
- const owned = (entry) => entry.teamId === owner.teamId && entry.projectId === owner.projectId;
843
- return [
844
- ...read.candidates.map(({ entry }) => ({ entry, reason: "other-owner" })),
845
- ...read.rejected.map(({ entry, reason }) => ({ entry, reason: owned(entry) ? reason : "other-owner" }))
846
- ];
847
- }
848
- function pickSnapshot(candidates, owner) {
849
- return candidates.filter(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId).toSorted((a, b) => a.builtBehind - b.builtBehind || Number(isDevEntry(b.entry)) - Number(isDevEntry(a.entry)))[0];
850
- }
851
- async function dropDevSnapshotsOn(context, replaced) {
852
- const { runnerSnapshots } = context;
853
- const listed = await runnerSnapshots.listEntries();
854
- if (!listed.ok) return { snapshotIds: [], failures: [{ message: cacheFailureText(listed.failure) }] };
855
- const snapshotIds = [];
856
- const failures = [];
857
- for (const entry of listed.value.entries) {
858
- if (!isDevEntry(entry) || entry.teamId !== replaced.teamId || entry.projectId !== replaced.projectId || entry.region !== replaced.region || entry.runtime !== replaced.runtime || entry.recipeName !== replaced.recipeName || entry.snapshotKey !== replaced.snapshotKey || entry.base !== replaced.base)
859
- continue;
860
- const removed = await runnerSnapshots.removeEntry(entry);
861
- if (removed.ok) snapshotIds.push(entry.snapshotId);
862
- else failures.push({ message: cacheFailureText(removed.failure) });
863
- }
864
- return { snapshotIds, failures };
865
- }
866
- function cacheFailureText(failure) {
867
- return `${failure.path}: ${failure.message}`;
868
- }
869
-
870
- // src/runner/snapshot-key.ts
871
- import { createHash as createHash2 } from "node:crypto";
872
- var SNAPSHOT_FORMAT = 2;
873
- var SANDBOX_ROOT = "/vercel/sandbox";
874
- var STAGED_FILES = {
875
- baseTarball: "base.tgz",
876
- baseFileList: "base-files",
877
- patch: "run.patch",
878
- untrackedTarball: "untracked.tgz",
879
- untrackedFileList: "untracked-files"
880
- };
881
- var GIT_IDENTITY = "-c user.email=storm-runner@vercel.invalid -c user.name='storm runner' -c commit.gpgsign=false";
882
- var RESET_TO_BASE = [
883
- "root=$(git rev-list --max-parents=0 HEAD)",
884
- 'git reset -q --hard "$root"',
885
- "git clean -ffdq"
886
- ];
887
- function bashScript(lines) {
888
- return ["set -euo pipefail", `cd ${SANDBOX_ROOT}`, ...lines].join("\n");
889
- }
890
- function baseIndexScript(base, staging) {
891
- const tarball = `${staging}/${STAGED_FILES.baseTarball}`;
892
- const fileList = `${staging}/${STAGED_FILES.baseFileList}`;
893
- return bashScript([
894
- `tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
895
- `rm -f ${tarball}`,
896
- "git -c init.defaultBranch=main init -q",
897
- `git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
898
- `rm -f ${fileList}`,
899
- `git ${GIT_IDENTITY} commit -q --no-verify -m 'base ${base}'`
900
- ]);
901
- }
902
- function applyScript(staging) {
903
- const patch = `${staging}/${STAGED_FILES.patch}`;
904
- const tarball = `${staging}/${STAGED_FILES.untrackedTarball}`;
905
- const fileList = `${staging}/${STAGED_FILES.untrackedFileList}`;
906
- return bashScript([
907
- ...RESET_TO_BASE,
908
- // A build may have rewritten tracked files with the same content.
909
- "git update-index -q --refresh || true",
910
- `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
911
- `if [ -s ${tarball} ]; then`,
912
- ` tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
913
- ` git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
914
- "fi",
915
- `git ${GIT_IDENTITY} commit -q --no-verify --allow-empty -m run`,
916
- `rm -f ${patch} ${tarball} ${fileList}`
917
- ]);
918
- }
919
- function snapshotKey(steps) {
920
- const text = (list) => list.flatMap(({ label, script, secrets }) => [label, script, `secrets=${(secrets ?? []).toSorted().join(",")}`]);
921
- return createHash2("sha256").update(
922
- [
923
- `format=${SNAPSHOT_FORMAT}`,
924
- ...text(steps.toolchains),
925
- baseIndexScript("<base>", "<staging>"),
926
- ...text(steps.prebuild)
927
- ].join("\0")
928
- ).digest("hex");
929
- }
930
- async function snapshotStepsAt(checkout, request2) {
931
- const context = baseStepContext(checkout, request2);
932
- const { snapshot, secrets } = request2.recipe;
933
- const toolchains = await resolveSteps(snapshot.toolchains, context, secrets);
934
- if (!toolchains.ok) return { ok: false, path: ["snapshot", "toolchains"], problem: toolchains.problem };
935
- const prebuild = await resolveSteps(snapshot.prebuild, context, secrets);
936
- if (!prebuild.ok) return { ok: false, path: ["snapshot", "prebuild"], problem: prebuild.problem };
937
- return {
938
- ok: true,
939
- toolchains: toolchains.steps,
940
- prebuild: prebuild.steps,
941
- key: snapshotKey({ toolchains: toolchains.steps, prebuild: prebuild.steps })
942
- };
943
- }
944
-
945
- // src/runner/prepare.ts
946
- async function prepareRunner(context, request2) {
947
- const { checkout } = context;
948
- const { recipe } = request2;
949
- const root = await checkout.repositoryRoot({ cwd: request2.cwd });
950
- if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
951
- const repoRoot = root.value;
952
- const head2 = await checkout.head({ repoRoot });
953
- if (!head2.ok) return { kind: "checkout-failed", failure: head2.failure };
954
- const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
955
- if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
956
- if (resolved.kind === "no-base-ref") return resolved;
957
- const { base } = resolved;
958
- const submodules2 = await checkout.submodules({ repoRoot });
959
- if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
960
- if (submodules2.value.length > 0) return { kind: "submodules", paths: [...submodules2.value] };
961
- const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
962
- if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
963
- const vcpus = resolveVcpus(recipe, request2.vcpusRun);
964
- if (!vcpus.ok) return { kind: "invalid-recipe", path: ["vcpus"], problem: vcpus.problem };
965
- const upload = await checkout.assembleUpload({ repoRoot, base });
966
- if (!upload.ok) return { kind: "checkout-failed", failure: upload.failure };
967
- const afterBase = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
968
- if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
969
- const devSnapshots = devSnapshotReuse(recipe, request2.reuseDevSnapshots);
970
- const listing = await removeExpiredEntries(context);
971
- const classified = await classifySnapshotEntries(context, {
972
- entries: listing.entries,
973
- repoRoot,
974
- recipe,
975
- base,
976
- snapshotKey: steps.key,
977
- commitsAfterBase: afterBase.value,
978
- devSnapshots
979
- });
980
- if (!classified.ok) return { kind: "checkout-failed", failure: classified.failure };
981
- const cache = classified.value;
982
- return {
983
- kind: "ok",
984
- prepared: {
985
- recipe,
986
- repoRoot,
987
- head: head2.value,
988
- base,
989
- baseRef: resolved.ref,
990
- toolchains: steps.toolchains,
991
- prebuild: steps.prebuild,
992
- snapshotKey: steps.key,
993
- vcpus: vcpus.vcpus,
994
- upload: upload.value,
995
- candidates: cache.candidates,
996
- rejected: cache.rejected,
997
- commitsAfterBase: afterBase.value,
998
- notes: listing.notes,
999
- devSnapshots
1000
- }
1001
- };
1002
- }
1003
-
1004
- // src/runner/ready.ts
1005
- import { posix } from "node:path";
1006
-
1007
- // src/runner/context.ts
1008
- function runnerPurpose(recipeName) {
1009
- return `storm-runner-${recipeName}`;
1010
- }
1011
- function runnerTags(recipeName, role, user) {
1012
- return { purpose: runnerPurpose(recipeName), user, role };
1013
- }
1014
-
1015
- // src/runner/snapshot-build.ts
1016
- var BUILD_SANDBOX_TIMEOUT_MS = 30 * 6e4;
1017
- var BASE_INDEX_LABEL = "Committing the base's files";
1018
- async function buildSnapshot(context, request2, control, progress) {
1019
- const { prepared, access } = request2;
1020
- const { recipe, repoRoot, base } = prepared;
1021
- const { scope, signal } = control;
1022
- const now = () => context.clock.now().getTime();
1023
- const startedAt = now();
1024
- await progress.emit({
1025
- kind: "snapshot-build-started",
1026
- base,
1027
- why: request2.why,
1028
- summary: recipe.snapshot.summary ?? [...prepared.toolchains, ...prepared.prebuild].map(({ label }) => label).join(", ")
1029
- });
1030
- const [started, archive] = await Promise.all([
1031
- scope.startBuildSandbox(access, {
1032
- region: recipe.region,
1033
- runtime: recipe.runtime,
1034
- vcpus: recipe.snapshot.vcpus,
1035
- timeoutMs: BUILD_SANDBOX_TIMEOUT_MS,
1036
- tags: runnerTags(recipe.name, "snapshot-build", request2.user)
1037
- }),
1038
- context.checkout.baseArchive({ repoRoot, base })
1039
- ]);
1040
- if (!started.ok) return sandboxStop("start-build-sandbox", started.failure);
1041
- const sandbox = started.value;
1042
- await progress.emit({
1043
- kind: "sandbox-started",
1044
- role: "snapshot-build",
1045
- name: sandbox.name,
1046
- region: recipe.region,
1047
- vcpus: recipe.snapshot.vcpus,
1048
- ms: now() - startedAt
1049
- });
1050
- if (!archive.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: archive.failure } };
1051
- const staged = await context.runnerSandboxes.upload(
1052
- sandbox,
1053
- [
1054
- { name: STAGED_FILES.baseTarball, content: archive.value.tarball },
1055
- { name: STAGED_FILES.baseFileList, content: archive.value.fileList }
1056
- ],
1057
- signal
1058
- );
1059
- if (!staged.ok) return sandboxStop("upload", staged.failure);
1060
- const recipeStep = ({ label, script, secrets }) => ({
1061
- label,
1062
- script,
1063
- secrets: stepSecrets(request2.secrets, secrets)
1064
- });
1065
- const steps = [
1066
- ...prepared.toolchains.map(recipeStep),
1067
- { label: BASE_INDEX_LABEL, script: baseIndexScript(base, staged.value.directory) },
1068
- ...prepared.prebuild.map(recipeStep)
1069
- ];
1070
- await progress.emit({ kind: "output-started", section: "snapshot", sandbox: sandbox.name, region: recipe.region });
1071
- for (const step of steps) {
1072
- const ran = await runStep(context, { sandbox, phase: "snapshot", ...step }, progress, signal);
1073
- if (ran.kind === "succeeded") continue;
1074
- const stop = ran.kind === "exited" ? {
1075
- kind: "failed",
1076
- failure: { kind: "snapshot-build-step-failed", label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1077
- } : sandboxStop("run-script", ran.failure);
1078
- await progress.emit({
1079
- kind: "output-ended",
1080
- section: "snapshot",
1081
- outcome: stop.kind === "aborted" ? "stopped" : "failed"
1082
- });
1083
- return stop;
1084
- }
1085
- await progress.emit({ kind: "output-ended", section: "snapshot", outcome: "finished" });
1086
- if (signal.aborted) return { kind: "aborted" };
1087
- await progress.emit({ kind: "snapshot-saving" });
1088
- const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
1089
- if (!saved.ok) return sandboxStop("save-snapshot", saved.failure);
1090
- const savedAt2 = context.clock.now();
1091
- const entry = {
1092
- teamId: access.teamId,
1093
- projectId: access.projectId,
1094
- region: recipe.region,
1095
- runtime: recipe.runtime,
1096
- recipeName: recipe.name,
1097
- snapshotKey: prepared.snapshotKey,
1098
- base,
1099
- snapshotId: saved.value.snapshotId,
1100
- createdAt: savedAt2.toISOString(),
1101
- expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1102
- };
1103
- const written = await context.runnerSnapshots.writeEntry(entry);
1104
- if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
1105
- const ms = now() - startedAt;
1106
- await progress.emit({
1107
- kind: "snapshot-built",
1108
- snapshotId: entry.snapshotId,
1109
- base,
1110
- ms,
1111
- sizeBytes: saved.value.sizeBytes,
1112
- builtBehind: prepared.commitsAfterBase
1113
- });
1114
- return {
1115
- kind: "ok",
1116
- value: { entry, ms, sizeBytes: saved.value.sizeBytes, cacheFailure: written.ok ? null : written.failure }
1117
- };
1118
- }
1119
-
1120
- // src/runner/ready.ts
1121
- var APPLY_LABEL = "Applying your changes";
1122
- async function obtainSnapshot(context, request2, control, progress) {
1123
- const { prepared, start } = request2;
1124
- if (control.signal.aborted) return { kind: "aborted" };
1125
- if (start.kind === "reuse") {
1126
- const { candidate } = start;
1127
- const { entry: entry2 } = candidate;
1128
- const snapshot2 = {
1129
- kind: isDevEntry(entry2) ? "dev" : "base",
1130
- builtAt: candidate.builtAt,
1131
- builtBehind: candidate.builtBehind
1132
- };
1133
- await progress.emit({
1134
- kind: "snapshot-reused",
1135
- snapshotId: entry2.snapshotId,
1136
- base: entry2.base,
1137
- branch: entry2.branch ?? null,
1138
- head: entry2.head ?? null,
1139
- snapshot: snapshot2
1140
- });
1141
- return { kind: "ok", value: { entry: entry2, snapshot: snapshot2, built: null } };
1142
- }
1143
- const building = await buildSnapshot(
1144
- context,
1145
- { prepared, access: request2.access, user: request2.user, secrets: request2.secrets, why: start.why },
1146
- control,
1147
- progress
1148
- );
1149
- if (building.kind !== "ok") return building;
1150
- const { entry } = building.value;
1151
- const snapshot = {
1152
- kind: "base",
1153
- builtAt: entry.base,
1154
- builtBehind: prepared.commitsAfterBase
1155
- };
1156
- return { kind: "ok", value: { entry, snapshot, built: building.value } };
1157
- }
1158
- async function readyRunner(context, request2, control, progress) {
1159
- const { prepared, access } = request2;
1160
- const { recipe, repoRoot } = prepared;
1161
- const { scope, signal } = control;
1162
- const now = () => context.clock.now().getTime();
1163
- const { entry, snapshot } = request2.start;
1164
- const built = request2.start.built !== null;
1165
- if (signal.aborted) return { kind: "aborted" };
1166
- await progress.emit({ kind: "runner-sandbox-starting", snapshotId: entry.snapshotId });
1167
- const startedAt = now();
1168
- const started = await scope.startRunnerSandbox(access, {
1169
- snapshotId: entry.snapshotId,
1170
- region: recipe.region,
1171
- vcpus: prepared.vcpus,
1172
- timeoutMs: recipe.timeoutMinutes * 6e4,
1173
- tags: runnerTags(recipe.name, "runner", request2.user)
1174
- });
1175
- if (!started.ok) {
1176
- if (started.failure.kind === "snapshot-gone") {
1177
- const removed = await context.runnerSnapshots.removeEntry(entry);
1178
- return { kind: "snapshot-gone", entry, removal: removed.ok ? void 0 : removed.failure };
1179
- }
1180
- return sandboxStop("start-runner-sandbox", started.failure);
1181
- }
1182
- const sandbox = started.value;
1183
- await progress.emit({
1184
- kind: "sandbox-started",
1185
- role: "runner",
1186
- name: sandbox.name,
1187
- region: recipe.region,
1188
- vcpus: prepared.vcpus,
1189
- ms: now() - startedAt
1190
- });
1191
- const changes = await uploadChanges(context, { prepared, sandbox, base: entry.base }, signal, progress);
1192
- if (changes.kind !== "ok") return changes;
1193
- const applied = await stage(
1194
- context,
1195
- {
1196
- sandbox,
1197
- phase: "apply",
1198
- step: { label: APPLY_LABEL, script: applyScript(changes.value.directory) },
1199
- region: recipe.region
1200
- },
1201
- signal,
1202
- progress
1203
- );
1204
- if (applied.kind !== "ok") return applied;
1205
- const loginPath = await context.runnerSandboxes.loginPath(sandbox, signal);
1206
- if (!loginPath.ok) return sandboxStop("login-path", loginPath.failure);
1207
- const installed = await stage(
1208
- context,
1209
- {
1210
- sandbox,
1211
- phase: "install",
1212
- step: recipe.run.install,
1213
- secrets: stepSecrets(request2.secrets, recipe.run.install.secrets),
1214
- region: recipe.region
1215
- },
1216
- signal,
1217
- progress
1218
- );
1219
- if (installed.kind !== "ok") return installed;
1220
- const builtOutputs = await stage(
1221
- context,
1222
- {
1223
- sandbox,
1224
- phase: "build",
1225
- step: recipe.run.build,
1226
- secrets: stepSecrets(request2.secrets, recipe.run.build.secrets),
1227
- region: recipe.region
1228
- },
1229
- signal,
1230
- progress
1231
- );
1232
- if (builtOutputs.kind !== "ok") return builtOutputs;
1233
- return {
1234
- kind: "ready",
1235
- runner: {
1236
- sandbox,
1237
- startedFrom: entry,
1238
- built,
1239
- snapshot,
1240
- uploadBytes: changes.value.bytes,
1241
- buildMs: builtOutputs.value,
1242
- vcpus: prepared.vcpus,
1243
- region: recipe.region,
1244
- runtime: recipe.runtime,
1245
- repoRoot,
1246
- cwd: posix.join(SANDBOX_ROOT, recipe.cwd),
1247
- env: recipe.env,
1248
- loginPath: loginPath.value
1249
- }
1250
- };
1251
- }
1252
- async function uploadChanges(context, request2, signal, progress) {
1253
- const { prepared } = request2;
1254
- await progress.emit({ kind: "uploading" });
1255
- const startedAt = context.clock.now().getTime();
1256
- let upload = prepared.upload;
1257
- if (request2.base !== prepared.base) {
1258
- const assembled = await context.checkout.assembleUpload({ repoRoot: prepared.repoRoot, base: request2.base });
1259
- if (!assembled.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: assembled.failure } };
1260
- upload = assembled.value;
1261
- }
1262
- const files = stagedChanges(upload);
1263
- const staged = await context.runnerSandboxes.upload(request2.sandbox, files, signal);
1264
- if (!staged.ok) return sandboxStop("upload", staged.failure);
1265
- const bytes = files.reduce((sum, file) => sum + file.content.byteLength, 0);
1266
- await progress.emit({ kind: "uploaded", bytes, ms: context.clock.now().getTime() - startedAt });
1267
- return { kind: "ok", value: { directory: staged.value.directory, bytes } };
1268
- }
1269
- function stagedChanges(upload) {
1270
- const encoder = new TextEncoder();
1271
- return [
1272
- { name: STAGED_FILES.patch, content: upload.patch },
1273
- {
1274
- name: STAGED_FILES.untrackedFileList,
1275
- content: encoder.encode(upload.untracked.map((path) => `${path}\0`).join(""))
1276
- },
1277
- ...upload.untrackedTarball === void 0 ? [] : [{ name: STAGED_FILES.untrackedTarball, content: upload.untrackedTarball }]
1278
- ];
1279
- }
1280
- async function stage(context, request2, signal, progress) {
1281
- if (signal.aborted) return { kind: "aborted" };
1282
- const { sandbox, phase, step } = request2;
1283
- const section = phase === "apply" ? void 0 : phase;
1284
- if (section !== void 0)
1285
- await progress.emit({ kind: "output-started", section, sandbox: sandbox.name, region: request2.region });
1286
- const ran = await runStep(
1287
- context,
1288
- {
1289
- sandbox,
1290
- phase,
1291
- label: step.label,
1292
- script: step.script,
1293
- ...request2.secrets === void 0 ? {} : { secrets: request2.secrets }
1294
- },
1295
- progress,
1296
- signal
1297
- );
1298
- if (ran.kind === "succeeded") {
1299
- if (section !== void 0) await progress.emit({ kind: "output-ended", section, outcome: "finished" });
1300
- return { kind: "ok", value: ran.ms };
1301
- }
1302
- const stop = ran.kind === "exited" ? {
1303
- kind: "failed",
1304
- failure: { kind: `${phase}-failed`, label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1305
- } : sandboxStop("run-script", ran.failure);
1306
- if (section !== void 0)
1307
- await progress.emit({ kind: "output-ended", section, outcome: stop.kind === "aborted" ? "stopped" : "failed" });
1308
- return stop;
1309
- }
1310
-
1311
- // src/runner/scope.ts
1312
- var CREATE_SETTLE_MS = 2e4;
1313
- var SNAPSHOT_SETTLE_MS = 2 * 6e4;
1314
- function runnerSandboxScope(context, progress, keep) {
1315
- const { runnerSandboxes: sandboxes, timer, clock } = context;
1316
- const live = /* @__PURE__ */ new Set();
1317
- const creating = /* @__PURE__ */ new Set();
1318
- const saving = /* @__PURE__ */ new Set();
1319
- const notStopped = [];
1320
- const notDeleted = [];
1321
- let kept = null;
1322
- let notKept = null;
1323
- let closing;
1324
- const track = (set, task) => {
1325
- set.add(task);
1326
- const forget = () => set.delete(task);
1327
- void task.then(forget, forget);
1328
- return task;
1329
- };
1330
- const remove = async (sandbox) => {
1331
- const deleted = await sandboxes.delete(sandbox);
1332
- if (!deleted.ok)
1333
- notDeleted.push({ name: sandbox.name, role: sandbox.role, message: failureMessage(deleted.failure) });
1334
- };
1335
- const stopAndRemove = async (sandbox) => {
1336
- const stopped = await sandboxes.stop(sandbox);
1337
- if (!stopped.ok) {
1338
- notStopped.push({
1339
- name: sandbox.name,
1340
- role: sandbox.role,
1341
- timeoutMinutes: Math.round(sandbox.timeoutMs / 6e4),
1342
- message: failureMessage(stopped.failure)
1343
- });
1344
- return;
1345
- }
1346
- await remove(sandbox);
1347
- };
1348
- const keepOrRemove = async (sandbox) => {
1349
- const keepMs = sandbox.role === "runner" ? keep.keepMs() : 0;
1350
- if (keepMs <= 0) return await stopAndRemove(sandbox);
1351
- const keeping = await sandboxes.keepRunning(sandbox, { until: new Date(clock.now().getTime() + keepMs) });
1352
- if (!keeping.ok) {
1353
- notKept = { name: sandbox.name, message: failureMessage(keeping.failure) };
1354
- return await stopAndRemove(sandbox);
1355
- }
1356
- kept = { name: sandbox.name, stopsAt: keeping.value.stopsAt.toISOString() };
1357
- await progress.emit({ kind: "sandbox-kept", ...kept });
1358
- };
1359
- const owned = (start) => {
1360
- if (closing !== void 0) return Promise.resolve({ ok: false, failure: { kind: "aborted" } });
1361
- return track(
1362
- creating,
1363
- (async () => {
1364
- const started = await start();
1365
- if (!started.ok) return started;
1366
- if (closing !== void 0) {
1367
- await stopAndRemove(started.value);
1368
- return { ok: false, failure: { kind: "aborted" } };
1369
- }
1370
- live.add(started.value);
1371
- return started;
1372
- })()
1373
- );
1374
- };
1375
- return {
1376
- get closed() {
1377
- return closing !== void 0;
1378
- },
1379
- startBuildSandbox: (access, request2) => owned(() => sandboxes.startBuildSandbox(access, request2)),
1380
- startRunnerSandbox: (access, request2) => owned(() => sandboxes.startRunnerSandbox(access, request2)),
1381
- saveSnapshot: (sandbox, request2) => track(
1382
- saving,
1383
- (async () => {
1384
- const saved = await sandboxes.saveSnapshot(sandbox, request2);
1385
- if (saved.ok && live.delete(sandbox)) await remove(sandbox);
1386
- return saved;
1387
- })()
1388
- ),
1389
- close() {
1390
- closing ??= (async () => {
1391
- if (saving.size > 0) await progress.emit({ kind: "waiting-for-snapshot", settleMs: SNAPSHOT_SETTLE_MS });
1392
- await Promise.all([
1393
- settleWithin(timer, creating, CREATE_SETTLE_MS),
1394
- settleWithin(timer, saving, SNAPSHOT_SETTLE_MS)
1395
- ]);
1396
- const held = [...live];
1397
- live.clear();
1398
- await Promise.all(held.map(keepOrRemove));
1399
- return { kept, notKept, notStopped: [...notStopped], notDeleted: [...notDeleted] };
1400
- })();
1401
- return closing;
1402
- }
858
+ } catch (error) {
859
+ return { ok: false, problem: `threw for ${describeResourceKeys(resourceKeys)}: ${errorMessage(error)}` };
860
+ }
861
+ return isPositiveInteger(returned) ? { ok: true, vcpus: returned } : {
862
+ ok: false,
863
+ problem: `must return a positive whole number, not ${describeRecipeValue(returned)} for ${describeResourceKeys(resourceKeys)}`
1403
864
  };
1404
865
  }
1405
- async function settleWithin(timer, tasks, ms) {
1406
- if (tasks.size === 0) return;
1407
- const done = new AbortController();
1408
- await Promise.race([Promise.allSettled(tasks), timer.sleep(ms, done.signal)]);
1409
- done.abort();
866
+ function describeResourceKeys(names) {
867
+ const last = names.at(-1);
868
+ if (last === void 0) return "a run with no resource";
869
+ return `a run with ${names.length === 1 ? last : `${names.slice(0, -1).join(", ")} and ${last}`}`;
1410
870
  }
1411
- function failureMessage(failure) {
1412
- return failure.message ?? failure.kind;
871
+ function describeRecipeValue(value) {
872
+ if (typeof value === "string") return JSON.stringify(value);
873
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
874
+ if (value === null) return "null";
875
+ if (value === void 0) return "undefined";
876
+ if (typeof value === "function") return "a function";
877
+ if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array";
878
+ if (typeof value === "object") return "an object";
879
+ return `a ${typeof value}`;
880
+ }
881
+ function errorMessage(error) {
882
+ return error instanceof Error ? error.message : String(error);
883
+ }
884
+ function orDefault(value, fallback) {
885
+ return value === void 0 ? fallback : value;
886
+ }
887
+ function isRecord(value) {
888
+ return typeof value === "object" && value !== null && !Array.isArray(value);
889
+ }
890
+ function isNonEmptyString(value) {
891
+ return typeof value === "string" && value.length > 0;
892
+ }
893
+ function isPositiveInteger(value) {
894
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
895
+ }
896
+ function isRelativePath(value) {
897
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split(/[/\\]/).includes("..");
1413
898
  }
1414
899
 
1415
- // src/runner/snapshot-save.ts
1416
- var FAILURE_TAIL_LINES = 3;
1417
- var TEMP_DIRECTORIES = ["/tmp", "/var/tmp", '"${TMPDIR:-}"'];
1418
- function scrubGitScript(root = SANDBOX_ROOT) {
1419
- return ["set -euo pipefail", `cd ${root}`, ...RESET_TO_BASE].join("\n");
900
+ // src/runner/snapshot-key.ts
901
+ var SNAPSHOT_FORMAT = 3;
902
+ var SANDBOX_ROOT = "/vercel/sandbox";
903
+ var STAGED_FILES = {
904
+ baseTarball: "base.tgz",
905
+ baseFileList: "base-files",
906
+ patch: "run.patch",
907
+ untrackedTarball: "untracked.tgz",
908
+ untrackedFileList: "untracked-files"
909
+ };
910
+ var GIT_IDENTITY = "-c user.email=storm-runner@vercel.invalid -c user.name='storm runner' -c commit.gpgsign=false";
911
+ function bashScript(lines, root = SANDBOX_ROOT) {
912
+ return ["set -euo pipefail", `cd ${root}`, ...lines].join("\n");
1420
913
  }
1421
- function scrubTempScript(directories = TEMP_DIRECTORIES) {
1422
- return [
1423
- "set -euo pipefail",
1424
- `for dir in ${directories.join(" ")}; do`,
1425
- ' [ -n "$dir" ] && [ -d "$dir" ] || continue',
1426
- ' find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
1427
- ' if [ -n "$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)" ]; then',
1428
- ' sudo -n find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
1429
- " fi",
1430
- ' left=$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)',
1431
- ` if [ -n "$left" ]; then echo "couldn't empty $dir: $left is left" >&2; exit 1; fi`,
1432
- "done"
1433
- ].join("\n");
1434
- }
1435
- async function saveDevSnapshot(context, request2, control, progress) {
1436
- const saved = await saveOnce(context, request2, control, progress);
1437
- if (saved.save.kind !== "saved") await progress.emit({ kind: "dev-snapshot-not-saved", save: saved.save });
1438
- return saved;
1439
- }
1440
- async function saveOnce(context, request2, control, progress) {
1441
- const unsaved = (save) => ({
1442
- save,
1443
- entry: null,
1444
- cacheFailure: null
1445
- });
1446
- const { ready, branch, head: head2 } = request2;
914
+ function baseIndexScript(base, staging) {
915
+ const tarball = `${staging}/${STAGED_FILES.baseTarball}`;
916
+ const fileList = `${staging}/${STAGED_FILES.baseFileList}`;
917
+ return bashScript([
918
+ `tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
919
+ `rm -f ${tarball}`,
920
+ "git -c init.defaultBranch=main init -q",
921
+ `git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
922
+ `rm -f ${fileList}`,
923
+ `git ${GIT_IDENTITY} commit -q --no-verify -m 'base ${base}'`
924
+ ]);
925
+ }
926
+ function applyScript(staging, root = SANDBOX_ROOT) {
927
+ const patch = `${staging}/${STAGED_FILES.patch}`;
928
+ const tarball = `${staging}/${STAGED_FILES.untrackedTarball}`;
929
+ const fileList = `${staging}/${STAGED_FILES.untrackedFileList}`;
930
+ return bashScript(
931
+ [
932
+ "root=$(git rev-list --max-parents=0 HEAD)",
933
+ 'git reset -q --hard "$root"',
934
+ "git clean -ffdq",
935
+ // A build may have rewritten tracked files with the same content.
936
+ "git update-index -q --refresh || true",
937
+ `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
938
+ `if [ -s ${tarball} ]; then`,
939
+ ` tar --warning=no-unknown-keyword -xzf ${tarball} -C ${root}`,
940
+ ` git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
941
+ "fi",
942
+ `git ${GIT_IDENTITY} commit -q --no-verify --allow-empty -m run`,
943
+ `rm -f ${patch} ${tarball} ${fileList}`
944
+ ],
945
+ root
946
+ );
947
+ }
948
+ function snapshotKey(steps) {
949
+ const text = (list) => list.flatMap(({ label, script, secrets }) => [label, script, `secrets=${(secrets ?? []).toSorted().join(",")}`]);
950
+ return createHash2("sha256").update(
951
+ [
952
+ `format=${SNAPSHOT_FORMAT}`,
953
+ ...text(steps.toolchains),
954
+ baseIndexScript("<base>", "<staging>"),
955
+ ...text(steps.prebuild)
956
+ ].join("\0")
957
+ ).digest("hex");
958
+ }
959
+ async function snapshotStepsAt(checkout, request2) {
960
+ const context = baseStepContext(checkout, request2);
961
+ const { snapshot, secrets } = request2.recipe;
962
+ const toolchains = await resolveSteps(snapshot.toolchains, context, secrets);
963
+ if (!toolchains.ok) return { ok: false, path: ["snapshot", "toolchains"], problem: toolchains.problem };
964
+ const prebuild = await resolveSteps(snapshot.prebuild, context, secrets);
965
+ if (!prebuild.ok) return { ok: false, path: ["snapshot", "prebuild"], problem: prebuild.problem };
966
+ return {
967
+ ok: true,
968
+ toolchains: toolchains.steps,
969
+ prebuild: prebuild.steps,
970
+ key: snapshotKey({ toolchains: toolchains.steps, prebuild: prebuild.steps })
971
+ };
972
+ }
973
+
974
+ // src/runner/snapshot-build.ts
975
+ var BUILD_SANDBOX_TIMEOUT_MS = 30 * 6e4;
976
+ var BASE_INDEX_LABEL = "Committing the base's files";
977
+ async function buildSnapshot(context, request2, control, progress) {
978
+ const { prepared, access } = request2;
979
+ const { recipe, repoRoot, base } = prepared;
1447
980
  const { scope, signal } = control;
1448
- const stopped = () => signal.aborted || scope.closed;
1449
- if (stopped()) return unsaved({ kind: "stopped" });
1450
- const { sandbox, startedFrom } = ready;
1451
- const startedAt = context.clock.now().getTime();
1452
- await progress.emit({ kind: "dev-snapshot-saving", branch });
1453
- for (const script of [scrubGitScript(), scrubTempScript()]) {
1454
- if (stopped()) return unsaved({ kind: "stopped" });
1455
- const ran = await runSaveScript(context, sandbox, script, signal);
1456
- if (ran.kind === "stopped") return unsaved(ran);
1457
- if (ran.kind === "failed") return unsaved({ kind: "failed", step: "scrub", message: ran.message });
1458
- }
1459
- if (stopped()) return unsaved({ kind: "stopped" });
981
+ const now = () => context.clock.now().getTime();
982
+ const startedAt = now();
983
+ await progress.emit({
984
+ kind: "snapshot-build-started",
985
+ base,
986
+ why: request2.why,
987
+ summary: recipe.snapshot.summary ?? [...prepared.toolchains, ...prepared.prebuild].map(({ label }) => label).join(", ")
988
+ });
989
+ const [started, archive] = await Promise.all([
990
+ scope.startBuildSandbox(access, {
991
+ region: recipe.region,
992
+ runtime: recipe.runtime,
993
+ vcpus: recipe.snapshot.vcpus,
994
+ timeoutMs: BUILD_SANDBOX_TIMEOUT_MS,
995
+ tags: runnerTags(recipe.name, "snapshot-build", request2.user)
996
+ }),
997
+ context.checkout.baseArchive({ repoRoot, base })
998
+ ]);
999
+ if (!started.ok) return sandboxStop("start-build-sandbox", started.failure);
1000
+ const sandbox = started.value;
1001
+ await progress.emit({
1002
+ kind: "sandbox-started",
1003
+ role: "snapshot-build",
1004
+ name: sandbox.name,
1005
+ region: recipe.region,
1006
+ vcpus: recipe.snapshot.vcpus,
1007
+ ms: now() - startedAt
1008
+ });
1009
+ if (!archive.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: archive.failure } };
1010
+ const staged = await context.runnerSandboxes.upload(
1011
+ sandbox,
1012
+ [
1013
+ { name: STAGED_FILES.baseTarball, content: archive.value.tarball },
1014
+ { name: STAGED_FILES.baseFileList, content: archive.value.fileList }
1015
+ ],
1016
+ signal
1017
+ );
1018
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
1019
+ const recipeStep = ({ label, script, secrets }) => ({
1020
+ label,
1021
+ script,
1022
+ secrets: stepSecrets(request2.secrets, secrets)
1023
+ });
1024
+ const steps = [
1025
+ ...prepared.toolchains.map(recipeStep),
1026
+ { label: BASE_INDEX_LABEL, script: baseIndexScript(base, staged.value.directory) },
1027
+ ...prepared.prebuild.map(recipeStep)
1028
+ ];
1029
+ await progress.emit({ kind: "output-started", section: "snapshot", sandbox: sandbox.name, region: recipe.region });
1030
+ for (const step of steps) {
1031
+ const ran = await runStep(context, { sandbox, phase: "snapshot", ...step }, progress, signal);
1032
+ if (ran.kind === "succeeded") continue;
1033
+ const stop = ran.kind === "exited" ? {
1034
+ kind: "failed",
1035
+ failure: { kind: "snapshot-build-step-failed", label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1036
+ } : sandboxStop("run-script", ran.failure);
1037
+ await progress.emit({
1038
+ kind: "output-ended",
1039
+ section: "snapshot",
1040
+ outcome: stop.kind === "aborted" ? "stopped" : "failed"
1041
+ });
1042
+ return stop;
1043
+ }
1044
+ await progress.emit({ kind: "output-ended", section: "snapshot", outcome: "finished" });
1045
+ if (signal.aborted) return { kind: "aborted" };
1046
+ await progress.emit({ kind: "snapshot-saving" });
1460
1047
  const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
1461
- if (!saved.ok)
1462
- return unsaved(
1463
- saved.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", step: "save-snapshot", message: saved.failure.message }
1464
- );
1465
- if (signal.aborted) return unsaved({ kind: "stopped" });
1466
- const savedAt2 = context.clock.now();
1048
+ if (!saved.ok) return sandboxStop("save-snapshot", saved.failure);
1049
+ const savedAt = context.clock.now();
1467
1050
  const entry = {
1468
- teamId: startedFrom.teamId,
1469
- projectId: startedFrom.projectId,
1470
- region: startedFrom.region,
1471
- runtime: startedFrom.runtime,
1472
- recipeName: startedFrom.recipeName,
1473
- snapshotKey: startedFrom.snapshotKey,
1474
- base: startedFrom.base,
1475
- ...branch === null ? {} : { branch },
1476
- head: head2,
1477
- repoRoot: ready.repoRoot,
1051
+ teamId: access.teamId,
1052
+ projectId: access.projectId,
1053
+ region: recipe.region,
1054
+ runtime: recipe.runtime,
1055
+ recipeName: recipe.name,
1056
+ snapshotKey: prepared.snapshotKey,
1057
+ base,
1478
1058
  snapshotId: saved.value.snapshotId,
1479
- createdAt: savedAt2.toISOString(),
1480
- expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1059
+ createdAt: savedAt.toISOString(),
1060
+ expiresAt: saved.value.expiresAt ?? new Date(savedAt.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1481
1061
  };
1482
1062
  const written = await context.runnerSnapshots.writeEntry(entry);
1483
1063
  if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
1484
- const ms = savedAt2.getTime() - startedAt;
1064
+ const ms = now() - startedAt;
1485
1065
  await progress.emit({
1486
- kind: "dev-snapshot-saved",
1066
+ kind: "snapshot-built",
1487
1067
  snapshotId: entry.snapshotId,
1488
- branch,
1489
- head: head2,
1068
+ base,
1490
1069
  ms,
1491
- sizeBytes: saved.value.sizeBytes
1070
+ sizeBytes: saved.value.sizeBytes,
1071
+ builtBehind: prepared.commitsAfterBase
1492
1072
  });
1493
1073
  return {
1494
- save: {
1495
- kind: "saved",
1496
- snapshotId: entry.snapshotId,
1497
- base: entry.base,
1498
- branch,
1499
- head: head2,
1500
- ms,
1501
- sizeBytes: saved.value.sizeBytes,
1502
- entryWritten: written.ok
1503
- },
1504
- entry,
1505
- cacheFailure: written.ok ? null : written.failure
1506
- };
1507
- }
1508
- async function runSaveScript(context, sandbox, script, signal) {
1509
- const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
1510
- const tail = outputTail(FAILURE_TAIL_LINES);
1511
- const keep = (text) => {
1512
- for (const line of splitLines(text)) tail.add(line);
1074
+ kind: "ok",
1075
+ value: { entry, ms, sizeBytes: saved.value.sizeBytes, cacheFailure: written.ok ? null : written.failure }
1513
1076
  };
1514
- const ran = await context.runnerSandboxes.runScript(
1515
- sandbox,
1516
- { script, env: STEP_ENV },
1517
- ({ stream, data }) => keep(splitters[stream].push(data)),
1518
- signal
1519
- );
1520
- keep(splitters.stdout.flush());
1521
- keep(splitters.stderr.flush());
1522
- if (!ran.ok)
1523
- return ran.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", message: ran.failure.message };
1524
- const { exitCode } = ran.value;
1525
- if (exitCode === 0) return { kind: "ok" };
1526
- const lines = tail.lines();
1527
- const ended = exitCode === null ? "ended without an exit code" : `exited ${exitCode}`;
1528
- return { kind: "failed", message: lines.length === 0 ? ended : `${ended}: ${lines.join(" / ")}` };
1529
- }
1530
-
1531
- // src/runner/snapshot-start.ts
1532
- function chooseSnapshotStart(read, owner) {
1533
- const pick = pickSnapshot(read.candidates, owner);
1534
- if (pick === void 0)
1535
- return { kind: "build", why: { kind: "no-snapshot", rejected: snapshotRejections(read, owner) } };
1536
- return { kind: "reuse", candidate: pick };
1537
1077
  }
1538
1078
 
1539
1079
  // src/runner/build-snapshots.ts
1540
1080
  async function prepareSnapshotBuild(context, request2) {
1541
- const { recipe, mode } = request2;
1542
- if (mode.kind === "checkout") {
1543
- const prepared = await prepareRunner(context, {
1544
- cwd: request2.cwd,
1545
- recipe,
1546
- vcpusRun: request2.vcpusRun,
1547
- reuseDevSnapshots: recipe.reuseDevSnapshot
1548
- });
1549
- if (prepared.kind !== "ok") return prepared;
1550
- return { kind: "ok", build: { kind: "checkout", prepared: prepared.prepared, full: mode.full } };
1551
- }
1552
1081
  const { checkout } = context;
1082
+ const { recipe, ref } = request2;
1553
1083
  const root = await checkout.repositoryRoot({ cwd: request2.cwd });
1554
1084
  if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
1555
1085
  const repoRoot = root.value;
1556
1086
  const head2 = await checkout.head({ repoRoot });
1557
1087
  if (!head2.ok) return { kind: "checkout-failed", failure: head2.failure };
1088
+ const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1089
+ if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1090
+ const mergeBase = resolved.kind === "resolved" ? { commit: resolved.base, ref: resolved.ref } : null;
1558
1091
  const submodules2 = await checkout.submodules({ repoRoot });
1559
1092
  if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
1560
1093
  if (submodules2.value.length > 0) return { kind: "submodules", paths: [...submodules2.value] };
1561
- const resolved = await checkout.resolveCommit({ repoRoot, ref: mode.ref });
1562
- if (!resolved.ok) return { kind: "checkout-failed", failure: resolved.failure };
1563
- if (resolved.value === null) return { kind: "ref-not-found", ref: mode.ref };
1564
- const base = resolved.value;
1094
+ let base;
1095
+ if (ref === void 0) {
1096
+ if (resolved.kind !== "resolved") return resolved;
1097
+ base = resolved.base;
1098
+ } else {
1099
+ const commit = await checkout.resolveCommit({ repoRoot, ref });
1100
+ if (!commit.ok) return { kind: "checkout-failed", failure: commit.failure };
1101
+ if (commit.value === null) return { kind: "ref-not-found", ref };
1102
+ base = commit.value;
1103
+ }
1565
1104
  const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
1566
1105
  if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1567
1106
  const listed = await context.runnerSnapshots.listEntries();
1568
1107
  const now = context.clock.now();
1569
1108
  const cached = (listed.ok ? listed.value.entries : []).filter(
1570
- (entry) => !isDevEntry(entry) && entry.base === base && entry.recipeName === recipe.name && entry.region === recipe.region && entry.runtime === recipe.runtime && entry.snapshotKey === steps.key && hasTimeLeft(entry, now)
1109
+ (entry) => entry.base === base && entry.recipeName === recipe.name && entry.region === recipe.region && entry.runtime === recipe.runtime && entry.snapshotKey === steps.key && hasTimeLeft(entry, now)
1571
1110
  );
1572
- const warnings = [];
1573
- if (head2.value.dirty) warnings.push({ kind: "uncommitted" });
1574
- let onBaseRef = false;
1575
- for (const ref of recipe.baseRefs) {
1576
- const contained = await checkout.contains({ repoRoot, ancestor: base, descendant: ref });
1577
- if (contained.ok && contained.value) onBaseRef = true;
1578
- }
1579
- if (!onBaseRef) warnings.push({ kind: "not-on-base-ref", refs: recipe.baseRefs });
1580
- const inHistory = await checkout.contains({ repoRoot, ancestor: base, descendant: "HEAD" });
1581
- const afterBase = inHistory.ok && inHistory.value ? await checkout.commitCount({ repoRoot, from: base, to: "HEAD" }) : void 0;
1111
+ const atMergeBase = base === mergeBase?.commit;
1112
+ let commitsAfterBase = null;
1113
+ if (atMergeBase) {
1114
+ const counted = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
1115
+ if (!counted.ok) return { kind: "checkout-failed", failure: counted.failure };
1116
+ commitsAfterBase = counted.value;
1117
+ }
1582
1118
  return {
1583
1119
  kind: "ok",
1584
1120
  build: {
1585
- kind: "base",
1586
1121
  plan: {
1587
1122
  recipe,
1588
1123
  repoRoot,
@@ -1590,20 +1125,20 @@ async function prepareSnapshotBuild(context, request2) {
1590
1125
  toolchains: steps.toolchains,
1591
1126
  prebuild: steps.prebuild,
1592
1127
  snapshotKey: steps.key,
1593
- commitsAfterBase: afterBase?.ok === true ? afterBase.value : null
1128
+ commitsAfterBase
1594
1129
  },
1595
- ref: mode.ref,
1596
1130
  head: head2.value,
1131
+ ref: ref ?? null,
1132
+ mergeBase,
1133
+ atMergeBase,
1597
1134
  cached,
1598
- full: mode.full,
1599
- warnings
1135
+ full: request2.full
1600
1136
  }
1601
1137
  };
1602
1138
  }
1603
- var ABORTED_EARLY = { kind: "aborted", baseSnapshot: null, dropped: null };
1604
1139
  async function buildSnapshots(context, request2, control, progress) {
1605
1140
  const { signal } = control;
1606
- const scope = runnerSandboxScope(context, progress, { keepMs: () => 0 });
1141
+ const scope = runnerSandboxScope(context, progress, { keepMs: 0 });
1607
1142
  const stop = () => {
1608
1143
  void progress.emit({ kind: "stopping", commandRunning: false, keepMs: 0 }).catch(() => void 0);
1609
1144
  void scope.close().catch(() => void 0);
@@ -1623,84 +1158,27 @@ async function buildSnapshots(context, request2, control, progress) {
1623
1158
  async function buildIn(context, request2, control, progress) {
1624
1159
  const { build, access, user, secrets } = request2;
1625
1160
  const { signal } = control;
1626
- if (signal.aborted) return ABORTED_EARLY;
1627
- if (build.kind === "base") {
1628
- const cached = build.cached.find((entry3) => entry3.teamId === access.teamId && entry3.projectId === access.projectId);
1629
- if (!build.full && cached !== void 0) return { kind: "up-to-date", snapshot: cached };
1630
- const built2 = await buildSnapshot(
1631
- context,
1632
- { prepared: build.plan, access, user, secrets, why: { kind: build.full ? "full" : "base" } },
1633
- control,
1634
- progress
1635
- );
1636
- if (built2.kind === "aborted") return ABORTED_EARLY;
1637
- if (built2.kind !== "ok") return built2;
1638
- const { entry: entry2, cacheFailure: cacheFailure2 } = built2.value;
1639
- const dropped2 = build.full && cacheFailure2 === null ? await dropOn(context, entry2, progress) : null;
1640
- if (signal.aborted) return { kind: "aborted", baseSnapshot: savedBaseOf(built2.value), dropped: dropped2 };
1641
- return baseOnlyEnd(built2.value, dropped2);
1642
- }
1643
- const { prepared } = build;
1644
- const start = build.full ? { kind: "build", why: { kind: "full" } } : chooseSnapshotStart(prepared, access);
1645
- if (start.kind === "reuse") {
1646
- const { entry: entry2 } = start.candidate;
1647
- if (isDevEntry(entry2) && entry2.head === prepared.head.commit && !prepared.head.dirty)
1648
- return { kind: "up-to-date", snapshot: entry2 };
1649
- if (prepared.devSnapshots !== "reuse") return { kind: "up-to-date", snapshot: entry2 };
1650
- }
1651
- const obtained = await obtainSnapshot(context, { prepared, access, user, secrets, start }, control, progress);
1652
- if (obtained.kind === "aborted") return ABORTED_EARLY;
1653
- if (obtained.kind !== "ok") return obtained;
1654
- const { built } = obtained.value;
1655
- const baseSnapshot = built === null ? null : savedBaseOf(built);
1656
- const dropped = build.full && baseSnapshot?.cached === true ? await dropOn(context, baseSnapshot.entry, progress) : null;
1657
- const aborted = { kind: "aborted", baseSnapshot, dropped };
1658
- if (signal.aborted) return aborted;
1659
- if (prepared.devSnapshots !== "reuse")
1660
- return built === null ? { kind: "up-to-date", snapshot: obtained.value.entry } : baseOnlyEnd(built, dropped);
1661
- const ready = await readyRunner(
1662
- context,
1663
- { prepared, access, user, secrets, start: obtained.value },
1664
- control,
1665
- progress
1666
- );
1667
- if (ready.kind === "aborted") return aborted;
1668
- if (ready.kind !== "ready") return ready;
1669
- const { runner } = ready;
1670
- const saved = await saveDevSnapshot(
1161
+ if (signal.aborted) return { kind: "aborted", snapshot: null };
1162
+ const cached = build.cached.find((entry2) => entry2.teamId === access.teamId && entry2.projectId === access.projectId);
1163
+ if (!build.full && cached !== void 0) return { kind: "up-to-date", snapshot: cached };
1164
+ const why = build.full ? "full" : build.ref === null ? "no-snapshot" : "base";
1165
+ const built = await buildSnapshot(
1671
1166
  context,
1672
- { ready: runner, branch: prepared.head.branch, head: prepared.head.commit },
1167
+ {
1168
+ prepared: build.plan,
1169
+ access,
1170
+ user,
1171
+ secrets,
1172
+ why: why === "no-snapshot" ? { kind: why, rejected: [] } : { kind: why }
1173
+ },
1673
1174
  control,
1674
1175
  progress
1675
1176
  );
1676
- if (saved.entry === null) {
1677
- const { save: save2 } = saved;
1678
- return save2.kind === "stopped" ? aborted : { kind: "dev-snapshot-not-saved", step: save2.step, message: save2.message, baseSnapshot };
1679
- }
1680
- const { entry, cacheFailure, save } = saved;
1681
- if (cacheFailure !== null)
1682
- return { kind: "not-cached", snapshot: entry, failure: cacheFailure, baseSnapshot, dropped };
1683
- return {
1684
- kind: "built",
1685
- baseSnapshot,
1686
- startedFrom: runner.startedFrom,
1687
- devSnapshot: { entry, ms: save.ms, sizeBytes: save.sizeBytes },
1688
- dropped
1689
- };
1690
- }
1691
- function savedBaseOf(built) {
1692
- return { entry: built.entry, cached: built.cacheFailure === null };
1693
- }
1694
- function baseOnlyEnd(built, dropped) {
1695
- const baseSnapshot = savedBaseOf(built);
1696
- return built.cacheFailure === null ? { kind: "built", baseSnapshot, startedFrom: null, devSnapshot: null, dropped } : { kind: "not-cached", snapshot: built.entry, failure: built.cacheFailure, baseSnapshot, dropped };
1697
- }
1698
- async function dropOn(context, built, progress) {
1699
- const dropped = await dropDevSnapshotsOn(context, built);
1700
- if (dropped.snapshotIds.length > 0)
1701
- await progress.emit({ kind: "dev-snapshots-dropped", snapshotIds: dropped.snapshotIds });
1702
- for (const { message } of dropped.failures) await progress.emit({ kind: "dev-snapshots-not-dropped", message });
1703
- return dropped;
1177
+ if (built.kind === "aborted") return { kind: "aborted", snapshot: null };
1178
+ if (built.kind !== "ok") return built;
1179
+ const { entry, cacheFailure, ms, sizeBytes } = built.value;
1180
+ if (signal.aborted) return { kind: "aborted", snapshot: { entry, cached: cacheFailure === null } };
1181
+ return cacheFailure === null ? { kind: "built", snapshot: entry, ms, sizeBytes } : { kind: "not-cached", snapshot: entry, failure: cacheFailure };
1704
1182
  }
1705
1183
 
1706
1184
  // src/runner/live/user.ts
@@ -1733,13 +1211,12 @@ async function inspectSnapshotCache(context, request2) {
1733
1211
  directory,
1734
1212
  checkout: null,
1735
1213
  picking: { kind: "none", why: "no-checkout" },
1736
- snapshots: shown.map((entry) => unchecked(entry, now, null)),
1214
+ snapshots: shown.map((entry) => unchecked(entry, now)),
1737
1215
  unreadable
1738
1216
  }
1739
1217
  };
1740
1218
  }
1741
1219
  const repoRoot = root.value;
1742
- const savedHere = (entry) => isDevEntry(entry) ? entry.repoRoot === repoRoot : null;
1743
1220
  const resolved = recipe === void 0 ? void 0 : await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1744
1221
  if (resolved?.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1745
1222
  if (recipe === void 0 || resolved === void 0 || resolved.kind !== "resolved") {
@@ -1749,7 +1226,7 @@ async function inspectSnapshotCache(context, request2) {
1749
1226
  directory,
1750
1227
  checkout: { repoRoot, head: head2.value, mergeBase: null },
1751
1228
  picking: { kind: "none", why: recipe === void 0 ? "no-recipe" : "no-base" },
1752
- snapshots: shown.map((entry) => unchecked(entry, now, savedHere(entry))),
1229
+ snapshots: shown.map((entry) => unchecked(entry, now)),
1753
1230
  unreadable
1754
1231
  }
1755
1232
  };
@@ -1759,69 +1236,42 @@ async function inspectSnapshotCache(context, request2) {
1759
1236
  if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1760
1237
  const afterBase = await checkout.commitCount({ repoRoot, from: mergeBase, to: "HEAD" });
1761
1238
  if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
1762
- const classified = await classifySnapshotEntries(context, {
1239
+ const read = classifySnapshotEntries(context, {
1763
1240
  entries,
1764
- repoRoot,
1765
1241
  recipe,
1766
1242
  base: mergeBase,
1767
1243
  snapshotKey: steps.key,
1768
- commitsAfterBase: afterBase.value,
1769
- devSnapshots: devSnapshotReuse(recipe, recipe.reuseDevSnapshot)
1244
+ commitsAfterBase: afterBase.value
1770
1245
  });
1771
- if (!classified.ok) return { kind: "checkout-failed", failure: classified.failure };
1772
- const read = classified.value;
1773
1246
  const owners = new Map(read.candidates.map(({ entry }) => [`${entry.teamId}\0${entry.projectId}`, entry]));
1774
1247
  const picked = /* @__PURE__ */ new Set();
1775
1248
  for (const owner of owners.values()) {
1776
- const start = chooseSnapshotStart(read, owner);
1777
- if (start.kind === "reuse") picked.add(start.candidate);
1249
+ const pick = pickSnapshot(read.candidates, owner);
1250
+ if (pick !== void 0) picked.add(pick);
1778
1251
  }
1779
- const inHistory = /* @__PURE__ */ new Map();
1780
- const behind = /* @__PURE__ */ new Map();
1252
+ const place = historyPlacer(context, { repoRoot, mergeBase, commitsAfterBase: afterBase.value });
1781
1253
  const snapshots = [];
1782
1254
  for (const verdict of read.verdicts) {
1783
1255
  const { entry } = verdict;
1784
1256
  if (!shows(entry)) continue;
1785
- const builtAt = builtAtCommit(entry);
1786
- const kind2 = isDevEntry(entry) ? "dev" : "base";
1787
1257
  const expired = isExpiredEntry(entry, now);
1788
1258
  if (verdict.kind === "candidate") {
1789
1259
  const { candidate } = verdict;
1790
- const isPicked = picked.has(candidate);
1791
1260
  snapshots.push({
1792
1261
  entry,
1793
- kind: kind2,
1794
- builtAt,
1795
1262
  inHistory: true,
1796
1263
  builtBehind: candidate.builtBehind,
1797
- savedHere: savedHere(entry),
1798
1264
  expired,
1799
- picked: isPicked,
1800
- reason: isPicked ? null : "not-picked"
1265
+ picked: picked.has(candidate),
1266
+ reason: null
1801
1267
  });
1802
1268
  continue;
1803
1269
  }
1804
- let contained = inHistory.get(builtAt);
1805
- if (contained === void 0) {
1806
- const asked = await checkout.contains({ repoRoot, ancestor: builtAt, descendant: "HEAD" });
1807
- if (!asked.ok) return { kind: "checkout-failed", failure: asked.failure };
1808
- contained = asked.value;
1809
- inHistory.set(builtAt, contained);
1810
- }
1811
- let builtBehind = contained ? behind.get(builtAt) : void 0;
1812
- if (contained && builtBehind === void 0) {
1813
- const counted = await checkout.commitCount({ repoRoot, from: builtAt, to: "HEAD" });
1814
- if (!counted.ok) return { kind: "checkout-failed", failure: counted.failure };
1815
- builtBehind = counted.value;
1816
- behind.set(builtAt, builtBehind);
1817
- }
1270
+ const placed = await place(entry.base);
1271
+ if (!placed.ok) return { kind: "checkout-failed", failure: placed.failure };
1818
1272
  snapshots.push({
1819
1273
  entry,
1820
- kind: kind2,
1821
- builtAt,
1822
- inHistory: contained,
1823
- builtBehind: builtBehind ?? null,
1824
- savedHere: savedHere(entry),
1274
+ ...placed.value,
1825
1275
  expired,
1826
1276
  picked: false,
1827
1277
  reason: verdict.kind === "rejected" ? verdict.rejection.reason : "other-recipe"
@@ -1838,19 +1288,36 @@ async function inspectSnapshotCache(context, request2) {
1838
1288
  }
1839
1289
  };
1840
1290
  }
1841
- function unchecked(entry, now, savedHere) {
1291
+ function unchecked(entry, now) {
1842
1292
  return {
1843
1293
  entry,
1844
- kind: isDevEntry(entry) ? "dev" : "base",
1845
- builtAt: builtAtCommit(entry),
1846
1294
  inHistory: null,
1847
1295
  builtBehind: null,
1848
- savedHere,
1849
1296
  expired: isExpiredEntry(entry, now),
1850
1297
  picked: false,
1851
1298
  reason: null
1852
1299
  };
1853
1300
  }
1301
+ function historyPlacer(context, request2) {
1302
+ const { repoRoot } = request2;
1303
+ const known = /* @__PURE__ */ new Map([
1304
+ [request2.mergeBase, { inHistory: true, builtBehind: request2.commitsAfterBase }]
1305
+ ]);
1306
+ return async (base) => {
1307
+ const answer = known.get(base);
1308
+ if (answer !== void 0) return { ok: true, value: answer };
1309
+ const contained = await context.checkout.contains({ repoRoot, ancestor: base, descendant: "HEAD" });
1310
+ if (!contained.ok) return contained;
1311
+ let placed = { inHistory: false, builtBehind: null };
1312
+ if (contained.value) {
1313
+ const counted = await context.checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
1314
+ if (!counted.ok) return counted;
1315
+ placed = { inHistory: true, builtBehind: counted.value };
1316
+ }
1317
+ known.set(base, placed);
1318
+ return { ok: true, value: placed };
1319
+ };
1320
+ }
1854
1321
 
1855
1322
  // src/runner/live/checkout-gateway.ts
1856
1323
  import { execFile, spawn } from "node:child_process";
@@ -2488,16 +1955,10 @@ var entrySchema = z4.object({
2488
1955
  recipeName: nonEmpty,
2489
1956
  snapshotKey: nonEmpty,
2490
1957
  base: nonEmpty,
2491
- branch: nonEmpty.exactOptional(),
2492
- head: nonEmpty.exactOptional(),
2493
- repoRoot: nonEmpty.exactOptional(),
2494
1958
  snapshotId: nonEmpty,
2495
1959
  createdAt: isoTime,
2496
1960
  expiresAt: isoTime
2497
- }).refine(
2498
- (entry) => entry.head === void 0 === (entry.repoRoot === void 0) && (entry.branch === void 0 || entry.head !== void 0),
2499
- { message: "has some of branch, head and repoRoot without head and repoRoot together" }
2500
- );
1961
+ });
2501
1962
  function parseSnapshotEntry(text) {
2502
1963
  let json;
2503
1964
  try {
@@ -2517,7 +1978,7 @@ function parseSnapshotEntry(text) {
2517
1978
  return { ok: true, value: entry };
2518
1979
  }
2519
1980
  function snapshotEntryText(entry) {
2520
- const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base, branch, head: head2, repoRoot } = entry;
1981
+ const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base } = entry;
2521
1982
  const { snapshotId, createdAt, expiresAt } = entry;
2522
1983
  const record = {
2523
1984
  version: 1,
@@ -2528,9 +1989,6 @@ function snapshotEntryText(entry) {
2528
1989
  recipeName,
2529
1990
  snapshotKey: snapshotKey2,
2530
1991
  base,
2531
- ...branch === void 0 ? {} : { branch },
2532
- ...head2 === void 0 ? {} : { head: head2 },
2533
- ...repoRoot === void 0 ? {} : { repoRoot },
2534
1992
  snapshotId,
2535
1993
  createdAt,
2536
1994
  expiresAt
@@ -2621,21 +2079,71 @@ function failureAt(path, error) {
2621
2079
  return { path, message: error instanceof Error ? error.message : String(error) };
2622
2080
  }
2623
2081
 
2082
+ // src/runner/prepare.ts
2083
+ async function prepareRunner(context, request2) {
2084
+ const { checkout } = context;
2085
+ const { recipe } = request2;
2086
+ const root = await checkout.repositoryRoot({ cwd: request2.cwd });
2087
+ if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
2088
+ const repoRoot = root.value;
2089
+ const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
2090
+ if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
2091
+ if (resolved.kind === "no-base-ref") return resolved;
2092
+ const { base } = resolved;
2093
+ const submodules2 = await checkout.submodules({ repoRoot });
2094
+ if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
2095
+ if (submodules2.value.length > 0) return { kind: "submodules", paths: [...submodules2.value] };
2096
+ const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
2097
+ if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
2098
+ const vcpus = resolveVcpus(recipe, request2.vcpusRun);
2099
+ if (!vcpus.ok) return { kind: "invalid-recipe", path: ["vcpus"], problem: vcpus.problem };
2100
+ const upload = await checkout.assembleUpload({ repoRoot, base });
2101
+ if (!upload.ok) return { kind: "checkout-failed", failure: upload.failure };
2102
+ const afterBase = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
2103
+ if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
2104
+ const listing = await removeExpiredEntries(context);
2105
+ const cache = classifySnapshotEntries(context, {
2106
+ entries: listing.entries,
2107
+ recipe,
2108
+ base,
2109
+ snapshotKey: steps.key,
2110
+ commitsAfterBase: afterBase.value
2111
+ });
2112
+ return {
2113
+ kind: "ok",
2114
+ prepared: {
2115
+ recipe,
2116
+ repoRoot,
2117
+ base,
2118
+ baseRef: resolved.ref,
2119
+ toolchains: steps.toolchains,
2120
+ prebuild: steps.prebuild,
2121
+ snapshotKey: steps.key,
2122
+ vcpus: vcpus.vcpus,
2123
+ upload: upload.value,
2124
+ candidates: cache.candidates,
2125
+ rejected: cache.rejected,
2126
+ commitsAfterBase: afterBase.value,
2127
+ notes: listing.notes
2128
+ }
2129
+ };
2130
+ }
2131
+
2624
2132
  // src/runner/sandboxed-command.ts
2625
- import { posix as posix2 } from "node:path";
2133
+ import { posix } from "node:path";
2626
2134
  function sandboxedCommand(request2) {
2627
2135
  const [first = "", ...rest] = request2.argv.map((argument) => rewritePaths(argument, request2.repoRoot, SANDBOX_ROOT));
2628
- const cmd = first.includes("/") && !first.startsWith("/") ? posix2.join(request2.cwd, first) : first;
2136
+ const cmd = first.includes("/") && !first.startsWith("/") ? posix.join(request2.cwd, first) : first;
2629
2137
  return { cmd, args: rest };
2630
2138
  }
2631
2139
  function sandboxEnvironment(request2) {
2632
2140
  const bins = [
2633
- .../* @__PURE__ */ new Set([posix2.join(request2.cwd, "node_modules/.bin"), posix2.join(SANDBOX_ROOT, "node_modules/.bin")])
2141
+ .../* @__PURE__ */ new Set([posix.join(request2.cwd, "node_modules/.bin"), posix.join(SANDBOX_ROOT, "node_modules/.bin")])
2634
2142
  ];
2635
2143
  return {
2636
2144
  PATH: [...bins, request2.loginPath].filter((part) => part !== "").join(":"),
2637
2145
  NO_UPDATE_NOTIFIER: "1",
2638
- ...request2.color ? { FORCE_COLOR: "1" } : { NO_COLOR: "1" },
2146
+ ...request2.env["FORCE_COLOR"] !== void 0 || request2.env["NO_COLOR"] !== void 0 ? {} : request2.color ? { FORCE_COLOR: "1" } : { NO_COLOR: "1" },
2639
2147
  ...request2.env,
2640
2148
  [RUN_PAYLOAD_VARIABLE]: request2.runPayload
2641
2149
  };
@@ -2675,7 +2183,7 @@ async function runCommandInSandbox(context, request2, control, progress) {
2675
2183
  if (!ran.ok) {
2676
2184
  if (ran.failure.kind !== "aborted")
2677
2185
  return { kind: "failed", failure: sandboxApiFailure("run-command", ran.failure) };
2678
- await progress.emit({ kind: "command-stopped", command: posix2.basename(command.cmd) });
2186
+ await progress.emit({ kind: "command-stopped", command: posix.basename(command.cmd) });
2679
2187
  return { kind: "killed" };
2680
2188
  }
2681
2189
  return { kind: "exited", exitCode: ran.value.exitCode, ms };
@@ -2725,32 +2233,187 @@ function followTestEvents(context, runner, testEvents, kill) {
2725
2233
  };
2726
2234
  }
2727
2235
 
2728
- // src/runner/session.ts
2729
- function savedAt(runner, head2) {
2730
- const { startedFrom } = runner;
2731
- return isDevEntry(startedFrom) && startedFrom.head === head2;
2732
- }
2733
- function saveDecision(ended, signal, mode, head2) {
2734
- if (ended === void 0 || signal.aborted) return { kind: "none" };
2735
- if (mode.kind === "never") return { kind: "skip", reason: mode.reason };
2736
- if (mode.kind === "always") return { kind: "save", runner: ended.runner };
2737
- if (ended.exitCode !== 0) return { kind: "skip", reason: "command-failed" };
2738
- if (savedAt(ended.runner, head2)) return { kind: "skip", reason: "already-saved" };
2739
- return { kind: "save", runner: ended.runner };
2236
+ // src/runner/ready.ts
2237
+ import { posix as posix2 } from "node:path";
2238
+ var APPLY_LABEL = "Applying your changes";
2239
+ async function readyRunner(context, request2, control, progress) {
2240
+ const { prepared, access } = request2;
2241
+ const { recipe, repoRoot } = prepared;
2242
+ const { scope, signal } = control;
2243
+ const now = () => context.clock.now().getTime();
2244
+ if (signal.aborted) return { kind: "aborted" };
2245
+ const pick = pickSnapshot(prepared.candidates, access);
2246
+ let entry;
2247
+ if (pick !== void 0) {
2248
+ ({ entry } = pick);
2249
+ await progress.emit({
2250
+ kind: "snapshot-reused",
2251
+ snapshotId: entry.snapshotId,
2252
+ base: entry.base,
2253
+ builtBehind: pick.builtBehind
2254
+ });
2255
+ } else {
2256
+ const why = { kind: "no-snapshot", rejected: snapshotRejections(prepared, access) };
2257
+ const building = await buildSnapshot(
2258
+ context,
2259
+ { prepared, access, user: request2.user, secrets: request2.secrets, why },
2260
+ control,
2261
+ progress
2262
+ );
2263
+ if (building.kind !== "ok") return building;
2264
+ ({ entry } = building.value);
2265
+ }
2266
+ const built = pick === void 0;
2267
+ if (signal.aborted) return { kind: "aborted" };
2268
+ await progress.emit({ kind: "runner-sandbox-starting", snapshotId: entry.snapshotId });
2269
+ const startedAt = now();
2270
+ const started = await scope.startRunnerSandbox(access, {
2271
+ snapshotId: entry.snapshotId,
2272
+ region: recipe.region,
2273
+ vcpus: prepared.vcpus,
2274
+ timeoutMs: recipe.timeoutMinutes * 6e4,
2275
+ tags: runnerTags(recipe.name, "runner", request2.user)
2276
+ });
2277
+ if (!started.ok) {
2278
+ if (started.failure.kind === "snapshot-gone") {
2279
+ const removed = await context.runnerSnapshots.removeEntry(entry);
2280
+ return { kind: "snapshot-gone", entry, removal: removed.ok ? void 0 : removed.failure };
2281
+ }
2282
+ return sandboxStop("start-runner-sandbox", started.failure);
2283
+ }
2284
+ const sandbox = started.value;
2285
+ await progress.emit({
2286
+ kind: "sandbox-started",
2287
+ role: "runner",
2288
+ name: sandbox.name,
2289
+ region: recipe.region,
2290
+ vcpus: prepared.vcpus,
2291
+ ms: now() - startedAt
2292
+ });
2293
+ const changes = await uploadChanges(context, { prepared, sandbox }, signal, progress);
2294
+ if (changes.kind !== "ok") return changes;
2295
+ const applied = await stage(
2296
+ context,
2297
+ {
2298
+ sandbox,
2299
+ phase: "apply",
2300
+ step: { label: APPLY_LABEL, script: applyScript(changes.value.directory) },
2301
+ region: recipe.region
2302
+ },
2303
+ signal,
2304
+ progress
2305
+ );
2306
+ if (applied.kind !== "ok") return applied;
2307
+ const loginPath = await context.runnerSandboxes.loginPath(sandbox, signal);
2308
+ if (!loginPath.ok) return sandboxStop("login-path", loginPath.failure);
2309
+ const installed = await stage(
2310
+ context,
2311
+ {
2312
+ sandbox,
2313
+ phase: "install",
2314
+ step: recipe.run.install,
2315
+ secrets: stepSecrets(request2.secrets, recipe.run.install.secrets),
2316
+ region: recipe.region
2317
+ },
2318
+ signal,
2319
+ progress
2320
+ );
2321
+ if (installed.kind !== "ok") return installed;
2322
+ const builtOutputs = await stage(
2323
+ context,
2324
+ {
2325
+ sandbox,
2326
+ phase: "build",
2327
+ step: recipe.run.build,
2328
+ secrets: stepSecrets(request2.secrets, recipe.run.build.secrets),
2329
+ region: recipe.region
2330
+ },
2331
+ signal,
2332
+ progress
2333
+ );
2334
+ if (builtOutputs.kind !== "ok") return builtOutputs;
2335
+ return {
2336
+ kind: "ready",
2337
+ runner: {
2338
+ sandbox,
2339
+ snapshotId: entry.snapshotId,
2340
+ base: entry.base,
2341
+ built,
2342
+ builtBehind: prepared.commitsAfterBase,
2343
+ uploadBytes: changes.value.bytes,
2344
+ buildMs: builtOutputs.value,
2345
+ vcpus: prepared.vcpus,
2346
+ region: recipe.region,
2347
+ runtime: recipe.runtime,
2348
+ repoRoot,
2349
+ cwd: posix2.join(SANDBOX_ROOT, recipe.cwd),
2350
+ env: recipe.env,
2351
+ loginPath: loginPath.value
2352
+ }
2353
+ };
2354
+ }
2355
+ async function uploadChanges(context, request2, signal, progress) {
2356
+ await progress.emit({ kind: "uploading" });
2357
+ const startedAt = context.clock.now().getTime();
2358
+ const files = stagedChanges(request2.prepared.upload);
2359
+ const staged = await context.runnerSandboxes.upload(request2.sandbox, files, signal);
2360
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
2361
+ const bytes = files.reduce((sum, file) => sum + file.content.byteLength, 0);
2362
+ await progress.emit({ kind: "uploaded", bytes, ms: context.clock.now().getTime() - startedAt });
2363
+ return { kind: "ok", value: { directory: staged.value.directory, bytes } };
2364
+ }
2365
+ function stagedChanges(upload) {
2366
+ const encoder = new TextEncoder();
2367
+ return [
2368
+ { name: STAGED_FILES.patch, content: upload.patch },
2369
+ {
2370
+ name: STAGED_FILES.untrackedFileList,
2371
+ content: encoder.encode(upload.untracked.map((path) => `${path}\0`).join(""))
2372
+ },
2373
+ ...upload.untrackedTarball === void 0 ? [] : [{ name: STAGED_FILES.untrackedTarball, content: upload.untrackedTarball }]
2374
+ ];
2375
+ }
2376
+ async function stage(context, request2, signal, progress) {
2377
+ if (signal.aborted) return { kind: "aborted" };
2378
+ const { sandbox, phase, step } = request2;
2379
+ const section = phase === "apply" ? void 0 : phase;
2380
+ if (section !== void 0)
2381
+ await progress.emit({ kind: "output-started", section, sandbox: sandbox.name, region: request2.region });
2382
+ const ran = await runStep(
2383
+ context,
2384
+ {
2385
+ sandbox,
2386
+ phase,
2387
+ label: step.label,
2388
+ script: step.script,
2389
+ ...request2.secrets === void 0 ? {} : { secrets: request2.secrets }
2390
+ },
2391
+ progress,
2392
+ signal
2393
+ );
2394
+ if (ran.kind === "succeeded") {
2395
+ if (section !== void 0) await progress.emit({ kind: "output-ended", section, outcome: "finished" });
2396
+ return { kind: "ok", value: ran.ms };
2397
+ }
2398
+ const stop = ran.kind === "exited" ? {
2399
+ kind: "failed",
2400
+ failure: { kind: `${phase}-failed`, label: step.label, exitCode: ran.exitCode, tail: ran.tail }
2401
+ } : sandboxStop("run-script", ran.failure);
2402
+ if (section !== void 0)
2403
+ await progress.emit({ kind: "output-ended", section, outcome: stop.kind === "aborted" ? "stopped" : "failed" });
2404
+ return stop;
2740
2405
  }
2406
+
2407
+ // src/runner/session.ts
2741
2408
  function openRunnerSession(context, request2, control, progress) {
2742
2409
  const { signal, cleanup } = control;
2743
- const unsaved = { kind: "keep", ms: request2.keepMs };
2744
- let saveStarted = false;
2745
- const keepMs = () => saveStarted ? 0 : request2.keepMs;
2746
- const scope = runnerSandboxScope(context, progress, { keepMs });
2410
+ const scope = runnerSandboxScope(context, progress, { keepMs: request2.keepMs });
2747
2411
  const closeScope = async () => ({ ...await scope.close(), target: request2.target });
2748
2412
  let readying = false;
2749
2413
  let readied;
2750
2414
  let commandRunning = false;
2751
- let ended;
2752
2415
  const stop = () => {
2753
- void progress.emit({ kind: "stopping", commandRunning, keepMs: keepMs() }).catch(() => void 0);
2416
+ void progress.emit({ kind: "stopping", commandRunning, keepMs: request2.keepMs }).catch(() => void 0);
2754
2417
  void scope.close().catch(() => void 0);
2755
2418
  };
2756
2419
  if (signal.aborted) stop();
@@ -2760,14 +2423,10 @@ function openRunnerSession(context, request2, control, progress) {
2760
2423
  if (readying) throw new Error("the runner session readies its runner sandbox once");
2761
2424
  readying = true;
2762
2425
  const { prepared, user, secrets } = request2;
2763
- const lane = { scope, signal: laneSignal };
2764
- const start = chooseSnapshotStart(prepared, access);
2765
- const obtained = await obtainSnapshot(context, { prepared, access, user, secrets, start }, lane, progress);
2766
- if (obtained.kind !== "ok") return obtained;
2767
2426
  const outcome = await readyRunner(
2768
2427
  context,
2769
- { prepared, access, user, secrets, start: obtained.value },
2770
- lane,
2428
+ { prepared, access, user, secrets },
2429
+ { scope, signal: laneSignal },
2771
2430
  progress
2772
2431
  );
2773
2432
  if (outcome.kind === "ready") readied = outcome.runner;
@@ -2776,7 +2435,7 @@ function openRunnerSession(context, request2, control, progress) {
2776
2435
  async runCommand(command) {
2777
2436
  if (readied === void 0) throw new Error("the runner session's runner sandbox isn't ready");
2778
2437
  commandRunning = true;
2779
- const ran = await runCommandInSandbox(
2438
+ return await runCommandInSandbox(
2780
2439
  context,
2781
2440
  {
2782
2441
  runner: readied,
@@ -2787,53 +2446,21 @@ function openRunnerSession(context, request2, control, progress) {
2787
2446
  { kill: signal },
2788
2447
  progress
2789
2448
  );
2790
- if (ran.kind === "exited") ended = { runner: readied, exitCode: ran.exitCode };
2791
- return ran;
2792
2449
  },
2793
2450
  async finish() {
2794
2451
  commandRunning = false;
2795
- const { prepared } = request2;
2796
- let save = null;
2797
- let noSave = null;
2798
- let action = unsaved;
2799
- const decision = saveDecision(ended, signal, request2.save, prepared.head.commit);
2800
- switch (decision.kind) {
2801
- case "none":
2802
- break;
2803
- case "skip":
2804
- noSave = decision.reason;
2805
- await progress.emit({ kind: "dev-snapshot-skipped", reason: noSave });
2806
- break;
2807
- case "save": {
2808
- saveStarted = true;
2809
- const plan = { kind: "save", branch: prepared.head.branch };
2810
- action = plan;
2811
- const saving = saveDevSnapshot(
2812
- context,
2813
- { ready: decision.runner, branch: plan.branch, head: prepared.head.commit },
2814
- { scope, signal },
2815
- progress
2816
- );
2817
- try {
2818
- await cleanup.release(plan);
2819
- } finally {
2820
- save = (await saving).save;
2821
- }
2822
- break;
2823
- }
2824
- }
2825
- await cleanup.startCleanup(action);
2452
+ await cleanup.startCleanup();
2826
2453
  const facts = await closeScope();
2827
2454
  signal.removeEventListener("abort", stop);
2828
- await cleanup.release(action);
2829
- return { save, noSave, cleanup: facts };
2455
+ await cleanup.release();
2456
+ return facts;
2830
2457
  },
2831
2458
  async close() {
2832
2459
  signal.removeEventListener("abort", stop);
2833
2460
  try {
2834
2461
  return await closeScope();
2835
2462
  } finally {
2836
- await cleanup.release(unsaved);
2463
+ await cleanup.release();
2837
2464
  }
2838
2465
  }
2839
2466
  };
@@ -2855,7 +2482,8 @@ function checkWith(schema, value) {
2855
2482
  var SETTING_CHECKS = {
2856
2483
  scope: (value) => checkWith(nonEmptyString, value),
2857
2484
  project: (value) => checkWith(nonEmptyString, value),
2858
- runner: checkRecipe
2485
+ runner: checkRecipe,
2486
+ testPlan: (value) => checkWith(booleanOption, value)
2859
2487
  };
2860
2488
  function isConfigSettingKey(key) {
2861
2489
  return Object.hasOwn(SETTING_CHECKS, key);
@@ -3004,34 +2632,6 @@ function fileProblem(problem) {
3004
2632
  return { key: null, location: null, problem };
3005
2633
  }
3006
2634
 
3007
- // src/config/typed-options.ts
3008
- function givenOptionsOf(_definition, values) {
3009
- return values;
3010
- }
3011
- function settingsOf(_definition, settings) {
3012
- return settings;
3013
- }
3014
- function resourceOptionsOf(_definition, value) {
3015
- return value;
3016
- }
3017
-
3018
- // src/config/recipe-run.ts
3019
- var NOT_PRESENT = Object.freeze({ present: false });
3020
- function recipeRun(resources) {
3021
- const run = {
3022
- get: ({ definition }) => {
3023
- const key = defaultResourceKey(definition);
3024
- const resource = Object.hasOwn(resources, key) ? resources[key] : void 0;
3025
- if (resource === void 0 || resource.definition !== definition.name) return NOT_PRESENT;
3026
- return Object.freeze({
3027
- present: true,
3028
- value: resourceOptionsOf(definition, Object.freeze({ ...resource.options }))
3029
- });
3030
- }
3031
- };
3032
- return { run: Object.freeze(run), resourceKeys: Object.keys(resources) };
3033
- }
3034
-
3035
2635
  // src/config/errors.ts
3036
2636
  import { z as z5 } from "zod";
3037
2637
  var problemSchema = z5.object({
@@ -3122,13 +2722,25 @@ var configErrors = defineErrors({
3122
2722
  }
3123
2723
  });
3124
2724
 
2725
+ // src/config/typed-options.ts
2726
+ function givenOptionsOf(_definition, values) {
2727
+ return values;
2728
+ }
2729
+ function settingsOf(_definition, settings) {
2730
+ return settings;
2731
+ }
2732
+ function resourceOptionsOf(_definition, value) {
2733
+ return value;
2734
+ }
2735
+
3125
2736
  // src/config/resolve.ts
3126
2737
  function resolveSettings(flags, file) {
3127
2738
  const pick = (flag, fromFile) => flag !== void 0 ? { value: flag, source: "flag" } : fromFile === void 0 ? void 0 : { value: fromFile, source: "file" };
3128
2739
  return {
3129
2740
  scope: pick(flags.scope, file?.scope),
3130
2741
  project: pick(flags.project, file?.project),
3131
- runner: pick(void 0, file?.runner)
2742
+ runner: pick(void 0, file?.runner),
2743
+ testPlan: pick(void 0, file?.testPlan)
3132
2744
  };
3133
2745
  }
3134
2746
  function optionSource(definition, option, file, flags) {
@@ -3710,6 +3322,23 @@ function errorLocation(error, name) {
3710
3322
  return void 0;
3711
3323
  }
3712
3324
 
3325
+ // src/config/recipe-run.ts
3326
+ var NOT_PRESENT = Object.freeze({ present: false });
3327
+ function recipeRun(resources) {
3328
+ const run = {
3329
+ get: ({ definition }) => {
3330
+ const key = defaultResourceKey(definition);
3331
+ const resource = Object.hasOwn(resources, key) ? resources[key] : void 0;
3332
+ if (resource === void 0 || resource.definition !== definition.name) return NOT_PRESENT;
3333
+ return Object.freeze({
3334
+ present: true,
3335
+ value: resourceOptionsOf(definition, Object.freeze({ ...resource.options }))
3336
+ });
3337
+ }
3338
+ };
3339
+ return { run: Object.freeze(run), resourceKeys: Object.keys(resources) };
3340
+ }
3341
+
3713
3342
  // src/config/resolver.ts
3714
3343
  function configResolver(launcher) {
3715
3344
  return {
@@ -3741,6 +3370,10 @@ export {
3741
3370
  credentialSourceErrors,
3742
3371
  credentialResolver,
3743
3372
  configErrors,
3373
+ RUNNER_SECRET_MIN_LENGTH,
3374
+ declaredSecretValues,
3375
+ readRunnerSecrets,
3376
+ RUNNER_SNAPSHOTS_SUBPATH,
3744
3377
  parseKeepTime,
3745
3378
  systemTimer,
3746
3379
  systemClock,
@@ -3749,12 +3382,6 @@ export {
3749
3382
  parseTestEvent,
3750
3383
  redactSecrets,
3751
3384
  lineSplitter,
3752
- devSnapshotsTrusted,
3753
- RUNNER_SNAPSHOTS_SUBPATH,
3754
- prepareRunner,
3755
- RUNNER_SECRET_MIN_LENGTH,
3756
- declaredSecretValues,
3757
- readRunnerSecrets,
3758
3385
  prepareSnapshotBuild,
3759
3386
  buildSnapshots,
3760
3387
  liveCheckoutGateway,
@@ -3763,6 +3390,7 @@ export {
3763
3390
  localUserName,
3764
3391
  liveRunnerSnapshotCacheGateway,
3765
3392
  unavailableRunnerSnapshotCacheGateway,
3393
+ prepareRunner,
3766
3394
  SANDBOX_TEST_EVENTS_PATH,
3767
3395
  openRunnerSession,
3768
3396
  inspectSnapshotCache,