@vercel/factory 0.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,743 @@
1
+ import {
2
+ SCHEMA_VERSION,
3
+ changeEvidenceSchema,
4
+ changeIdSchema,
5
+ changeSchema,
6
+ changeStateSchema,
7
+ factoryIdSchema,
8
+ harnessSchema,
9
+ isoDateTimeSchema,
10
+ levelSchema,
11
+ receiptIdSchema,
12
+ replyToSchema,
13
+ repositoryIdSchema,
14
+ repositoryIdsSchema,
15
+ schemaVersionSchema,
16
+ signalIdSchema,
17
+ standardTaskKinds,
18
+ taskDevboxSchema,
19
+ taskIdSchema,
20
+ taskKindSchema,
21
+ taskOriginSchema,
22
+ taskQuestionSchema,
23
+ taskSchema,
24
+ taskStateSchema,
25
+ usdSchema,
26
+ vocabularySchema
27
+ } from "./chunk-BSDWPFKE.js";
28
+ import {
29
+ RecordExistsError,
30
+ RecordNotFoundError,
31
+ VersionConflictError
32
+ } from "./chunk-CEF6VJZC.js";
33
+
34
+ // src/dispatch.ts
35
+ var DispatchRefusedError = class extends Error {
36
+ taskId;
37
+ reason;
38
+ constructor(taskId, reason) {
39
+ super(`dispatch of "${taskId}" refused: ${reason}`);
40
+ this.name = "DispatchRefusedError";
41
+ this.taskId = taskId;
42
+ this.reason = reason;
43
+ }
44
+ };
45
+ async function dispatchTask(stores, taskId, options) {
46
+ const task = await stores.tasks.get(taskId);
47
+ if (task === null) {
48
+ throw new RecordNotFoundError("tasks", taskId);
49
+ }
50
+ if (task.kind === "question") {
51
+ throw new DispatchRefusedError(taskId, "question tasks are answered, not dispatched");
52
+ }
53
+ for (const dependencyId of task.dependsOn ?? []) {
54
+ const dependency = await stores.tasks.get(dependencyId);
55
+ if (dependency === null) {
56
+ throw new DispatchRefusedError(taskId, `dependency "${dependencyId}" does not exist`);
57
+ }
58
+ if (dependency.changeId === void 0) {
59
+ throw new DispatchRefusedError(
60
+ taskId,
61
+ `dependency "${dependencyId}" has not produced a change`
62
+ );
63
+ }
64
+ }
65
+ const running = await stores.tasks.transition(taskId, "running");
66
+ try {
67
+ await options.launch(running);
68
+ } catch (error) {
69
+ const reason = (error instanceof Error ? error.message : String(error)).slice(0, 500);
70
+ await stores.tasks.transition(taskId, "failed", { reason: `launch failed: ${reason}` }).catch(() => void 0);
71
+ throw error;
72
+ }
73
+ return running;
74
+ }
75
+
76
+ // src/schema/budget.ts
77
+ import { z as z2 } from "zod";
78
+
79
+ // src/schema/repository.ts
80
+ import { z } from "zod";
81
+ var repositorySlugSchema = z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?\/[a-z0-9._-]+$/).describe("owner/name, lowercase, e.g. acme/web.");
82
+ var repositorySchema = z.strictObject({
83
+ schemaVersion: schemaVersionSchema,
84
+ id: repositoryIdSchema,
85
+ slug: repositorySlugSchema,
86
+ defaultBranch: z.string().min(1).describe("Branch changes land on, usually main."),
87
+ enabled: z.boolean().describe("Whether the factory may work on this repository."),
88
+ dependsOn: z.array(repositorySlugSchema).describe("Slugs of repositories this one consumes, for multi-repo work ordering."),
89
+ devbox: z.strictObject({
90
+ projectId: z.string().min(1),
91
+ teamId: z.string().min(1),
92
+ snapshot: z.string().min(1).optional().describe("Prebuilt snapshot to boot from.")
93
+ }).optional().describe("Devbox execution config. Absent when this repository never uses devboxes."),
94
+ connectedAt: isoDateTimeSchema
95
+ });
96
+
97
+ // src/schema/budget.ts
98
+ var budgetMonthSchema = z2.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/);
99
+ var budgetSchema = z2.strictObject({
100
+ schemaVersion: schemaVersionSchema,
101
+ factoryId: factoryIdSchema,
102
+ month: budgetMonthSchema,
103
+ limits: z2.strictObject({
104
+ totalUsd: usdSchema,
105
+ investigationUsd: usdSchema,
106
+ perTaskReservationUsd: usdSchema,
107
+ warningPercent: z2.number().int().min(1).max(100),
108
+ perRepositoryUsd: z2.record(repositorySlugSchema, usdSchema).optional()
109
+ }),
110
+ notices: z2.strictObject({
111
+ warningAt: isoDateTimeSchema.optional(),
112
+ exhaustedAt: isoDateTimeSchema.optional()
113
+ })
114
+ });
115
+
116
+ // src/schema/receipt.ts
117
+ import { z as z3 } from "zod";
118
+ var standardReceiptStates = [
119
+ "dispatched",
120
+ "succeeded",
121
+ "failed",
122
+ "needs_human",
123
+ "cancelled",
124
+ "settled",
125
+ "merged",
126
+ "deployed",
127
+ "rolled_out",
128
+ "rolled_back"
129
+ ];
130
+ var standardReceiptPhases = [
131
+ "budget",
132
+ "dispatch",
133
+ "implementation",
134
+ "verification",
135
+ "pull_request",
136
+ "cleanup"
137
+ ];
138
+ var standardReceiptKinds = [...standardTaskKinds, "change"];
139
+ var receiptStateSchema = vocabularySchema.describe(
140
+ "What happened, e.g. dispatched, settled, merged, or a custom event name."
141
+ );
142
+ var receiptPhaseSchema = vocabularySchema.describe(
143
+ "Where in the process it happened, e.g. dispatch or verification."
144
+ );
145
+ var receiptKindSchema = vocabularySchema.describe(
146
+ "What the receipt is about: a task kind, change, or a custom kind."
147
+ );
148
+ var costSchema = z3.strictObject({
149
+ totalUsd: usdSchema
150
+ });
151
+ var receiptSchema = z3.strictObject({
152
+ schemaVersion: schemaVersionSchema,
153
+ receiptId: receiptIdSchema,
154
+ repositoryIds: repositoryIdsSchema.describe("Repositories the recorded event concerns."),
155
+ taskId: taskIdSchema.optional(),
156
+ changeId: changeIdSchema.optional(),
157
+ kind: receiptKindSchema,
158
+ state: receiptStateSchema,
159
+ phase: receiptPhaseSchema.optional(),
160
+ reason: z3.string().min(1).max(2e3).optional().describe("Why it happened. Scrubbed and truncated; never secrets."),
161
+ attempt: z3.number().int().min(1).describe("Attempt the event belongs to."),
162
+ cost: costSchema.optional().describe("Measured cost. Settled receipts only."),
163
+ decidedBy: z3.string().min(1).optional().describe("Human who made the decision. Change receipts only."),
164
+ recordedAt: isoDateTimeSchema
165
+ }).superRefine((receipt, ctx) => {
166
+ if (receipt.state === "settled" && receipt.cost === void 0) {
167
+ ctx.addIssue({
168
+ code: "custom",
169
+ path: ["cost"],
170
+ message: "settled receipts require cost"
171
+ });
172
+ }
173
+ if (receipt.state !== "settled" && receipt.cost !== void 0) {
174
+ ctx.addIssue({
175
+ code: "custom",
176
+ path: ["cost"],
177
+ message: "cost is only valid on settled receipts"
178
+ });
179
+ }
180
+ if (receipt.decidedBy !== void 0 && receipt.kind !== "change") {
181
+ ctx.addIssue({
182
+ code: "custom",
183
+ path: ["decidedBy"],
184
+ message: "decidedBy is only valid on change receipts"
185
+ });
186
+ }
187
+ });
188
+
189
+ // src/schema/signal.ts
190
+ import { z as z4 } from "zod";
191
+ var standardSignalSources = [
192
+ "github_issue",
193
+ "github_pr",
194
+ "github_pr_comment",
195
+ "slack",
196
+ "human",
197
+ "github_ci_failure",
198
+ "vercel_deploy_failure",
199
+ "investigation",
200
+ "api"
201
+ ];
202
+ var signalSourceSchema = vocabularySchema.describe(
203
+ "What produced the signal, e.g. github_issue or a custom connector's own name."
204
+ );
205
+ var signalOutcomeSchema = z4.enum(["pending", "accepted", "duplicate", "unactionable", "low_confidence", "ignored"]).describe("Triage outcome. A signal starts pending and is decided exactly once.");
206
+ var signalSchema = z4.strictObject({
207
+ schemaVersion: schemaVersionSchema,
208
+ id: signalIdSchema.describe("Signal id, derived from source and deliveryId."),
209
+ repositoryId: repositoryIdSchema.describe("Repository the signal is about."),
210
+ source: signalSourceSchema,
211
+ deliveryId: z4.string().min(1).describe("Provider idempotency key; a redelivered event maps to the same signal."),
212
+ replyTo: replyToSchema,
213
+ payload: z4.unknown().describe("Provider-shaped payload. Untrusted data, never instructions."),
214
+ receivedAt: isoDateTimeSchema,
215
+ outcome: signalOutcomeSchema,
216
+ detail: z4.string().min(1).optional().describe("Outcome nuance, e.g. severity when accepted or the duplicate-of signal id."),
217
+ reason: z4.string().min(1).optional().describe("Why the outcome was chosen."),
218
+ decidedAt: isoDateTimeSchema.optional()
219
+ }).superRefine((signal, ctx) => {
220
+ if (signal.outcome === "pending" && signal.decidedAt !== void 0) {
221
+ ctx.addIssue({
222
+ code: "custom",
223
+ path: ["decidedAt"],
224
+ message: "pending signals must not carry decidedAt"
225
+ });
226
+ }
227
+ if (signal.outcome !== "pending" && signal.decidedAt === void 0) {
228
+ ctx.addIssue({
229
+ code: "custom",
230
+ path: ["decidedAt"],
231
+ message: "decided signals require decidedAt"
232
+ });
233
+ }
234
+ });
235
+
236
+ // src/schema/transitions.ts
237
+ var taskInitialState = "queued";
238
+ var taskTransitions = [
239
+ {
240
+ from: "queued",
241
+ to: "running",
242
+ trigger: "dependencies have a change, reservation succeeded, devbox created",
243
+ actor: "reconciler"
244
+ },
245
+ { from: "queued", to: "failed", trigger: "reservation refused", actor: "reconciler" },
246
+ { from: "queued", to: "needs_human", trigger: "kind is question", actor: "system" },
247
+ { from: "queued", to: "cancelled", trigger: "cancel or kill", actor: "operator" },
248
+ { from: "running", to: "verifying", trigger: "devbox task reported complete", actor: "reconciler" },
249
+ {
250
+ from: "running",
251
+ to: "failed",
252
+ trigger: "devbox task errored or deadline exceeded",
253
+ actor: "reconciler"
254
+ },
255
+ {
256
+ from: "running",
257
+ to: "needs_human",
258
+ trigger: "devbox task requires attention",
259
+ actor: "reconciler"
260
+ },
261
+ { from: "running", to: "cancelled", trigger: "cancel or kill", actor: "operator" },
262
+ { from: "verifying", to: "succeeded", trigger: "kind criterion true", actor: "reconciler" },
263
+ {
264
+ from: "verifying",
265
+ to: "running",
266
+ trigger: "verification failed below attempt limit",
267
+ actor: "reconciler"
268
+ },
269
+ {
270
+ from: "verifying",
271
+ to: "failed",
272
+ trigger: "verification failed at attempt limit",
273
+ actor: "reconciler"
274
+ },
275
+ { from: "verifying", to: "cancelled", trigger: "cancel or kill", actor: "operator" },
276
+ { from: "needs_human", to: "succeeded", trigger: "question answered", actor: "operator" },
277
+ { from: "needs_human", to: "queued", trigger: "operator retry", actor: "operator" },
278
+ { from: "needs_human", to: "cancelled", trigger: "cancel or kill", actor: "operator" },
279
+ { from: "failed", to: "queued", trigger: "operator retry", actor: "operator" }
280
+ ];
281
+ var changeInitialState = "verifying";
282
+ var changeTransitions = [
283
+ {
284
+ from: "verifying",
285
+ to: "ready",
286
+ trigger: "verification task succeeded, risk and confidence written",
287
+ actor: "reconciler"
288
+ },
289
+ {
290
+ from: "verifying",
291
+ to: "closed",
292
+ trigger: "verification failed at attempt limit or pr closed upstream",
293
+ actor: "reconciler"
294
+ },
295
+ { from: "ready", to: "merged", trigger: "pr merged on github", actor: "webhook" },
296
+ { from: "ready", to: "closed", trigger: "pr closed without merge", actor: "webhook" },
297
+ {
298
+ from: "merged",
299
+ to: "deployed",
300
+ trigger: "production deployment ready containing the merge sha",
301
+ actor: "webhook"
302
+ },
303
+ {
304
+ from: "deployed",
305
+ to: "rolled_out",
306
+ trigger: "no flag, or flag ramped to full and held",
307
+ actor: "foreman"
308
+ },
309
+ { from: "deployed", to: "rolled_back", trigger: "rollback rule crossed", actor: "foreman" },
310
+ {
311
+ from: "rolled_out",
312
+ to: "rolled_back",
313
+ trigger: "rollback rule crossed or flag flipped off",
314
+ actor: "foreman"
315
+ },
316
+ { from: "rolled_back", to: "deployed", trigger: "human retried the ramp", actor: "human" }
317
+ ];
318
+ var signalInitialOutcome = "pending";
319
+ var signalOutcomeTransitions = [
320
+ { from: "pending", to: "accepted", trigger: "classified as actionable", actor: "reconciler" },
321
+ { from: "pending", to: "duplicate", trigger: "classified as duplicate", actor: "reconciler" },
322
+ {
323
+ from: "pending",
324
+ to: "unactionable",
325
+ trigger: "classified as unactionable",
326
+ actor: "reconciler"
327
+ },
328
+ {
329
+ from: "pending",
330
+ to: "low_confidence",
331
+ trigger: "classified below confidence threshold",
332
+ actor: "reconciler"
333
+ },
334
+ { from: "pending", to: "ignored", trigger: "classified as ignorable", actor: "reconciler" }
335
+ ];
336
+ function isTransitionAllowed(transitions, from, to) {
337
+ return transitions.some((transition) => transition.from === from && transition.to === to);
338
+ }
339
+ function legalNextStates(transitions, from) {
340
+ return [
341
+ ...new Set(
342
+ transitions.filter((transition) => transition.from === from).map((t) => t.to)
343
+ )
344
+ ];
345
+ }
346
+ var InvalidTransitionError = class extends Error {
347
+ from;
348
+ to;
349
+ legalNextStates;
350
+ constructor(from, to, legal) {
351
+ super(
352
+ legal.length > 0 ? `invalid transition from "${from}" to "${to}"; legal next states: ${legal.map((state) => `"${state}"`).join(", ")}` : `invalid transition from "${from}" to "${to}"; "${from}" is terminal`
353
+ );
354
+ this.name = "InvalidTransitionError";
355
+ this.from = from;
356
+ this.to = to;
357
+ this.legalNextStates = legal;
358
+ }
359
+ };
360
+ function assertTransition(transitions, from, to) {
361
+ if (!isTransitionAllowed(transitions, from, to)) {
362
+ throw new InvalidTransitionError(from, to, legalNextStates(transitions, from));
363
+ }
364
+ }
365
+ function terminalStates(transitions) {
366
+ const states = /* @__PURE__ */ new Set();
367
+ for (const transition of transitions) {
368
+ states.add(transition.from);
369
+ states.add(transition.to);
370
+ }
371
+ return [...states].filter(
372
+ (state) => !transitions.some((transition) => transition.from === state)
373
+ );
374
+ }
375
+
376
+ // src/store/engine.ts
377
+ import { createHash, randomUUID } from "crypto";
378
+ var taskReceiptStates = {
379
+ running: "dispatched",
380
+ succeeded: "succeeded",
381
+ failed: "failed",
382
+ needs_human: "needs_human",
383
+ cancelled: "cancelled"
384
+ };
385
+ var changeReceiptStates = {
386
+ merged: "merged",
387
+ deployed: "deployed",
388
+ rolled_out: "rolled_out",
389
+ rolled_back: "rolled_back"
390
+ };
391
+ function randomId(prefix) {
392
+ return `${prefix}_${randomUUID().replaceAll("-", "")}`;
393
+ }
394
+ function derivedId(prefix, key) {
395
+ return `${prefix}_${createHash("sha256").update(key).digest("hex").slice(0, 32)}`;
396
+ }
397
+ function bumpsAttempt(from, to) {
398
+ return to === "queued" || from === "verifying" && to === "running";
399
+ }
400
+ function createStores(options) {
401
+ const { driver } = options;
402
+ const now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
403
+ async function read(collection, id, schema) {
404
+ const record = await driver.get(collection, id);
405
+ if (record === null) {
406
+ return null;
407
+ }
408
+ return { value: schema.parse(record.value), version: record.version };
409
+ }
410
+ async function mustRead(collection, id, schema) {
411
+ const record = await read(collection, id, schema);
412
+ if (record === null) {
413
+ throw new RecordNotFoundError(collection, id);
414
+ }
415
+ return record;
416
+ }
417
+ async function listAll(collection, schema) {
418
+ const entries = await driver.list(collection);
419
+ return entries.map((entry) => schema.parse(entry.record.value));
420
+ }
421
+ async function insertReceipt(receiptId, receipt) {
422
+ const full = receiptSchema.parse({
423
+ ...receipt,
424
+ schemaVersion: SCHEMA_VERSION,
425
+ receiptId,
426
+ recordedAt: now()
427
+ });
428
+ try {
429
+ await driver.insert("receipts", receiptId, full);
430
+ return full;
431
+ } catch (error) {
432
+ if (error instanceof RecordExistsError) {
433
+ const existing = await mustRead("receipts", receiptId, receiptSchema);
434
+ return existing.value;
435
+ }
436
+ throw error;
437
+ }
438
+ }
439
+ async function appendReceipt(key, receipt) {
440
+ await insertReceipt(derivedId("rcpt", key), receipt);
441
+ }
442
+ return {
443
+ driverName: driver.name,
444
+ repositories: {
445
+ async put(repository) {
446
+ const parsed = repositorySchema.parse(repository);
447
+ const existing = await read("repositories", parsed.id, repositorySchema);
448
+ if (existing === null) {
449
+ await driver.insert("repositories", parsed.id, parsed);
450
+ } else {
451
+ await driver.update("repositories", parsed.id, parsed, existing.version);
452
+ }
453
+ return parsed;
454
+ },
455
+ async get(id) {
456
+ const record = await read("repositories", id, repositorySchema);
457
+ return record === null ? null : record.value;
458
+ },
459
+ list() {
460
+ return listAll("repositories", repositorySchema);
461
+ }
462
+ },
463
+ signals: {
464
+ async create(input) {
465
+ const id = derivedId("sig", `${input.source}:${input.deliveryId}`);
466
+ const signal = signalSchema.parse({
467
+ schemaVersion: SCHEMA_VERSION,
468
+ id,
469
+ repositoryId: input.repositoryId,
470
+ source: input.source,
471
+ deliveryId: input.deliveryId,
472
+ replyTo: input.replyTo,
473
+ payload: input.payload,
474
+ receivedAt: now(),
475
+ outcome: "pending"
476
+ });
477
+ try {
478
+ await driver.insert("signals", id, signal);
479
+ return signal;
480
+ } catch (error) {
481
+ if (error instanceof RecordExistsError) {
482
+ const existing = await mustRead("signals", id, signalSchema);
483
+ return existing.value;
484
+ }
485
+ throw error;
486
+ }
487
+ },
488
+ async get(id) {
489
+ const record = await read("signals", id, signalSchema);
490
+ return record === null ? null : record.value;
491
+ },
492
+ async decide(id, outcome, decideOptions = {}) {
493
+ const existing = await mustRead("signals", id, signalSchema);
494
+ assertTransition(signalOutcomeTransitions, existing.value.outcome, outcome);
495
+ const next = signalSchema.parse({
496
+ ...existing.value,
497
+ outcome,
498
+ detail: decideOptions.detail,
499
+ reason: decideOptions.reason,
500
+ decidedAt: now()
501
+ });
502
+ await driver.update("signals", id, next, existing.version);
503
+ return next;
504
+ },
505
+ list() {
506
+ return listAll("signals", signalSchema);
507
+ }
508
+ },
509
+ tasks: {
510
+ async create(input) {
511
+ const timestamp = now();
512
+ const task = taskSchema.parse({
513
+ schemaVersion: SCHEMA_VERSION,
514
+ id: randomId("task"),
515
+ repositoryIds: input.repositoryIds,
516
+ kind: input.kind,
517
+ area: input.area,
518
+ state: taskInitialState,
519
+ origin: input.origin,
520
+ dependsOn: input.dependsOn,
521
+ replyTo: input.replyTo,
522
+ attempt: 1,
523
+ question: input.question,
524
+ createdAt: timestamp,
525
+ updatedAt: timestamp
526
+ });
527
+ await driver.insert("tasks", task.id, task);
528
+ return task;
529
+ },
530
+ async get(id) {
531
+ const record = await read("tasks", id, taskSchema);
532
+ return record === null ? null : record.value;
533
+ },
534
+ async transition(id, to, transitionOptions = {}) {
535
+ const existing = await mustRead("tasks", id, taskSchema);
536
+ assertTransition(taskTransitions, existing.value.state, to);
537
+ const attempt = bumpsAttempt(existing.value.state, to) ? existing.value.attempt + 1 : existing.value.attempt;
538
+ const next = taskSchema.parse({
539
+ ...existing.value,
540
+ ...transitionOptions.patch,
541
+ state: to,
542
+ attempt,
543
+ updatedAt: now()
544
+ });
545
+ const receiptState = taskReceiptStates[to];
546
+ if (receiptState !== void 0 && next.repositoryIds !== void 0) {
547
+ await appendReceipt(`task:${id}:${receiptState}:${attempt}`, {
548
+ repositoryIds: next.repositoryIds,
549
+ taskId: id,
550
+ changeId: next.changeId,
551
+ kind: next.kind,
552
+ state: receiptState,
553
+ reason: transitionOptions.reason,
554
+ attempt
555
+ });
556
+ }
557
+ await driver.update("tasks", id, next, existing.version);
558
+ return next;
559
+ },
560
+ list() {
561
+ return listAll("tasks", taskSchema);
562
+ }
563
+ },
564
+ changes: {
565
+ async create(input) {
566
+ const timestamp = now();
567
+ const change = changeSchema.parse({
568
+ schemaVersion: SCHEMA_VERSION,
569
+ id: randomId("chg"),
570
+ repositoryId: input.repositoryId,
571
+ taskId: input.taskId,
572
+ groupId: input.groupId,
573
+ prNumber: input.prNumber,
574
+ prUrl: input.prUrl,
575
+ author: input.author,
576
+ risk: input.risk,
577
+ confidence: input.confidence,
578
+ evidence: input.evidence,
579
+ state: changeInitialState,
580
+ createdAt: timestamp,
581
+ updatedAt: timestamp
582
+ });
583
+ await driver.insert("changes", change.id, change);
584
+ return change;
585
+ },
586
+ async get(id) {
587
+ const record = await read("changes", id, changeSchema);
588
+ return record === null ? null : record.value;
589
+ },
590
+ async transition(id, to, transitionOptions = {}) {
591
+ const existing = await mustRead("changes", id, changeSchema);
592
+ assertTransition(changeTransitions, existing.value.state, to);
593
+ const next = changeSchema.parse({
594
+ ...existing.value,
595
+ ...transitionOptions.patch,
596
+ state: to,
597
+ updatedAt: now()
598
+ });
599
+ const receiptState = changeReceiptStates[to];
600
+ if (receiptState !== void 0) {
601
+ await appendReceipt(`change:${id}:${receiptState}`, {
602
+ repositoryIds: [next.repositoryId],
603
+ taskId: next.taskId,
604
+ changeId: id,
605
+ kind: "change",
606
+ state: receiptState,
607
+ reason: transitionOptions.reason,
608
+ attempt: 1,
609
+ decidedBy: next.decidedBy
610
+ });
611
+ }
612
+ await driver.update("changes", id, next, existing.version);
613
+ return next;
614
+ },
615
+ list() {
616
+ return listAll("changes", changeSchema);
617
+ }
618
+ },
619
+ receipts: {
620
+ append(input) {
621
+ const { dedupeKey, attempt, ...fields } = input;
622
+ const receiptId = dedupeKey === void 0 ? randomId("rcpt") : derivedId("rcpt", `custom:${dedupeKey}`);
623
+ return insertReceipt(receiptId, { ...fields, attempt: attempt ?? 1 });
624
+ },
625
+ async get(id) {
626
+ const record = await read("receipts", id, receiptSchema);
627
+ return record === null ? null : record.value;
628
+ },
629
+ list() {
630
+ return listAll("receipts", receiptSchema);
631
+ }
632
+ }
633
+ };
634
+ }
635
+
636
+ // src/store/memory.ts
637
+ function createInMemoryDriver() {
638
+ const collections = /* @__PURE__ */ new Map();
639
+ function collection(name) {
640
+ let existing = collections.get(name);
641
+ if (existing === void 0) {
642
+ existing = /* @__PURE__ */ new Map();
643
+ collections.set(name, existing);
644
+ }
645
+ return existing;
646
+ }
647
+ return {
648
+ name: "memory",
649
+ get(name, id) {
650
+ const record = collection(name).get(id);
651
+ return Promise.resolve(record === void 0 ? null : structuredClone(record));
652
+ },
653
+ insert(name, id, value) {
654
+ const records = collection(name);
655
+ if (records.has(id)) {
656
+ return Promise.reject(new RecordExistsError(name, id));
657
+ }
658
+ records.set(id, { value: structuredClone(value), version: 1 });
659
+ return Promise.resolve();
660
+ },
661
+ update(name, id, value, expectedVersion) {
662
+ const records = collection(name);
663
+ const existing = records.get(id);
664
+ if (existing === void 0) {
665
+ return Promise.reject(new RecordNotFoundError(name, id));
666
+ }
667
+ if (existing.version !== expectedVersion) {
668
+ return Promise.reject(new VersionConflictError(name, id, expectedVersion));
669
+ }
670
+ records.set(id, { value: structuredClone(value), version: existing.version + 1 });
671
+ return Promise.resolve();
672
+ },
673
+ list(name) {
674
+ const entries = [...collection(name)].map(([id, record]) => ({
675
+ id,
676
+ record: structuredClone(record)
677
+ }));
678
+ return Promise.resolve(entries);
679
+ }
680
+ };
681
+ }
682
+ export {
683
+ DispatchRefusedError,
684
+ InvalidTransitionError,
685
+ RecordExistsError,
686
+ RecordNotFoundError,
687
+ SCHEMA_VERSION,
688
+ VersionConflictError,
689
+ assertTransition,
690
+ budgetMonthSchema,
691
+ budgetSchema,
692
+ changeEvidenceSchema,
693
+ changeIdSchema,
694
+ changeInitialState,
695
+ changeSchema,
696
+ changeStateSchema,
697
+ changeTransitions,
698
+ costSchema,
699
+ createInMemoryDriver,
700
+ createStores,
701
+ dispatchTask,
702
+ factoryIdSchema,
703
+ harnessSchema,
704
+ isTransitionAllowed,
705
+ isoDateTimeSchema,
706
+ legalNextStates,
707
+ levelSchema,
708
+ receiptIdSchema,
709
+ receiptKindSchema,
710
+ receiptPhaseSchema,
711
+ receiptSchema,
712
+ receiptStateSchema,
713
+ replyToSchema,
714
+ repositoryIdSchema,
715
+ repositoryIdsSchema,
716
+ repositorySchema,
717
+ repositorySlugSchema,
718
+ schemaVersionSchema,
719
+ signalIdSchema,
720
+ signalInitialOutcome,
721
+ signalOutcomeSchema,
722
+ signalOutcomeTransitions,
723
+ signalSchema,
724
+ signalSourceSchema,
725
+ standardReceiptKinds,
726
+ standardReceiptPhases,
727
+ standardReceiptStates,
728
+ standardSignalSources,
729
+ standardTaskKinds,
730
+ taskDevboxSchema,
731
+ taskIdSchema,
732
+ taskInitialState,
733
+ taskKindSchema,
734
+ taskOriginSchema,
735
+ taskQuestionSchema,
736
+ taskSchema,
737
+ taskStateSchema,
738
+ taskTransitions,
739
+ terminalStates,
740
+ usdSchema,
741
+ vocabularySchema
742
+ };
743
+ //# sourceMappingURL=index.js.map