@vercel/factory 0.0.13 → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/dist/api.d.mts +225 -0
  3. package/dist/api.mjs +312 -0
  4. package/dist/api.mjs.map +1 -0
  5. package/dist/approval-JX2Px9IC.mjs +132 -0
  6. package/dist/approval-JX2Px9IC.mjs.map +1 -0
  7. package/dist/blob/index.d.mts +4 -3
  8. package/dist/blob/index.mjs +21 -15
  9. package/dist/blob/index.mjs.map +1 -1
  10. package/dist/budget-DzSiIA4t.mjs +42 -0
  11. package/dist/budget-DzSiIA4t.mjs.map +1 -0
  12. package/dist/build-factory.mjs +1 -1
  13. package/dist/{change-CzEAoFVE.mjs → change-D2U6v7Ek.mjs} +10 -76
  14. package/dist/change-D2U6v7Ek.mjs.map +1 -0
  15. package/dist/communication-Kd9nU5RP.mjs +30 -0
  16. package/dist/communication-Kd9nU5RP.mjs.map +1 -0
  17. package/dist/connectors/index.d.mts +3 -2
  18. package/dist/connectors/index.mjs +53 -26
  19. package/dist/connectors/index.mjs.map +1 -1
  20. package/dist/connectors/slack.d.mts +13 -2
  21. package/dist/connectors/slack.mjs +18 -2
  22. package/dist/connectors/slack.mjs.map +1 -1
  23. package/dist/coordination-Cq08hb1l.mjs +76 -0
  24. package/dist/coordination-Cq08hb1l.mjs.map +1 -0
  25. package/dist/dispatch-BaZS3PT8.d.mts +76 -0
  26. package/dist/{driver-BJutB0PE.d.mts → driver-BC0Mt5KG.d.mts} +2 -2
  27. package/dist/driver-Bbd25rNM.mjs.map +1 -1
  28. package/dist/{dispatch-B77cuPxh.d.mts → engine-DFHU2Pe-.d.mts} +356 -288
  29. package/dist/engine-WaUM2cGA.mjs +1068 -0
  30. package/dist/engine-WaUM2cGA.mjs.map +1 -0
  31. package/dist/eve/index.d.mts +44 -334
  32. package/dist/eve/index.mjs +51 -38
  33. package/dist/eve/index.mjs.map +1 -1
  34. package/dist/{factory-config-BJcjsPKl.mjs → factory-config-BoRXOw43.mjs} +5 -41
  35. package/dist/factory-config-BoRXOw43.mjs.map +1 -0
  36. package/dist/{github-DXsxboUL.d.mts → github-C5HNBN6p.d.mts} +11 -3
  37. package/dist/github.d.mts +2 -2
  38. package/dist/github.mjs +15 -1
  39. package/dist/github.mjs.map +1 -1
  40. package/dist/{id-DwCihQr4.mjs → id-BLIkCVue.mjs} +4 -2
  41. package/dist/{id-DwCihQr4.mjs.map → id-BLIkCVue.mjs.map} +1 -1
  42. package/dist/index-Bw6hggoH.d.mts +40 -0
  43. package/dist/index.d.mts +176 -6
  44. package/dist/index.mjs +50 -652
  45. package/dist/index.mjs.map +1 -1
  46. package/dist/postgres/index.d.mts +1 -1
  47. package/dist/{approval-CwhTP1XB.mjs → task-CcOyOJ3k.mjs} +18 -133
  48. package/dist/task-CcOyOJ3k.mjs.map +1 -0
  49. package/package.json +5 -1
  50. package/dist/approval-CwhTP1XB.mjs.map +0 -1
  51. package/dist/change-CzEAoFVE.mjs.map +0 -1
  52. package/dist/factory-config-BJcjsPKl.mjs.map +0 -1
  53. package/dist/index-Cy4jfXh5.d.mts +0 -67
  54. package/dist/signal-CHVEmzvI.d.mts +0 -59
@@ -0,0 +1,132 @@
1
+ import { h as vocabularySchema } from "./id-BLIkCVue.mjs";
2
+ import { z } from "zod";
3
+ import { createHash } from "node:crypto";
4
+ //#region src/schema/finding.ts
5
+ const findingPrioritySchema = z.enum([
6
+ "P0",
7
+ "P1",
8
+ "P2",
9
+ "P3"
10
+ ]).describe("Urgency of a finding: P0 is drop-everything, P3 is nice-to-have.");
11
+ const findingCategorySchema = z.enum([
12
+ "security",
13
+ "correctness",
14
+ "reliability",
15
+ "performance",
16
+ "compatibility",
17
+ "accessibility",
18
+ "documentation",
19
+ "maintainability",
20
+ "testing",
21
+ "usability"
22
+ ]);
23
+ const findingVerificationLevelSchema = z.enum([
24
+ "unverified",
25
+ "supported",
26
+ "confirmed"
27
+ ]).describe("How sure the reporter is: unverified = suspected from reading; supported = evidence points to it; confirmed = demonstrated.");
28
+ const findingVerificationMethodSchema = z.enum([
29
+ "code_inspection",
30
+ "static_analysis",
31
+ "manual_reproduction",
32
+ "unit_test",
33
+ "integration_test",
34
+ "e2e_test",
35
+ "runtime_observation",
36
+ "documentation"
37
+ ]);
38
+ /**
39
+ * What was done to check the finding. Forces a reporter to distinguish "I
40
+ * think this is a problem" from "I demonstrated it", which is the axis a human
41
+ * approving fixes cares about most.
42
+ */
43
+ const findingVerificationSchema = z.strictObject({
44
+ level: findingVerificationLevelSchema,
45
+ method: findingVerificationMethodSchema,
46
+ summary: z.string().min(1).max(2e3).describe("What was checked and what it showed."),
47
+ limitations: z.string().min(1).max(2e3).optional().describe("What could not be checked.")
48
+ });
49
+ /** A single problem found in a repository, as a scanner or agent reports it. */
50
+ const findingSchema = z.strictObject({
51
+ title: z.string().min(1).max(200),
52
+ body: z.string().min(1).max(8e3).describe("The problem, its impact, and how to fix it. Markdown."),
53
+ path: z.string().min(1).max(500).optional().describe("Repository-relative file path."),
54
+ line: z.number().int().min(1).optional(),
55
+ endLine: z.number().int().min(1).optional(),
56
+ priority: findingPrioritySchema,
57
+ category: findingCategorySchema,
58
+ verification: findingVerificationSchema,
59
+ tool: z.string().min(1).max(100).optional().describe("Scanner that produced it, e.g. deepsec."),
60
+ ruleId: z.string().min(1).max(200).optional().describe("Scanner rule or check id, when there is one.")
61
+ });
62
+ /**
63
+ * Stable identity of a finding across scans, used as the signal's delivery id
64
+ * so re-reporting is a no-op instead of a second task. A scanner finding is
65
+ * the same problem when the same tool reports the same rule on the same file;
66
+ * its title is model-written prose and changes between runs, so it is left
67
+ * out. Without a rule id the title is all there is, normalised.
68
+ */
69
+ function findingFingerprint(repositoryId, finding) {
70
+ const parts = finding.tool !== void 0 && finding.ruleId !== void 0 && finding.path !== void 0 ? [
71
+ repositoryId,
72
+ finding.tool,
73
+ finding.ruleId,
74
+ finding.path
75
+ ] : [
76
+ repositoryId,
77
+ finding.tool ?? "",
78
+ finding.ruleId ?? "",
79
+ finding.path ?? "",
80
+ finding.title.trim().toLowerCase().replaceAll(/\s+/gu, " ")
81
+ ];
82
+ return createHash("sha256").update(parts.join(" ")).digest("hex").slice(0, 32);
83
+ }
84
+ //#endregion
85
+ //#region src/approval.ts
86
+ /**
87
+ * One approval rule. Every listed field must match for the rule to apply;
88
+ * absent fields match anything. Rules are evaluated first-match.
89
+ */
90
+ const approvalRuleSchema = z.strictObject({
91
+ source: vocabularySchema.optional().describe("Signal source, e.g. security_scan or github_issue."),
92
+ kind: vocabularySchema.optional().describe("Task kind, e.g. code_change."),
93
+ priority: z.array(findingPrioritySchema).min(1).optional().describe("Finding priorities the rule applies to."),
94
+ require: z.boolean().describe("Whether matching tasks wait for a human before dispatch.")
95
+ });
96
+ const approvalPolicySchema = z.array(approvalRuleSchema).describe("First-match rules deciding which tasks need a human before they run.");
97
+ /**
98
+ * The default: fixes for security findings wait for a human; everything else
99
+ * runs as it always has. Handoffs between agents (verification) never wait,
100
+ * because a human already approved the work they continue.
101
+ */
102
+ const defaultApprovalPolicy = [
103
+ {
104
+ kind: "verification",
105
+ require: false
106
+ },
107
+ {
108
+ source: "security_scan",
109
+ require: true
110
+ },
111
+ { require: false }
112
+ ];
113
+ /**
114
+ * Decide at task-creation time whether a task needs approval. Pure: the answer
115
+ * is stamped on the task and never re-evaluated, so a later policy change
116
+ * cannot silently release work a human was expecting to see.
117
+ */
118
+ function requiresApproval(policy, subject) {
119
+ for (const rule of policy) {
120
+ if (rule.source !== void 0 && rule.source !== subject.source) continue;
121
+ if (rule.kind !== void 0 && rule.kind !== subject.kind) continue;
122
+ if (rule.priority !== void 0) {
123
+ if (subject.priority === void 0 || !rule.priority.includes(subject.priority)) continue;
124
+ }
125
+ return rule.require;
126
+ }
127
+ return false;
128
+ }
129
+ //#endregion
130
+ export { findingCategorySchema as a, findingSchema as c, findingVerificationSchema as d, requiresApproval as i, findingVerificationLevelSchema as l, approvalRuleSchema as n, findingFingerprint as o, defaultApprovalPolicy as r, findingPrioritySchema as s, approvalPolicySchema as t, findingVerificationMethodSchema as u };
131
+
132
+ //# sourceMappingURL=approval-JX2Px9IC.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-JX2Px9IC.mjs","names":[],"sources":["../src/schema/finding.ts","../src/approval.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\n\nexport const findingPrioritySchema = z\n .enum([\"P0\", \"P1\", \"P2\", \"P3\"])\n .describe(\"Urgency of a finding: P0 is drop-everything, P3 is nice-to-have.\");\n\nexport const findingCategorySchema = z.enum([\n \"security\",\n \"correctness\",\n \"reliability\",\n \"performance\",\n \"compatibility\",\n \"accessibility\",\n \"documentation\",\n \"maintainability\",\n \"testing\",\n \"usability\",\n]);\n\nexport const findingVerificationLevelSchema = z\n .enum([\"unverified\", \"supported\", \"confirmed\"])\n .describe(\n \"How sure the reporter is: unverified = suspected from reading; supported = evidence points to it; confirmed = demonstrated.\",\n );\n\nexport const findingVerificationMethodSchema = z.enum([\n \"code_inspection\",\n \"static_analysis\",\n \"manual_reproduction\",\n \"unit_test\",\n \"integration_test\",\n \"e2e_test\",\n \"runtime_observation\",\n \"documentation\",\n]);\n\n/**\n * What was done to check the finding. Forces a reporter to distinguish \"I\n * think this is a problem\" from \"I demonstrated it\", which is the axis a human\n * approving fixes cares about most.\n */\nexport const findingVerificationSchema = z.strictObject({\n level: findingVerificationLevelSchema,\n method: findingVerificationMethodSchema,\n summary: z.string().min(1).max(2000).describe(\"What was checked and what it showed.\"),\n limitations: z.string().min(1).max(2000).optional().describe(\"What could not be checked.\"),\n});\n\n/** A single problem found in a repository, as a scanner or agent reports it. */\nexport const findingSchema = z.strictObject({\n title: z.string().min(1).max(200),\n body: z.string().min(1).max(8000).describe(\"The problem, its impact, and how to fix it. Markdown.\"),\n path: z.string().min(1).max(500).optional().describe(\"Repository-relative file path.\"),\n line: z.number().int().min(1).optional(),\n endLine: z.number().int().min(1).optional(),\n priority: findingPrioritySchema,\n category: findingCategorySchema,\n verification: findingVerificationSchema,\n tool: z.string().min(1).max(100).optional().describe(\"Scanner that produced it, e.g. deepsec.\"),\n ruleId: z.string().min(1).max(200).optional().describe(\"Scanner rule or check id, when there is one.\"),\n});\n\nexport type FindingPriority = z.infer<typeof findingPrioritySchema>;\nexport type FindingCategory = z.infer<typeof findingCategorySchema>;\nexport type FindingVerification = z.infer<typeof findingVerificationSchema>;\nexport type Finding = z.infer<typeof findingSchema>;\n\n/**\n * Stable identity of a finding across scans, used as the signal's delivery id\n * so re-reporting is a no-op instead of a second task. A scanner finding is\n * the same problem when the same tool reports the same rule on the same file;\n * its title is model-written prose and changes between runs, so it is left\n * out. Without a rule id the title is all there is, normalised.\n */\nexport function findingFingerprint(repositoryId: string, finding: Finding): string {\n const parts =\n finding.tool !== undefined && finding.ruleId !== undefined && finding.path !== undefined\n ? [repositoryId, finding.tool, finding.ruleId, finding.path]\n : [\n repositoryId,\n finding.tool ?? \"\",\n finding.ruleId ?? \"\",\n finding.path ?? \"\",\n finding.title.trim().toLowerCase().replaceAll(/\\s+/gu, \" \"),\n ];\n return createHash(\"sha256\").update(parts.join(\" \")).digest(\"hex\").slice(0, 32);\n}\n","import { z } from \"zod\";\nimport { vocabularySchema } from \"./schema/common\";\nimport { findingPrioritySchema, type FindingPriority } from \"./schema/finding\";\n\n/**\n * One approval rule. Every listed field must match for the rule to apply;\n * absent fields match anything. Rules are evaluated first-match.\n */\nexport const approvalRuleSchema = z.strictObject({\n source: vocabularySchema.optional().describe(\"Signal source, e.g. security_scan or github_issue.\"),\n kind: vocabularySchema.optional().describe(\"Task kind, e.g. code_change.\"),\n priority: z\n .array(findingPrioritySchema)\n .min(1)\n .optional()\n .describe(\"Finding priorities the rule applies to.\"),\n require: z.boolean().describe(\"Whether matching tasks wait for a human before dispatch.\"),\n});\n\nexport const approvalPolicySchema = z\n .array(approvalRuleSchema)\n .describe(\"First-match rules deciding which tasks need a human before they run.\");\n\nexport type ApprovalRule = z.infer<typeof approvalRuleSchema>;\nexport type ApprovalPolicy = z.infer<typeof approvalPolicySchema>;\n\n/**\n * The default: fixes for security findings wait for a human; everything else\n * runs as it always has. Handoffs between agents (verification) never wait,\n * because a human already approved the work they continue.\n */\nexport const defaultApprovalPolicy: ApprovalPolicy = [\n { kind: \"verification\", require: false },\n { source: \"security_scan\", require: true },\n { require: false },\n];\n\nexport interface ApprovalSubject {\n source?: string;\n kind: string;\n priority?: FindingPriority;\n}\n\n/**\n * Decide at task-creation time whether a task needs approval. Pure: the answer\n * is stamped on the task and never re-evaluated, so a later policy change\n * cannot silently release work a human was expecting to see.\n */\nexport function requiresApproval(policy: ApprovalPolicy, subject: ApprovalSubject): boolean {\n for (const rule of policy) {\n if (rule.source !== undefined && rule.source !== subject.source) continue;\n if (rule.kind !== undefined && rule.kind !== subject.kind) continue;\n if (rule.priority !== undefined) {\n if (subject.priority === undefined || !rule.priority.includes(subject.priority)) continue;\n }\n return rule.require;\n }\n return false;\n}\n"],"mappings":";;;;AAGA,MAAa,wBAAwB,EAClC,KAAK;CAAC;CAAM;CAAM;CAAM;AAAI,CAAC,CAAC,CAC9B,SAAS,kEAAkE;AAE9E,MAAa,wBAAwB,EAAE,KAAK;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,iCAAiC,EAC3C,KAAK;CAAC;CAAc;CAAa;AAAW,CAAC,CAAC,CAC9C,SACC,6HACF;AAEF,MAAa,kCAAkC,EAAE,KAAK;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAOD,MAAa,4BAA4B,EAAE,aAAa;CACtD,OAAO;CACP,QAAQ;CACR,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAI,CAAC,CAAC,SAAS,sCAAsC;CACpF,aAAa,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CA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AAM,KAAK,GAAG,CAAC,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;AAC/E;;;;;;;AC/EA,MAAa,qBAAqB,EAAE,aAAa;CAC/C,QAAQ,iBAAiB,SAAS,CAAC,CAAC,SAAS,oDAAoD;CACjG,MAAM,iBAAiB,SAAS,CAAC,CAAC,SAAS,8BAA8B;CACzE,UAAU,EACP,MAAM,qBAAqB,CAAC,CAC5B,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,yCAAyC;CACrD,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS,0DAA0D;AAC1F,CAAC;AAED,MAAa,uBAAuB,EACjC,MAAM,kBAAkB,CAAC,CACzB,SAAS,sEAAsE;;;;;;AAUlF,MAAa,wBAAwC;CACnD;EAAE,MAAM;EAAgB,SAAS;CAAM;CACvC;EAAE,QAAQ;EAAiB,SAAS;CAAK;CACzC,EAAE,SAAS,MAAM;AACnB;;;;;;AAaA,SAAgB,iBAAiB,QAAwB,SAAmC;CAC1F,KAAK,MAAM,QAAQ,QAAQ;EACzB,IAAI,KAAK,WAAW,KAAA,KAAa,KAAK,WAAW,QAAQ,QAAQ;EACjE,IAAI,KAAK,SAAS,KAAA,KAAa,KAAK,SAAS,QAAQ,MAAM;EAC3D,IAAI,KAAK,aAAa,KAAA,GAChB;OAAA,QAAQ,aAAa,KAAA,KAAa,CAAC,KAAK,SAAS,SAAS,QAAQ,QAAQ,GAAG;EAAA;EAEnF,OAAO,KAAK;CACd;CACA,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { i as StoreDriver } from "../driver-BJutB0PE.mjs";
1
+ import { i as StoreDriver } from "../driver-BC0Mt5KG.mjs";
2
2
  //#region src/blob/index.d.ts
3
3
  interface BlobObject {
4
4
  body: string;
@@ -17,11 +17,12 @@ interface BlobDriverOptions {
17
17
  client?: BlobClient;
18
18
  /** Path prefix inside the blob store; defaults to "factory". */
19
19
  prefix?: string;
20
+ /** Maximum Blob downloads in flight while listing a collection. Default 32. */
21
+ readConcurrency?: number;
20
22
  }
21
23
  /**
22
24
  * Store driver on Vercel Blob: durable and dependency-free (one Blob store on
23
- * the project, no database). Inserts and receipts are exactly as safe as on
24
- * Postgres (create-if-absent is atomic). Updates read the latest content,
25
+ * the project, no database). Inserts are create-if-absent. Updates read the latest content,
25
26
  * bypassing Blob's CDN cache, and write with an ETag precondition, so a
26
27
  * writer that lost a race gets a VersionConflictError rather than
27
28
  * overwriting the winner.
@@ -53,8 +53,7 @@ const vercelBlobClient = {
53
53
  };
54
54
  /**
55
55
  * Store driver on Vercel Blob: durable and dependency-free (one Blob store on
56
- * the project, no database). Inserts and receipts are exactly as safe as on
57
- * Postgres (create-if-absent is atomic). Updates read the latest content,
56
+ * the project, no database). Inserts are create-if-absent. Updates read the latest content,
58
57
  * bypassing Blob's CDN cache, and write with an ETag precondition, so a
59
58
  * writer that lost a race gets a VersionConflictError rather than
60
59
  * overwriting the winner.
@@ -62,6 +61,8 @@ const vercelBlobClient = {
62
61
  function createBlobDriver(options = {}) {
63
62
  const client = options.client ?? vercelBlobClient;
64
63
  const prefix = options.prefix ?? "factory";
64
+ const readConcurrency = options.readConcurrency ?? 32;
65
+ if (!Number.isInteger(readConcurrency) || readConcurrency < 1) throw new Error("Blob read concurrency must be a positive integer");
65
66
  function pathFor(collection, id) {
66
67
  return `${prefix}/${collection}/${id}.json`;
67
68
  }
@@ -119,19 +120,24 @@ function createBlobDriver(options = {}) {
119
120
  async list(collection) {
120
121
  const dir = `${prefix}/${collection}/`;
121
122
  const paths = await client.listPaths(dir);
122
- const entries = [];
123
- for (const pathname of paths) {
124
- const id = pathname.slice(dir.length).replace(/\.json$/u, "");
125
- const record = await readRecord(collection, id);
126
- if (record !== null) entries.push({
127
- id,
128
- record: {
129
- value: record.value,
130
- version: record.version
131
- }
132
- });
133
- }
134
- return entries;
123
+ const entries = new Array(paths.length);
124
+ let next = 0;
125
+ const workers = Array.from({ length: Math.min(readConcurrency, paths.length) }, async () => {
126
+ while (next < paths.length) {
127
+ const index = next++;
128
+ const id = paths[index].slice(dir.length).replace(/\.json$/u, "");
129
+ const record = await readRecord(collection, id);
130
+ entries[index] = record === null ? null : {
131
+ id,
132
+ record: {
133
+ value: record.value,
134
+ version: record.version
135
+ }
136
+ };
137
+ }
138
+ });
139
+ await Promise.all(workers);
140
+ return entries.filter((entry) => entry !== null);
135
141
  }
136
142
  };
137
143
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/blob/index.ts"],"sourcesContent":["import { get, list, put } from \"@vercel/blob\";\nimport {\n RecordExistsError,\n RecordNotFoundError,\n VersionConflictError,\n type CollectionName,\n type StoredEntry,\n type StoreDriver,\n} from \"../store/driver\";\n\nexport interface BlobObject {\n body: string;\n etag: string;\n}\n\n/** The narrow blob operations the driver needs; injectable for tests. */\nexport interface BlobClient {\n /** Must return the latest content, never a cached copy. */\n read(pathname: string): Promise<BlobObject | null>;\n /** Must reject if overwrite is false and the path exists, or if ifMatch is given and the ETag differs. */\n write(pathname: string, body: string, overwrite: boolean, ifMatch?: string): Promise<void>;\n listPaths(prefix: string): Promise<string[]>;\n}\n\n// @vercel/blob throws BlobNotFoundError with the message\n// \"Vercel Blob: The requested blob does not exist\".\nfunction isNotFoundError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"BlobNotFoundError\" ||\n /does not exist|not.?found|404/iu.test(error.message))\n );\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error instanceof Error &&\n /already exists|not allowed to overwrite|overwrite/iu.test(error.message)\n );\n}\n\n// @vercel/blob throws BlobPreconditionFailedError when ifMatch does not hold.\nfunction isPreconditionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"BlobPreconditionFailedError\" || /precondition|etag|412/iu.test(error.message))\n );\n}\n\nexport const vercelBlobClient: BlobClient = {\n async read(pathname) {\n let result;\n try {\n // Uncached: the ledger is read-modify-write and must see the latest version.\n result = await get(pathname, { access: \"private\", useCache: false });\n } catch (error) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n if (result === null || result.stream === null) {\n return null;\n }\n return { body: await new Response(result.stream).text(), etag: result.blob.etag };\n },\n\n async write(pathname, body, overwrite, ifMatch) {\n await put(pathname, body, {\n access: \"private\",\n allowOverwrite: overwrite,\n contentType: \"application/json\",\n ...(ifMatch === undefined ? {} : { ifMatch }),\n });\n },\n\n async listPaths(prefix) {\n const paths: string[] = [];\n let cursor: string | undefined;\n do {\n const page = await list({ prefix, cursor, limit: 1000 });\n paths.push(...page.blobs.map((blob) => blob.pathname));\n cursor = page.hasMore ? page.cursor : undefined;\n } while (cursor !== undefined);\n return paths;\n },\n};\n\nexport interface BlobDriverOptions {\n client?: BlobClient;\n /** Path prefix inside the blob store; defaults to \"factory\". */\n prefix?: string;\n}\n\n/**\n * Store driver on Vercel Blob: durable and dependency-free (one Blob store on\n * the project, no database). Inserts and receipts are exactly as safe as on\n * Postgres (create-if-absent is atomic). Updates read the latest content,\n * bypassing Blob's CDN cache, and write with an ETag precondition, so a\n * writer that lost a race gets a VersionConflictError rather than\n * overwriting the winner.\n */\nexport function createBlobDriver(options: BlobDriverOptions = {}): StoreDriver {\n const client = options.client ?? vercelBlobClient;\n const prefix = options.prefix ?? \"factory\";\n\n function pathFor(collection: CollectionName, id: string): string {\n return `${prefix}/${collection}/${id}.json`;\n }\n\n async function readRecord(\n collection: CollectionName,\n id: string,\n ): Promise<{ value: unknown; version: number; etag: string } | null> {\n let object: BlobObject | null;\n try {\n object = await client.read(pathFor(collection, id));\n } catch (error) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n if (object === null) {\n return null;\n }\n const parsed = JSON.parse(object.body) as { value: unknown; version: number };\n if (typeof parsed.version !== \"number\") {\n throw new Error(`malformed stored record at ${pathFor(collection, id)}`);\n }\n return { value: parsed.value, version: parsed.version, etag: object.etag };\n }\n\n return {\n name: \"blob\",\n\n async get(collection, id) {\n const record = await readRecord(collection, id);\n return record === null ? null : { value: record.value, version: record.version };\n },\n\n async insert(collection, id, value) {\n try {\n await client.write(\n pathFor(collection, id),\n JSON.stringify({ value, version: 1 }),\n false,\n );\n } catch (error) {\n if (isAlreadyExistsError(error)) {\n throw new RecordExistsError(collection, id);\n }\n throw error;\n }\n },\n\n async update(collection, id, value, expectedVersion) {\n const existing = await readRecord(collection, id);\n if (existing === null) {\n throw new RecordNotFoundError(collection, id);\n }\n if (existing.version !== expectedVersion) {\n throw new VersionConflictError(collection, id, expectedVersion);\n }\n try {\n await client.write(\n pathFor(collection, id),\n JSON.stringify({ value, version: expectedVersion + 1 }),\n true,\n // The write API's ifMatch rejects the weak form (W/\"…\") that reads return.\n existing.etag.replace(/^W\\//u, \"\"),\n );\n } catch (error) {\n if (isPreconditionError(error)) {\n throw new VersionConflictError(collection, id, expectedVersion);\n }\n throw error;\n }\n },\n\n async list(collection) {\n const dir = `${prefix}/${collection}/`;\n const paths = await client.listPaths(dir);\n const entries: StoredEntry[] = [];\n for (const pathname of paths) {\n const id = pathname.slice(dir.length).replace(/\\.json$/u, \"\");\n const record = await readRecord(collection, id);\n if (record !== null) {\n entries.push({ id, record: { value: record.value, version: record.version } });\n }\n }\n return entries;\n },\n };\n}\n"],"mappings":";;;AA0BA,SAAS,gBAAgB,OAAyB;CAChD,OACE,iBAAiB,UAChB,MAAM,SAAS,uBACd,kCAAkC,KAAK,MAAM,OAAO;AAE1D;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,iBAAiB,SACjB,sDAAsD,KAAK,MAAM,OAAO;AAE5E;AAGA,SAAS,oBAAoB,OAAyB;CACpD,OACE,iBAAiB,UAChB,MAAM,SAAS,iCAAiC,0BAA0B,KAAK,MAAM,OAAO;AAEjG;AAEA,MAAa,mBAA+B;CAC1C,MAAM,KAAK,UAAU;EACnB,IAAI;EACJ,IAAI;GAEF,SAAS,MAAM,IAAI,UAAU;IAAE,QAAQ;IAAW,UAAU;GAAM,CAAC;EACrE,SAAS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EAAE;IAC5D,MAAM,SAAS,MAAM,WAAW,YAAY,EAAE;IAC9C,IAAI,WAAW,MACb,QAAQ,KAAK;KAAE;KAAI,QAAQ;MAAE,OAAO,OAAO;MAAO,SAAS,OAAO;KAAQ;IAAE,CAAC;GAEjF;GACA,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/blob/index.ts"],"sourcesContent":["import { get, list, put } from \"@vercel/blob\";\nimport {\n RecordExistsError,\n RecordNotFoundError,\n VersionConflictError,\n type CollectionName,\n type StoredEntry,\n type StoreDriver,\n} from \"../store/driver\";\n\nexport interface BlobObject {\n body: string;\n etag: string;\n}\n\n/** The narrow blob operations the driver needs; injectable for tests. */\nexport interface BlobClient {\n /** Must return the latest content, never a cached copy. */\n read(pathname: string): Promise<BlobObject | null>;\n /** Must reject if overwrite is false and the path exists, or if ifMatch is given and the ETag differs. */\n write(pathname: string, body: string, overwrite: boolean, ifMatch?: string): Promise<void>;\n listPaths(prefix: string): Promise<string[]>;\n}\n\n// @vercel/blob throws BlobNotFoundError with the message\n// \"Vercel Blob: The requested blob does not exist\".\nfunction isNotFoundError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"BlobNotFoundError\" ||\n /does not exist|not.?found|404/iu.test(error.message))\n );\n}\n\nfunction isAlreadyExistsError(error: unknown): boolean {\n return (\n error instanceof Error &&\n /already exists|not allowed to overwrite|overwrite/iu.test(error.message)\n );\n}\n\n// @vercel/blob throws BlobPreconditionFailedError when ifMatch does not hold.\nfunction isPreconditionError(error: unknown): boolean {\n return (\n error instanceof Error &&\n (error.name === \"BlobPreconditionFailedError\" || /precondition|etag|412/iu.test(error.message))\n );\n}\n\nexport const vercelBlobClient: BlobClient = {\n async read(pathname) {\n let result;\n try {\n // Uncached: the ledger is read-modify-write and must see the latest version.\n result = await get(pathname, { access: \"private\", useCache: false });\n } catch (error) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n if (result === null || result.stream === null) {\n return null;\n }\n return { body: await new Response(result.stream).text(), etag: result.blob.etag };\n },\n\n async write(pathname, body, overwrite, ifMatch) {\n await put(pathname, body, {\n access: \"private\",\n allowOverwrite: overwrite,\n contentType: \"application/json\",\n ...(ifMatch === undefined ? {} : { ifMatch }),\n });\n },\n\n async listPaths(prefix) {\n const paths: string[] = [];\n let cursor: string | undefined;\n do {\n const page = await list({ prefix, cursor, limit: 1000 });\n paths.push(...page.blobs.map((blob) => blob.pathname));\n cursor = page.hasMore ? page.cursor : undefined;\n } while (cursor !== undefined);\n return paths;\n },\n};\n\nexport interface BlobDriverOptions {\n client?: BlobClient;\n /** Path prefix inside the blob store; defaults to \"factory\". */\n prefix?: string;\n /** Maximum Blob downloads in flight while listing a collection. Default 32. */\n readConcurrency?: number;\n}\n\n/**\n * Store driver on Vercel Blob: durable and dependency-free (one Blob store on\n * the project, no database). Inserts are create-if-absent. Updates read the latest content,\n * bypassing Blob's CDN cache, and write with an ETag precondition, so a\n * writer that lost a race gets a VersionConflictError rather than\n * overwriting the winner.\n */\nexport function createBlobDriver(options: BlobDriverOptions = {}): StoreDriver {\n const client = options.client ?? vercelBlobClient;\n const prefix = options.prefix ?? \"factory\";\n const readConcurrency = options.readConcurrency ?? 32;\n if (!Number.isInteger(readConcurrency) || readConcurrency < 1) {\n throw new Error(\"Blob read concurrency must be a positive integer\");\n }\n\n function pathFor(collection: CollectionName, id: string): string {\n return `${prefix}/${collection}/${id}.json`;\n }\n\n async function readRecord(\n collection: CollectionName,\n id: string,\n ): Promise<{ value: unknown; version: number; etag: string } | null> {\n let object: BlobObject | null;\n try {\n object = await client.read(pathFor(collection, id));\n } catch (error) {\n if (isNotFoundError(error)) {\n return null;\n }\n throw error;\n }\n if (object === null) {\n return null;\n }\n const parsed = JSON.parse(object.body) as { value: unknown; version: number };\n if (typeof parsed.version !== \"number\") {\n throw new Error(`malformed stored record at ${pathFor(collection, id)}`);\n }\n return { value: parsed.value, version: parsed.version, etag: object.etag };\n }\n\n return {\n name: \"blob\",\n\n async get(collection, id) {\n const record = await readRecord(collection, id);\n return record === null ? null : { value: record.value, version: record.version };\n },\n\n async insert(collection, id, value) {\n try {\n await client.write(\n pathFor(collection, id),\n JSON.stringify({ value, version: 1 }),\n false,\n );\n } catch (error) {\n if (isAlreadyExistsError(error)) {\n throw new RecordExistsError(collection, id);\n }\n throw error;\n }\n },\n\n async update(collection, id, value, expectedVersion) {\n const existing = await readRecord(collection, id);\n if (existing === null) {\n throw new RecordNotFoundError(collection, id);\n }\n if (existing.version !== expectedVersion) {\n throw new VersionConflictError(collection, id, expectedVersion);\n }\n try {\n await client.write(\n pathFor(collection, id),\n JSON.stringify({ value, version: expectedVersion + 1 }),\n true,\n // The write API's ifMatch rejects the weak form (W/\"…\") that reads return.\n existing.etag.replace(/^W\\//u, \"\"),\n );\n } catch (error) {\n if (isPreconditionError(error)) {\n throw new VersionConflictError(collection, id, expectedVersion);\n }\n throw error;\n }\n },\n\n async list(collection) {\n const dir = `${prefix}/${collection}/`;\n const paths = await client.listPaths(dir);\n const entries: (StoredEntry | null)[] = new Array(paths.length);\n let next = 0;\n const workers = Array.from(\n { length: Math.min(readConcurrency, paths.length) },\n async () => {\n while (next < paths.length) {\n const index = next++;\n const pathname = paths[index]!;\n const id = pathname.slice(dir.length).replace(/\\.json$/u, \"\");\n const record = await readRecord(collection, id);\n entries[index] = record === null\n ? null\n : { id, record: { value: record.value, version: record.version } };\n }\n },\n );\n await Promise.all(workers);\n return entries.filter((entry): entry is StoredEntry => entry !== null);\n },\n };\n}\n"],"mappings":";;;AA0BA,SAAS,gBAAgB,OAAyB;CAChD,OACE,iBAAiB,UAChB,MAAM,SAAS,uBACd,kCAAkC,KAAK,MAAM,OAAO;AAE1D;AAEA,SAAS,qBAAqB,OAAyB;CACrD,OACE,iBAAiB,SACjB,sDAAsD,KAAK,MAAM,OAAO;AAE5E;AAGA,SAAS,oBAAoB,OAAyB;CACpD,OACE,iBAAiB,UAChB,MAAM,SAAS,iCAAiC,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AC3B,MAAM,IAAI,qBAAqB,YAAY,IAAI,eAAe;IAEhE,MAAM;GACR;EACF;EAEA,MAAM,KAAK,YAAY;GACrB,MAAM,MAAM,GAAG,OAAO,GAAG,WAAW;GACpC,MAAM,QAAQ,MAAM,OAAO,UAAU,GAAG;GACxC,MAAM,UAAkC,IAAI,MAAM,MAAM,MAAM;GAC9D,IAAI,OAAO;GACX,MAAM,UAAU,MAAM,KACpB,EAAE,QAAQ,KAAK,IAAI,iBAAiB,MAAM,MAAM,EAAE,GAClD,YAAY;IACV,OAAO,OAAO,MAAM,QAAQ;KAC1B,MAAM,QAAQ;KAEd,MAAM,KADW,MAAM,MACJ,CAAC,MAAM,IAAI,MAAM,CAAC,CAAC,QAAQ,YAAY,EAAE;KAC5D,MAAM,SAAS,MAAM,WAAW,YAAY,EAAE;KAC9C,QAAQ,SAAS,WAAW,OACxB,OACA;MAAE;MAAI,QAAQ;OAAE,OAAO,OAAO;OAAO,SAAS,OAAO;MAAQ;KAAE;IACrE;GACF,CACF;GACA,MAAM,QAAQ,IAAI,OAAO;GACzB,OAAO,QAAQ,QAAQ,UAAgC,UAAU,IAAI;EACvE;CACF;AACF"}
@@ -0,0 +1,42 @@
1
+ import { d as isoDateTimeSchema, m as usdSchema, o as repositoryIdSchema, p as schemaVersionSchema, r as factoryIdSchema } from "./id-BLIkCVue.mjs";
2
+ import { z } from "zod";
3
+ //#region src/schema/repository.ts
4
+ const repositorySlugSchema = z.string().regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?\/[a-z0-9._-]+$/).describe("owner/name, lowercase, e.g. acme/web.");
5
+ const repositorySchema = z.strictObject({
6
+ schemaVersion: schemaVersionSchema,
7
+ id: repositoryIdSchema,
8
+ slug: repositorySlugSchema,
9
+ defaultBranch: z.string().min(1).describe("Branch changes land on, usually main."),
10
+ enabled: z.boolean().describe("Whether the factory may work on this repository."),
11
+ dependsOn: z.array(repositorySlugSchema).describe("Slugs of repositories this one consumes, for multi-repo work ordering."),
12
+ devbox: z.strictObject({
13
+ projectId: z.string().min(1),
14
+ teamId: z.string().min(1),
15
+ snapshot: z.string().min(1).optional().describe("Prebuilt snapshot to boot from.")
16
+ }).optional().describe("Devbox execution config. Absent when this repository never uses devboxes."),
17
+ connectedAt: isoDateTimeSchema
18
+ });
19
+ //#endregion
20
+ //#region src/schema/budget.ts
21
+ const budgetMonthSchema = z.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/);
22
+ const budgetLimitsSchema = z.strictObject({
23
+ totalUsd: usdSchema,
24
+ investigationUsd: usdSchema,
25
+ perTaskReservationUsd: usdSchema,
26
+ warningPercent: z.number().int().min(1).max(100),
27
+ perRepositoryUsd: z.record(repositorySlugSchema, usdSchema).optional()
28
+ });
29
+ const budgetSchema = z.strictObject({
30
+ schemaVersion: schemaVersionSchema,
31
+ factoryId: factoryIdSchema,
32
+ month: budgetMonthSchema,
33
+ limits: budgetLimitsSchema,
34
+ notices: z.strictObject({
35
+ warningAt: isoDateTimeSchema.optional(),
36
+ exhaustedAt: isoDateTimeSchema.optional()
37
+ })
38
+ });
39
+ //#endregion
40
+ export { repositorySlugSchema as a, repositorySchema as i, budgetMonthSchema as n, budgetSchema as r, budgetLimitsSchema as t };
41
+
42
+ //# sourceMappingURL=budget-DzSiIA4t.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"budget-DzSiIA4t.mjs","names":[],"sources":["../src/schema/repository.ts","../src/schema/budget.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { isoDateTimeSchema, schemaVersionSchema } from \"./common\";\nimport { repositoryIdSchema } from \"./id\";\n\nexport const repositorySlugSchema = z\n .string()\n .regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?\\/[a-z0-9._-]+$/)\n .describe(\"owner/name, lowercase, e.g. acme/web.\");\n\nexport const repositorySchema = z.strictObject({\n schemaVersion: schemaVersionSchema,\n id: repositoryIdSchema,\n slug: repositorySlugSchema,\n defaultBranch: z.string().min(1).describe(\"Branch changes land on, usually main.\"),\n enabled: z.boolean().describe(\"Whether the factory may work on this repository.\"),\n dependsOn: z\n .array(repositorySlugSchema)\n .describe(\"Slugs of repositories this one consumes, for multi-repo work ordering.\"),\n devbox: z\n .strictObject({\n projectId: z.string().min(1),\n teamId: z.string().min(1),\n snapshot: z.string().min(1).optional().describe(\"Prebuilt snapshot to boot from.\"),\n })\n .optional()\n .describe(\"Devbox execution config. Absent when this repository never uses devboxes.\"),\n connectedAt: isoDateTimeSchema,\n});\n\nexport type RepositorySlug = z.infer<typeof repositorySlugSchema>;\nexport type Repository = z.infer<typeof repositorySchema>;\n","import { z } from \"zod\";\nimport { isoDateTimeSchema, schemaVersionSchema, usdSchema } from \"./common\";\nimport { factoryIdSchema } from \"./id\";\nimport { repositorySlugSchema } from \"./repository\";\n\nexport const budgetMonthSchema = z.string().regex(/^\\d{4}-(0[1-9]|1[0-2])$/);\n\nexport const budgetLimitsSchema = z.strictObject({\n totalUsd: usdSchema,\n investigationUsd: usdSchema,\n perTaskReservationUsd: usdSchema,\n warningPercent: z.number().int().min(1).max(100),\n perRepositoryUsd: z.record(repositorySlugSchema, usdSchema).optional(),\n});\n\nexport const budgetSchema = z.strictObject({\n schemaVersion: schemaVersionSchema,\n factoryId: factoryIdSchema,\n month: budgetMonthSchema,\n limits: budgetLimitsSchema,\n notices: z.strictObject({\n warningAt: isoDateTimeSchema.optional(),\n exhaustedAt: isoDateTimeSchema.optional(),\n }),\n});\n\nexport type BudgetLimits = z.infer<typeof budgetLimitsSchema>;\nexport type Budget = z.infer<typeof budgetSchema>;\n"],"mappings":";;;AAIA,MAAa,uBAAuB,EACjC,OAAO,CAAC,CACR,MAAM,+CAA+C,CAAC,CACtD,SAAS,uCAAuC;AAEnD,MAAa,mBAAmB,EAAE,aAAa;CAC7C,eAAe;CACf,IAAI;CACJ,MAAM;CACN,eAAe,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,uCAAuC;CACjF,SAAS,EAAE,QAAQ,CAAC,CAAC,SAAS,kDAAkD;CAChF,WAAW,EACR,MAAM,oBAAoB,CAAC,CAC3B,SAAS,wEAAwE;CACpF,QAAQ,EACL,aAAa;EACZ,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EAC3B,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;EACxB,UAAU,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,iCAAiC;CACnF,CAAC,CAAC,CACD,SAAS,CAAC,CACV,SAAS,2EAA2E;CACvF,aAAa;AACf,CAAC;;;ACtBD,MAAa,oBAAoB,EAAE,OAAO,CAAC,CAAC,MAAM,yBAAyB;AAE3E,MAAa,qBAAqB,EAAE,aAAa;CAC/C,UAAU;CACV,kBAAkB;CAClB,uBAAuB;CACvB,gBAAgB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,GAAG;CAC/C,kBAAkB,EAAE,OAAO,sBAAsB,SAAS,CAAC,CAAC,SAAS;AACvE,CAAC;AAED,MAAa,eAAe,EAAE,aAAa;CACzC,eAAe;CACf,WAAW;CACX,OAAO;CACP,QAAQ;CACR,SAAS,EAAE,aAAa;EACtB,WAAW,kBAAkB,SAAS;EACtC,aAAa,kBAAkB,SAAS;CAC1C,CAAC;AACH,CAAC"}
@@ -1,4 +1,4 @@
1
- import { n as defineFactory } from "./factory-config-BJcjsPKl.mjs";
1
+ import { n as defineFactory } from "./factory-config-BoRXOw43.mjs";
2
2
  import { readdirSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  //#region src/build-factory.ts
@@ -1,5 +1,5 @@
1
- import { d as schemaVersionSchema, i as repositoryIdSchema, l as isoDateTimeSchema, n as factoryIdSchema, s as taskIdSchema, t as changeIdSchema } from "./id-DwCihQr4.mjs";
2
- import { _ as taskExecutionRepositoryIdsSchema } from "./approval-CwhTP1XB.mjs";
1
+ import { d as isoDateTimeSchema, l as taskIdSchema, n as changeIdSchema, o as repositoryIdSchema, p as schemaVersionSchema, r as factoryIdSchema } from "./id-BLIkCVue.mjs";
2
+ import { o as taskExecutionRepositoryIdsSchema } from "./task-CcOyOJ3k.mjs";
3
3
  import { n as RecordNotFoundError, r as VersionConflictError } from "./driver-Bbd25rNM.mjs";
4
4
  import { z } from "zod";
5
5
  import { createHash } from "node:crypto";
@@ -125,78 +125,6 @@ async function sweepBudget(stores, options) {
125
125
  };
126
126
  }
127
127
  //#endregion
128
- //#region src/coordination.ts
129
- /** Create one non-executable parent and one independently executable child per repository. */
130
- async function createCoordination(stores, input) {
131
- const repositoryIds = [...new Set(input.repositoryIds)];
132
- if (repositoryIds.length < 2) throw new Error("coordination requires at least two distinct repositories");
133
- const parent = await stores.tasks.create({
134
- repositoryIds,
135
- kind: "coordination",
136
- origin: input.signalId === void 0 ? { operator: input.operator } : { signalId: input.signalId },
137
- replyTo: input.replyTo,
138
- dedupeKey: input.dedupeKey
139
- });
140
- return {
141
- parent: parent.state === "queued" ? await stores.tasks.transition(parent.id, "running", { reason: "repository-scoped child tasks created" }) : parent,
142
- children: await Promise.all(repositoryIds.map((repositoryId) => stores.tasks.create({
143
- repositoryIds: [repositoryId],
144
- kind: "code_change",
145
- origin: { parentTaskId: parent.id },
146
- replyTo: input.replyTo,
147
- dedupeKey: input.dedupeKey === void 0 ? void 0 : `${input.dedupeKey}:${repositoryId}`
148
- })))
149
- };
150
- }
151
- /** Reconcile a coordination parent from its direct children without ever dispatching the parent. */
152
- async function reconcileCoordination(stores, parentTaskId, options) {
153
- const parent = await stores.tasks.get(parentTaskId);
154
- if (parent === null) throw new RecordNotFoundError("tasks", parentTaskId);
155
- if (parent.kind !== "coordination") throw new Error(`task ${parentTaskId} is ${parent.kind}, not coordination`);
156
- const children = (await stores.tasks.list()).filter((task) => task.origin.parentTaskId === parentTaskId);
157
- if (children.length !== parent.repositoryIds.length) return {
158
- status: "pending",
159
- parent,
160
- children
161
- };
162
- if (parent.state === "succeeded" || parent.state === "failed") return {
163
- status: parent.state,
164
- transitioned: false,
165
- parent,
166
- children
167
- };
168
- if (children.some((child) => child.state === "failed" || child.state === "cancelled")) {
169
- await options.present({
170
- status: "failed",
171
- parent,
172
- children
173
- });
174
- return {
175
- status: "failed",
176
- transitioned: true,
177
- parent: await stores.tasks.transition(parent.id, "failed", { reason: "one or more repository tasks failed" }),
178
- children
179
- };
180
- }
181
- if (!children.every((child) => child.state === "succeeded")) return {
182
- status: "pending",
183
- parent,
184
- children
185
- };
186
- await options.present({
187
- status: "succeeded",
188
- parent,
189
- children
190
- });
191
- await stores.tasks.transition(parent.id, "verifying", { reason: "all repository tasks succeeded" });
192
- return {
193
- status: "succeeded",
194
- transitioned: true,
195
- parent: await stores.tasks.transition(parent.id, "succeeded", { reason: "aggregate multi-repository handoff is ready" }),
196
- children
197
- };
198
- }
199
- //#endregion
200
128
  //#region src/schema/transitions.ts
201
129
  const taskInitialState = "queued";
202
130
  const taskTransitions = [
@@ -329,6 +257,12 @@ const taskTransitions = [
329
257
  ];
330
258
  const changeInitialState = "verifying";
331
259
  const changeTransitions = [
260
+ {
261
+ from: "ready",
262
+ to: "verifying",
263
+ trigger: "a code_change task updated the existing pull request head",
264
+ actor: "reconciler"
265
+ },
332
266
  {
333
267
  from: "verifying",
334
268
  to: "ready",
@@ -615,6 +549,6 @@ const changeSchema = z.strictObject({
615
549
  });
616
550
  });
617
551
  //#endregion
618
- export { budgetStatus as C, sweepBudget as D, deriveFactoryId as E, sweepSettlements as O, budgetMonthOf as S, computeMonthSpendUsd as T, taskInitialState as _, BudgetExhaustedError as a, createCoordination as b, dispatchTask as c, changeInitialState as d, changeTransitions as f, signalOutcomeTransitions as g, signalInitialOutcome as h, levelSchema as i, InvalidTransitionError as l, legalNextStates as m, changeSchema as n, DEFAULT_MAX_LAUNCH_ATTEMPTS as o, isTransitionAllowed as p, changeStateSchema as r, DispatchRefusedError as s, changeEvidenceSchema as t, assertTransition as u, taskTransitions as v, canReserve as w, reconcileCoordination as x, terminalStates as y };
552
+ export { computeMonthSpendUsd as C, sweepSettlements as E, canReserve as S, sweepBudget as T, taskInitialState as _, BudgetExhaustedError as a, budgetMonthOf as b, dispatchTask as c, changeInitialState as d, changeTransitions as f, signalOutcomeTransitions as g, signalInitialOutcome as h, levelSchema as i, InvalidTransitionError as l, legalNextStates as m, changeSchema as n, DEFAULT_MAX_LAUNCH_ATTEMPTS as o, isTransitionAllowed as p, changeStateSchema as r, DispatchRefusedError as s, changeEvidenceSchema as t, assertTransition as u, taskTransitions as v, deriveFactoryId as w, budgetStatus as x, terminalStates as y };
619
553
 
620
- //# sourceMappingURL=change-CzEAoFVE.mjs.map
554
+ //# sourceMappingURL=change-D2U6v7Ek.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-D2U6v7Ek.mjs","names":[],"sources":["../src/budget.ts","../src/schema/transitions.ts","../src/dispatch.ts","../src/schema/change.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { factoryIdSchema, type FactoryId, type TaskId } from \"./schema/id\";\nimport type { BudgetLimits } from \"./schema/budget\";\nimport type { Task } from \"./schema/task\";\nimport type { FactoryStores } from \"./store/engine\";\n\n/**\n * Stable factory identity for budget rows. Nothing mints factory ids yet, so\n * the app derives one from a deployment-stable seed such as the Vercel\n * project id.\n */\nexport function deriveFactoryId(seed: string): FactoryId {\n return factoryIdSchema.parse(\n `fac_${createHash(\"sha256\").update(seed).digest(\"hex\").slice(0, 32)}`,\n );\n}\n\n/** The budget month (\"YYYY-MM\", UTC) a timestamp falls into. */\nexport function budgetMonthOf(isoDateTime: string): string {\n return isoDateTime.slice(0, 7);\n}\n\n// Currency math runs in integer micro-dollars so decimal limits compare\n// exactly; 0.1 + 0.2 must never refuse an exact-fit reservation.\nfunction microsOf(usd: number): number {\n return Math.round(usd * 1_000_000);\n}\n\n/**\n * Monthly spend is derived from task rows, never stored: each task counts its\n * settled cost once that exists, otherwise its held reservation. A task\n * settles once, so a settled row never also counts its reservation.\n * Attribution uses the reservation time so tasks that wait across a month\n * boundary charge the month they actually ran in.\n */\nexport function computeMonthSpendUsd(tasks: readonly Task[], month: string): number {\n let spendMicros = 0;\n for (const task of tasks) {\n if (budgetMonthOf(task.reservedAt ?? task.createdAt) !== month) {\n continue;\n }\n spendMicros += microsOf(task.settledUsd ?? task.reservedUsd ?? 0);\n }\n return spendMicros / 1_000_000;\n}\n\nexport type BudgetStatus = \"ok\" | \"warning\" | \"exhausted\";\n\n/**\n * True when one more per-task slice fits under the monthly total. Dispatch\n * refuses on this exact predicate and budgetStatus reports \"exhausted\" on its\n * negation, so refusing and reporting can never disagree.\n */\nexport function canReserve(\n spendUsd: number,\n limits: Pick<BudgetLimits, \"totalUsd\" | \"perTaskReservationUsd\">,\n): boolean {\n return microsOf(spendUsd) + microsOf(limits.perTaskReservationUsd) <= microsOf(limits.totalUsd);\n}\n\nexport function budgetStatus(\n spendUsd: number,\n limits: Pick<BudgetLimits, \"totalUsd\" | \"perTaskReservationUsd\" | \"warningPercent\">,\n): BudgetStatus {\n if (!canReserve(spendUsd, limits)) {\n return \"exhausted\";\n }\n // Integer comparison: spend/total * 100 >= warningPercent without float\n // drift on decimal limits.\n if (microsOf(spendUsd) * 100 >= microsOf(limits.totalUsd) * limits.warningPercent) {\n return \"warning\";\n }\n return \"ok\";\n}\n\nconst TERMINAL_TASK_STATES = new Set<Task[\"state\"]>([\"succeeded\", \"failed\", \"cancelled\"]);\n\nexport interface SettleSweepOptions {\n /** How long a terminal task waits for late usage before the sweep settles it. */\n graceMinutes?: number;\n now?: () => Date;\n}\n\nexport interface SettleSweepResult {\n settled: { taskId: TaskId; totalUsd: number }[];\n}\n\n/**\n * Settle reserved terminal tasks the session hook did not: a task that ended\n * after its session (a change verified later) or whose session died. Settles\n * at the recorded usage, or at zero with a warning reason when none was\n * recorded within the grace window.\n */\nexport async function sweepSettlements(\n stores: FactoryStores,\n options: SettleSweepOptions = {},\n): Promise<SettleSweepResult> {\n const graceMs = (options.graceMinutes ?? 10) * 60_000;\n const nowMs = (options.now ?? (() => new Date()))().getTime();\n const settled: SettleSweepResult[\"settled\"] = [];\n for (const task of await stores.tasks.list()) {\n if (task.reservedUsd === undefined || task.settledUsd !== undefined) {\n continue;\n }\n if (!TERMINAL_TASK_STATES.has(task.state)) {\n continue;\n }\n if (nowMs - Date.parse(task.updatedAt) < graceMs) {\n continue;\n }\n // A concurrent writer (operator retry, another sweep) may move the task\n // between the list and the settle; skip it rather than aborting the pass.\n const totalUsd = task.usage?.costUsd ?? 0;\n try {\n const result = await stores.tasks.settle(\n task.id,\n { totalUsd },\n {\n reason: task.usage === undefined\n ? \"usage missing after ten minutes; settled at zero\"\n : \"measured usage settled by sweep\",\n },\n );\n // Report this settlement's amount, not the task's accumulated total.\n settled.push({ taskId: result.id, totalUsd });\n } catch {\n continue;\n }\n }\n return { settled };\n}\n\nexport interface BudgetNotice {\n outcome: \"budget_warning\" | \"budget_exhausted\";\n month: string;\n spendUsd: number;\n limits: BudgetLimits;\n}\n\nexport interface BudgetSweepOptions {\n factoryId: FactoryId;\n limits: BudgetLimits;\n /** Defaults to the current UTC month. */\n month?: string;\n now?: () => Date;\n /** Owner-only delivery; invoked at most once per month per outcome. */\n notify?: (notice: BudgetNotice) => Promise<void>;\n}\n\nexport interface BudgetSweepResult {\n month: string;\n spendUsd: number;\n status: BudgetStatus;\n warned: boolean;\n exhausted: boolean;\n}\n\n/**\n * Ensure the month's budget row, derive spend, and record threshold crossings\n * write-once. Delivery comes first and the stamp only lands after it, so a\n * failed notification retries on the next sweep instead of being lost; the\n * write-once stamp still keeps each threshold to one message per month.\n */\nexport async function sweepBudget(\n stores: FactoryStores,\n options: BudgetSweepOptions,\n): Promise<BudgetSweepResult> {\n const now = options.now ?? (() => new Date());\n const month = options.month ?? budgetMonthOf(now().toISOString());\n const budget = await stores.budgets.ensure({\n factoryId: options.factoryId,\n month,\n limits: options.limits,\n });\n const spendUsd = computeMonthSpendUsd(await stores.tasks.list(), month);\n const status = budgetStatus(spendUsd, options.limits);\n\n async function crossThreshold(\n notice: \"warning\" | \"exhausted\",\n outcome: BudgetNotice[\"outcome\"],\n ): Promise<boolean> {\n const field = notice === \"warning\" ? \"warningAt\" : \"exhaustedAt\";\n if (budget.notices[field] !== undefined) {\n return false;\n }\n if (options.notify !== undefined) {\n try {\n await options.notify({ outcome, month, spendUsd, limits: options.limits });\n } catch {\n // Leave the notice unstamped so the next sweep retries delivery.\n return false;\n }\n }\n return (await stores.budgets.stampNotice(month, notice)).stamped;\n }\n\n let warned = false;\n let exhausted = false;\n if (status === \"exhausted\") {\n exhausted = await crossThreshold(\"exhausted\", \"budget_exhausted\");\n // The warning threshold was necessarily crossed too; stamp it silently so\n // a later settle-down cannot deliver \"warning\" after \"exhausted\".\n if (budget.notices.warningAt === undefined) {\n await stores.budgets.stampNotice(month, \"warning\");\n }\n } else if (status === \"warning\") {\n warned = await crossThreshold(\"warning\", \"budget_warning\");\n }\n return { month, spendUsd, status, warned, exhausted };\n}\n","import type { ChangeState } from \"./change\";\nimport type { SignalOutcome } from \"./signal\";\nimport type { TaskState } from \"./task\";\n\nexport type TransitionActor =\n | \"system\"\n | \"reconciler\"\n | \"foreman\"\n | \"operator\"\n | \"webhook\"\n | \"human\";\n\nexport interface Transition<State extends string> {\n readonly from: State;\n readonly to: State;\n readonly trigger: string;\n readonly actor: TransitionActor;\n}\n\nexport const taskInitialState = \"queued\" satisfies TaskState;\n\nexport const taskTransitions: readonly Transition<TaskState>[] = [\n {\n from: \"queued\",\n to: \"running\",\n trigger: \"dependencies have a change, reservation succeeded, devbox created\",\n actor: \"reconciler\",\n },\n { from: \"queued\", to: \"failed\", trigger: \"reservation refused\", actor: \"reconciler\" },\n { from: \"queued\", to: \"needs_human\", trigger: \"kind is question\", actor: \"system\" },\n { from: \"queued\", to: \"cancelled\", trigger: \"cancel or kill\", actor: \"operator\" },\n { from: \"running\", to: \"verifying\", trigger: \"devbox task reported complete\", actor: \"reconciler\" },\n {\n from: \"running\",\n to: \"queued\",\n trigger: \"launch failed below attempt limit\",\n actor: \"reconciler\",\n },\n {\n from: \"running\",\n to: \"failed\",\n trigger: \"devbox task errored, deadline exceeded, or launch failed at attempt limit\",\n actor: \"reconciler\",\n },\n {\n from: \"running\",\n to: \"needs_human\",\n trigger: \"an open QuestionTask requests human input or action\",\n actor: \"reconciler\",\n },\n { from: \"running\", to: \"cancelled\", trigger: \"cancel or kill\", actor: \"operator\" },\n { from: \"running\", to: \"stalled\", trigger: \"no progress within the stall window\", actor: \"reconciler\" },\n {\n from: \"stalled\",\n to: \"queued\",\n trigger: \"replacement attempt below attempt limit, or operator retry\",\n actor: \"reconciler\",\n },\n { from: \"stalled\", to: \"failed\", trigger: \"attempt limit exhausted\", actor: \"reconciler\" },\n { from: \"stalled\", to: \"cancelled\", trigger: \"cancel or kill\", actor: \"operator\" },\n { from: \"verifying\", to: \"succeeded\", trigger: \"kind criterion true\", actor: \"reconciler\" },\n {\n from: \"verifying\",\n to: \"running\",\n trigger: \"verification failed below attempt limit\",\n actor: \"reconciler\",\n },\n {\n from: \"verifying\",\n to: \"failed\",\n trigger: \"verification failed at attempt limit\",\n actor: \"reconciler\",\n },\n { from: \"verifying\", to: \"cancelled\", trigger: \"cancel or kill\", actor: \"operator\" },\n { from: \"needs_human\", to: \"succeeded\", trigger: \"question answered\", actor: \"operator\" },\n { from: \"needs_human\", to: \"queued\", trigger: \"operator retry\", actor: \"operator\" },\n { from: \"needs_human\", to: \"cancelled\", trigger: \"cancel or kill\", actor: \"operator\" },\n { from: \"failed\", to: \"queued\", trigger: \"operator retry\", actor: \"operator\" },\n];\n\nexport const changeInitialState = \"verifying\" satisfies ChangeState;\n\nexport const changeTransitions: readonly Transition<ChangeState>[] = [\n {\n from: \"ready\",\n to: \"verifying\",\n trigger: \"a code_change task updated the existing pull request head\",\n actor: \"reconciler\",\n },\n {\n from: \"verifying\",\n to: \"ready\",\n trigger: \"configured verification policy completed, risk and confidence written\",\n actor: \"reconciler\",\n },\n {\n from: \"verifying\",\n to: \"closed\",\n trigger: \"verification failed at attempt limit or pr closed upstream\",\n actor: \"reconciler\",\n },\n { from: \"ready\", to: \"merged\", trigger: \"pr merged on github\", actor: \"webhook\" },\n { from: \"ready\", to: \"closed\", trigger: \"pr closed without merge\", actor: \"webhook\" },\n {\n from: \"merged\",\n to: \"deployed\",\n trigger: \"production deployment ready containing the merge sha\",\n actor: \"webhook\",\n },\n {\n from: \"deployed\",\n to: \"rolled_out\",\n trigger: \"no flag, or flag ramped to full and held\",\n actor: \"foreman\",\n },\n { from: \"deployed\", to: \"rolled_back\", trigger: \"rollback rule crossed\", actor: \"foreman\" },\n {\n from: \"rolled_out\",\n to: \"rolled_back\",\n trigger: \"rollback rule crossed or flag flipped off\",\n actor: \"foreman\",\n },\n { from: \"rolled_back\", to: \"deployed\", trigger: \"human retried the ramp\", actor: \"human\" },\n];\n\nexport const signalInitialOutcome = \"pending\" satisfies SignalOutcome;\n\nexport const signalOutcomeTransitions: readonly Transition<SignalOutcome>[] = [\n { from: \"pending\", to: \"accepted\", trigger: \"classified as actionable\", actor: \"reconciler\" },\n { from: \"pending\", to: \"duplicate\", trigger: \"classified as duplicate\", actor: \"reconciler\" },\n {\n from: \"pending\",\n to: \"unactionable\",\n trigger: \"classified as unactionable\",\n actor: \"reconciler\",\n },\n {\n from: \"pending\",\n to: \"low_confidence\",\n trigger: \"classified below confidence threshold\",\n actor: \"reconciler\",\n },\n { from: \"pending\", to: \"ignored\", trigger: \"classified as ignorable\", actor: \"reconciler\" },\n];\n\nexport function isTransitionAllowed<State extends string>(\n transitions: readonly Transition<State>[],\n from: State,\n to: State,\n): boolean {\n return transitions.some((transition) => transition.from === from && transition.to === to);\n}\n\nexport function legalNextStates<State extends string>(\n transitions: readonly Transition<State>[],\n from: State,\n): readonly State[] {\n return [\n ...new Set(\n transitions.filter((transition) => transition.from === from).map((t) => t.to),\n ),\n ];\n}\n\nexport class InvalidTransitionError<State extends string> extends Error {\n readonly from: State;\n readonly to: State;\n readonly legalNextStates: readonly State[];\n\n constructor(from: State, to: State, legal: readonly State[]) {\n super(\n legal.length > 0\n ? `invalid transition from \"${from}\" to \"${to}\"; legal next states: ${legal\n .map((state) => `\"${state}\"`)\n .join(\", \")}`\n : `invalid transition from \"${from}\" to \"${to}\"; \"${from}\" is terminal`,\n );\n this.name = \"InvalidTransitionError\";\n this.from = from;\n this.to = to;\n this.legalNextStates = legal;\n }\n}\n\nexport function assertTransition<State extends string>(\n transitions: readonly Transition<State>[],\n from: State,\n to: State,\n): void {\n if (!isTransitionAllowed(transitions, from, to)) {\n throw new InvalidTransitionError(from, to, legalNextStates(transitions, from));\n }\n}\n\nexport function terminalStates<State extends string>(\n transitions: readonly Transition<State>[],\n): readonly State[] {\n const states = new Set<State>();\n for (const transition of transitions) {\n states.add(transition.from);\n states.add(transition.to);\n }\n return [...states].filter(\n (state) => !transitions.some((transition) => transition.from === state),\n );\n}\n","import { budgetMonthOf, canReserve, computeMonthSpendUsd } from \"./budget\";\nimport type { BudgetLimits } from \"./schema/budget\";\nimport type { TaskId } from \"./schema/id\";\nimport { taskExecutionRepositoryIdsSchema, type ExecutionReference, type Task } from \"./schema/task\";\nimport { InvalidTransitionError } from \"./schema/transitions\";\nimport { RecordNotFoundError, VersionConflictError } from \"./store/driver\";\nimport type { FactoryStores } from \"./store/engine\";\n\nexport class DispatchRefusedError extends Error {\n readonly taskId: TaskId;\n readonly reason: string;\n\n constructor(taskId: TaskId, reason: string) {\n super(`dispatch of \"${taskId}\" refused: ${reason}`);\n this.name = \"DispatchRefusedError\";\n this.taskId = taskId;\n this.reason = reason;\n }\n}\n\n/**\n * An exhausted budget is definitive, not a retryable refusal: the task has\n * already been failed and receipted when this throws, so it never re-enters\n * the sweep. Operator retry recovers it once budget frees up.\n */\nexport class BudgetExhaustedError extends Error {\n readonly taskId: TaskId;\n readonly month: string;\n readonly spendUsd: number;\n\n constructor(taskId: TaskId, month: string, spendUsd: number) {\n super(`dispatch of \"${taskId}\" refused: budget for ${month} is exhausted at $${spendUsd}`);\n this.name = \"BudgetExhaustedError\";\n this.taskId = taskId;\n this.month = month;\n this.spendUsd = spendUsd;\n }\n}\n\nexport interface DispatchBudget {\n limits: Pick<BudgetLimits, \"totalUsd\" | \"perTaskReservationUsd\">;\n /** Defaults to the current UTC month. */\n month?: string;\n now?: () => Date;\n}\n\nexport interface DispatchOptions {\n /**\n * Starts the durable execution for the task (an Eve agent run). Runs after\n * the task has won the queued -> running transition. Returning the\n * provider's execution reference records it on the task so the reconciler\n * can find the run; returning nothing leaves the task reachable only by the\n * stall window.\n */\n launch: (task: Task) => Promise<ExecutionReference | void>;\n /** How many launches to try before the task fails for good; a failure re-queues for the next sweep. */\n maxLaunchAttempts?: number;\n /**\n * Reserve-before-execution. When set, dispatch refuses definitively once\n * the month's derived spend cannot fit another reservation, and otherwise\n * stamps the reservation in the same write that wins queued -> running.\n */\n budget?: DispatchBudget;\n}\n\n// A fresh Vercel project rejects its own agents' sessions until its identity\n// finishes provisioning; at one sweep per minute the budget must outlast that.\nexport const DEFAULT_MAX_LAUNCH_ATTEMPTS = 45;\n\n/**\n * The handshake between recorded work and execution: win the store-gated\n * transition (at most one dispatcher can succeed), then start the run. A\n * launch failure re-queues the task (bumping its attempt) until the attempt\n * limit, then fails it; a crash between the transition and the launch leaves\n * a running task with no execution, which the sweep reaps.\n */\nexport async function dispatchTask(\n stores: FactoryStores,\n taskId: TaskId,\n options: DispatchOptions,\n): Promise<Task> {\n const task = await stores.tasks.get(taskId);\n if (task === null) {\n throw new RecordNotFoundError(\"tasks\", taskId);\n }\n if (task.kind === \"question\") {\n throw new DispatchRefusedError(taskId, \"question tasks are answered, not dispatched\");\n }\n if (task.kind === \"coordination\") {\n throw new DispatchRefusedError(taskId, \"coordination tasks are reconciled, not dispatched\");\n }\n if (!taskExecutionRepositoryIdsSchema.safeParse(task.repositoryIds).success) {\n throw new DispatchRefusedError(taskId, \"task execution requires exactly one repository\");\n }\n if (task.approval === \"required\") {\n throw new DispatchRefusedError(taskId, \"awaiting human approval\");\n }\n if (task.approval === \"denied\") {\n throw new DispatchRefusedError(taskId, \"approval was denied\");\n }\n for (const dependencyId of task.dependsOn ?? []) {\n const dependency = await stores.tasks.get(dependencyId);\n if (dependency === null) {\n throw new DispatchRefusedError(taskId, `dependency \"${dependencyId}\" does not exist`);\n }\n if (dependency.changeId === undefined) {\n throw new DispatchRefusedError(\n taskId,\n `dependency \"${dependencyId}\" has not produced a change`,\n );\n }\n }\n\n // The reservation gates queued -> running only; any other state falls\n // through to the transition below, which rejects it as invalid.\n let reservation: { reservedUsd: number; reservedAt: string } | undefined;\n if (options.budget !== undefined && task.state === \"queued\") {\n const budgetNow = (options.budget.now ?? (() => new Date()))().toISOString();\n const month = options.budget.month ?? budgetMonthOf(budgetNow);\n // This task's own retained reservation from a prior attempt is excluded,\n // because re-reserving overwrites it. Its settled cost stays counted:\n // that money was actually spent and a retry must not reopen it.\n const rows = (await stores.tasks.list()).map((row) =>\n row.id === taskId ? { ...row, reservedUsd: undefined } : row,\n );\n const spendUsd = computeMonthSpendUsd(rows, month);\n const { totalUsd, perTaskReservationUsd } = options.budget.limits;\n if (!canReserve(spendUsd, options.budget.limits)) {\n const reason = `budget exhausted: ${month} spend $${spendUsd} cannot fit a $${perTaskReservationUsd} reservation under $${totalUsd}`;\n // Fail first, so BudgetExhaustedError's contract (task already failed)\n // holds; losing the task to a concurrent dispatcher surfaces as a\n // refusal, never as a false exhaustion with a misleading receipt.\n try {\n await stores.tasks.transition(taskId, \"failed\", { reason, expectFrom: \"queued\" });\n } catch (error) {\n if (error instanceof InvalidTransitionError || error instanceof VersionConflictError) {\n throw new DispatchRefusedError(taskId, \"another dispatcher took the task\");\n }\n throw error;\n }\n // Best-effort: the failed transition above already wrote its own\n // receipt carrying this reason, so losing this supplementary one\n // cannot lose the evidence.\n if (task.repositoryIds !== undefined) {\n await stores.receipts\n .append({\n repositoryIds: task.repositoryIds,\n taskId,\n kind: task.kind,\n state: \"reservation_refused\",\n phase: \"budget\",\n reason,\n attempt: task.attempt,\n dedupeKey: `task:${taskId}:reservation_refused:${task.attempt}`,\n })\n .catch(() => undefined);\n }\n throw new BudgetExhaustedError(taskId, month, spendUsd);\n }\n reservation = { reservedUsd: perTaskReservationUsd, reservedAt: budgetNow };\n }\n\n // A resurrected task keeps its settled cost: multi-attempt accumulation is\n // an open spec decision, so the first settlement stays authoritative and\n // the new slice is only held until then.\n const running = await stores.tasks.transition(\n taskId,\n \"running\",\n reservation === undefined\n ? undefined\n : {\n patch: {\n reservedUsd: reservation.reservedUsd,\n reservedAt: reservation.reservedAt,\n },\n },\n );\n let execution: ExecutionReference | void;\n try {\n execution = await options.launch(running);\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).slice(0, 500);\n const limit = options.maxLaunchAttempts ?? DEFAULT_MAX_LAUNCH_ATTEMPTS;\n if (running.attempt < limit) {\n const retryReason = `launch failed (attempt ${running.attempt} of ${limit}), will retry: ${reason}`;\n await stores.tasks.transition(taskId, \"queued\", { reason: retryReason }).catch(() => undefined);\n // The queued transition writes no receipt; leave one so the retry is visible.\n if (running.repositoryIds !== undefined) {\n await stores.receipts\n .append({\n repositoryIds: running.repositoryIds,\n taskId,\n kind: \"task\",\n state: \"launch_retry\",\n reason: retryReason,\n dedupeKey: `task:${taskId}:launch_retry:${running.attempt}`,\n })\n .catch(() => undefined);\n }\n } else {\n await stores.tasks\n .transition(taskId, \"failed\", { reason: `launch failed after ${running.attempt} attempts: ${reason}` })\n .catch(() => undefined);\n }\n throw error;\n }\n if (execution === undefined) {\n return running;\n }\n // The run exists either way; a lost write here leaves a running task with\n // no reference, which the stall sweep still reaps.\n return stores.tasks.recordExecution(taskId, execution).catch(() => running);\n}\n","import { z } from \"zod\";\nimport { isoDateTimeSchema, schemaVersionSchema } from \"./common\";\nimport { changeIdSchema, repositoryIdSchema, taskIdSchema } from \"./id\";\n\nexport const levelSchema = z.enum([\"low\", \"medium\", \"high\"]);\n\nexport const changeStateSchema = z.enum([\n \"verifying\",\n \"ready\",\n \"merged\",\n \"deployed\",\n \"rolled_out\",\n \"rolled_back\",\n \"closed\",\n]);\n\nconst postMergeStates: readonly string[] = [\"merged\", \"deployed\", \"rolled_out\", \"rolled_back\"];\n\nexport const changeEvidenceSchema = z.strictObject({\n reproVerified: z.boolean(),\n testsAdded: z.number().int().min(0),\n checksGreen: z.boolean(),\n attackPassed: z.boolean(),\n scopeMatches: z.boolean(),\n previewUrl: z.url().optional(),\n});\n\nexport const changeSchema = z\n .strictObject({\n schemaVersion: schemaVersionSchema,\n id: changeIdSchema,\n repositoryId: repositoryIdSchema,\n taskId: taskIdSchema.optional(),\n groupId: taskIdSchema.optional(),\n prNumber: z.number().int().min(1),\n prUrl: z.url(),\n author: z.string().min(1),\n risk: levelSchema,\n confidence: levelSchema,\n evidence: changeEvidenceSchema,\n state: changeStateSchema,\n mergeSha: z\n .string()\n .regex(/^[0-9a-f]{40}$/)\n .optional()\n .describe(\"Merge commit sha recorded when the pull request merges, matched against production deployments.\"),\n decidedBy: z.string().min(1).optional(),\n createdAt: isoDateTimeSchema,\n updatedAt: isoDateTimeSchema,\n })\n .superRefine((change, ctx) => {\n if (postMergeStates.includes(change.state) && change.decidedBy === undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"decidedBy\"],\n message: `${change.state} changes require decidedBy`,\n });\n }\n });\n\nexport type Level = z.infer<typeof levelSchema>;\nexport type ChangeState = z.infer<typeof changeStateSchema>;\nexport type ChangeEvidence = z.infer<typeof changeEvidenceSchema>;\nexport type Change = z.infer<typeof changeSchema>;\n"],"mappings":";;;;;;;;;;;AAWA,SAAgB,gBAAgB,MAAyB;CACvD,OAAO,gBAAgB,MACrB,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE,GACpE;AACF;;AAGA,SAAgB,cAAc,aAA6B;CACzD,OAAO,YAAY,MAAM,GAAG,CAAC;AAC/B;AAIA,S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,IAAI,gBAAgB,SAAS,OAAO,KAAK,KAAK,OAAO,cAAc,KAAA,GACjE,IAAI,SAAS;EACX,MAAM;EACN,MAAM,CAAC,WAAW;EAClB,SAAS,GAAG,OAAO,MAAM;CAC3B,CAAC;AAEL,CAAC"}
@@ -0,0 +1,30 @@
1
+ import { f as replyToSchema, l as taskIdSchema, n as changeIdSchema, s as repositoryIdsSchema } from "./id-BLIkCVue.mjs";
2
+ import { z } from "zod";
3
+ //#region src/schema/communication.ts
4
+ const communicationOutcomes = [
5
+ "accepted",
6
+ "started",
7
+ "succeeded",
8
+ "failed",
9
+ "needs_human",
10
+ "question",
11
+ "digest",
12
+ "rolled_back",
13
+ "budget_warning",
14
+ "budget_exhausted",
15
+ "message"
16
+ ];
17
+ const communicationOutcomeSchema = z.enum(communicationOutcomes).describe("Lifecycle outcome a connector should render and deliver.");
18
+ const communicationEventSchema = z.strictObject({
19
+ eventId: z.string().min(1).describe("Stable idempotency key for this delivery."),
20
+ repositoryIds: repositoryIdsSchema,
21
+ taskId: taskIdSchema.optional(),
22
+ changeId: changeIdSchema.optional(),
23
+ replyTo: replyToSchema,
24
+ outcome: communicationOutcomeSchema,
25
+ data: z.record(z.string(), z.unknown()).describe("Outcome-specific connector payload.")
26
+ });
27
+ //#endregion
28
+ export { communicationOutcomeSchema as n, communicationOutcomes as r, communicationEventSchema as t };
29
+
30
+ //# sourceMappingURL=communication-Kd9nU5RP.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"communication-Kd9nU5RP.mjs","names":[],"sources":["../src/schema/communication.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { replyToSchema } from \"./common\";\nimport { changeIdSchema, repositoryIdsSchema, taskIdSchema } from \"./id\";\n\nexport const communicationOutcomes = [\n \"accepted\",\n \"started\",\n \"succeeded\",\n \"failed\",\n \"needs_human\",\n \"question\",\n \"digest\",\n \"rolled_back\",\n \"budget_warning\",\n \"budget_exhausted\",\n \"message\",\n] as const;\n\nexport const communicationOutcomeSchema = z\n .enum(communicationOutcomes)\n .describe(\"Lifecycle outcome a connector should render and deliver.\");\n\nexport const communicationEventSchema = z.strictObject({\n eventId: z.string().min(1).describe(\"Stable idempotency key for this delivery.\"),\n repositoryIds: repositoryIdsSchema,\n taskId: taskIdSchema.optional(),\n changeId: changeIdSchema.optional(),\n replyTo: replyToSchema,\n outcome: communicationOutcomeSchema,\n data: z.record(z.string(), z.unknown()).describe(\"Outcome-specific connector payload.\"),\n});\n\nexport type CommunicationOutcome = z.infer<typeof communicationOutcomeSchema>;\nexport type CommunicationEvent = z.infer<typeof communicationEventSchema>;\n"],"mappings":";;;AAIA,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,6BAA6B,EACvC,KAAK,qBAAqB,CAAC,CAC3B,SAAS,0DAA0D;AAEtE,MAAa,2BAA2B,EAAE,aAAa;CACrD,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,2CAA2C;CAC/E,eAAe;CACf,QAAQ,aAAa,SAAS;CAC9B,UAAU,eAAe,SAAS;CAClC,SAAS;CACT,SAAS;CACT,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS,qCAAqC;AACxF,CAAC"}
@@ -1,2 +1,3 @@
1
- import { a as NormalizedSignal, c as communicationEventSchema, d as createCommunicationRouter, i as CommunicationRouter, l as communicationOutcomeSchema, n as CommunicationEvent, o as SignalNormalizer, r as CommunicationOutcome, s as WebhookEvent, t as CommunicationAdapter, u as communicationOutcomes } from "../index-Cy4jfXh5.mjs";
2
- export { CommunicationAdapter, CommunicationEvent, CommunicationOutcome, CommunicationRouter, NormalizedSignal, SignalNormalizer, WebhookEvent, communicationEventSchema, communicationOutcomeSchema, communicationOutcomes, createCommunicationRouter };
1
+ import { ct as CommunicationOutcome, dt as communicationOutcomes, lt as communicationEventSchema, st as CommunicationEvent, ut as communicationOutcomeSchema } from "../engine-DFHU2Pe-.mjs";
2
+ import { a as WebhookEvent, c as OutboxSweepResult, i as SignalNormalizer, l as createOutboxCommunicationRouter, n as CommunicationRouter, o as createCommunicationRouter, r as NormalizedSignal, s as OutboxDeliveryOptions, t as CommunicationAdapter, u as sweepCommunicationOutbox } from "../index-Bw6hggoH.mjs";
3
+ export { CommunicationAdapter, type CommunicationEvent, type CommunicationOutcome, CommunicationRouter, NormalizedSignal, OutboxDeliveryOptions, OutboxSweepResult, SignalNormalizer, WebhookEvent, communicationEventSchema, communicationOutcomeSchema, communicationOutcomes, createCommunicationRouter, createOutboxCommunicationRouter, sweepCommunicationOutbox };