effect-ci 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2207 @@
1
+ import {
2
+ boundedCommandOutput
3
+ } from "./chunk-WGBTI7DS.js";
4
+ import {
5
+ makeSourceQueries
6
+ } from "./chunk-MZ5FQEN6.js";
7
+ import {
8
+ pathPatterns
9
+ } from "./chunk-U3DVQKHN.js";
10
+ import {
11
+ cacheLog,
12
+ untracedHits
13
+ } from "./chunk-WOG7K3QJ.js";
14
+
15
+ // ../ci/src/index.ts
16
+ import { spawn } from "node:child_process";
17
+ import { existsSync, readFileSync, writeSync } from "node:fs";
18
+ import { dirname, join, relative } from "node:path";
19
+ import picomatch from "picomatch";
20
+ import * as Cache from "effect/Cache";
21
+ import * as Cause from "effect/Cause";
22
+ import * as Duration from "effect/Duration";
23
+ import * as Effect2 from "effect/Effect";
24
+ import * as Exit from "effect/Exit";
25
+ import * as Redacted from "effect/Redacted";
26
+ import * as Schedule from "effect/Schedule";
27
+ import * as Context from "effect/Context";
28
+
29
+ // ../ci/src/turbo.ts
30
+ import * as Effect from "effect/Effect";
31
+
32
+ // ../ci/src/turbo-bridge.ts
33
+ var turboBridge = String.raw`
34
+ async function turboBridge(request) {
35
+ const fs = await import("node:fs");
36
+ const path = await import("node:path");
37
+ const { createRequire } = await import("node:module");
38
+ const { spawnSync } = await import("node:child_process");
39
+ const root = fs.realpathSync(process.cwd());
40
+ const cache = ".effect-ci/turbo/cache";
41
+ const limit = 48 * 1024;
42
+ const safePath = (value, cacheFile = false) => {
43
+ if (!value || path.isAbsolute(value) || /[\\\x00-\x1f]/.test(value) ||
44
+ value.split("/").some(part => !part || part === "." || part === ".." || part === ".git" || part === "node_modules") ||
45
+ (value.split("/").includes(".effect-ci") && !(cacheFile && value.startsWith(cache + "/")))) {
46
+ throw Error(("Unsupported Turbo output path: " + value));
47
+ }
48
+ let current = root;
49
+ for (const part of value.split("/")) {
50
+ current = path.join(current, part);
51
+ if (fs.lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink())
52
+ throw Error("Turbo output symlinks are unsupported");
53
+ }
54
+ return path.join(root, value);
55
+ };
56
+ const save = (value) => {
57
+ const body = JSON.stringify(value);
58
+ if (Buffer.byteLength(body) > limit)
59
+ throw Error("Turbo prototype result exceeds 48 KiB");
60
+ fs.mkdirSync(path.dirname(request.file), { recursive: true });
61
+ fs.writeFileSync(request.file, body);
62
+ };
63
+ const restore = () => {
64
+ if (Buffer.byteLength(JSON.stringify(request.files ?? [])) > limit)
65
+ throw Error("Turbo prototype inputs exceed 48 KiB");
66
+ for (const file of request.files ?? []) {
67
+ const target = safePath(file.path, true);
68
+ fs.mkdirSync(path.dirname(target), { recursive: true });
69
+ fs.writeFileSync(target, Buffer.from(file.data, "base64"), { mode: file.mode });
70
+ fs.chmodSync(target, file.mode);
71
+ }
72
+ };
73
+ if (request.operation === "restore") {
74
+ restore();
75
+ return;
76
+ }
77
+ const require = createRequire(path.join(root, "package.json"));
78
+ const turbo = require.resolve("turbo/bin/turbo");
79
+ const execute = (args, echo = false) => {
80
+ const result = spawnSync(process.execPath, [turbo, ...args], {
81
+ cwd: root,
82
+ encoding: "utf8",
83
+ env: { ...process.env, TURBO_TELEMETRY_DISABLED: "1" },
84
+ maxBuffer: 16 * 1024 * 1024,
85
+ });
86
+ if (echo || result.status !== 0) {
87
+ process.stdout.write(result.stdout ?? "");
88
+ process.stderr.write(result.stderr ?? "");
89
+ }
90
+ if (result.error)
91
+ throw result.error;
92
+ if (result.status !== 0)
93
+ throw Error(("Native Turbo failed (" + result.status + ")"));
94
+ return JSON.parse(result.stdout);
95
+ };
96
+ const flags = ["--cache=local:rw", ("--cache-dir=" + cache)];
97
+ if (request.operation === "plan") {
98
+ const tags = request.tags ?? [];
99
+ const include = tags.map(tag => ("{has: {field: TAG, value: " + JSON.stringify(tag) + "}}"));
100
+ const exclude = tags.map(tag => ("{not: {has: {field: TAG, value: " + JSON.stringify("!" + tag) + "}}}"));
101
+ const query = execute(["query", ("query { packages { items {\n tasks(filter: {and: [{or: [" + include.join(",") + "]}, " + exclude.join(",") + "]}) {\n items { fullName }\n }\n } } }")]);
102
+ if (query.errors?.length || !Array.isArray(query.data?.packages?.items))
103
+ throw Error("Native Turbo tag query failed");
104
+ const targets = query.data.packages.items.flatMap((item) => item.tasks.items.map(task => task.fullName)).sort();
105
+ if (!targets.length)
106
+ throw Error("No Turbo tasks matched the requested tags");
107
+ save(execute(["run", ...targets, ...flags, "--dry=json"]));
108
+ return;
109
+ }
110
+ restore();
111
+ const task = request.task;
112
+ const planned = execute(["run", task.taskId, ...flags, "--dry=json"]);
113
+ for (const item of planned.tasks) {
114
+ if (request.hashes?.[item.taskId] !== item.hash)
115
+ throw Error(("Turbo task identity changed: " + item.taskId));
116
+ if (item.taskId !== task.taskId && (item.cache.status !== "HIT" || item.cache.source !== "LOCAL")) {
117
+ throw Error(("Required native Turbo cache is missing: " + item.taskId + "; task admission refused"));
118
+ }
119
+ }
120
+ if (!planned.tasks.some(item => item.taskId === task.taskId))
121
+ throw Error("Native Turbo omitted the requested task");
122
+ const summaries = ".turbo/runs";
123
+ const before = new Set(fs.existsSync(summaries) ? fs.readdirSync(summaries) : []);
124
+ const run = spawnSync(process.execPath, [turbo, "run", task.taskId, ...flags, "--summarize"], {
125
+ cwd: root, encoding: "utf8", env: { ...process.env, TURBO_TELEMETRY_DISABLED: "1" },
126
+ maxBuffer: 16 * 1024 * 1024,
127
+ });
128
+ process.stdout.write(run.stdout ?? "");
129
+ process.stderr.write(run.stderr ?? "");
130
+ if (run.error)
131
+ throw run.error;
132
+ if (run.status !== 0)
133
+ throw Error(("Native Turbo task failed: " + task.taskId));
134
+ const created = fs.readdirSync(summaries).filter(name => !before.has(name) && name.endsWith(".json"));
135
+ const [summaryFile] = created;
136
+ if (created.length !== 1 || !summaryFile)
137
+ throw Error("Expected one native Turbo run summary");
138
+ const summary = JSON.parse(fs.readFileSync(path.join(summaries, summaryFile), "utf8"));
139
+ const result = summary.tasks.find((item) => item.taskId === task.taskId);
140
+ if (!result || result.hash !== task.hash || result.execution?.exitCode !== 0)
141
+ throw Error("Invalid native Turbo task result");
142
+ for (const item of summary.tasks) {
143
+ if (item.taskId !== task.taskId && (item.cache.status !== "HIT" || item.hash !== request.hashes?.[item.taskId])) {
144
+ throw Error(("Native Turbo reran a prerequisite: " + item.taskId));
145
+ }
146
+ }
147
+ const owned = [];
148
+ let encodedSize = Buffer.byteLength(JSON.stringify({ taskId: task.taskId, hash: task.hash, files: request.files ?? [] }));
149
+ const append = (output, target, mode) => {
150
+ const info = fs.lstatSync(target);
151
+ if (!info.isFile()) throw Error("Only regular Turbo files are supported");
152
+ const file = { path: output, data: "", mode, owner: task.taskId };
153
+ encodedSize += Buffer.byteLength(JSON.stringify(file)) + 4 * Math.ceil(info.size / 3) + 1;
154
+ if (encodedSize > limit) throw Error("Turbo result exceeds the prototype byte limit");
155
+ owned.push({ ...file, data: Buffer.from(fs.readFileSync(target)).toString("base64") });
156
+ };
157
+ if (!Array.isArray(result.expandedOutputs) || result.expandedOutputs.length > 1000)
158
+ throw Error("Turbo output inventory exceeds the prototype limit");
159
+ for (const output of result.expandedOutputs) {
160
+ const target = safePath(output);
161
+ const info = fs.lstatSync(target);
162
+ if (info.isDirectory())
163
+ continue;
164
+ if (!info.isFile() || info.size > limit)
165
+ throw Error("Only regular Turbo output files are supported");
166
+ append(output, target, info.mode & 0o777);
167
+ }
168
+ const cacheFiles = fs.readdirSync(cache).filter(name => name === ("" + task.hash + "-meta.json") || name === ("" + task.hash + ".tar.zst"));
169
+ if (cacheFiles.length !== 2)
170
+ throw Error(("Native Turbo did not publish a complete local cache: " + task.taskId));
171
+ for (const name of cacheFiles) {
172
+ const output = ("" + cache + "/" + name);
173
+ const target = safePath(output, true);
174
+ if (fs.statSync(target).size > limit)
175
+ throw Error("Turbo cache entry exceeds the prototype limit");
176
+ append(output, target, 0o600);
177
+ }
178
+ const files = new Map((request.files ?? []).map(file => [file.path, file]));
179
+ for (const file of owned) {
180
+ const previous = files.get(file.path);
181
+ if (previous && previous.owner !== file.owner)
182
+ throw Error(("Turbo tasks claim the same output: " + file.path));
183
+ files.set(file.path, file);
184
+ }
185
+ save({ taskId: task.taskId, hash: task.hash, files: [...files.values()] });
186
+ }
187
+ `;
188
+
189
+ // ../ci/src/turbo.ts
190
+ var shell = (value) => `'${value.replaceAll("'", "'\\''")}'`;
191
+ var command = (request) => `node --input-type=module -e ${shell(`await (${turboBridge})(${JSON.stringify(request)})`)}`;
192
+ var parsePlan = (body) => {
193
+ const plan = JSON.parse(body);
194
+ if (plan.version !== "1" || plan.turboVersion !== "2.11.10" || !Array.isArray(plan.tasks) || !plan.tasks.length || plan.tasks.length > 256) throw Error("Turbo adapter requires a 2.11.10 native task plan with at most 256 tasks");
195
+ const tasks = /* @__PURE__ */ new Map();
196
+ for (const task of plan.tasks) {
197
+ if (typeof task.taskId !== "string" || !task.taskId.includes("#") || task.taskId.startsWith("-") || /[\x00-\x1f]/.test(task.taskId) || tasks.has(task.taskId) || !/^[a-f0-9]{16}$/.test(task.hash) || !Array.isArray(task.dependencies) || typeof task.command !== "string" || !task.command || task.command === "<NONEXISTENT>" || task.resolvedTaskDefinition?.cache !== true || task.resolvedTaskDefinition.persistent !== false || task.resolvedTaskDefinition.interactive !== false || !Array.isArray(task.with) || task.with.length) {
198
+ throw Error(`Unsupported distributed Turbo task: ${task.taskId}`);
199
+ }
200
+ tasks.set(task.taskId, task);
201
+ }
202
+ const active = /* @__PURE__ */ new Set();
203
+ const complete = /* @__PURE__ */ new Set();
204
+ const visit = (id) => {
205
+ if (complete.has(id)) return;
206
+ if (active.has(id)) throw Error(`Cyclic Turbo task graph: ${id}`);
207
+ const task = tasks.get(id);
208
+ if (!task) throw Error(`Missing Turbo task dependency: ${id}`);
209
+ active.add(id);
210
+ task.dependencies.forEach(visit);
211
+ active.delete(id);
212
+ complete.add(id);
213
+ };
214
+ tasks.forEach((task) => visit(task.taskId));
215
+ return plan;
216
+ };
217
+ var mergeFiles = (inputs, tasks) => {
218
+ const files = /* @__PURE__ */ new Map();
219
+ for (const { task, body } of inputs) {
220
+ if (new TextEncoder().encode(body).length > 48 * 1024) throw Error("Turbo prototype result exceeds 48 KiB");
221
+ const result2 = JSON.parse(body);
222
+ if (result2.taskId !== task.taskId || result2.hash !== task.hash || !Array.isArray(result2.files)) throw Error("Invalid Turbo output manifest");
223
+ const owners = /* @__PURE__ */ new Set();
224
+ const visit = (id) => {
225
+ if (owners.has(id)) return;
226
+ owners.add(id);
227
+ tasks.get(id).dependencies.forEach(visit);
228
+ };
229
+ visit(task.taskId);
230
+ for (const file of result2.files) {
231
+ if (!file || typeof file.path !== "string" || typeof file.owner !== "string" || !owners.has(file.owner) || typeof file.data !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(file.data) || !Number.isInteger(file.mode) || file.mode < 0 || file.mode > 511) throw Error("Invalid Turbo output file");
232
+ const previous = files.get(file.path);
233
+ if (previous && (previous.owner !== file.owner || previous.data !== file.data || previous.mode !== file.mode)) {
234
+ throw Error(`Conflicting Turbo output: ${file.path}`);
235
+ }
236
+ files.set(file.path, file);
237
+ }
238
+ }
239
+ const result = [...files.values()].sort((left, right) => left.path.localeCompare(right.path));
240
+ if (new TextEncoder().encode(JSON.stringify(result)).length > 48 * 1024) throw Error("Turbo prototype join exceeds 48 KiB");
241
+ return result;
242
+ };
243
+ var makeTurboToolchain = (workspace, namespace, prerequisites) => ({
244
+ workspace,
245
+ tags: (...tags) => Effect.suspend(() => {
246
+ if (!tags.length || tags.some((tag) => !tag || tag.startsWith("!") || tag.length > 128)) {
247
+ return Effect.fail(Error("Provide positive Turbo tag names"));
248
+ }
249
+ const prefix = `${namespace}:turbo:${JSON.stringify([...new Set(tags)].sort())}`;
250
+ const planFile = ".effect-ci/turbo/plan.json";
251
+ const discover = action(`${prefix}:plan`, function* () {
252
+ yield* prerequisites;
253
+ return () => workspace.exec(command({ operation: "plan", file: planFile, tags }));
254
+ });
255
+ return Effect.gen(function* () {
256
+ const planned = yield* discover();
257
+ if ((yield* executionMode) === "plan") return planned;
258
+ if (planned.kind !== "remote" || !planned.revision) {
259
+ return yield* Effect.fail(Error("Distributed Turbo requires a snapshot-backed runner; use makeSnapshotRunner or Cloudflare"));
260
+ }
261
+ const body = yield* planned.readFile(planFile);
262
+ if (!body) return yield* Effect.fail(Error("Native Turbo did not produce a task plan"));
263
+ const plan = yield* Effect.try({ try: () => parsePlan(body), catch: (error) => error });
264
+ const hashes = Object.fromEntries(plan.tasks.map((task) => [task.taskId, task.hash]));
265
+ const tasks = new Map(plan.tasks.map((task) => [task.taskId, task]));
266
+ const factories = /* @__PURE__ */ new Map();
267
+ const resultFile = (task) => `.effect-ci/turbo/results/${task.hash}.json`;
268
+ const filesFrom = (inputs) => Effect.gen(function* () {
269
+ const bodies = [];
270
+ for (const input of inputs) {
271
+ const manifest = yield* input.workspace.readFile(resultFile(input.task));
272
+ if (!manifest) return yield* Effect.fail(Error(`Missing Turbo output manifest: ${input.task.taskId}`));
273
+ bodies.push({ task: input.task, body: manifest });
274
+ }
275
+ return yield* Effect.try({ try: () => mergeFiles(bodies, tasks), catch: (error) => error });
276
+ });
277
+ const factory = (id) => {
278
+ const existing = factories.get(id);
279
+ if (existing) return existing;
280
+ const task = tasks.get(id);
281
+ const parents = task.dependencies.map((dependency) => ({ task: tasks.get(dependency), run: factory(dependency) }));
282
+ const run2 = action(`${prefix}:${id}`, function* () {
283
+ if (!parents.length) yield* discover();
284
+ yield* parallel(parents.map((parent) => parent.run()));
285
+ const results = yield* Effect.all(parents.map((parent) => parent.run()));
286
+ const files2 = yield* filesFrom(parents.map((parent, index) => ({ task: parent.task, workspace: results[index] })));
287
+ return () => planned.exec(command({
288
+ operation: "run",
289
+ file: resultFile(task),
290
+ task,
291
+ hashes,
292
+ files: files2
293
+ }));
294
+ });
295
+ factories.set(id, run2);
296
+ return run2;
297
+ };
298
+ const dependencies = new Set(plan.tasks.flatMap((task) => task.dependencies));
299
+ const sinks = plan.tasks.filter((task) => !dependencies.has(task.taskId));
300
+ yield* parallel(sinks.map((task) => factory(task.taskId)()));
301
+ const outputs = yield* Effect.all(sinks.map((task) => factory(task.taskId)()));
302
+ const files = yield* filesFrom(sinks.map((task, index) => ({ task, workspace: outputs[index] })));
303
+ return yield* planned.exec(command({ operation: "restore", file: planFile, files }));
304
+ });
305
+ })
306
+ });
307
+
308
+ // ../ci/src/observers.ts
309
+ function makeRuntimeObservers(input, timeoutMs = 2e4) {
310
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 2e4 || input.length > 8)
311
+ throw Error("Invalid observational delivery policy");
312
+ const ids = /* @__PURE__ */ new Set();
313
+ const observers = input.map((observer) => {
314
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(observer.id) || ids.has(observer.id) || typeof observer.deliver !== "function")
315
+ throw Error("Invalid observational destination");
316
+ ids.add(observer.id);
317
+ return { id: observer.id, deliver: observer.deliver, blocked: false, queue: Promise.resolve() };
318
+ });
319
+ const receipts = [];
320
+ let sequence = 0, omittedReceipts = 0, droppedEvents = 0;
321
+ const record = (receipt) => {
322
+ if (receipts.length === 256) {
323
+ receipts.shift();
324
+ omittedReceipts++;
325
+ }
326
+ receipts.push(Object.freeze(receipt));
327
+ };
328
+ return Object.freeze({
329
+ async publish(event) {
330
+ const current = ++sequence;
331
+ if (current > 256) {
332
+ droppedEvents++;
333
+ return;
334
+ }
335
+ const observation = Object.freeze({
336
+ type: event.type,
337
+ workflowId: event.workflowId,
338
+ timestamp: event.timestamp,
339
+ ..."stepId" in event ? { stepId: event.stepId } : {},
340
+ ..."status" in event ? { status: event.status } : {},
341
+ ..."conclusion" in event ? { conclusion: event.conclusion } : {}
342
+ });
343
+ await Promise.all(observers.map((observer) => {
344
+ const delivery = observer.queue.then(async () => {
345
+ let status = "blocked";
346
+ if (!observer.blocked) {
347
+ const abort = new AbortController();
348
+ let timer;
349
+ try {
350
+ status = await Promise.race([
351
+ Promise.resolve().then(() => observer.deliver(observation, abort.signal)).then(
352
+ () => "delivered",
353
+ () => "failed"
354
+ ),
355
+ new Promise((resolve) => {
356
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
357
+ })
358
+ ]);
359
+ if (status !== "delivered") observer.blocked = true;
360
+ } finally {
361
+ if (timer !== void 0) clearTimeout(timer);
362
+ abort.abort();
363
+ }
364
+ }
365
+ record({ sequence: current, observer: observer.id, event: event.type, status });
366
+ });
367
+ observer.queue = delivery;
368
+ return delivery;
369
+ }));
370
+ },
371
+ snapshot: () => Object.freeze({ receipts: Object.freeze([...receipts]), omittedReceipts, droppedEvents })
372
+ });
373
+ }
374
+
375
+ // ../ci/src/index.ts
376
+ var WorkflowPlanError = class extends Error {
377
+ _tag = "WorkflowPlanError";
378
+ constructor(message) {
379
+ super(message);
380
+ }
381
+ };
382
+ var planRerun = (plan, requested) => {
383
+ const nodes = new Map(plan.nodes.map((node) => [node.id, node]));
384
+ const requestedIds = new Set(requested);
385
+ const uniqueRequested = [...requestedIds];
386
+ for (const id of uniqueRequested) {
387
+ if (!nodes.has(id)) {
388
+ throw new WorkflowPlanError(`Unknown workflow node: ${id}`);
389
+ }
390
+ }
391
+ const dependents = /* @__PURE__ */ new Map();
392
+ for (const node of plan.nodes) {
393
+ for (const dependency of node.dependencies) {
394
+ const children = dependents.get(dependency) ?? /* @__PURE__ */ new Set();
395
+ children.add(node.id);
396
+ dependents.set(dependency, children);
397
+ }
398
+ }
399
+ const affected = new Set(uniqueRequested);
400
+ const pending = [...uniqueRequested];
401
+ for (let index = 0; index < pending.length; index += 1) {
402
+ const id = pending[index];
403
+ for (const dependent of dependents.get(id) ?? []) {
404
+ if (affected.has(dependent)) continue;
405
+ affected.add(dependent);
406
+ pending.push(dependent);
407
+ }
408
+ }
409
+ return {
410
+ requested: plan.nodes.filter((node) => requestedIds.has(node.id)).map((node) => node.id),
411
+ rerun: plan.nodes.filter((node) => affected.has(node.id)).map((node) => node.id),
412
+ reuse: plan.nodes.filter((node) => !affected.has(node.id)).map((node) => node.id)
413
+ };
414
+ };
415
+ var eventFileDescriptor = Number(process.env.EFFECT_CI_EVENT_FD);
416
+ var writeEvent = (event) => {
417
+ if (!Number.isInteger(eventFileDescriptor)) return;
418
+ writeSync(eventFileDescriptor, `${JSON.stringify(event)}
419
+ `);
420
+ };
421
+ var makeEventEmitter = (handler, observers) => (event) => Effect2.tryPromise({
422
+ try: async () => {
423
+ writeEvent(event);
424
+ await handler?.(event);
425
+ await observers?.publish(event);
426
+ },
427
+ catch: (error) => error
428
+ }).pipe(Effect2.orDie);
429
+ var publishAttempt = (handler, attempt) => Effect2.tryPromise({
430
+ try: async () => {
431
+ await handler?.(attempt);
432
+ },
433
+ catch: (error) => error
434
+ }).pipe(Effect2.orDie);
435
+ var Runtime = class extends Context.Service()(
436
+ "@effect-ci-testbed/Runtime"
437
+ ) {
438
+ };
439
+ var CurrentStep = class extends Context.Service()(
440
+ "@effect-ci-testbed/CurrentStep"
441
+ ) {
442
+ };
443
+ var Attempt = class extends Context.Service()("@effect-ci-testbed/Attempt") {
444
+ };
445
+ var executionMode = Effect2.gen(function* () {
446
+ return (yield* Runtime).mode;
447
+ });
448
+ var force = Effect2.gen(function* () {
449
+ return (yield* Runtime).force;
450
+ });
451
+ var PolicyBody = class extends Context.Service()("@effect-ci-testbed/PolicyBody") {
452
+ };
453
+ var CommandError = class extends Error {
454
+ _tag = "CommandError";
455
+ stepId;
456
+ command;
457
+ cwd;
458
+ exitCode;
459
+ details;
460
+ output;
461
+ constructor(stepId, command2, cwd, exitCode, details, output) {
462
+ super(`Command failed (${exitCode}): ${command2}${details ? `
463
+ ${details}` : ""}`);
464
+ this.stepId = stepId;
465
+ this.command = command2;
466
+ this.cwd = cwd;
467
+ this.exitCode = exitCode;
468
+ this.details = details;
469
+ this.output = output;
470
+ }
471
+ };
472
+ var CommandCheckpointError = class extends Error {
473
+ _tag = "CommandCheckpointError";
474
+ stage = "checkpoint-ack";
475
+ processExitCode = null;
476
+ effects = "unknown";
477
+ stepId;
478
+ command;
479
+ cwd;
480
+ checkpoint;
481
+ constructor(stepId, command2, cwd, checkpoint) {
482
+ super(`Native command checkpoint acknowledgement failed (stage=checkpoint-ack; process exit unknown): ${command2}. External effects may already exist; reconcile the same identity, never retry automatically`);
483
+ this.name = "CommandCheckpointError";
484
+ this.stepId = stepId;
485
+ this.command = command2;
486
+ this.cwd = cwd;
487
+ this.checkpoint = checkpoint;
488
+ }
489
+ };
490
+ var CommandExecutionError = class extends Error {
491
+ _tag = "CommandExecutionError";
492
+ stage = "container-execution";
493
+ processExitCode = null;
494
+ effects = "unknown";
495
+ stepId;
496
+ command;
497
+ cwd;
498
+ constructor(stepId, command2, cwd) {
499
+ super(`Container command result unavailable (stage=container-execution; process exit unknown): ${command2}. External effects may already exist; reconcile the same identity, never retry automatically`);
500
+ this.name = "CommandExecutionError";
501
+ this.stepId = stepId;
502
+ this.command = command2;
503
+ this.cwd = cwd;
504
+ }
505
+ };
506
+ var ApprovalError = class extends Error {
507
+ _tag = "ApprovalError";
508
+ stepId;
509
+ decision;
510
+ constructor(stepId, decision, message) {
511
+ super(message);
512
+ this.stepId = stepId;
513
+ this.decision = decision;
514
+ }
515
+ };
516
+ var SecretError = class extends Error {
517
+ _tag = "SecretError";
518
+ secret;
519
+ constructor(secret, message = `Missing required secret: ${secret}`) {
520
+ super(message);
521
+ this.secret = secret;
522
+ }
523
+ };
524
+ var SecretStore = class extends Context.Service()(
525
+ "@effect-ci-testbed/SecretStore"
526
+ ) {
527
+ };
528
+ var Secret = (name) => {
529
+ if (!name.trim()) throw new Error("CI secret name cannot be empty");
530
+ return Effect2.gen(function* () {
531
+ const runtime = yield* Runtime;
532
+ const stepId = yield* CurrentStep;
533
+ yield* runtime.requireSecret(stepId, name);
534
+ if (runtime.mode === "plan") {
535
+ return Redacted.make("", { label: name });
536
+ }
537
+ const store = yield* SecretStore;
538
+ return yield* store.resolve(name);
539
+ });
540
+ };
541
+ var RollbackError = class extends Error {
542
+ _tag = "RollbackError";
543
+ stepId;
544
+ original;
545
+ rollback;
546
+ constructor(stepId, original, rollback) {
547
+ super(`Rollback for ${stepId} failed after the original action failed`, {
548
+ cause: new AggregateError([original, rollback])
549
+ });
550
+ this.stepId = stepId;
551
+ this.original = original;
552
+ this.rollback = rollback;
553
+ }
554
+ };
555
+ var Approval = class extends Context.Service()(
556
+ "@effect-ci-testbed/Approval"
557
+ ) {
558
+ };
559
+ var Workspace = class _Workspace {
560
+ cwd;
561
+ kind;
562
+ id;
563
+ revision;
564
+ constructor(cwd, kind, id, revision) {
565
+ this.cwd = cwd;
566
+ this.kind = kind;
567
+ this.id = id;
568
+ this.revision = revision;
569
+ }
570
+ static local(cwd) {
571
+ return new _Workspace(cwd, "local");
572
+ }
573
+ static remote(id, cwd, revision) {
574
+ return new _Workspace(cwd, "remote", id, revision);
575
+ }
576
+ withRevision(revision) {
577
+ return new _Workspace(this.cwd, this.kind, this.id, revision);
578
+ }
579
+ directory(path) {
580
+ if (!path || path.startsWith("/") || path.split("/").includes("..")) {
581
+ throw new Error(`Workspace directory must be relative: ${path}`);
582
+ }
583
+ return new _Workspace(join(this.cwd, path), this.kind, this.id, this.revision);
584
+ }
585
+ exec(command2, options) {
586
+ const workspace = this;
587
+ return Effect2.gen(function* () {
588
+ const runtime = yield* Runtime;
589
+ const stepId = yield* CurrentStep;
590
+ return yield* runtime.execute(stepId, workspace, command2, options);
591
+ });
592
+ }
593
+ readFile(path) {
594
+ if (path.startsWith("/") || path.split("/").includes("..")) {
595
+ return Effect2.fail(new Error(`Workspace path must be relative: ${path}`));
596
+ }
597
+ const workspace = this;
598
+ return Effect2.gen(function* () {
599
+ const runtime = yield* Runtime;
600
+ const stepId = yield* CurrentStep;
601
+ return yield* runtime.readFile(stepId, workspace, path);
602
+ });
603
+ }
604
+ exists(path) {
605
+ if (path.startsWith("/") || path.split("/").includes("..")) {
606
+ return Effect2.fail(new Error(`Workspace path must be relative: ${path}`));
607
+ }
608
+ const workspace = this;
609
+ return Effect2.gen(function* () {
610
+ const runtime = yield* Runtime;
611
+ const stepId = yield* CurrentStep;
612
+ return yield* runtime.exists(stepId, workspace, path);
613
+ });
614
+ }
615
+ checkpoint(name) {
616
+ const workspace = this;
617
+ return Effect2.gen(function* () {
618
+ const runtime = yield* Runtime;
619
+ const stepId = yield* CurrentStep;
620
+ return yield* runtime.checkpoint(stepId, workspace, name);
621
+ });
622
+ }
623
+ /** Compare deployable bytes against the host-selected successful baseline.
624
+ * Without a provider or complete knowledge, run work rather than skip it.
625
+ */
626
+ changed(patterns) {
627
+ const workspace = this;
628
+ return Effect2.gen(function* () {
629
+ return yield* (yield* Runtime).changed(yield* CurrentStep, workspace, patterns);
630
+ });
631
+ }
632
+ };
633
+ var WorkspaceCheckpoint = class {
634
+ name;
635
+ workspace;
636
+ handle;
637
+ constructor(name, workspace, handle) {
638
+ this.name = name;
639
+ this.workspace = workspace;
640
+ this.handle = handle;
641
+ }
642
+ restore() {
643
+ const checkpoint = this;
644
+ return Effect2.gen(function* () {
645
+ const runtime = yield* Runtime;
646
+ const stepId = yield* CurrentStep;
647
+ return yield* runtime.restore(stepId, checkpoint);
648
+ });
649
+ }
650
+ };
651
+ var WorkspaceArtifact = class {
652
+ name;
653
+ paths;
654
+ checkpoint;
655
+ constructor(name, paths, checkpoint) {
656
+ this.name = name;
657
+ this.paths = paths;
658
+ this.checkpoint = checkpoint;
659
+ }
660
+ };
661
+ var validateArtifact = (name, paths) => {
662
+ if (!name.trim()) throw new Error("CI artifact name cannot be empty");
663
+ if (paths.length === 0) throw new Error("CI artifact requires at least one path");
664
+ for (const path of paths) {
665
+ if (!path || path.startsWith("/") || path.split("/").includes("..")) {
666
+ throw new Error(`CI artifact path must be repository-relative: ${path}`);
667
+ }
668
+ }
669
+ };
670
+ var Artifact = {
671
+ publish: (workspace, options) => {
672
+ validateArtifact(options.name, options.paths);
673
+ return Effect2.gen(function* () {
674
+ const runtime = yield* Runtime;
675
+ const stepId = yield* CurrentStep;
676
+ yield* runtime.recordArtifact(stepId, {
677
+ direction: "publish",
678
+ name: options.name,
679
+ paths: options.paths
680
+ });
681
+ const checkpoint = yield* workspace.checkpoint(`artifact:${options.name}`);
682
+ return new WorkspaceArtifact(options.name, [...options.paths], checkpoint);
683
+ });
684
+ },
685
+ restore: (artifact) => Effect2.gen(function* () {
686
+ const runtime = yield* Runtime;
687
+ const stepId = yield* CurrentStep;
688
+ yield* runtime.recordArtifact(stepId, {
689
+ direction: "restore",
690
+ name: artifact.name,
691
+ paths: artifact.paths
692
+ });
693
+ return yield* artifact.checkpoint.restore();
694
+ })
695
+ };
696
+ var PackageManagerError = class extends Error {
697
+ _tag = "PackageManagerError";
698
+ cwd;
699
+ constructor(cwd, message) {
700
+ super(message);
701
+ this.cwd = cwd;
702
+ }
703
+ };
704
+ var Apt = (workspace) => Effect2.gen(function* () {
705
+ const packageName = /^[a-zA-Z0-9][a-zA-Z0-9+.-]*$/;
706
+ return {
707
+ workspace,
708
+ install: (packages) => {
709
+ const invalid = packages.find((name) => !packageName.test(name));
710
+ if (invalid) {
711
+ return Effect2.fail(new PackageManagerError(
712
+ workspace.cwd,
713
+ `Invalid apt package name: ${invalid}`
714
+ ));
715
+ }
716
+ const names = packages.join(" ");
717
+ const install = `apt-get install --yes --no-install-recommends ${names}`;
718
+ return workspace.exec(
719
+ `if [ "$(id -u)" -eq 0 ]; then apt-get update && DEBIAN_FRONTEND=noninteractive ${install}; else sudo apt-get update && sudo env DEBIAN_FRONTEND=noninteractive ${install}; fi`
720
+ );
721
+ }
722
+ };
723
+ });
724
+ var VitePlusAvailable = Context.Reference(
725
+ "@effect-ci-testbed/VitePlusAvailable",
726
+ { defaultValue: () => () => false }
727
+ );
728
+ var shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
729
+ var vp = `PATH="$PATH:$PWD/node_modules/.bin" vp`;
730
+ var vitePlusRun = (workspace, name, cache) => Effect2.gen(function* () {
731
+ let noCache = (yield* force) ? " --no-cache" : cache ? " --cache" : "";
732
+ let traced = !(yield* force);
733
+ if ((yield* executionMode) === "execute") {
734
+ const file = `node_modules/.effect-ci-vite-plus-run-plan-${name.replaceAll(/[^\w-]/g, "_")}.json`;
735
+ yield* workspace.exec(
736
+ `mkdir -p node_modules && ${vp} run --dry-run --json${noCache} -vv ${shellQuote(name)} > ${file}`,
737
+ { diagnostic: true }
738
+ );
739
+ const body = yield* workspace.readFile(file);
740
+ if (body === void 0) return yield* Effect2.fail(new Error(`Vite+ wrote no run plan to ${file}`));
741
+ const lines = yield* Effect2.try({ try: () => cacheLog(body), catch: (error) => error });
742
+ for (const line of lines) yield* line.level === "Info" ? Effect2.logInfo(line.message) : Effect2.logDebug(line.message);
743
+ const untraced = traced ? untracedHits(body) : [];
744
+ if (untraced.length > 0) {
745
+ yield* Effect2.logWarning(`vite+ ${untraced.join(", ")}: the cached run read no project files, so running without the cache`);
746
+ noCache = " --no-cache";
747
+ traced = false;
748
+ }
749
+ }
750
+ return yield* workspace.exec(
751
+ `${vp} run -v${noCache} ${shellQuote(name)}`,
752
+ traced ? { trace: { tool: "vite-plus", task: name } } : void 0
753
+ );
754
+ });
755
+ var withVitePlus = (manager, vitePlus) => ({
756
+ ...manager,
757
+ vitePlus,
758
+ run: (name, options) => vitePlus ? vitePlusRun(manager.workspace, name, options?.cache ?? true) : manager.run(name)
759
+ });
760
+ var fromPackageManagerField = (contents) => {
761
+ if (!contents) return void 0;
762
+ const packageJson = JSON.parse(contents);
763
+ const name = packageJson.packageManager?.split("@")[0];
764
+ return name === "npm" || name === "pnpm" || name === "yarn" || name === "bun" ? name : void 0;
765
+ };
766
+ var lockfiles = [
767
+ ["npm", "package-lock.json"],
768
+ ["pnpm", "pnpm-lock.yaml"],
769
+ ["yarn", "yarn.lock"],
770
+ ["bun", "bun.lock"],
771
+ ["bun", "bun.lockb"]
772
+ ];
773
+ var detectJavaScript = (workspace) => Effect2.gen(function* () {
774
+ const packageJson = yield* workspace.readFile("package.json");
775
+ const lockfileMatches = [];
776
+ for (const [name2, file] of lockfiles) {
777
+ if (yield* workspace.exists(file)) {
778
+ lockfileMatches.push(name2);
779
+ }
780
+ }
781
+ const names = [...new Set(lockfileMatches)];
782
+ if (names.length > 1) {
783
+ return yield* Effect2.fail(new PackageManagerError(
784
+ workspace.cwd,
785
+ `Multiple JavaScript package-manager lockfiles found: ${names.join(", ")}`
786
+ ));
787
+ }
788
+ const declaredManager = yield* Effect2.try({
789
+ try: () => fromPackageManagerField(packageJson),
790
+ catch: (error) => new PackageManagerError(workspace.cwd, String(error))
791
+ });
792
+ if (!declaredManager && names.length === 0) {
793
+ let ancestor = workspace;
794
+ while (!(yield* ancestor.exists(".git")) && dirname(ancestor.cwd) !== ancestor.cwd) {
795
+ ancestor = workspace.kind === "local" ? Workspace.local(dirname(ancestor.cwd)) : Workspace.remote(workspace.id, dirname(ancestor.cwd), workspace.revision);
796
+ const ancestorManifest = yield* ancestor.readFile("package.json");
797
+ const workspaceYaml = yield* ancestor.readFile("pnpm-workspace.yaml");
798
+ const member = yield* Effect2.tryPromise({
799
+ try: async () => {
800
+ const manifest = JSON.parse(ancestorManifest ?? "{}");
801
+ const patterns = workspaceYaml !== void 0 ? (await import("yaml")).parse(workspaceYaml)?.packages ?? [] : Array.isArray(manifest.workspaces) ? manifest.workspaces : manifest.workspaces?.packages;
802
+ if (patterns === void 0) return void 0;
803
+ if (!Array.isArray(patterns) || patterns.some((pattern) => typeof pattern !== "string"))
804
+ throw new Error("Workspace packages must be an array of globs");
805
+ const path = relative(ancestor.cwd, workspace.cwd).split("\\").join("/");
806
+ const included = patterns.filter((pattern) => !pattern.startsWith("!"));
807
+ const excluded = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1));
808
+ return patterns.length > 0 && picomatch(included.length ? included : ["**"])(path) && !picomatch([...excluded, "**/node_modules/**", "**/bower_components/**"])(path);
809
+ },
810
+ catch: (error) => new PackageManagerError(ancestor.cwd, String(error))
811
+ });
812
+ if (member === false) break;
813
+ if (member) {
814
+ const owner = yield* detectJavaScript(ancestor);
815
+ return {
816
+ ...owner,
817
+ workspace,
818
+ install: (options) => owner.install(options).pipe(Effect2.as(workspace)),
819
+ run: (script) => workspace.exec(`${owner.name} run ${JSON.stringify(script)}`),
820
+ exec: (command3) => workspace.exec(`${owner.name === "bun" ? "bunx" : owner.name === "npm" ? "npm exec --" : `${owner.name} exec`} ${command3}`)
821
+ };
822
+ }
823
+ }
824
+ }
825
+ const name = yield* Effect2.try({
826
+ try: () => {
827
+ const [lockfileManager] = names;
828
+ const detected = declaredManager ?? lockfileManager;
829
+ if (!detected) {
830
+ throw new PackageManagerError(
831
+ workspace.cwd,
832
+ "Could not detect a JavaScript package manager from packageManager or a lockfile"
833
+ );
834
+ }
835
+ return detected;
836
+ },
837
+ catch: (error) => error instanceof PackageManagerError ? error : new PackageManagerError(workspace.cwd, String(error))
838
+ });
839
+ const standalonePnpm = name === "pnpm" && !(yield* workspace.exists("pnpm-workspace.yaml"));
840
+ const executable = name === "pnpm" && standalonePnpm ? "pnpm --ignore-workspace" : name;
841
+ const command2 = (operation, value, frozenLockfile = false, offline = false, runnerCache = workspace.kind === "remote") => {
842
+ switch (operation) {
843
+ case "install": {
844
+ const offlineFlag = offline ? " --offline" : "";
845
+ const pnpmStore = runnerCache ? " --store-dir .effect-ci/cache/pnpm" : "";
846
+ if (!frozenLockfile) {
847
+ switch (name) {
848
+ case "npm":
849
+ return `npm_config_cache=.effect-ci/cache/npm npm install${offlineFlag}`;
850
+ case "pnpm":
851
+ return `${executable} install${pnpmStore}${offlineFlag}`;
852
+ case "yarn":
853
+ return `YARN_CACHE_FOLDER=.effect-ci/cache/yarn yarn install${offlineFlag}`;
854
+ case "bun":
855
+ return `bun install --cache-dir .effect-ci/cache/bun${offlineFlag}`;
856
+ }
857
+ }
858
+ switch (name) {
859
+ case "npm":
860
+ return `npm_config_cache=.effect-ci/cache/npm npm ci${offlineFlag}`;
861
+ case "pnpm":
862
+ return `${executable} install --frozen-lockfile${pnpmStore}${offlineFlag}`;
863
+ case "yarn":
864
+ return `YARN_CACHE_FOLDER=.effect-ci/cache/yarn yarn install --immutable${offlineFlag}`;
865
+ case "bun":
866
+ return `bun install --frozen-lockfile --cache-dir .effect-ci/cache/bun${offlineFlag}`;
867
+ }
868
+ }
869
+ case "run":
870
+ return `${executable} run ${JSON.stringify(value)}`;
871
+ case "exec":
872
+ if (name === "bun") return `bunx ${value}`;
873
+ return name === "npm" ? `npm exec -- ${value}` : `${executable} exec ${value}`;
874
+ }
875
+ };
876
+ return {
877
+ name,
878
+ workspace,
879
+ install: (options) => Effect2.gen(function* () {
880
+ const runtime = yield* Runtime;
881
+ const frozenLockfile = options?.frozenLockfile ?? true;
882
+ return yield* workspace.exec(command2(
883
+ "install",
884
+ void 0,
885
+ frozenLockfile,
886
+ options?.offline ?? false,
887
+ workspace.kind === "remote" || runtime.ci
888
+ ));
889
+ }),
890
+ run: (script) => workspace.exec(command2("run", script)),
891
+ exec: (executable2) => workspace.exec(command2("exec", executable2))
892
+ };
893
+ }).pipe(
894
+ Effect2.mapError((error) => error instanceof PackageManagerError ? error : new PackageManagerError(workspace.cwd, String(error)))
895
+ );
896
+ var JavaScript = (workspace) => Effect2.gen(function* () {
897
+ const manager = yield* detectJavaScript(workspace);
898
+ const available = yield* VitePlusAvailable;
899
+ return withVitePlus(manager, available(workspace));
900
+ });
901
+ var VitePlus = (workspace) => detectJavaScript(workspace).pipe(Effect2.map((manager) => withVitePlus(manager, true)));
902
+ var PackageManager = { Apt, JavaScript, VitePlus };
903
+ var ToolchainError = class extends Error {
904
+ _tag = "ToolchainError";
905
+ cwd;
906
+ constructor(cwd, message) {
907
+ super(message);
908
+ this.cwd = cwd;
909
+ }
910
+ };
911
+ var miseEnvironment = [
912
+ "MISE_DATA_DIR=.effect-ci/cache/mise/data",
913
+ "MISE_CACHE_DIR=.effect-ci/cache/mise/cache"
914
+ ].join(" ");
915
+ var nodeVersion = (packageJson) => {
916
+ if (!packageJson) return void 0;
917
+ const value = JSON.parse(packageJson);
918
+ const runtime = Array.isArray(value.devEngines?.runtime) ? value.devEngines.runtime[0] : value.devEngines?.runtime;
919
+ return runtime?.name === "node" ? runtime.version : void 0;
920
+ };
921
+ var Node = (workspace) => Effect2.gen(function* () {
922
+ let version;
923
+ for (const path of [".node-version", ".nvmrc"]) {
924
+ const contents = yield* workspace.readFile(path);
925
+ if (contents) {
926
+ version = contents.trim();
927
+ break;
928
+ }
929
+ }
930
+ version ??= nodeVersion(yield* workspace.readFile("package.json"));
931
+ if (!version) {
932
+ return yield* Effect2.fail(new ToolchainError(
933
+ workspace.cwd,
934
+ "Could not find a Node.js version in .node-version, .nvmrc, or package.json#devEngines.runtime"
935
+ ));
936
+ }
937
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._+*/-]*$/.test(version)) {
938
+ return yield* Effect2.fail(new ToolchainError(
939
+ workspace.cwd,
940
+ `Invalid Node.js version request: ${version}`
941
+ ));
942
+ }
943
+ const tool = `node@${version}`;
944
+ return {
945
+ version,
946
+ workspace,
947
+ install: () => workspace.exec(`${miseEnvironment} mise --yes install ${tool}`),
948
+ exec: (command2) => workspace.exec(
949
+ `${miseEnvironment} mise exec ${tool} -- ${command2}`
950
+ )
951
+ };
952
+ }).pipe(
953
+ Effect2.mapError((error) => error instanceof ToolchainError ? error : new ToolchainError(workspace.cwd, String(error)))
954
+ );
955
+ var Mise = (workspace) => Effect2.gen(function* () {
956
+ const configurations = ["mise.toml", ".mise.toml", ".tool-versions"];
957
+ let configured = false;
958
+ for (const path of configurations) {
959
+ if (yield* workspace.exists(path)) {
960
+ configured = true;
961
+ break;
962
+ }
963
+ }
964
+ if (!configured) {
965
+ return yield* Effect2.fail(new ToolchainError(
966
+ workspace.cwd,
967
+ `Could not find a Mise configuration (${configurations.join(", ")})`
968
+ ));
969
+ }
970
+ return {
971
+ workspace,
972
+ install: (options) => workspace.exec(
973
+ `${miseEnvironment} mise --yes${options?.locked ? " --locked" : ""} install`
974
+ ),
975
+ exec: (command2) => workspace.exec(
976
+ `${miseEnvironment} mise exec -- ${command2}`
977
+ )
978
+ };
979
+ }).pipe(
980
+ Effect2.mapError((error) => error instanceof ToolchainError ? error : new ToolchainError(workspace.cwd, String(error)))
981
+ );
982
+ var Turbo = (workspace) => Effect2.gen(function* () {
983
+ const runtime = yield* Runtime;
984
+ const owner = yield* CurrentStep;
985
+ const dependencies = [...runtime.edges].filter((edge) => edge.startsWith(`${owner}->`)).map((edge) => edge.slice(owner.length + 2));
986
+ return makeTurboToolchain(workspace, owner, Effect2.gen(function* () {
987
+ const current = yield* CurrentStep;
988
+ for (const dependency of dependencies) yield* runtime.addDependency(current, dependency);
989
+ }));
990
+ });
991
+ var Toolchain = { Node, Mise, Turbo };
992
+ var Source = class extends Context.Service()(
993
+ "@effect-ci-testbed/Source"
994
+ ) {
995
+ };
996
+ var localSource = {
997
+ checkout: () => Effect2.succeed(Workspace.local(process.cwd())),
998
+ reference: { kind: "local", path: process.cwd() }
999
+ };
1000
+ var cacheOrElse = (operation, fallback) => Effect2.suspend(operation).pipe(Effect2.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect2.failCause(Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason))) : Effect2.succeed(fallback)));
1001
+ var localWorkspaceFileSystem = {
1002
+ exists: (workspace, path) => Effect2.sync(() => existsSync(join(workspace.cwd, path))),
1003
+ readFile: (workspace, path) => Effect2.try({
1004
+ try: () => {
1005
+ const target = join(workspace.cwd, path);
1006
+ return existsSync(target) ? readFileSync(target, "utf8") : void 0;
1007
+ },
1008
+ catch: (error) => error
1009
+ })
1010
+ };
1011
+ var WorkflowEvent = class extends Context.Service()(
1012
+ "@effect-ci-testbed/WorkflowEvent"
1013
+ ) {
1014
+ };
1015
+ var Condition = {
1016
+ event: (...oneOf) => ({
1017
+ _tag: "event",
1018
+ oneOf
1019
+ }),
1020
+ ref: (...oneOf) => ({
1021
+ _tag: "ref",
1022
+ oneOf
1023
+ }),
1024
+ all: (...conditions) => ({
1025
+ _tag: "all",
1026
+ conditions
1027
+ }),
1028
+ any: (...conditions) => ({
1029
+ _tag: "any",
1030
+ conditions
1031
+ }),
1032
+ not: (condition) => ({ _tag: "not", condition })
1033
+ };
1034
+ var matchesCondition = (condition, event) => {
1035
+ const payloadRef = event.payload && typeof event.payload === "object" && "ref" in event.payload && typeof event.payload.ref === "string" ? event.payload.ref : void 0;
1036
+ const ref = event.ref ?? payloadRef;
1037
+ switch (condition._tag) {
1038
+ case "event":
1039
+ return condition.oneOf.includes(event.type);
1040
+ case "ref":
1041
+ return ref !== void 0 && condition.oneOf.includes(ref);
1042
+ case "all":
1043
+ return condition.conditions.every((child) => matchesCondition(child, event));
1044
+ case "any":
1045
+ return condition.conditions.some((child) => matchesCondition(child, event));
1046
+ case "not":
1047
+ return !matchesCondition(condition.condition, event);
1048
+ }
1049
+ };
1050
+ var actionDefinitions = /* @__PURE__ */ new WeakMap();
1051
+ var registerDefinition = (runtime, definition) => {
1052
+ const existing = runtime.definitions.get(definition.id);
1053
+ if (existing && existing !== definition && (!definition.identity || existing.identity !== definition.identity)) {
1054
+ throw new Error(`Duplicate CI action id: ${definition.id}`);
1055
+ }
1056
+ if (!existing) runtime.definitions.set(definition.id, definition);
1057
+ };
1058
+ var bodyToEffect = (body) => {
1059
+ if (Effect2.isEffect(body)) return body;
1060
+ return Effect2.suspend(() => {
1061
+ const result = body();
1062
+ if (Effect2.isEffect(result)) return result;
1063
+ if (result && typeof result === "object" && "next" in result) {
1064
+ return Effect2.gen(() => result);
1065
+ }
1066
+ if (result && typeof result === "object" && "then" in result) {
1067
+ return Effect2.tryPromise({
1068
+ try: () => result,
1069
+ catch: (error) => error
1070
+ });
1071
+ }
1072
+ return Effect2.succeed(result);
1073
+ });
1074
+ };
1075
+ var validateStepOptions = (id, options) => {
1076
+ if (options.retries) {
1077
+ if (!Number.isInteger(options.retries.limit) || options.retries.limit < 0) {
1078
+ throw new Error(`CI step ${id} retry limit must be a non-negative integer`);
1079
+ }
1080
+ if (typeof options.retries.delay === "number" && options.retries.delay < 0) {
1081
+ throw new Error(`CI step ${id} retry delay cannot be negative`);
1082
+ }
1083
+ }
1084
+ if (typeof options.timeout === "number" && options.timeout <= 0) {
1085
+ throw new Error(`CI step ${id} timeout must be greater than zero`);
1086
+ }
1087
+ };
1088
+ var runStep = (definition, dependencies = []) => {
1089
+ const id = definition.id;
1090
+ const effect = Effect2.gen(function* () {
1091
+ const boundary = yield* Effect2.serviceOption(PolicyBody);
1092
+ if (boundary._tag === "Some" && boundary.value) {
1093
+ return yield* Effect2.fail(new WorkflowPlanError(
1094
+ `Resolve dependency ${id} during action construction, before returning the policy-bearing body`
1095
+ ));
1096
+ }
1097
+ const runtime = yield* Runtime;
1098
+ registerDefinition(runtime, definition);
1099
+ const parent = yield* CurrentStep;
1100
+ yield* runtime.addDependency(parent, id);
1101
+ for (const dependency of dependencies) {
1102
+ yield* runtime.addDependency(id, dependency);
1103
+ }
1104
+ return yield* Cache.get(runtime.cache, id);
1105
+ });
1106
+ actionIds.set(effect, id);
1107
+ actionDefinitions.set(effect, definition);
1108
+ return effect;
1109
+ };
1110
+ var actionIds = /* @__PURE__ */ new WeakMap();
1111
+ var actionFactories = /* @__PURE__ */ new WeakSet();
1112
+ var actionFactoryIds = /* @__PURE__ */ new WeakMap();
1113
+ var optionalEffects = /* @__PURE__ */ new WeakSet();
1114
+ var optional = (effect) => {
1115
+ const stepId = actionIds.get(effect);
1116
+ if (!stepId) throw new Error("CI.optional expects a CI action or step");
1117
+ const optionalEffect = Effect2.gen(function* () {
1118
+ const runtime = yield* Runtime;
1119
+ yield* runtime.markOptional(stepId);
1120
+ return yield* effect.pipe(
1121
+ Effect2.catch((error) => runtime.recoverOptional(stepId).pipe(
1122
+ Effect2.flatMap((recovered) => recovered ? Effect2.succeed(void 0) : Effect2.fail(error))
1123
+ ))
1124
+ );
1125
+ });
1126
+ actionIds.set(optionalEffect, stepId);
1127
+ const definition = actionDefinitions.get(effect);
1128
+ if (definition) actionDefinitions.set(optionalEffect, definition);
1129
+ optionalEffects.add(optionalEffect);
1130
+ return optionalEffect;
1131
+ };
1132
+ var when = (condition, effect) => {
1133
+ const stepId = actionIds.get(effect);
1134
+ if (!stepId) throw new Error("CI.when expects a CI action or step");
1135
+ const conditional = Effect2.gen(function* () {
1136
+ const runtime = yield* Runtime;
1137
+ const definition2 = actionDefinitions.get(effect);
1138
+ if (definition2) registerDefinition(runtime, definition2);
1139
+ const parent = yield* CurrentStep;
1140
+ if (runtime.mode === "plan") {
1141
+ const value = yield* effect;
1142
+ const node = runtime.nodes.get(stepId);
1143
+ if (node) node.condition = condition;
1144
+ return value;
1145
+ }
1146
+ const event = yield* WorkflowEvent;
1147
+ if (matchesCondition(condition, event)) return yield* effect;
1148
+ yield* runtime.addDependency(parent, stepId);
1149
+ yield* runtime.skip(stepId, condition);
1150
+ return void 0;
1151
+ });
1152
+ actionIds.set(conditional, stepId);
1153
+ const definition = actionDefinitions.get(effect);
1154
+ if (definition) actionDefinitions.set(conditional, definition);
1155
+ return conditional;
1156
+ };
1157
+ var parallel = (effects) => {
1158
+ const steps = effects.map((effect) => {
1159
+ const id = actionIds.get(effect);
1160
+ if (!id) throw new Error("CI.parallel expects CI actions or steps");
1161
+ return { id, optional: optionalEffects.has(effect) };
1162
+ });
1163
+ return Effect2.gen(function* () {
1164
+ const runtime = yield* Runtime;
1165
+ const parent = yield* CurrentStep;
1166
+ yield* runtime.addParallel(parent, steps);
1167
+ return yield* Effect2.validate(
1168
+ effects,
1169
+ (effect) => effect,
1170
+ { concurrency: "unbounded", discard: true }
1171
+ ).pipe(Effect2.mapError((errors) => {
1172
+ const distinct = [...new Set(errors)];
1173
+ return distinct.length === 1 ? distinct[0] : new AggregateError(
1174
+ distinct,
1175
+ `${distinct.length} parallel actions failed. Inspect the failed action checkpoints.`
1176
+ );
1177
+ }));
1178
+ });
1179
+ };
1180
+ var step = (id, body, options = {}) => {
1181
+ validateStepOptions(id, options);
1182
+ return runStep({ id, body: bodyToEffect(body), options });
1183
+ };
1184
+ var action = (id, construction, options = {}) => {
1185
+ const identity = {};
1186
+ const factory = (...args) => {
1187
+ validateStepOptions(id, options);
1188
+ const rollback = options.rollback ? (() => {
1189
+ const rollbackEffect = options.rollback();
1190
+ const rollbackId = actionFactoryIds.get(options.rollback);
1191
+ if (!rollbackId) {
1192
+ throw new Error(`Rollback for ${id} must be a CI action`);
1193
+ }
1194
+ return { id: rollbackId, effect: rollbackEffect };
1195
+ })() : void 0;
1196
+ const { rollback: _rollback, ...stepOptions } = options;
1197
+ const definition = {
1198
+ identity,
1199
+ id,
1200
+ body: bodyToEffect(construction).pipe(
1201
+ Effect2.flatMap((handler) => bodyToEffect(() => handler(...args)))
1202
+ ),
1203
+ prepare: bodyToEffect(construction).pipe(
1204
+ Effect2.map((handler) => bodyToEffect(() => handler(...args)))
1205
+ ),
1206
+ options: stepOptions,
1207
+ ...rollback ? { rollback } : {}
1208
+ };
1209
+ return runStep(definition);
1210
+ };
1211
+ actionFactories.add(factory);
1212
+ actionFactoryIds.set(factory, id);
1213
+ return factory;
1214
+ };
1215
+ var check = (id, construction, options = {}) => action(id, bodyToEffect(construction).pipe(Effect2.map((handler) => (...args) => Effect2.asVoid(bodyToEffect(() => handler(...args))))), options);
1216
+ var isAction = (value) => typeof value === "function" && actionFactories.has(value);
1217
+ var workflow = (id, body) => ({
1218
+ id,
1219
+ effect: bodyToEffect(body)
1220
+ });
1221
+ var makeLocalCommandExecutor = (output = "inherit") => ({
1222
+ execute: ({ command: command2, onOutput, stepId, workspace }) => Effect2.callback((resume) => {
1223
+ const stdout = [];
1224
+ const stderr = [];
1225
+ const { EFFECT_CI_EVENT_FD: _eventPipe, ...commandEnvironment } = process.env;
1226
+ const colorDepth = output === "inherit" && process.env.FORCE_COLOR === void 0 && process.env.NO_COLOR === void 0 && process.env.NODE_DISABLE_COLORS === void 0 ? Math.max(
1227
+ process.stdout.isTTY ? process.stdout.getColorDepth() : 1,
1228
+ process.stderr.isTTY ? process.stderr.getColorDepth() : 1
1229
+ ) : 1;
1230
+ const child = spawn(command2, {
1231
+ cwd: workspace.cwd,
1232
+ env: colorDepth > 1 ? { ...commandEnvironment, FORCE_COLOR: colorDepth >= 24 ? "3" : colorDepth >= 8 ? "2" : "1" } : commandEnvironment,
1233
+ shell: true,
1234
+ stdio: ["inherit", "pipe", "pipe"]
1235
+ });
1236
+ const forward = (stream, chunk) => {
1237
+ const text = chunk.toString();
1238
+ if (stream === "stdout") {
1239
+ stdout.push(text);
1240
+ } else {
1241
+ stderr.push(text);
1242
+ }
1243
+ onOutput(stream, text);
1244
+ };
1245
+ child.stdout?.on("data", (chunk) => forward("stdout", chunk));
1246
+ child.stderr?.on("data", (chunk) => forward("stderr", chunk));
1247
+ child.once("error", () => resume(Effect2.fail(new CommandError(stepId, command2, workspace.cwd, 1))));
1248
+ child.once("close", (code) => {
1249
+ const stdoutText = stdout.join(""), stderrText = stderr.join("");
1250
+ const limit = 32 * 1024;
1251
+ resume(code === 0 ? Effect2.succeed({ exitCode: 0, stderr: stderrText, stdout: stdoutText }) : Effect2.fail(new CommandError(stepId, command2, workspace.cwd, code ?? 1, void 0, {
1252
+ stdout: stdoutText.slice(-limit),
1253
+ stderr: stderrText.slice(-limit),
1254
+ truncated: stdoutText.length > limit || stderrText.length > limit
1255
+ })));
1256
+ });
1257
+ return Effect2.sync(() => child.kill("SIGTERM"));
1258
+ })
1259
+ });
1260
+ var withStepPolicy = (effect, options) => {
1261
+ let attempt = 0;
1262
+ const effectBody = effect;
1263
+ effect = Effect2.suspend(() => effectBody.pipe(Effect2.provideService(Attempt, ++attempt)));
1264
+ const timed = options.timeout === void 0 ? effect : effect.pipe(Effect2.timeout(options.timeout));
1265
+ const retries = options.retries;
1266
+ if (!retries || retries.limit <= 0) return timed;
1267
+ const schedule = retries.backoff === "exponential" ? Schedule.exponential(retries.delay) : retries.backoff === "linear" ? Schedule.addDelay(
1268
+ Schedule.forever,
1269
+ ({ output: attempt2 }) => Effect2.succeed(Duration.times(
1270
+ Duration.fromInputUnsafe(retries.delay),
1271
+ attempt2 + 1
1272
+ ))
1273
+ ) : Schedule.spaced(retries.delay);
1274
+ return timed.pipe(Effect2.retry({ times: retries.limit, schedule }));
1275
+ };
1276
+ var makeRuntime = (workflowId, ci, mode, output, emitEvent, event, approvalHandler, commandExecutor = makeLocalCommandExecutor(output), workspaceFileSystem = localWorkspaceFileSystem, workspacePersistence = {
1277
+ commit: ({ workspace }) => Effect2.succeed(workspace),
1278
+ checkpoint: () => Effect2.succeed({ provider: "local", value: void 0 }),
1279
+ restore: ({ checkpoint }) => Effect2.succeed(checkpoint.workspace)
1280
+ }, checkCache, rerun, actionExecutor, stepResultCache, workspaceChanges, force2 = false) => Effect2.gen(function* () {
1281
+ const definitions = /* @__PURE__ */ new Map();
1282
+ const bufferedEvents = /* @__PURE__ */ new Map();
1283
+ const emitOutsideBody = emitEvent;
1284
+ emitEvent = (event2) => {
1285
+ const buffer = "stepId" in event2 ? bufferedEvents.get(event2.stepId) : void 0;
1286
+ return buffer ? Effect2.sync(() => {
1287
+ buffer.push(event2);
1288
+ }) : emitOutsideBody(event2);
1289
+ };
1290
+ const nodes = /* @__PURE__ */ new Map();
1291
+ const afterEdges = /* @__PURE__ */ new Set();
1292
+ const edges = /* @__PURE__ */ new Set();
1293
+ const failureOrigins = /* @__PURE__ */ new Map();
1294
+ const optionalSteps = /* @__PURE__ */ new Set();
1295
+ const outputs = /* @__PURE__ */ new Map();
1296
+ const parallelSteps = /* @__PURE__ */ new Set();
1297
+ const completedRollbacks = [];
1298
+ const reusable = new Set(rerun?.selection.reuse ?? []);
1299
+ const previousNodes = new Map(
1300
+ rerun?.previous.plan.nodes.map((node) => [node.id, node]) ?? []
1301
+ );
1302
+ let workflowBarrier = { after: [], dependencies: [] };
1303
+ let runtime;
1304
+ for (const id of reusable) {
1305
+ const previousNode = previousNodes.get(id);
1306
+ if (!previousNode) {
1307
+ return yield* Effect2.fail(new WorkflowPlanError(
1308
+ `Previous attempt has no plan node for reusable step: ${id}`
1309
+ ));
1310
+ }
1311
+ if (!Object.hasOwn(rerun?.previous.outputs ?? {}, id)) {
1312
+ return yield* Effect2.fail(new WorkflowPlanError(
1313
+ `Previous attempt has no output for reusable step: ${id}`
1314
+ ));
1315
+ }
1316
+ for (const dependency of previousNode.dependencies) edges.add(`${id}->${dependency}`);
1317
+ for (const dependency of previousNode.after) afterEdges.add(`${id}->${dependency}`);
1318
+ if (previousNode.optional) optionalSteps.add(id);
1319
+ nodes.set(id, {
1320
+ id,
1321
+ artifacts: [...previousNode.artifacts ?? []],
1322
+ commands: [...previousNode.commands],
1323
+ ...previousNode.approval ? { approval: previousNode.approval } : {},
1324
+ ...previousNode.condition ? { condition: previousNode.condition } : {},
1325
+ ...previousNode.rollbackFor ? { rollbackFor: previousNode.rollbackFor } : {},
1326
+ secrets: new Set(previousNode.secrets ?? []),
1327
+ executedCommands: 0,
1328
+ verifiedCommands: 0,
1329
+ status: "reused"
1330
+ });
1331
+ outputs.set(id, rerun.previous.outputs[id]);
1332
+ yield* emitEvent({
1333
+ type: "step.status",
1334
+ workflowId,
1335
+ stepId: id,
1336
+ status: "reused",
1337
+ optional: previousNode.optional,
1338
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1339
+ });
1340
+ }
1341
+ const cache = yield* Cache.make({
1342
+ capacity: 1e3,
1343
+ timeToLive: Duration.infinity,
1344
+ requireServicesAt: "lookup",
1345
+ lookup: (id) => {
1346
+ const definition = definitions.get(id);
1347
+ if (!definition) return Effect2.fail(new Error(`Unknown CI step: ${id}`));
1348
+ const node = nodes.get(id) ?? {
1349
+ id,
1350
+ artifacts: [],
1351
+ commands: [],
1352
+ secrets: /* @__PURE__ */ new Set(),
1353
+ executedCommands: 0,
1354
+ verifiedCommands: 0,
1355
+ status: "planned"
1356
+ };
1357
+ nodes.set(id, node);
1358
+ if (reusable.has(id)) {
1359
+ const reused = Effect2.succeed(outputs.get(id));
1360
+ if (!definition.rollback || mode !== "execute") return reused;
1361
+ return runtime.registerRollback(
1362
+ id,
1363
+ definition.rollback.id,
1364
+ definition.rollback.effect
1365
+ ).pipe(
1366
+ Effect2.tap(() => Effect2.sync(() => {
1367
+ completedRollbacks.push({
1368
+ primaryId: id,
1369
+ rollbackId: definition.rollback.id,
1370
+ effect: definition.rollback.effect
1371
+ });
1372
+ })),
1373
+ Effect2.andThen(reused)
1374
+ );
1375
+ }
1376
+ node.status = mode === "plan" ? "planned" : "queued";
1377
+ const queued = emitEvent({
1378
+ type: "step.status",
1379
+ workflowId,
1380
+ stepId: id,
1381
+ status: node.status,
1382
+ optional: optionalSteps.has(id),
1383
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1384
+ });
1385
+ const prepared = definition.prepare ?? Effect2.succeed(definition.body);
1386
+ const commit = (value) => mode === "execute" && value instanceof Workspace ? workspacePersistence.commit({ stepId: id, workflowId, workspace: value }) : Effect2.succeed(value);
1387
+ const body = prepared.pipe(Effect2.flatMap((leaf) => {
1388
+ if (mode === "execute" && actionExecutor && definition.options.checkpoint !== "command" && (definition.options.retries !== void 0 || definition.options.timeout !== void 0)) {
1389
+ node.status = "running";
1390
+ const started = emitEvent({
1391
+ type: "step.status",
1392
+ workflowId,
1393
+ stepId: id,
1394
+ status: "running",
1395
+ optional: optionalSteps.has(id),
1396
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1397
+ });
1398
+ return started.pipe(Effect2.andThen(actionExecutor.execute({
1399
+ stepId: id,
1400
+ options: definition.options,
1401
+ run: (attempt) => Effect2.sync(() => {
1402
+ node.commands.length = 0;
1403
+ bufferedEvents.set(id, []);
1404
+ }).pipe(
1405
+ Effect2.andThen(leaf),
1406
+ Effect2.flatMap(commit),
1407
+ Effect2.map((value) => ({
1408
+ value,
1409
+ commands: [...node.commands],
1410
+ events: [...bufferedEvents.get(id)],
1411
+ metadata: {
1412
+ artifacts: [...node.artifacts],
1413
+ secrets: [...node.secrets],
1414
+ ...node.approval ? { approval: node.approval } : {}
1415
+ }
1416
+ })),
1417
+ Effect2.provideService(Attempt, attempt),
1418
+ Effect2.provideService(PolicyBody, true)
1419
+ )
1420
+ })), Effect2.tap((result) => {
1421
+ bufferedEvents.delete(id);
1422
+ return Effect2.forEach(result.events ?? [], emitOutsideBody, { discard: true });
1423
+ }), Effect2.ensuring(Effect2.sync(() => {
1424
+ bufferedEvents.delete(id);
1425
+ })), Effect2.map((result) => {
1426
+ node.commands.splice(0, node.commands.length, ...result.commands);
1427
+ if (result.metadata) {
1428
+ node.artifacts.splice(0, node.artifacts.length, ...result.metadata.artifacts);
1429
+ node.secrets.clear();
1430
+ for (const secret of result.metadata.secrets) node.secrets.add(secret);
1431
+ if (result.metadata.approval) node.approval = result.metadata.approval;
1432
+ }
1433
+ return result.value;
1434
+ }));
1435
+ }
1436
+ return (commandExecutor.handlesStepOptions ? leaf : withStepPolicy(leaf, definition.options)).pipe(Effect2.flatMap(commit));
1437
+ }));
1438
+ const resultRequest = { workflowId, stepId: id, event };
1439
+ let resultReused = false;
1440
+ const reusableBody = mode === "execute" && stepResultCache && !definition.rollback ? (force2 ? Effect2.succeed(void 0) : cacheOrElse(() => stepResultCache.lookup(resultRequest), void 0)).pipe(
1441
+ Effect2.flatMap((stored) => {
1442
+ if (stored !== void 0) {
1443
+ resultReused = true;
1444
+ return Effect2.succeed(stored.value);
1445
+ }
1446
+ return body.pipe(Effect2.tap((value) => cacheOrElse(() => stepResultCache.record(resultRequest, value), void 0)));
1447
+ })
1448
+ ) : body;
1449
+ return queued.pipe(
1450
+ Effect2.andThen(reusableBody),
1451
+ Effect2.provideService(CurrentStep, id),
1452
+ Effect2.annotateLogs({ "ci.step": id, "ci.attempt": 1 }),
1453
+ Effect2.tap((value) => Effect2.sync(() => {
1454
+ outputs.set(id, value);
1455
+ })),
1456
+ Effect2.tap(() => {
1457
+ if (!definition.rollback) return Effect2.void;
1458
+ if (mode === "plan") {
1459
+ return runtime.registerRollback(
1460
+ id,
1461
+ definition.rollback.id,
1462
+ definition.rollback.effect
1463
+ );
1464
+ }
1465
+ return runtime.registerRollback(
1466
+ id,
1467
+ definition.rollback.id,
1468
+ definition.rollback.effect
1469
+ ).pipe(Effect2.tap(() => Effect2.sync(() => {
1470
+ completedRollbacks.push({
1471
+ primaryId: id,
1472
+ rollbackId: definition.rollback.id,
1473
+ effect: definition.rollback.effect
1474
+ });
1475
+ })));
1476
+ }),
1477
+ Effect2.tap(() => {
1478
+ node.status = mode === "plan" ? "planned" : resultReused ? "reused" : node.verifiedCommands > 0 && node.executedCommands === 0 ? "verified" : "complete";
1479
+ return emitEvent({
1480
+ type: "step.status",
1481
+ workflowId,
1482
+ stepId: id,
1483
+ status: node.status,
1484
+ optional: optionalSteps.has(id),
1485
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1486
+ });
1487
+ }),
1488
+ Effect2.onExit((exit2) => {
1489
+ if (Exit.isSuccess(exit2)) return Effect2.void;
1490
+ const cause = exit2.cause;
1491
+ const interrupted = !Cause.hasFails(cause) && !Cause.hasDies(cause);
1492
+ const error = Cause.squash(cause);
1493
+ const origin = failureOrigins.get(error);
1494
+ node.status = interrupted || origin && origin !== id ? "skipped" : "failed";
1495
+ if (!interrupted && !origin) failureOrigins.set(error, id);
1496
+ const status = emitEvent({
1497
+ type: "step.status",
1498
+ workflowId,
1499
+ stepId: id,
1500
+ status: node.status,
1501
+ optional: optionalSteps.has(id),
1502
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1503
+ });
1504
+ if (error instanceof CommandError && error.stepId === id && error.output && node.status === "failed") {
1505
+ const output2 = boundedCommandOutput(error.output.stdout, error.output.stderr);
1506
+ return emitEvent({
1507
+ type: "step.command.failed",
1508
+ workflowId,
1509
+ stepId: id,
1510
+ diagnostics: {
1511
+ version: 1,
1512
+ stepId: id,
1513
+ command: error.command,
1514
+ cwd: error.cwd,
1515
+ exitCode: error.exitCode,
1516
+ output: { ...output2, truncated: output2.truncated || error.output.truncated }
1517
+ },
1518
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1519
+ }).pipe(Effect2.andThen(status));
1520
+ }
1521
+ if ((error instanceof CommandExecutionError || error instanceof CommandCheckpointError) && error.stepId === id && node.status === "failed") {
1522
+ return emitEvent({
1523
+ type: "step.command.unavailable",
1524
+ workflowId,
1525
+ stepId: id,
1526
+ stage: error.stage,
1527
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1528
+ }).pipe(Effect2.andThen(status));
1529
+ }
1530
+ return status;
1531
+ })
1532
+ );
1533
+ }
1534
+ });
1535
+ runtime = {
1536
+ definitions,
1537
+ ci,
1538
+ workflowId,
1539
+ mode,
1540
+ force: force2,
1541
+ nodes,
1542
+ afterEdges,
1543
+ edges,
1544
+ optionalSteps,
1545
+ outputs,
1546
+ cache,
1547
+ addDependency: (parent, child) => Effect2.gen(function* () {
1548
+ if (parent === "$workflow") {
1549
+ if (parallelSteps.delete(child)) return;
1550
+ if (workflowBarrier.dependencies.includes(child) || workflowBarrier.after.includes(child)) return;
1551
+ for (const dependency of workflowBarrier.dependencies) {
1552
+ edges.add(`${child}->${dependency}`);
1553
+ }
1554
+ for (const dependency of workflowBarrier.after) {
1555
+ afterEdges.add(`${child}->${dependency}`);
1556
+ }
1557
+ workflowBarrier = optionalSteps.has(child) ? { after: [child], dependencies: [] } : { after: [], dependencies: [child] };
1558
+ return;
1559
+ }
1560
+ edges.add(`${parent}->${child}`);
1561
+ yield* emitEvent({
1562
+ type: "dependency.added",
1563
+ workflowId,
1564
+ stepId: parent,
1565
+ dependency: child,
1566
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1567
+ });
1568
+ }),
1569
+ addParallel: (parent, steps) => Effect2.sync(() => {
1570
+ if (parent !== "$workflow") return;
1571
+ for (const step2 of steps) {
1572
+ if (step2.optional) optionalSteps.add(step2.id);
1573
+ parallelSteps.add(step2.id);
1574
+ for (const dependency of workflowBarrier.dependencies) {
1575
+ edges.add(`${step2.id}->${dependency}`);
1576
+ }
1577
+ for (const dependency of workflowBarrier.after) {
1578
+ afterEdges.add(`${step2.id}->${dependency}`);
1579
+ }
1580
+ }
1581
+ workflowBarrier = {
1582
+ after: steps.filter((step2) => step2.optional).map((step2) => step2.id),
1583
+ dependencies: steps.filter((step2) => !step2.optional).map((step2) => step2.id)
1584
+ };
1585
+ }),
1586
+ markOptional: (stepId) => Effect2.sync(() => {
1587
+ optionalSteps.add(stepId);
1588
+ }),
1589
+ skip: (stepId, condition) => Effect2.gen(function* () {
1590
+ const definition = definitions.get(stepId);
1591
+ if (!definition) {
1592
+ return yield* Effect2.die(new Error(`Unknown CI step: ${stepId}`));
1593
+ }
1594
+ const node = nodes.get(stepId) ?? {
1595
+ id: stepId,
1596
+ artifacts: [],
1597
+ commands: [],
1598
+ secrets: /* @__PURE__ */ new Set(),
1599
+ executedCommands: 0,
1600
+ verifiedCommands: 0,
1601
+ status: "skipped"
1602
+ };
1603
+ node.condition = condition;
1604
+ node.status = "skipped";
1605
+ nodes.set(stepId, node);
1606
+ yield* emitEvent({
1607
+ type: "step.status",
1608
+ workflowId,
1609
+ stepId,
1610
+ status: "skipped",
1611
+ optional: optionalSteps.has(stepId),
1612
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1613
+ });
1614
+ }),
1615
+ registerRollback: (primaryId, rollbackId, rollback) => Effect2.gen(function* () {
1616
+ const node = nodes.get(rollbackId) ?? {
1617
+ id: rollbackId,
1618
+ artifacts: [],
1619
+ commands: [],
1620
+ secrets: /* @__PURE__ */ new Set(),
1621
+ executedCommands: 0,
1622
+ verifiedCommands: 0,
1623
+ status: mode === "plan" ? "planned" : "skipped"
1624
+ };
1625
+ node.rollbackFor = primaryId;
1626
+ nodes.set(rollbackId, node);
1627
+ if (mode !== "plan") return;
1628
+ const barrier = workflowBarrier;
1629
+ workflowBarrier = { after: [], dependencies: [] };
1630
+ yield* rollback.pipe(
1631
+ Effect2.provideService(CurrentStep, "$rollback"),
1632
+ Effect2.asVoid,
1633
+ Effect2.ensuring(Effect2.sync(() => {
1634
+ workflowBarrier = barrier;
1635
+ }))
1636
+ );
1637
+ const planned = nodes.get(rollbackId);
1638
+ if (planned) planned.rollbackFor = primaryId;
1639
+ }),
1640
+ unwind: (original) => Effect2.gen(function* () {
1641
+ if (mode !== "execute") return;
1642
+ const failedId = failureOrigins.get(original);
1643
+ const failedRollback = failedId ? definitions.get(failedId)?.rollback : void 0;
1644
+ const rollbacks = [
1645
+ ...failedId && failedRollback ? [{
1646
+ primaryId: failedId,
1647
+ rollbackId: failedRollback.id,
1648
+ effect: failedRollback.effect
1649
+ }] : [],
1650
+ ...[...completedRollbacks].reverse().filter(
1651
+ ({ primaryId }) => primaryId !== failedId
1652
+ )
1653
+ ];
1654
+ const failures = [];
1655
+ for (const rollback of rollbacks) {
1656
+ yield* runtime.registerRollback(
1657
+ rollback.primaryId,
1658
+ rollback.rollbackId,
1659
+ rollback.effect
1660
+ ).pipe(Effect2.orDie);
1661
+ yield* rollback.effect.pipe(
1662
+ Effect2.provideService(CurrentStep, "$rollback"),
1663
+ Effect2.asVoid,
1664
+ Effect2.catchCause((cause) => Cause.hasFails(cause) || Cause.hasDies(cause) ? Effect2.sync(() => {
1665
+ failures.push(Cause.squash(cause));
1666
+ }) : Effect2.failCause(cause))
1667
+ );
1668
+ }
1669
+ if (failures.length > 0) {
1670
+ return yield* Effect2.fail(new RollbackError(
1671
+ failedId ?? "workflow",
1672
+ original,
1673
+ failures.length === 1 ? failures[0] : new AggregateError(failures)
1674
+ ));
1675
+ }
1676
+ }),
1677
+ requireSecret: (stepId, name) => Effect2.sync(() => {
1678
+ const node = nodes.get(stepId);
1679
+ if (!node) throw new Error(`Missing plan node for ${stepId}`);
1680
+ node.secrets.add(name);
1681
+ }),
1682
+ recordArtifact: (stepId, artifact) => Effect2.sync(() => {
1683
+ const node = nodes.get(stepId);
1684
+ if (!node) throw new Error(`Missing plan node for ${stepId}`);
1685
+ node.artifacts.push(artifact);
1686
+ }),
1687
+ recoverOptional: (stepId) => Effect2.gen(function* () {
1688
+ const node = nodes.get(stepId);
1689
+ if (!node || node.status !== "failed") return false;
1690
+ node.status = "warning";
1691
+ yield* emitEvent({
1692
+ type: "step.status",
1693
+ workflowId,
1694
+ stepId,
1695
+ status: node.status,
1696
+ optional: true,
1697
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1698
+ });
1699
+ return true;
1700
+ }),
1701
+ execute: (stepId, workspace, command2, execOptions) => {
1702
+ const node = nodes.get(stepId);
1703
+ if (!node) return Effect2.die(new Error(`Missing plan node for ${stepId}`));
1704
+ node.commands.push({ command: command2, cwd: workspace.cwd });
1705
+ const commandIndex = node.commands.length;
1706
+ if (mode === "plan") {
1707
+ return Effect2.succeed(workspace);
1708
+ }
1709
+ const started = node.status !== "running" ? (() => {
1710
+ node.status = "running";
1711
+ return emitEvent({
1712
+ type: "step.status",
1713
+ workflowId,
1714
+ stepId,
1715
+ status: "running",
1716
+ optional: optionalSteps.has(stepId),
1717
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1718
+ });
1719
+ })() : Effect2.void;
1720
+ const reuse = definitions.get(stepId)?.options.reuse;
1721
+ const policy = reuse && { scope: reuse === true ? "inputs" : reuse.scope ?? "inputs" };
1722
+ const checkCacheRequest = policy && !execOptions?.diagnostic ? {
1723
+ command: command2,
1724
+ event,
1725
+ policy,
1726
+ stepId,
1727
+ workflowId,
1728
+ workspace,
1729
+ ...execOptions?.trace ? { trace: execOptions.trace } : {}
1730
+ } : void 0;
1731
+ const verified = checkCache && checkCacheRequest && !force2 ? cacheOrElse(() => checkCache.lookup(checkCacheRequest), false) : Effect2.succeed(false);
1732
+ return started.pipe(
1733
+ Effect2.andThen(verified),
1734
+ Effect2.flatMap((isVerified) => {
1735
+ if (isVerified) {
1736
+ node.verifiedCommands++;
1737
+ return Effect2.succeed(workspace);
1738
+ }
1739
+ if (!execOptions?.diagnostic) node.executedCommands++;
1740
+ const definitionOptions = definitions.get(stepId)?.options;
1741
+ return commandExecutor.execute({
1742
+ command: command2,
1743
+ commandIndex,
1744
+ onOutput: (stream, text) => {
1745
+ if (output !== "inherit") return;
1746
+ if (stream === "stdout") process.stdout.write(text);
1747
+ else process.stderr.write(text);
1748
+ },
1749
+ options: {
1750
+ ...definitionOptions?.retries ? { retries: definitionOptions.retries } : {},
1751
+ ...definitionOptions?.timeout === void 0 ? {} : { timeout: definitionOptions.timeout }
1752
+ },
1753
+ stepId,
1754
+ workflowId,
1755
+ workspace
1756
+ }).pipe(
1757
+ // Adapters normally throw CommandError themselves (native runners
1758
+ // must fail before checkpointing). Never trust a returned nonzero
1759
+ // result as success or record reusable evidence for it.
1760
+ Effect2.flatMap((result) => result.exitCode === 0 ? Effect2.succeed(result) : Effect2.fail(new CommandError(
1761
+ stepId,
1762
+ command2,
1763
+ workspace.cwd,
1764
+ result.exitCode,
1765
+ void 0,
1766
+ boundedCommandOutput(result.stdout, result.stderr)
1767
+ ))),
1768
+ Effect2.tap((result) => checkCache && checkCacheRequest ? cacheOrElse(() => checkCache.record(checkCacheRequest, result), void 0) : Effect2.void),
1769
+ Effect2.flatMap((result) => Effect2.gen(function* () {
1770
+ if (result.stdout) {
1771
+ yield* emitEvent({
1772
+ type: "step.output",
1773
+ workflowId,
1774
+ stepId,
1775
+ stream: "stdout",
1776
+ text: result.stdout,
1777
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1778
+ });
1779
+ }
1780
+ if (result.stderr) {
1781
+ yield* emitEvent({
1782
+ type: "step.output",
1783
+ workflowId,
1784
+ stepId,
1785
+ stream: "stderr",
1786
+ text: result.stderr,
1787
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1788
+ });
1789
+ }
1790
+ return workspace;
1791
+ }))
1792
+ );
1793
+ })
1794
+ );
1795
+ },
1796
+ changed: (stepId, workspace, input) => Effect2.suspend(() => {
1797
+ const patterns = pathPatterns(input);
1798
+ if (mode === "plan" || !workspaceChanges) return Effect2.succeed(true);
1799
+ return cacheOrElse(() => workspaceChanges.changed({ workflowId, stepId, workspace, patterns }).pipe(Effect2.timeout("30 seconds")), void 0).pipe(Effect2.map((value) => value !== false));
1800
+ }),
1801
+ readFile: (stepId, workspace, path) => workspaceFileSystem.readFile(
1802
+ workspace,
1803
+ path,
1804
+ stepId
1805
+ ),
1806
+ exists: (stepId, workspace, path) => workspaceFileSystem.exists(
1807
+ workspace,
1808
+ path,
1809
+ stepId
1810
+ ),
1811
+ checkpoint: (stepId, workspace, name) => {
1812
+ if (mode === "plan") {
1813
+ return Effect2.succeed(new WorkspaceCheckpoint(
1814
+ name,
1815
+ workspace,
1816
+ { provider: "plan", value: void 0 }
1817
+ ));
1818
+ }
1819
+ return workspacePersistence.checkpoint({
1820
+ name,
1821
+ stepId,
1822
+ workflowId,
1823
+ workspace
1824
+ }).pipe(
1825
+ Effect2.map((handle) => new WorkspaceCheckpoint(
1826
+ name,
1827
+ workspace.withRevision(handle),
1828
+ handle
1829
+ ))
1830
+ );
1831
+ },
1832
+ restore: (stepId, checkpoint) => mode === "plan" ? Effect2.succeed(checkpoint.workspace) : workspacePersistence.restore({ checkpoint, stepId, workflowId }),
1833
+ requestApproval: (stepId, request) => {
1834
+ const node = nodes.get(stepId);
1835
+ if (!node) return Effect2.die(new Error(`Missing plan node for ${stepId}`));
1836
+ node.approval = request;
1837
+ if (mode === "plan") {
1838
+ return Effect2.succeed({ decision: "approved" });
1839
+ }
1840
+ if (!approvalHandler) {
1841
+ return Effect2.fail(new ApprovalError(
1842
+ stepId,
1843
+ "unavailable",
1844
+ `No approval handler is available for ${stepId}`
1845
+ ));
1846
+ }
1847
+ const requestId = `${workflowId}:${stepId}`;
1848
+ const requested = emitEvent({
1849
+ type: "approval.requested",
1850
+ workflowId,
1851
+ stepId,
1852
+ requestId,
1853
+ approval: request,
1854
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1855
+ });
1856
+ return requested.pipe(
1857
+ Effect2.andThen(approvalHandler.request({
1858
+ ...request,
1859
+ requestId,
1860
+ stepId,
1861
+ workflowId
1862
+ })),
1863
+ Effect2.mapError((error) => error instanceof ApprovalError ? error : new ApprovalError(stepId, "unavailable", String(error))),
1864
+ Effect2.flatMap((result) => {
1865
+ const resolved = emitEvent({
1866
+ type: "approval.resolved",
1867
+ workflowId,
1868
+ stepId,
1869
+ requestId,
1870
+ decision: result.decision,
1871
+ ...result.actor ? { actor: result.actor } : {},
1872
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1873
+ });
1874
+ return resolved.pipe(
1875
+ Effect2.andThen(result.decision === "approved" ? Effect2.succeed(result) : Effect2.fail(new ApprovalError(
1876
+ stepId,
1877
+ "rejected",
1878
+ `${stepId} was rejected${result.actor ? ` by ${result.actor}` : ""}`
1879
+ )))
1880
+ );
1881
+ })
1882
+ );
1883
+ }
1884
+ };
1885
+ return runtime;
1886
+ });
1887
+ var toPlan = (workflowId, runtime, environment) => {
1888
+ const dependencies = /* @__PURE__ */ new Map();
1889
+ for (const edge of runtime.edges) {
1890
+ const [parent, child] = edge.split("->");
1891
+ const children = dependencies.get(parent) ?? [];
1892
+ children.push(child);
1893
+ dependencies.set(parent, children);
1894
+ }
1895
+ const after = /* @__PURE__ */ new Map();
1896
+ for (const edge of runtime.afterEdges) {
1897
+ const [parent, child] = edge.split("->");
1898
+ const children = after.get(parent) ?? [];
1899
+ children.push(child);
1900
+ after.set(parent, children);
1901
+ }
1902
+ const ordered = [];
1903
+ const visited = /* @__PURE__ */ new Set();
1904
+ const visit = (id) => {
1905
+ if (visited.has(id)) return;
1906
+ visited.add(id);
1907
+ const prerequisites = [
1908
+ ...dependencies.get(id) ?? [],
1909
+ ...after.get(id) ?? []
1910
+ ];
1911
+ for (const dependency of [...new Set(prerequisites)].sort()) visit(dependency);
1912
+ const node = runtime.nodes.get(id);
1913
+ if (node) ordered.push(node);
1914
+ };
1915
+ for (const id of [...runtime.nodes.keys()].sort()) visit(id);
1916
+ return {
1917
+ workflowId,
1918
+ environment,
1919
+ mode: runtime.mode,
1920
+ nodes: ordered.map((node) => ({
1921
+ id: node.id,
1922
+ after: [...after.get(node.id) ?? []].sort(),
1923
+ dependencies: [...dependencies.get(node.id) ?? []].sort(),
1924
+ commands: [...node.commands],
1925
+ artifacts: [...node.artifacts],
1926
+ ...node.condition ? { condition: node.condition } : {},
1927
+ ...node.rollbackFor ? { rollbackFor: node.rollbackFor } : {},
1928
+ ...node.approval ? { approval: node.approval } : {},
1929
+ optional: runtime.optionalSteps.has(node.id),
1930
+ options: runtime.definitions.get(node.id)?.options ?? {},
1931
+ secrets: [...node.secrets].sort(),
1932
+ status: node.status
1933
+ }))
1934
+ };
1935
+ };
1936
+ var formatCondition = (condition) => {
1937
+ switch (condition._tag) {
1938
+ case "event":
1939
+ return `event in [${condition.oneOf.join(", ")}]`;
1940
+ case "ref":
1941
+ return `ref in [${condition.oneOf.join(", ")}]`;
1942
+ case "all":
1943
+ return condition.conditions.map(formatCondition).join(" and ");
1944
+ case "any":
1945
+ return `(${condition.conditions.map(formatCondition).join(" or ")})`;
1946
+ case "not":
1947
+ return `not (${formatCondition(condition.condition)})`;
1948
+ }
1949
+ };
1950
+ var formatPlan = (plan) => {
1951
+ const lines = [
1952
+ `CI ${plan.mode === "plan" ? "plan" : "execution summary"}: ${plan.workflowId}`,
1953
+ `Environment: ${plan.environment}`
1954
+ ];
1955
+ for (const node of plan.nodes) {
1956
+ const after = node.after.length > 0 ? ` after ${node.after.join(", ")}` : "";
1957
+ const dependencies = node.dependencies.length > 0 ? ` depends on ${node.dependencies.join(", ")}` : "";
1958
+ const optional2 = node.optional ? " (optional)" : "";
1959
+ const rollback = node.rollbackFor ? ` rolls back ${node.rollbackFor}` : "";
1960
+ const suffix = `${dependencies}${after}${rollback}${optional2}`;
1961
+ const status = node.status === "complete" ? "\u2713" : node.status === "reused" ? "\u21BB" : node.status === "verified" ? "\u25C6" : node.status === "warning" ? "\u26A0" : node.status === "failed" ? "\xD7" : node.status === "skipped" ? "\u2013" : "\u25CB";
1962
+ lines.push("", `${status} ${node.id}${suffix}`);
1963
+ if (node.condition) {
1964
+ lines.push(` if: ${formatCondition(node.condition)}`);
1965
+ }
1966
+ if (plan.mode === "plan") {
1967
+ if (node.approval) {
1968
+ lines.push(` approval: ${node.approval.title}`);
1969
+ }
1970
+ if (node.secrets.length > 0) {
1971
+ lines.push(` secrets: ${node.secrets.join(", ")}`);
1972
+ }
1973
+ for (const artifact of node.artifacts) {
1974
+ lines.push(
1975
+ ` artifact ${artifact.direction}: ${artifact.name} (${artifact.paths.join(", ")})`
1976
+ );
1977
+ }
1978
+ for (const entry of node.commands) {
1979
+ lines.push(` $ ${entry.command}`, ` cwd: ${entry.cwd}`);
1980
+ }
1981
+ }
1982
+ }
1983
+ return lines.join("\n");
1984
+ };
1985
+ var interpret = (workflowDefinition, mode, options) => Effect2.gen(function* () {
1986
+ const environment = options.env ?? "development";
1987
+ const event = options.event ?? { type: "workflow_dispatch" };
1988
+ const emitEvent = makeEventEmitter(options.onEvent, options.observers);
1989
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
1990
+ const previous = options.rerun?.previous;
1991
+ if (previous && previous.workflowId !== workflowDefinition.id) {
1992
+ return yield* Effect2.fail(new WorkflowPlanError(
1993
+ `Cannot rerun ${previous.workflowId} as ${workflowDefinition.id}`
1994
+ ));
1995
+ }
1996
+ const selection = previous ? planRerun(previous.plan, options.rerun?.steps ?? []) : void 0;
1997
+ const attemptNumber = previous ? previous.number + 1 : 1;
1998
+ const attemptId = `${workflowDefinition.id}:${attemptNumber}:${globalThis.crypto.randomUUID()}`;
1999
+ yield* emitEvent({
2000
+ type: "workflow.started",
2001
+ workflowId: workflowDefinition.id,
2002
+ environment,
2003
+ mode,
2004
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2005
+ });
2006
+ const runtime = yield* makeRuntime(
2007
+ workflowDefinition.id,
2008
+ options.ci ?? (typeof process !== "undefined" && process.env.CI !== void 0),
2009
+ mode,
2010
+ options.output ?? "inherit",
2011
+ emitEvent,
2012
+ event,
2013
+ options.approval,
2014
+ options.executor ?? makeLocalCommandExecutor(options.output),
2015
+ options.workspaceFileSystem,
2016
+ options.workspacePersistence,
2017
+ options.checkCache,
2018
+ previous && selection ? { previous, selection } : void 0,
2019
+ options.actionExecutor,
2020
+ options.stepResultCache,
2021
+ options.workspaceChanges,
2022
+ options.force
2023
+ );
2024
+ const approval = {
2025
+ request: (request) => Effect2.gen(function* () {
2026
+ const currentRuntime = yield* Runtime;
2027
+ const stepId = yield* CurrentStep;
2028
+ return yield* currentRuntime.requestApproval(stepId, request);
2029
+ })
2030
+ };
2031
+ const secrets = options.secrets ?? {
2032
+ resolve: (name) => {
2033
+ const value = typeof process === "undefined" ? void 0 : process.env[name];
2034
+ return value === void 0 ? Effect2.fail(new SecretError(name)) : Effect2.succeed(Redacted.make(value, { label: name }));
2035
+ }
2036
+ };
2037
+ const result = yield* workflowDefinition.effect.pipe(
2038
+ Effect2.catchCause((cause) => Cause.hasFails(cause) || Cause.hasDies(cause) ? runtime.unwind(Cause.squash(cause)).pipe(
2039
+ Effect2.flatMap(() => Effect2.failCause(cause))
2040
+ ) : Effect2.failCause(cause)),
2041
+ Effect2.provideService(Runtime, runtime),
2042
+ Effect2.provideService(CurrentStep, "$workflow"),
2043
+ Effect2.provideService(PolicyBody, false),
2044
+ Effect2.provideService(Attempt, 1),
2045
+ Effect2.provideService(Source, makeSourceQueries(options.source ?? localSource, {
2046
+ executor: options.executor ?? makeLocalCommandExecutor(options.output),
2047
+ workflowId: workflowDefinition.id,
2048
+ event,
2049
+ mode
2050
+ })),
2051
+ Effect2.provideService(WorkflowEvent, event),
2052
+ Effect2.provideService(Approval, approval),
2053
+ Effect2.provideService(SecretStore, secrets),
2054
+ Effect2.exit
2055
+ );
2056
+ const plan = toPlan(
2057
+ workflowDefinition.id,
2058
+ runtime,
2059
+ environment
2060
+ );
2061
+ const completedAt = (/* @__PURE__ */ new Date()).toISOString();
2062
+ const attempt = Object.freeze({
2063
+ id: attemptId,
2064
+ number: attemptNumber,
2065
+ workflowId: workflowDefinition.id,
2066
+ ...previous ? { previousAttemptId: previous.id } : {},
2067
+ requested: Object.freeze([...selection?.requested ?? []]),
2068
+ plan,
2069
+ outputs: Object.freeze(Object.fromEntries(runtime.outputs)),
2070
+ conclusion: Exit.isFailure(result) ? "failure" : "success",
2071
+ startedAt,
2072
+ completedAt
2073
+ });
2074
+ yield* emitEvent({
2075
+ type: "workflow.plan",
2076
+ workflowId: workflowDefinition.id,
2077
+ plan,
2078
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2079
+ });
2080
+ if (Exit.isFailure(result)) {
2081
+ yield* emitEvent({
2082
+ type: "workflow.completed",
2083
+ workflowId: workflowDefinition.id,
2084
+ conclusion: "failure",
2085
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2086
+ });
2087
+ yield* publishAttempt(options.onAttempt, attempt);
2088
+ return yield* Effect2.failCause(result.cause);
2089
+ }
2090
+ yield* emitEvent({
2091
+ type: "workflow.completed",
2092
+ workflowId: workflowDefinition.id,
2093
+ conclusion: "success",
2094
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2095
+ });
2096
+ yield* publishAttempt(options.onAttempt, attempt);
2097
+ return { attempt, plan, value: result.value };
2098
+ });
2099
+ var run = (workflowDefinition, options = {}) => interpret(workflowDefinition, options.mode ?? "execute", options).pipe(
2100
+ Effect2.tap(({ plan }) => options.output === "silent" ? Effect2.void : Effect2.sync(() => console.log(`
2101
+ ${formatPlan(plan)}`)))
2102
+ );
2103
+ var runPromise2 = (workflowDefinition, options) => Effect2.runPromise(run(workflowDefinition, options));
2104
+ var fromPackageJson = (manifest, options = {}) => {
2105
+ const tasks = new Set(options.tasks);
2106
+ const scripts = Object.keys(manifest.scripts ?? {});
2107
+ const duplicate = scripts.find((name) => tasks.has(name));
2108
+ if (duplicate) throw new Error(`Task ${duplicate} is defined in both package.json and Vite+ run.tasks`);
2109
+ const names = [...scripts, ...tasks];
2110
+ if (names.length === 0) {
2111
+ throw new Error("Zero-config CI found no package.json scripts or Vite+ run.tasks");
2112
+ }
2113
+ const visited = /* @__PURE__ */ new Set();
2114
+ const visiting = /* @__PURE__ */ new Set();
2115
+ const validateDependencies = (name) => {
2116
+ if (visiting.has(name)) throw new Error(`Circular Vite+ task dependency: ${name}`);
2117
+ if (visited.has(name)) return;
2118
+ if (!names.includes(name)) throw new Error(`Unknown Vite+ task dependency: ${name}`);
2119
+ visiting.add(name);
2120
+ for (const dependency of options.taskDependencies?.[name] ?? []) validateDependencies(dependency);
2121
+ visiting.delete(name);
2122
+ visited.add(name);
2123
+ };
2124
+ for (const name of names) validateDependencies(name);
2125
+ const privateName = (name) => names.includes(name) ? privateName(`$${name}`) : name;
2126
+ const checkout = action(privateName("checkout"), function* () {
2127
+ const source = yield* Source;
2128
+ return () => source.checkout();
2129
+ });
2130
+ const install = action(privateName("install"), () => function* () {
2131
+ const workspace = yield* checkout();
2132
+ const packageManager = yield* PackageManager.JavaScript(workspace);
2133
+ return yield* packageManager.install();
2134
+ });
2135
+ const actions = Object.fromEntries(names.map((name) => [
2136
+ name,
2137
+ action(name, () => function* () {
2138
+ if ((yield* executionMode) === "plan") {
2139
+ for (const dependency of options.taskDependencies?.[name] ?? []) yield* actions[dependency]();
2140
+ }
2141
+ const workspace = yield* install();
2142
+ const packageManager = yield* (tasks.has(name) ? PackageManager.VitePlus : PackageManager.JavaScript)(workspace);
2143
+ return yield* packageManager.run(name);
2144
+ })
2145
+ ]));
2146
+ return {
2147
+ requiresTarget: true,
2148
+ actions,
2149
+ /** Shared preparation for trusted runner-added checks; not a CLI target. */
2150
+ checkout,
2151
+ workflow: workflow(manifest.name ?? "ci", function* () {
2152
+ const runtime = yield* Runtime;
2153
+ if (runtime.mode === "execute") return yield* Effect2.fail(
2154
+ new Error("Auto-discovered projects require an explicit action; choose from the discovered actions")
2155
+ );
2156
+ let workspace;
2157
+ for (const name of names) workspace = yield* actions[name]();
2158
+ return workspace;
2159
+ })
2160
+ };
2161
+ };
2162
+
2163
+ export {
2164
+ makeRuntimeObservers,
2165
+ WorkflowPlanError,
2166
+ planRerun,
2167
+ Attempt,
2168
+ executionMode,
2169
+ force,
2170
+ CommandError,
2171
+ CommandCheckpointError,
2172
+ CommandExecutionError,
2173
+ ApprovalError,
2174
+ SecretError,
2175
+ Secret,
2176
+ RollbackError,
2177
+ Approval,
2178
+ Workspace,
2179
+ WorkspaceCheckpoint,
2180
+ WorkspaceArtifact,
2181
+ Artifact,
2182
+ PackageManagerError,
2183
+ Apt,
2184
+ VitePlusAvailable,
2185
+ JavaScript,
2186
+ VitePlus,
2187
+ PackageManager,
2188
+ ToolchainError,
2189
+ Toolchain,
2190
+ Source,
2191
+ WorkflowEvent,
2192
+ Condition,
2193
+ matchesCondition,
2194
+ optional,
2195
+ when,
2196
+ parallel,
2197
+ step,
2198
+ action,
2199
+ check,
2200
+ isAction,
2201
+ workflow,
2202
+ formatCondition,
2203
+ formatPlan,
2204
+ run,
2205
+ runPromise2 as runPromise,
2206
+ fromPackageJson
2207
+ };