@cnc-tools/storm 0.12.0 → 0.13.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 (96) hide show
  1. package/dist/bin/storm.js +1 -1
  2. package/dist/build-info.js +1 -1
  3. package/dist/chunks/{chunk-4XT5RC5T.js → chunk-2NZXL6OH.js} +6 -42
  4. package/dist/chunks/{chunk-ISGQJIQM.js → chunk-5UMJNVKT.js} +1 -1
  5. package/dist/chunks/{chunk-FSP3SJ35.js → chunk-6EQKA7LI.js} +16 -46
  6. package/dist/chunks/{chunk-Y3BUNNRG.js → chunk-AX4EQZUS.js} +4 -4
  7. package/dist/chunks/{chunk-RYRJNHL7.js → chunk-DOFB2ACU.js} +3 -9
  8. package/dist/chunks/{chunk-SXW6XN4R.js → chunk-EGNP3S6C.js} +3 -3
  9. package/dist/chunks/{chunk-FK4RLDEK.js → chunk-N7E6DAUE.js} +1 -1
  10. package/dist/chunks/{chunk-U7M3ZB3Z.js → chunk-Q4TKRILH.js} +33 -167
  11. package/dist/chunks/{chunk-TMQQYHUX.js → chunk-RTILVSYQ.js} +1 -1
  12. package/dist/chunks/{chunk-7D6LC5JY.js → chunk-X4WBJIOF.js} +7 -39
  13. package/dist/chunks/{chunk-TEEZL3GA.js → chunk-YGS5VRQT.js} +11 -68
  14. package/dist/chunks/{chunk-ODQHQJLE.js → chunk-ZDJLKF2G.js} +742 -1117
  15. package/dist/chunks/{live-app-AZ5N5HBD.js → live-app-QFHS54SX.js} +4 -4
  16. package/dist/commands/exec/command.d.ts +2 -90
  17. package/dist/commands/exec/command.js +10 -10
  18. package/dist/commands/exec/define-run-command.d.ts +2 -90
  19. package/dist/commands/exec/live-view.js +18 -22
  20. package/dist/commands/exec/outcomes.d.ts +2 -106
  21. package/dist/commands/exec/outcomes.js +4 -35
  22. package/dist/commands/exec/progress.d.ts +3 -19
  23. package/dist/commands/exec/progress.js +16 -60
  24. package/dist/commands/exec/run-command.d.ts +4 -23
  25. package/dist/commands/exec/run-command.js +5 -79
  26. package/dist/commands/exec/run-metadata.d.ts +0 -6
  27. package/dist/commands/exec/run-metadata.js +2 -8
  28. package/dist/commands/exec/snapshot-text.d.ts +7 -16
  29. package/dist/commands/exec/snapshot-text.js +9 -49
  30. package/dist/commands/exec/view.js +2 -12
  31. package/dist/commands/playwright/command.d.ts +2 -90
  32. package/dist/commands/playwright/command.js +11 -11
  33. package/dist/commands/runs/facts.d.ts +1 -37
  34. package/dist/commands/runs/facts.js +4 -36
  35. package/dist/commands/runs/list/command.d.ts +0 -72
  36. package/dist/commands/runs/list/command.js +5 -5
  37. package/dist/commands/runs/list/outcomes.d.ts +0 -36
  38. package/dist/commands/runs/logs/command.js +5 -5
  39. package/dist/commands/runs/show/command.d.ts +0 -72
  40. package/dist/commands/runs/show/command.js +13 -40
  41. package/dist/commands/runs/show/metadata.js +1 -1
  42. package/dist/commands/runs/show/outcomes.d.ts +0 -36
  43. package/dist/commands/runs/show/outcomes.js +8 -42
  44. package/dist/commands/snapshots/build/command.d.ts +14 -411
  45. package/dist/commands/snapshots/build/command.js +56 -231
  46. package/dist/commands/snapshots/build/metadata.js +10 -7
  47. package/dist/commands/snapshots/build/outcomes.d.ts +11 -241
  48. package/dist/commands/snapshots/build/outcomes.js +29 -196
  49. package/dist/commands/snapshots/list/command.d.ts +2 -36
  50. package/dist/commands/snapshots/list/command.js +17 -53
  51. package/dist/commands/snapshots/list/metadata.js +1 -1
  52. package/dist/commands/snapshots/list/outcomes.d.ts +2 -37
  53. package/dist/commands/snapshots/list/outcomes.js +13 -53
  54. package/dist/commands/vitest/command.d.ts +2 -90
  55. package/dist/commands/vitest/command.js +11 -11
  56. package/dist/core/events.d.ts +5 -6
  57. package/dist/core/run-state.d.ts +7 -29
  58. package/dist/core/run-state.js +3 -26
  59. package/dist/core/run.d.ts +6 -14
  60. package/dist/core/run.js +17 -28
  61. package/dist/extensions/testserver/commands/pool/create/command.js +1 -1
  62. package/dist/run-directory/index.d.ts +1 -1
  63. package/dist/run-directory/index.js +0 -1
  64. package/dist/run-directory/recording.js +2 -2
  65. package/dist/run-directory/run-record.d.ts +14 -132
  66. package/dist/run-directory/run-record.js +8 -68
  67. package/dist/runner/build-snapshots.d.ts +50 -114
  68. package/dist/runner/build-snapshots.js +70 -159
  69. package/dist/runner/events.d.ts +4 -88
  70. package/dist/runner/gateways.d.ts +5 -23
  71. package/dist/runner/index.d.ts +5 -6
  72. package/dist/runner/index.js +1 -1
  73. package/dist/runner/live/snapshot-records.js +7 -18
  74. package/dist/runner/prepare.d.ts +11 -22
  75. package/dist/runner/prepare.js +6 -17
  76. package/dist/runner/ready.d.ts +16 -45
  77. package/dist/runner/ready.js +34 -59
  78. package/dist/runner/recipe.d.ts +0 -44
  79. package/dist/runner/recipe.js +0 -41
  80. package/dist/runner/scope.d.ts +8 -25
  81. package/dist/runner/scope.js +4 -8
  82. package/dist/runner/session.d.ts +18 -65
  83. package/dist/runner/session.js +15 -83
  84. package/dist/runner/snapshot-build.d.ts +2 -2
  85. package/dist/runner/snapshot-cache.d.ts +22 -74
  86. package/dist/runner/snapshot-cache.js +15 -107
  87. package/dist/runner/snapshot-inspect.d.ts +9 -13
  88. package/dist/runner/snapshot-inspect.js +48 -57
  89. package/dist/runner/snapshot-key.d.ts +9 -14
  90. package/dist/runner/snapshot-key.js +15 -22
  91. package/package.json +1 -1
  92. package/skills/read-run-output.md +8 -9
  93. package/dist/runner/snapshot-save.d.ts +0 -70
  94. package/dist/runner/snapshot-save.js +0 -160
  95. package/dist/runner/snapshot-start.d.ts +0 -25
  96. package/dist/runner/snapshot-start.js +0 -16
@@ -125,6 +125,201 @@ function baseStepContext(checkout, request2) {
125
125
  };
126
126
  }
127
127
 
128
+ // src/runner/scope.ts
129
+ var CREATE_SETTLE_MS = 2e4;
130
+ var SNAPSHOT_SETTLE_MS = 2 * 6e4;
131
+ function runnerSandboxScope(context, progress, keep) {
132
+ const { runnerSandboxes: sandboxes, timer, clock } = context;
133
+ const live = /* @__PURE__ */ new Set();
134
+ const creating = /* @__PURE__ */ new Set();
135
+ const saving = /* @__PURE__ */ new Set();
136
+ const notStopped = [];
137
+ const notDeleted = [];
138
+ let kept = null;
139
+ let notKept = null;
140
+ let closing;
141
+ const track = (set, task) => {
142
+ set.add(task);
143
+ const forget = () => set.delete(task);
144
+ void task.then(forget, forget);
145
+ return task;
146
+ };
147
+ const remove = async (sandbox) => {
148
+ const deleted = await sandboxes.delete(sandbox);
149
+ if (!deleted.ok)
150
+ notDeleted.push({ name: sandbox.name, role: sandbox.role, message: failureMessage(deleted.failure) });
151
+ };
152
+ const stopAndRemove = async (sandbox) => {
153
+ const stopped = await sandboxes.stop(sandbox);
154
+ if (!stopped.ok) {
155
+ notStopped.push({
156
+ name: sandbox.name,
157
+ role: sandbox.role,
158
+ timeoutMinutes: Math.round(sandbox.timeoutMs / 6e4),
159
+ message: failureMessage(stopped.failure)
160
+ });
161
+ return;
162
+ }
163
+ await remove(sandbox);
164
+ };
165
+ const keepOrRemove = async (sandbox) => {
166
+ const keepMs = sandbox.role === "runner" ? keep.keepMs : 0;
167
+ if (keepMs <= 0) return await stopAndRemove(sandbox);
168
+ const keeping = await sandboxes.keepRunning(sandbox, { until: new Date(clock.now().getTime() + keepMs) });
169
+ if (!keeping.ok) {
170
+ notKept = { name: sandbox.name, message: failureMessage(keeping.failure) };
171
+ return await stopAndRemove(sandbox);
172
+ }
173
+ kept = { name: sandbox.name, stopsAt: keeping.value.stopsAt.toISOString() };
174
+ await progress.emit({ kind: "sandbox-kept", ...kept });
175
+ };
176
+ const owned = (start) => {
177
+ if (closing !== void 0) return Promise.resolve({ ok: false, failure: { kind: "aborted" } });
178
+ return track(
179
+ creating,
180
+ (async () => {
181
+ const started = await start();
182
+ if (!started.ok) return started;
183
+ if (closing !== void 0) {
184
+ await stopAndRemove(started.value);
185
+ return { ok: false, failure: { kind: "aborted" } };
186
+ }
187
+ live.add(started.value);
188
+ return started;
189
+ })()
190
+ );
191
+ };
192
+ return {
193
+ startBuildSandbox: (access, request2) => owned(() => sandboxes.startBuildSandbox(access, request2)),
194
+ startRunnerSandbox: (access, request2) => owned(() => sandboxes.startRunnerSandbox(access, request2)),
195
+ saveSnapshot: (sandbox, request2) => track(
196
+ saving,
197
+ (async () => {
198
+ const saved = await sandboxes.saveSnapshot(sandbox, request2);
199
+ if (saved.ok && live.delete(sandbox)) await remove(sandbox);
200
+ return saved;
201
+ })()
202
+ ),
203
+ close() {
204
+ closing ??= (async () => {
205
+ if (saving.size > 0) await progress.emit({ kind: "waiting-for-snapshot", settleMs: SNAPSHOT_SETTLE_MS });
206
+ await Promise.all([
207
+ settleWithin(timer, creating, CREATE_SETTLE_MS),
208
+ settleWithin(timer, saving, SNAPSHOT_SETTLE_MS)
209
+ ]);
210
+ const held = [...live];
211
+ live.clear();
212
+ await Promise.all(held.map(keepOrRemove));
213
+ return { kept, notKept, notStopped: [...notStopped], notDeleted: [...notDeleted] };
214
+ })();
215
+ return closing;
216
+ }
217
+ };
218
+ }
219
+ async function settleWithin(timer, tasks, ms) {
220
+ if (tasks.size === 0) return;
221
+ const done = new AbortController();
222
+ await Promise.race([Promise.allSettled(tasks), timer.sleep(ms, done.signal)]);
223
+ done.abort();
224
+ }
225
+ function failureMessage(failure) {
226
+ return failure.message ?? failure.kind;
227
+ }
228
+
229
+ // src/runner/context.ts
230
+ function runnerPurpose(recipeName) {
231
+ return `storm-runner-${recipeName}`;
232
+ }
233
+ function runnerTags(recipeName, role, user) {
234
+ return { purpose: runnerPurpose(recipeName), user, role };
235
+ }
236
+
237
+ // src/runner/snapshot-cache.ts
238
+ import { createHash } from "node:crypto";
239
+ var RUNNER_SNAPSHOTS_SUBPATH = ["runner", "snapshots"];
240
+ var SNAPSHOT_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1e3;
241
+ var SNAPSHOT_MIN_REMAINING_MS = 60 * 60 * 1e3;
242
+ function snapshotEntryIdentity(entry) {
243
+ return createHash("sha256").update(
244
+ [
245
+ entry.teamId,
246
+ entry.projectId,
247
+ entry.region,
248
+ entry.runtime,
249
+ entry.recipeName,
250
+ entry.snapshotKey,
251
+ entry.base
252
+ ].join("\0")
253
+ ).digest("hex").slice(0, 32);
254
+ }
255
+ function snapshotEntryFileName(entry) {
256
+ return `${snapshotEntryIdentity(entry)}.json`;
257
+ }
258
+ function isExpiredEntry(entry, now) {
259
+ return Date.parse(entry.expiresAt) <= now.getTime();
260
+ }
261
+ function hasTimeLeft(entry, now) {
262
+ return Date.parse(entry.expiresAt) - now.getTime() > SNAPSHOT_MIN_REMAINING_MS;
263
+ }
264
+ async function removeExpiredEntries(context) {
265
+ const { runnerSnapshots } = context;
266
+ const listed = await runnerSnapshots.listEntries();
267
+ if (!listed.ok) return { entries: [], notes: [{ kind: "cache-unreadable", failure: listed.failure }] };
268
+ const now = context.clock.now();
269
+ const entries = [];
270
+ const notes = [];
271
+ for (const entry of listed.value.entries) {
272
+ if (!isExpiredEntry(entry, now)) {
273
+ entries.push(entry);
274
+ continue;
275
+ }
276
+ const removed = await runnerSnapshots.removeEntry(entry);
277
+ if (!removed.ok) notes.push({ kind: "expired-entry-not-removed", entry, failure: removed.failure });
278
+ }
279
+ return { entries, notes };
280
+ }
281
+ function classifySnapshotEntries(context, request2) {
282
+ const { entries, recipe, base, snapshotKey: snapshotKey2, commitsAfterBase } = request2;
283
+ const now = context.clock.now();
284
+ const candidates = [];
285
+ const rejected = [];
286
+ const verdicts = [];
287
+ const reject = (entry, reason) => {
288
+ const rejection = { entry, reason };
289
+ rejected.push(rejection);
290
+ verdicts.push({ kind: "rejected", entry, rejection });
291
+ };
292
+ for (const entry of entries) {
293
+ if (entry.region !== recipe.region || entry.runtime !== recipe.runtime || entry.recipeName !== recipe.name) {
294
+ verdicts.push({ kind: "other-recipe", entry });
295
+ continue;
296
+ }
297
+ if (isExpiredEntry(entry, now)) reject(entry, "expired");
298
+ else if (!hasTimeLeft(entry, now)) reject(entry, "expires-soon");
299
+ else if (entry.base !== base) reject(entry, "other-base");
300
+ else if (entry.snapshotKey !== snapshotKey2) reject(entry, "steps-changed");
301
+ else {
302
+ const candidate = { entry, builtBehind: commitsAfterBase };
303
+ candidates.push(candidate);
304
+ verdicts.push({ kind: "candidate", entry, candidate });
305
+ }
306
+ }
307
+ return { candidates, rejected, verdicts };
308
+ }
309
+ function snapshotRejections(read, owner) {
310
+ const owned = (entry) => entry.teamId === owner.teamId && entry.projectId === owner.projectId;
311
+ return [
312
+ ...read.candidates.map(({ entry }) => ({ entry, reason: "other-owner" })),
313
+ ...read.rejected.map(({ entry, reason }) => ({ entry, reason: owned(entry) ? reason : "other-owner" }))
314
+ ];
315
+ }
316
+ function pickSnapshot(candidates, owner) {
317
+ return candidates.find(({ entry }) => entry.teamId === owner.teamId && entry.projectId === owner.projectId);
318
+ }
319
+
320
+ // src/runner/snapshot-key.ts
321
+ import { createHash as createHash2 } from "node:crypto";
322
+
128
323
  // src/time/duration.ts
129
324
  var MIN_TTL_MINUTES = 10;
130
325
  var MAX_TTL_MINUTES = 300;
@@ -342,16 +537,6 @@ function sandboxStop(operation, failure) {
342
537
  }
343
538
 
344
539
  // 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
540
  var RECIPE_DEFAULTS = {
356
541
  cwd: ".",
357
542
  timeout: "60m",
@@ -369,9 +554,6 @@ var RECIPE_KEYS = /* @__PURE__ */ new Set([
369
554
  "secrets",
370
555
  "timeout",
371
556
  "keepSandbox",
372
- "saveDevSnapshot",
373
- "reuseDevSnapshot",
374
- "trustDevSnapshots",
375
557
  "baseRefs",
376
558
  "region",
377
559
  "runtime"
@@ -434,20 +616,6 @@ function checkRecipe(value) {
434
616
  ["keepSandbox"],
435
617
  `must be 0, or a whole number of minutes or hours up to 5h, not ${describeRecipeValue(keepSandbox)}`
436
618
  );
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
619
  const baseRefs = checkBaseRefs(value["baseRefs"], report);
452
620
  const region = orDefault(value["region"], RECIPE_DEFAULTS.region);
453
621
  if (!isNonEmptyString(region)) report(["region"], `must be a non-empty string, not ${describeRecipeValue(region)}`);
@@ -469,9 +637,6 @@ function checkRecipe(value) {
469
637
  timeout,
470
638
  timeoutMinutes,
471
639
  keepSandboxMinutes,
472
- ...typeof saveDevSnapshot2 === "boolean" ? { saveDevSnapshot: saveDevSnapshot2 } : {},
473
- reuseDevSnapshot,
474
- trustDevSnapshots,
475
640
  baseRefs,
476
641
  region,
477
642
  runtime
@@ -689,900 +854,269 @@ function resolveVcpus(recipe, { run, resourceKeys }) {
689
854
  let returned;
690
855
  try {
691
856
  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
- }
857
+ } catch (error) {
858
+ return { ok: false, problem: `threw for ${describeResourceKeys(resourceKeys)}: ${errorMessage(error)}` };
859
+ }
860
+ return isPositiveInteger(returned) ? { ok: true, vcpus: returned } : {
861
+ ok: false,
862
+ problem: `must return a positive whole number, not ${describeRecipeValue(returned)} for ${describeResourceKeys(resourceKeys)}`
1403
863
  };
1404
864
  }
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();
865
+ function describeResourceKeys(names) {
866
+ const last = names.at(-1);
867
+ if (last === void 0) return "a run with no resource";
868
+ return `a run with ${names.length === 1 ? last : `${names.slice(0, -1).join(", ")} and ${last}`}`;
1410
869
  }
1411
- function failureMessage(failure) {
1412
- return failure.message ?? failure.kind;
870
+ function describeRecipeValue(value) {
871
+ if (typeof value === "string") return JSON.stringify(value);
872
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
873
+ if (value === null) return "null";
874
+ if (value === void 0) return "undefined";
875
+ if (typeof value === "function") return "a function";
876
+ if (Array.isArray(value)) return value.length === 0 ? "an empty array" : "an array";
877
+ if (typeof value === "object") return "an object";
878
+ return `a ${typeof value}`;
879
+ }
880
+ function errorMessage(error) {
881
+ return error instanceof Error ? error.message : String(error);
882
+ }
883
+ function orDefault(value, fallback) {
884
+ return value === void 0 ? fallback : value;
885
+ }
886
+ function isRecord(value) {
887
+ return typeof value === "object" && value !== null && !Array.isArray(value);
888
+ }
889
+ function isNonEmptyString(value) {
890
+ return typeof value === "string" && value.length > 0;
891
+ }
892
+ function isPositiveInteger(value) {
893
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
894
+ }
895
+ function isRelativePath(value) {
896
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !value.split(/[/\\]/).includes("..");
1413
897
  }
1414
898
 
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");
899
+ // src/runner/snapshot-key.ts
900
+ var SNAPSHOT_FORMAT = 3;
901
+ var SANDBOX_ROOT = "/vercel/sandbox";
902
+ var STAGED_FILES = {
903
+ baseTarball: "base.tgz",
904
+ baseFileList: "base-files",
905
+ patch: "run.patch",
906
+ untrackedTarball: "untracked.tgz",
907
+ untrackedFileList: "untracked-files"
908
+ };
909
+ var GIT_IDENTITY = "-c user.email=storm-runner@vercel.invalid -c user.name='storm runner' -c commit.gpgsign=false";
910
+ function bashScript(lines, root = SANDBOX_ROOT) {
911
+ return ["set -euo pipefail", `cd ${root}`, ...lines].join("\n");
1420
912
  }
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;
913
+ function baseIndexScript(base, staging) {
914
+ const tarball = `${staging}/${STAGED_FILES.baseTarball}`;
915
+ const fileList = `${staging}/${STAGED_FILES.baseFileList}`;
916
+ return bashScript([
917
+ `tar --warning=no-unknown-keyword -xzf ${tarball} -C ${SANDBOX_ROOT}`,
918
+ `rm -f ${tarball}`,
919
+ "git -c init.defaultBranch=main init -q",
920
+ `git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
921
+ `rm -f ${fileList}`,
922
+ `git ${GIT_IDENTITY} commit -q --no-verify -m 'base ${base}'`
923
+ ]);
924
+ }
925
+ function applyScript(staging, root = SANDBOX_ROOT) {
926
+ const patch = `${staging}/${STAGED_FILES.patch}`;
927
+ const tarball = `${staging}/${STAGED_FILES.untrackedTarball}`;
928
+ const fileList = `${staging}/${STAGED_FILES.untrackedFileList}`;
929
+ return bashScript(
930
+ [
931
+ "root=$(git rev-list --max-parents=0 HEAD)",
932
+ 'git reset -q --hard "$root"',
933
+ "git clean -ffdq",
934
+ // A build may have rewritten tracked files with the same content.
935
+ "git update-index -q --refresh || true",
936
+ `if [ -s ${patch} ]; then git apply --index --binary ${patch}; fi`,
937
+ `if [ -s ${tarball} ]; then`,
938
+ ` tar --warning=no-unknown-keyword -xzf ${tarball} -C ${root}`,
939
+ ` git --literal-pathspecs add -f --pathspec-from-file=${fileList} --pathspec-file-nul`,
940
+ "fi",
941
+ `git ${GIT_IDENTITY} commit -q --no-verify --allow-empty -m run`,
942
+ `rm -f ${patch} ${tarball} ${fileList}`
943
+ ],
944
+ root
945
+ );
946
+ }
947
+ function snapshotKey(steps) {
948
+ const text = (list) => list.flatMap(({ label, script, secrets }) => [label, script, `secrets=${(secrets ?? []).toSorted().join(",")}`]);
949
+ return createHash2("sha256").update(
950
+ [
951
+ `format=${SNAPSHOT_FORMAT}`,
952
+ ...text(steps.toolchains),
953
+ baseIndexScript("<base>", "<staging>"),
954
+ ...text(steps.prebuild)
955
+ ].join("\0")
956
+ ).digest("hex");
957
+ }
958
+ async function snapshotStepsAt(checkout, request2) {
959
+ const context = baseStepContext(checkout, request2);
960
+ const { snapshot, secrets } = request2.recipe;
961
+ const toolchains = await resolveSteps(snapshot.toolchains, context, secrets);
962
+ if (!toolchains.ok) return { ok: false, path: ["snapshot", "toolchains"], problem: toolchains.problem };
963
+ const prebuild = await resolveSteps(snapshot.prebuild, context, secrets);
964
+ if (!prebuild.ok) return { ok: false, path: ["snapshot", "prebuild"], problem: prebuild.problem };
965
+ return {
966
+ ok: true,
967
+ toolchains: toolchains.steps,
968
+ prebuild: prebuild.steps,
969
+ key: snapshotKey({ toolchains: toolchains.steps, prebuild: prebuild.steps })
970
+ };
971
+ }
972
+
973
+ // src/runner/snapshot-build.ts
974
+ var BUILD_SANDBOX_TIMEOUT_MS = 30 * 6e4;
975
+ var BASE_INDEX_LABEL = "Committing the base's files";
976
+ async function buildSnapshot(context, request2, control, progress) {
977
+ const { prepared, access } = request2;
978
+ const { recipe, repoRoot, base } = prepared;
1447
979
  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" });
980
+ const now = () => context.clock.now().getTime();
981
+ const startedAt = now();
982
+ await progress.emit({
983
+ kind: "snapshot-build-started",
984
+ base,
985
+ why: request2.why,
986
+ summary: recipe.snapshot.summary ?? [...prepared.toolchains, ...prepared.prebuild].map(({ label }) => label).join(", ")
987
+ });
988
+ const [started, archive] = await Promise.all([
989
+ scope.startBuildSandbox(access, {
990
+ region: recipe.region,
991
+ runtime: recipe.runtime,
992
+ vcpus: recipe.snapshot.vcpus,
993
+ timeoutMs: BUILD_SANDBOX_TIMEOUT_MS,
994
+ tags: runnerTags(recipe.name, "snapshot-build", request2.user)
995
+ }),
996
+ context.checkout.baseArchive({ repoRoot, base })
997
+ ]);
998
+ if (!started.ok) return sandboxStop("start-build-sandbox", started.failure);
999
+ const sandbox = started.value;
1000
+ await progress.emit({
1001
+ kind: "sandbox-started",
1002
+ role: "snapshot-build",
1003
+ name: sandbox.name,
1004
+ region: recipe.region,
1005
+ vcpus: recipe.snapshot.vcpus,
1006
+ ms: now() - startedAt
1007
+ });
1008
+ if (!archive.ok) return { kind: "failed", failure: { kind: "checkout-failed", failure: archive.failure } };
1009
+ const staged = await context.runnerSandboxes.upload(
1010
+ sandbox,
1011
+ [
1012
+ { name: STAGED_FILES.baseTarball, content: archive.value.tarball },
1013
+ { name: STAGED_FILES.baseFileList, content: archive.value.fileList }
1014
+ ],
1015
+ signal
1016
+ );
1017
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
1018
+ const recipeStep = ({ label, script, secrets }) => ({
1019
+ label,
1020
+ script,
1021
+ secrets: stepSecrets(request2.secrets, secrets)
1022
+ });
1023
+ const steps = [
1024
+ ...prepared.toolchains.map(recipeStep),
1025
+ { label: BASE_INDEX_LABEL, script: baseIndexScript(base, staged.value.directory) },
1026
+ ...prepared.prebuild.map(recipeStep)
1027
+ ];
1028
+ await progress.emit({ kind: "output-started", section: "snapshot", sandbox: sandbox.name, region: recipe.region });
1029
+ for (const step of steps) {
1030
+ const ran = await runStep(context, { sandbox, phase: "snapshot", ...step }, progress, signal);
1031
+ if (ran.kind === "succeeded") continue;
1032
+ const stop = ran.kind === "exited" ? {
1033
+ kind: "failed",
1034
+ failure: { kind: "snapshot-build-step-failed", label: step.label, exitCode: ran.exitCode, tail: ran.tail }
1035
+ } : sandboxStop("run-script", ran.failure);
1036
+ await progress.emit({
1037
+ kind: "output-ended",
1038
+ section: "snapshot",
1039
+ outcome: stop.kind === "aborted" ? "stopped" : "failed"
1040
+ });
1041
+ return stop;
1042
+ }
1043
+ await progress.emit({ kind: "output-ended", section: "snapshot", outcome: "finished" });
1044
+ if (signal.aborted) return { kind: "aborted" };
1045
+ await progress.emit({ kind: "snapshot-saving" });
1460
1046
  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();
1047
+ if (!saved.ok) return sandboxStop("save-snapshot", saved.failure);
1048
+ const savedAt = context.clock.now();
1467
1049
  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,
1050
+ teamId: access.teamId,
1051
+ projectId: access.projectId,
1052
+ region: recipe.region,
1053
+ runtime: recipe.runtime,
1054
+ recipeName: recipe.name,
1055
+ snapshotKey: prepared.snapshotKey,
1056
+ base,
1478
1057
  snapshotId: saved.value.snapshotId,
1479
- createdAt: savedAt2.toISOString(),
1480
- expiresAt: saved.value.expiresAt ?? new Date(savedAt2.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1058
+ createdAt: savedAt.toISOString(),
1059
+ expiresAt: saved.value.expiresAt ?? new Date(savedAt.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString()
1481
1060
  };
1482
1061
  const written = await context.runnerSnapshots.writeEntry(entry);
1483
1062
  if (!written.ok) await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
1484
- const ms = savedAt2.getTime() - startedAt;
1063
+ const ms = now() - startedAt;
1485
1064
  await progress.emit({
1486
- kind: "dev-snapshot-saved",
1065
+ kind: "snapshot-built",
1487
1066
  snapshotId: entry.snapshotId,
1488
- branch,
1489
- head: head2,
1067
+ base,
1490
1068
  ms,
1491
- sizeBytes: saved.value.sizeBytes
1069
+ sizeBytes: saved.value.sizeBytes,
1070
+ builtBehind: prepared.commitsAfterBase
1492
1071
  });
1493
1072
  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);
1073
+ kind: "ok",
1074
+ value: { entry, ms, sizeBytes: saved.value.sizeBytes, cacheFailure: written.ok ? null : written.failure }
1513
1075
  };
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
1076
  }
1538
1077
 
1539
1078
  // src/runner/build-snapshots.ts
1540
1079
  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
1080
  const { checkout } = context;
1081
+ const { recipe, ref } = request2;
1553
1082
  const root = await checkout.repositoryRoot({ cwd: request2.cwd });
1554
1083
  if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
1555
1084
  const repoRoot = root.value;
1556
1085
  const head2 = await checkout.head({ repoRoot });
1557
1086
  if (!head2.ok) return { kind: "checkout-failed", failure: head2.failure };
1087
+ const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1088
+ if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1089
+ const mergeBase = resolved.kind === "resolved" ? { commit: resolved.base, ref: resolved.ref } : null;
1558
1090
  const submodules2 = await checkout.submodules({ repoRoot });
1559
1091
  if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
1560
1092
  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;
1093
+ let base;
1094
+ if (ref === void 0) {
1095
+ if (resolved.kind !== "resolved") return resolved;
1096
+ base = resolved.base;
1097
+ } else {
1098
+ const commit = await checkout.resolveCommit({ repoRoot, ref });
1099
+ if (!commit.ok) return { kind: "checkout-failed", failure: commit.failure };
1100
+ if (commit.value === null) return { kind: "ref-not-found", ref };
1101
+ base = commit.value;
1102
+ }
1565
1103
  const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
1566
1104
  if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1567
1105
  const listed = await context.runnerSnapshots.listEntries();
1568
1106
  const now = context.clock.now();
1569
1107
  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)
1108
+ (entry) => entry.base === base && entry.recipeName === recipe.name && entry.region === recipe.region && entry.runtime === recipe.runtime && entry.snapshotKey === steps.key && hasTimeLeft(entry, now)
1571
1109
  );
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;
1110
+ const atMergeBase = base === mergeBase?.commit;
1111
+ let commitsAfterBase = null;
1112
+ if (atMergeBase) {
1113
+ const counted = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
1114
+ if (!counted.ok) return { kind: "checkout-failed", failure: counted.failure };
1115
+ commitsAfterBase = counted.value;
1116
+ }
1582
1117
  return {
1583
1118
  kind: "ok",
1584
1119
  build: {
1585
- kind: "base",
1586
1120
  plan: {
1587
1121
  recipe,
1588
1122
  repoRoot,
@@ -1590,20 +1124,20 @@ async function prepareSnapshotBuild(context, request2) {
1590
1124
  toolchains: steps.toolchains,
1591
1125
  prebuild: steps.prebuild,
1592
1126
  snapshotKey: steps.key,
1593
- commitsAfterBase: afterBase?.ok === true ? afterBase.value : null
1127
+ commitsAfterBase
1594
1128
  },
1595
- ref: mode.ref,
1596
1129
  head: head2.value,
1130
+ ref: ref ?? null,
1131
+ mergeBase,
1132
+ atMergeBase,
1597
1133
  cached,
1598
- full: mode.full,
1599
- warnings
1134
+ full: request2.full
1600
1135
  }
1601
1136
  };
1602
1137
  }
1603
- var ABORTED_EARLY = { kind: "aborted", baseSnapshot: null, dropped: null };
1604
1138
  async function buildSnapshots(context, request2, control, progress) {
1605
1139
  const { signal } = control;
1606
- const scope = runnerSandboxScope(context, progress, { keepMs: () => 0 });
1140
+ const scope = runnerSandboxScope(context, progress, { keepMs: 0 });
1607
1141
  const stop = () => {
1608
1142
  void progress.emit({ kind: "stopping", commandRunning: false, keepMs: 0 }).catch(() => void 0);
1609
1143
  void scope.close().catch(() => void 0);
@@ -1623,84 +1157,27 @@ async function buildSnapshots(context, request2, control, progress) {
1623
1157
  async function buildIn(context, request2, control, progress) {
1624
1158
  const { build, access, user, secrets } = request2;
1625
1159
  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(
1160
+ if (signal.aborted) return { kind: "aborted", snapshot: null };
1161
+ const cached = build.cached.find((entry2) => entry2.teamId === access.teamId && entry2.projectId === access.projectId);
1162
+ if (!build.full && cached !== void 0) return { kind: "up-to-date", snapshot: cached };
1163
+ const why = build.full ? "full" : build.ref === null ? "no-snapshot" : "base";
1164
+ const built = await buildSnapshot(
1671
1165
  context,
1672
- { ready: runner, branch: prepared.head.branch, head: prepared.head.commit },
1166
+ {
1167
+ prepared: build.plan,
1168
+ access,
1169
+ user,
1170
+ secrets,
1171
+ why: why === "no-snapshot" ? { kind: why, rejected: [] } : { kind: why }
1172
+ },
1673
1173
  control,
1674
1174
  progress
1675
1175
  );
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;
1176
+ if (built.kind === "aborted") return { kind: "aborted", snapshot: null };
1177
+ if (built.kind !== "ok") return built;
1178
+ const { entry, cacheFailure, ms, sizeBytes } = built.value;
1179
+ if (signal.aborted) return { kind: "aborted", snapshot: { entry, cached: cacheFailure === null } };
1180
+ return cacheFailure === null ? { kind: "built", snapshot: entry, ms, sizeBytes } : { kind: "not-cached", snapshot: entry, failure: cacheFailure };
1704
1181
  }
1705
1182
 
1706
1183
  // src/runner/live/user.ts
@@ -1733,13 +1210,12 @@ async function inspectSnapshotCache(context, request2) {
1733
1210
  directory,
1734
1211
  checkout: null,
1735
1212
  picking: { kind: "none", why: "no-checkout" },
1736
- snapshots: shown.map((entry) => unchecked(entry, now, null)),
1213
+ snapshots: shown.map((entry) => unchecked(entry, now)),
1737
1214
  unreadable
1738
1215
  }
1739
1216
  };
1740
1217
  }
1741
1218
  const repoRoot = root.value;
1742
- const savedHere = (entry) => isDevEntry(entry) ? entry.repoRoot === repoRoot : null;
1743
1219
  const resolved = recipe === void 0 ? void 0 : await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
1744
1220
  if (resolved?.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
1745
1221
  if (recipe === void 0 || resolved === void 0 || resolved.kind !== "resolved") {
@@ -1749,7 +1225,7 @@ async function inspectSnapshotCache(context, request2) {
1749
1225
  directory,
1750
1226
  checkout: { repoRoot, head: head2.value, mergeBase: null },
1751
1227
  picking: { kind: "none", why: recipe === void 0 ? "no-recipe" : "no-base" },
1752
- snapshots: shown.map((entry) => unchecked(entry, now, savedHere(entry))),
1228
+ snapshots: shown.map((entry) => unchecked(entry, now)),
1753
1229
  unreadable
1754
1230
  }
1755
1231
  };
@@ -1759,69 +1235,42 @@ async function inspectSnapshotCache(context, request2) {
1759
1235
  if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
1760
1236
  const afterBase = await checkout.commitCount({ repoRoot, from: mergeBase, to: "HEAD" });
1761
1237
  if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
1762
- const classified = await classifySnapshotEntries(context, {
1238
+ const read = classifySnapshotEntries(context, {
1763
1239
  entries,
1764
- repoRoot,
1765
1240
  recipe,
1766
1241
  base: mergeBase,
1767
1242
  snapshotKey: steps.key,
1768
- commitsAfterBase: afterBase.value,
1769
- devSnapshots: devSnapshotReuse(recipe, recipe.reuseDevSnapshot)
1243
+ commitsAfterBase: afterBase.value
1770
1244
  });
1771
- if (!classified.ok) return { kind: "checkout-failed", failure: classified.failure };
1772
- const read = classified.value;
1773
1245
  const owners = new Map(read.candidates.map(({ entry }) => [`${entry.teamId}\0${entry.projectId}`, entry]));
1774
1246
  const picked = /* @__PURE__ */ new Set();
1775
1247
  for (const owner of owners.values()) {
1776
- const start = chooseSnapshotStart(read, owner);
1777
- if (start.kind === "reuse") picked.add(start.candidate);
1248
+ const pick = pickSnapshot(read.candidates, owner);
1249
+ if (pick !== void 0) picked.add(pick);
1778
1250
  }
1779
- const inHistory = /* @__PURE__ */ new Map();
1780
- const behind = /* @__PURE__ */ new Map();
1251
+ const place = historyPlacer(context, { repoRoot, mergeBase, commitsAfterBase: afterBase.value });
1781
1252
  const snapshots = [];
1782
1253
  for (const verdict of read.verdicts) {
1783
1254
  const { entry } = verdict;
1784
1255
  if (!shows(entry)) continue;
1785
- const builtAt = builtAtCommit(entry);
1786
- const kind2 = isDevEntry(entry) ? "dev" : "base";
1787
1256
  const expired = isExpiredEntry(entry, now);
1788
1257
  if (verdict.kind === "candidate") {
1789
1258
  const { candidate } = verdict;
1790
- const isPicked = picked.has(candidate);
1791
1259
  snapshots.push({
1792
1260
  entry,
1793
- kind: kind2,
1794
- builtAt,
1795
1261
  inHistory: true,
1796
1262
  builtBehind: candidate.builtBehind,
1797
- savedHere: savedHere(entry),
1798
1263
  expired,
1799
- picked: isPicked,
1800
- reason: isPicked ? null : "not-picked"
1264
+ picked: picked.has(candidate),
1265
+ reason: null
1801
1266
  });
1802
1267
  continue;
1803
1268
  }
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
- }
1269
+ const placed = await place(entry.base);
1270
+ if (!placed.ok) return { kind: "checkout-failed", failure: placed.failure };
1818
1271
  snapshots.push({
1819
1272
  entry,
1820
- kind: kind2,
1821
- builtAt,
1822
- inHistory: contained,
1823
- builtBehind: builtBehind ?? null,
1824
- savedHere: savedHere(entry),
1273
+ ...placed.value,
1825
1274
  expired,
1826
1275
  picked: false,
1827
1276
  reason: verdict.kind === "rejected" ? verdict.rejection.reason : "other-recipe"
@@ -1838,19 +1287,36 @@ async function inspectSnapshotCache(context, request2) {
1838
1287
  }
1839
1288
  };
1840
1289
  }
1841
- function unchecked(entry, now, savedHere) {
1290
+ function unchecked(entry, now) {
1842
1291
  return {
1843
1292
  entry,
1844
- kind: isDevEntry(entry) ? "dev" : "base",
1845
- builtAt: builtAtCommit(entry),
1846
1293
  inHistory: null,
1847
1294
  builtBehind: null,
1848
- savedHere,
1849
1295
  expired: isExpiredEntry(entry, now),
1850
1296
  picked: false,
1851
1297
  reason: null
1852
1298
  };
1853
1299
  }
1300
+ function historyPlacer(context, request2) {
1301
+ const { repoRoot } = request2;
1302
+ const known = /* @__PURE__ */ new Map([
1303
+ [request2.mergeBase, { inHistory: true, builtBehind: request2.commitsAfterBase }]
1304
+ ]);
1305
+ return async (base) => {
1306
+ const answer = known.get(base);
1307
+ if (answer !== void 0) return { ok: true, value: answer };
1308
+ const contained = await context.checkout.contains({ repoRoot, ancestor: base, descendant: "HEAD" });
1309
+ if (!contained.ok) return contained;
1310
+ let placed = { inHistory: false, builtBehind: null };
1311
+ if (contained.value) {
1312
+ const counted = await context.checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
1313
+ if (!counted.ok) return counted;
1314
+ placed = { inHistory: true, builtBehind: counted.value };
1315
+ }
1316
+ known.set(base, placed);
1317
+ return { ok: true, value: placed };
1318
+ };
1319
+ }
1854
1320
 
1855
1321
  // src/runner/live/checkout-gateway.ts
1856
1322
  import { execFile, spawn } from "node:child_process";
@@ -2488,16 +1954,10 @@ var entrySchema = z4.object({
2488
1954
  recipeName: nonEmpty,
2489
1955
  snapshotKey: nonEmpty,
2490
1956
  base: nonEmpty,
2491
- branch: nonEmpty.exactOptional(),
2492
- head: nonEmpty.exactOptional(),
2493
- repoRoot: nonEmpty.exactOptional(),
2494
1957
  snapshotId: nonEmpty,
2495
1958
  createdAt: isoTime,
2496
1959
  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
- );
1960
+ });
2501
1961
  function parseSnapshotEntry(text) {
2502
1962
  let json;
2503
1963
  try {
@@ -2517,7 +1977,7 @@ function parseSnapshotEntry(text) {
2517
1977
  return { ok: true, value: entry };
2518
1978
  }
2519
1979
  function snapshotEntryText(entry) {
2520
- const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base, branch, head: head2, repoRoot } = entry;
1980
+ const { teamId, projectId, region, runtime, recipeName, snapshotKey: snapshotKey2, base } = entry;
2521
1981
  const { snapshotId, createdAt, expiresAt } = entry;
2522
1982
  const record = {
2523
1983
  version: 1,
@@ -2528,9 +1988,6 @@ function snapshotEntryText(entry) {
2528
1988
  recipeName,
2529
1989
  snapshotKey: snapshotKey2,
2530
1990
  base,
2531
- ...branch === void 0 ? {} : { branch },
2532
- ...head2 === void 0 ? {} : { head: head2 },
2533
- ...repoRoot === void 0 ? {} : { repoRoot },
2534
1991
  snapshotId,
2535
1992
  createdAt,
2536
1993
  expiresAt
@@ -2621,16 +2078,66 @@ function failureAt(path, error) {
2621
2078
  return { path, message: error instanceof Error ? error.message : String(error) };
2622
2079
  }
2623
2080
 
2081
+ // src/runner/prepare.ts
2082
+ async function prepareRunner(context, request2) {
2083
+ const { checkout } = context;
2084
+ const { recipe } = request2;
2085
+ const root = await checkout.repositoryRoot({ cwd: request2.cwd });
2086
+ if (!root.ok) return { kind: "checkout-failed", failure: root.failure };
2087
+ const repoRoot = root.value;
2088
+ const resolved = await resolveBase(checkout, { repoRoot, baseRefs: recipe.baseRefs });
2089
+ if (resolved.kind === "failed") return { kind: "checkout-failed", failure: resolved.failure };
2090
+ if (resolved.kind === "no-base-ref") return resolved;
2091
+ const { base } = resolved;
2092
+ const submodules2 = await checkout.submodules({ repoRoot });
2093
+ if (!submodules2.ok) return { kind: "checkout-failed", failure: submodules2.failure };
2094
+ if (submodules2.value.length > 0) return { kind: "submodules", paths: [...submodules2.value] };
2095
+ const steps = await snapshotStepsAt(checkout, { repoRoot, base, recipe });
2096
+ if (!steps.ok) return { kind: "invalid-recipe", path: steps.path, problem: steps.problem };
2097
+ const vcpus = resolveVcpus(recipe, request2.vcpusRun);
2098
+ if (!vcpus.ok) return { kind: "invalid-recipe", path: ["vcpus"], problem: vcpus.problem };
2099
+ const upload = await checkout.assembleUpload({ repoRoot, base });
2100
+ if (!upload.ok) return { kind: "checkout-failed", failure: upload.failure };
2101
+ const afterBase = await checkout.commitCount({ repoRoot, from: base, to: "HEAD" });
2102
+ if (!afterBase.ok) return { kind: "checkout-failed", failure: afterBase.failure };
2103
+ const listing = await removeExpiredEntries(context);
2104
+ const cache = classifySnapshotEntries(context, {
2105
+ entries: listing.entries,
2106
+ recipe,
2107
+ base,
2108
+ snapshotKey: steps.key,
2109
+ commitsAfterBase: afterBase.value
2110
+ });
2111
+ return {
2112
+ kind: "ok",
2113
+ prepared: {
2114
+ recipe,
2115
+ repoRoot,
2116
+ base,
2117
+ baseRef: resolved.ref,
2118
+ toolchains: steps.toolchains,
2119
+ prebuild: steps.prebuild,
2120
+ snapshotKey: steps.key,
2121
+ vcpus: vcpus.vcpus,
2122
+ upload: upload.value,
2123
+ candidates: cache.candidates,
2124
+ rejected: cache.rejected,
2125
+ commitsAfterBase: afterBase.value,
2126
+ notes: listing.notes
2127
+ }
2128
+ };
2129
+ }
2130
+
2624
2131
  // src/runner/sandboxed-command.ts
2625
- import { posix as posix2 } from "node:path";
2132
+ import { posix } from "node:path";
2626
2133
  function sandboxedCommand(request2) {
2627
2134
  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;
2135
+ const cmd = first.includes("/") && !first.startsWith("/") ? posix.join(request2.cwd, first) : first;
2629
2136
  return { cmd, args: rest };
2630
2137
  }
2631
2138
  function sandboxEnvironment(request2) {
2632
2139
  const bins = [
2633
- .../* @__PURE__ */ new Set([posix2.join(request2.cwd, "node_modules/.bin"), posix2.join(SANDBOX_ROOT, "node_modules/.bin")])
2140
+ .../* @__PURE__ */ new Set([posix.join(request2.cwd, "node_modules/.bin"), posix.join(SANDBOX_ROOT, "node_modules/.bin")])
2634
2141
  ];
2635
2142
  return {
2636
2143
  PATH: [...bins, request2.loginPath].filter((part) => part !== "").join(":"),
@@ -2675,7 +2182,7 @@ async function runCommandInSandbox(context, request2, control, progress) {
2675
2182
  if (!ran.ok) {
2676
2183
  if (ran.failure.kind !== "aborted")
2677
2184
  return { kind: "failed", failure: sandboxApiFailure("run-command", ran.failure) };
2678
- await progress.emit({ kind: "command-stopped", command: posix2.basename(command.cmd) });
2185
+ await progress.emit({ kind: "command-stopped", command: posix.basename(command.cmd) });
2679
2186
  return { kind: "killed" };
2680
2187
  }
2681
2188
  return { kind: "exited", exitCode: ran.value.exitCode, ms };
@@ -2725,32 +2232,187 @@ function followTestEvents(context, runner, testEvents, kill) {
2725
2232
  };
2726
2233
  }
2727
2234
 
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 };
2235
+ // src/runner/ready.ts
2236
+ import { posix as posix2 } from "node:path";
2237
+ var APPLY_LABEL = "Applying your changes";
2238
+ async function readyRunner(context, request2, control, progress) {
2239
+ const { prepared, access } = request2;
2240
+ const { recipe, repoRoot } = prepared;
2241
+ const { scope, signal } = control;
2242
+ const now = () => context.clock.now().getTime();
2243
+ if (signal.aborted) return { kind: "aborted" };
2244
+ const pick = pickSnapshot(prepared.candidates, access);
2245
+ let entry;
2246
+ if (pick !== void 0) {
2247
+ ({ entry } = pick);
2248
+ await progress.emit({
2249
+ kind: "snapshot-reused",
2250
+ snapshotId: entry.snapshotId,
2251
+ base: entry.base,
2252
+ builtBehind: pick.builtBehind
2253
+ });
2254
+ } else {
2255
+ const why = { kind: "no-snapshot", rejected: snapshotRejections(prepared, access) };
2256
+ const building = await buildSnapshot(
2257
+ context,
2258
+ { prepared, access, user: request2.user, secrets: request2.secrets, why },
2259
+ control,
2260
+ progress
2261
+ );
2262
+ if (building.kind !== "ok") return building;
2263
+ ({ entry } = building.value);
2264
+ }
2265
+ const built = pick === void 0;
2266
+ if (signal.aborted) return { kind: "aborted" };
2267
+ await progress.emit({ kind: "runner-sandbox-starting", snapshotId: entry.snapshotId });
2268
+ const startedAt = now();
2269
+ const started = await scope.startRunnerSandbox(access, {
2270
+ snapshotId: entry.snapshotId,
2271
+ region: recipe.region,
2272
+ vcpus: prepared.vcpus,
2273
+ timeoutMs: recipe.timeoutMinutes * 6e4,
2274
+ tags: runnerTags(recipe.name, "runner", request2.user)
2275
+ });
2276
+ if (!started.ok) {
2277
+ if (started.failure.kind === "snapshot-gone") {
2278
+ const removed = await context.runnerSnapshots.removeEntry(entry);
2279
+ return { kind: "snapshot-gone", entry, removal: removed.ok ? void 0 : removed.failure };
2280
+ }
2281
+ return sandboxStop("start-runner-sandbox", started.failure);
2282
+ }
2283
+ const sandbox = started.value;
2284
+ await progress.emit({
2285
+ kind: "sandbox-started",
2286
+ role: "runner",
2287
+ name: sandbox.name,
2288
+ region: recipe.region,
2289
+ vcpus: prepared.vcpus,
2290
+ ms: now() - startedAt
2291
+ });
2292
+ const changes = await uploadChanges(context, { prepared, sandbox }, signal, progress);
2293
+ if (changes.kind !== "ok") return changes;
2294
+ const applied = await stage(
2295
+ context,
2296
+ {
2297
+ sandbox,
2298
+ phase: "apply",
2299
+ step: { label: APPLY_LABEL, script: applyScript(changes.value.directory) },
2300
+ region: recipe.region
2301
+ },
2302
+ signal,
2303
+ progress
2304
+ );
2305
+ if (applied.kind !== "ok") return applied;
2306
+ const loginPath = await context.runnerSandboxes.loginPath(sandbox, signal);
2307
+ if (!loginPath.ok) return sandboxStop("login-path", loginPath.failure);
2308
+ const installed = await stage(
2309
+ context,
2310
+ {
2311
+ sandbox,
2312
+ phase: "install",
2313
+ step: recipe.run.install,
2314
+ secrets: stepSecrets(request2.secrets, recipe.run.install.secrets),
2315
+ region: recipe.region
2316
+ },
2317
+ signal,
2318
+ progress
2319
+ );
2320
+ if (installed.kind !== "ok") return installed;
2321
+ const builtOutputs = await stage(
2322
+ context,
2323
+ {
2324
+ sandbox,
2325
+ phase: "build",
2326
+ step: recipe.run.build,
2327
+ secrets: stepSecrets(request2.secrets, recipe.run.build.secrets),
2328
+ region: recipe.region
2329
+ },
2330
+ signal,
2331
+ progress
2332
+ );
2333
+ if (builtOutputs.kind !== "ok") return builtOutputs;
2334
+ return {
2335
+ kind: "ready",
2336
+ runner: {
2337
+ sandbox,
2338
+ snapshotId: entry.snapshotId,
2339
+ base: entry.base,
2340
+ built,
2341
+ builtBehind: prepared.commitsAfterBase,
2342
+ uploadBytes: changes.value.bytes,
2343
+ buildMs: builtOutputs.value,
2344
+ vcpus: prepared.vcpus,
2345
+ region: recipe.region,
2346
+ runtime: recipe.runtime,
2347
+ repoRoot,
2348
+ cwd: posix2.join(SANDBOX_ROOT, recipe.cwd),
2349
+ env: recipe.env,
2350
+ loginPath: loginPath.value
2351
+ }
2352
+ };
2353
+ }
2354
+ async function uploadChanges(context, request2, signal, progress) {
2355
+ await progress.emit({ kind: "uploading" });
2356
+ const startedAt = context.clock.now().getTime();
2357
+ const files = stagedChanges(request2.prepared.upload);
2358
+ const staged = await context.runnerSandboxes.upload(request2.sandbox, files, signal);
2359
+ if (!staged.ok) return sandboxStop("upload", staged.failure);
2360
+ const bytes = files.reduce((sum, file) => sum + file.content.byteLength, 0);
2361
+ await progress.emit({ kind: "uploaded", bytes, ms: context.clock.now().getTime() - startedAt });
2362
+ return { kind: "ok", value: { directory: staged.value.directory, bytes } };
2363
+ }
2364
+ function stagedChanges(upload) {
2365
+ const encoder = new TextEncoder();
2366
+ return [
2367
+ { name: STAGED_FILES.patch, content: upload.patch },
2368
+ {
2369
+ name: STAGED_FILES.untrackedFileList,
2370
+ content: encoder.encode(upload.untracked.map((path) => `${path}\0`).join(""))
2371
+ },
2372
+ ...upload.untrackedTarball === void 0 ? [] : [{ name: STAGED_FILES.untrackedTarball, content: upload.untrackedTarball }]
2373
+ ];
2374
+ }
2375
+ async function stage(context, request2, signal, progress) {
2376
+ if (signal.aborted) return { kind: "aborted" };
2377
+ const { sandbox, phase, step } = request2;
2378
+ const section = phase === "apply" ? void 0 : phase;
2379
+ if (section !== void 0)
2380
+ await progress.emit({ kind: "output-started", section, sandbox: sandbox.name, region: request2.region });
2381
+ const ran = await runStep(
2382
+ context,
2383
+ {
2384
+ sandbox,
2385
+ phase,
2386
+ label: step.label,
2387
+ script: step.script,
2388
+ ...request2.secrets === void 0 ? {} : { secrets: request2.secrets }
2389
+ },
2390
+ progress,
2391
+ signal
2392
+ );
2393
+ if (ran.kind === "succeeded") {
2394
+ if (section !== void 0) await progress.emit({ kind: "output-ended", section, outcome: "finished" });
2395
+ return { kind: "ok", value: ran.ms };
2396
+ }
2397
+ const stop = ran.kind === "exited" ? {
2398
+ kind: "failed",
2399
+ failure: { kind: `${phase}-failed`, label: step.label, exitCode: ran.exitCode, tail: ran.tail }
2400
+ } : sandboxStop("run-script", ran.failure);
2401
+ if (section !== void 0)
2402
+ await progress.emit({ kind: "output-ended", section, outcome: stop.kind === "aborted" ? "stopped" : "failed" });
2403
+ return stop;
2740
2404
  }
2405
+
2406
+ // src/runner/session.ts
2741
2407
  function openRunnerSession(context, request2, control, progress) {
2742
2408
  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 });
2409
+ const scope = runnerSandboxScope(context, progress, { keepMs: request2.keepMs });
2747
2410
  const closeScope = async () => ({ ...await scope.close(), target: request2.target });
2748
2411
  let readying = false;
2749
2412
  let readied;
2750
2413
  let commandRunning = false;
2751
- let ended;
2752
2414
  const stop = () => {
2753
- void progress.emit({ kind: "stopping", commandRunning, keepMs: keepMs() }).catch(() => void 0);
2415
+ void progress.emit({ kind: "stopping", commandRunning, keepMs: request2.keepMs }).catch(() => void 0);
2754
2416
  void scope.close().catch(() => void 0);
2755
2417
  };
2756
2418
  if (signal.aborted) stop();
@@ -2760,14 +2422,10 @@ function openRunnerSession(context, request2, control, progress) {
2760
2422
  if (readying) throw new Error("the runner session readies its runner sandbox once");
2761
2423
  readying = true;
2762
2424
  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
2425
  const outcome = await readyRunner(
2768
2426
  context,
2769
- { prepared, access, user, secrets, start: obtained.value },
2770
- lane,
2427
+ { prepared, access, user, secrets },
2428
+ { scope, signal: laneSignal },
2771
2429
  progress
2772
2430
  );
2773
2431
  if (outcome.kind === "ready") readied = outcome.runner;
@@ -2776,7 +2434,7 @@ function openRunnerSession(context, request2, control, progress) {
2776
2434
  async runCommand(command) {
2777
2435
  if (readied === void 0) throw new Error("the runner session's runner sandbox isn't ready");
2778
2436
  commandRunning = true;
2779
- const ran = await runCommandInSandbox(
2437
+ return await runCommandInSandbox(
2780
2438
  context,
2781
2439
  {
2782
2440
  runner: readied,
@@ -2787,53 +2445,21 @@ function openRunnerSession(context, request2, control, progress) {
2787
2445
  { kill: signal },
2788
2446
  progress
2789
2447
  );
2790
- if (ran.kind === "exited") ended = { runner: readied, exitCode: ran.exitCode };
2791
- return ran;
2792
2448
  },
2793
2449
  async finish() {
2794
2450
  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);
2451
+ await cleanup.startCleanup();
2826
2452
  const facts = await closeScope();
2827
2453
  signal.removeEventListener("abort", stop);
2828
- await cleanup.release(action);
2829
- return { save, noSave, cleanup: facts };
2454
+ await cleanup.release();
2455
+ return facts;
2830
2456
  },
2831
2457
  async close() {
2832
2458
  signal.removeEventListener("abort", stop);
2833
2459
  try {
2834
2460
  return await closeScope();
2835
2461
  } finally {
2836
- await cleanup.release(unsaved);
2462
+ await cleanup.release();
2837
2463
  }
2838
2464
  }
2839
2465
  };
@@ -3004,34 +2630,6 @@ function fileProblem(problem) {
3004
2630
  return { key: null, location: null, problem };
3005
2631
  }
3006
2632
 
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
2633
  // src/config/errors.ts
3036
2634
  import { z as z5 } from "zod";
3037
2635
  var problemSchema = z5.object({
@@ -3122,6 +2720,17 @@ var configErrors = defineErrors({
3122
2720
  }
3123
2721
  });
3124
2722
 
2723
+ // src/config/typed-options.ts
2724
+ function givenOptionsOf(_definition, values) {
2725
+ return values;
2726
+ }
2727
+ function settingsOf(_definition, settings) {
2728
+ return settings;
2729
+ }
2730
+ function resourceOptionsOf(_definition, value) {
2731
+ return value;
2732
+ }
2733
+
3125
2734
  // src/config/resolve.ts
3126
2735
  function resolveSettings(flags, file) {
3127
2736
  const pick = (flag, fromFile) => flag !== void 0 ? { value: flag, source: "flag" } : fromFile === void 0 ? void 0 : { value: fromFile, source: "file" };
@@ -3710,6 +3319,23 @@ function errorLocation(error, name) {
3710
3319
  return void 0;
3711
3320
  }
3712
3321
 
3322
+ // src/config/recipe-run.ts
3323
+ var NOT_PRESENT = Object.freeze({ present: false });
3324
+ function recipeRun(resources) {
3325
+ const run = {
3326
+ get: ({ definition }) => {
3327
+ const key = defaultResourceKey(definition);
3328
+ const resource = Object.hasOwn(resources, key) ? resources[key] : void 0;
3329
+ if (resource === void 0 || resource.definition !== definition.name) return NOT_PRESENT;
3330
+ return Object.freeze({
3331
+ present: true,
3332
+ value: resourceOptionsOf(definition, Object.freeze({ ...resource.options }))
3333
+ });
3334
+ }
3335
+ };
3336
+ return { run: Object.freeze(run), resourceKeys: Object.keys(resources) };
3337
+ }
3338
+
3713
3339
  // src/config/resolver.ts
3714
3340
  function configResolver(launcher) {
3715
3341
  return {
@@ -3741,6 +3367,10 @@ export {
3741
3367
  credentialSourceErrors,
3742
3368
  credentialResolver,
3743
3369
  configErrors,
3370
+ RUNNER_SECRET_MIN_LENGTH,
3371
+ declaredSecretValues,
3372
+ readRunnerSecrets,
3373
+ RUNNER_SNAPSHOTS_SUBPATH,
3744
3374
  parseKeepTime,
3745
3375
  systemTimer,
3746
3376
  systemClock,
@@ -3749,12 +3379,6 @@ export {
3749
3379
  parseTestEvent,
3750
3380
  redactSecrets,
3751
3381
  lineSplitter,
3752
- devSnapshotsTrusted,
3753
- RUNNER_SNAPSHOTS_SUBPATH,
3754
- prepareRunner,
3755
- RUNNER_SECRET_MIN_LENGTH,
3756
- declaredSecretValues,
3757
- readRunnerSecrets,
3758
3382
  prepareSnapshotBuild,
3759
3383
  buildSnapshots,
3760
3384
  liveCheckoutGateway,
@@ -3763,6 +3387,7 @@ export {
3763
3387
  localUserName,
3764
3388
  liveRunnerSnapshotCacheGateway,
3765
3389
  unavailableRunnerSnapshotCacheGateway,
3390
+ prepareRunner,
3766
3391
  SANDBOX_TEST_EVENTS_PATH,
3767
3392
  openRunnerSession,
3768
3393
  inspectSnapshotCache,