@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 @@
1
+ {"version":3,"file":"engine-WaUM2cGA.mjs","names":[],"sources":["../src/schema/answer.ts","../src/schema/receipt.ts","../src/schema/outbox.ts","../src/schema/signal.ts","../src/schema/session.ts","../src/store/engine.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { isoDateTimeSchema, replyToSchema, schemaVersionSchema } from \"./common\";\nimport { answerIdSchema, repositoryIdsSchema, taskIdSchema } from \"./id\";\n\nexport const answerEventSchema = z.strictObject({\n schemaVersion: schemaVersionSchema,\n id: answerIdSchema,\n questionTaskId: taskIdSchema,\n parentTaskId: taskIdSchema.optional(),\n repositoryIds: repositoryIdsSchema,\n replyTo: replyToSchema,\n question: z.string().min(1),\n answer: z.string().min(1).max(4000),\n answeredBy: z.string().min(1),\n recordedAt: isoDateTimeSchema,\n});\n\nexport type AnswerEvent = z.infer<typeof answerEventSchema>;\n","import { z } from \"zod\";\nimport { isoDateTimeSchema, schemaVersionSchema, usdSchema, vocabularySchema } from \"./common\";\nimport { changeIdSchema, receiptIdSchema, repositoryIdsSchema, taskIdSchema } from \"./id\";\nimport { standardTaskKinds } from \"./task\";\n\n/** States the engine writes on transitions. Any vocabulary value is valid. */\nexport const standardReceiptStates = [\n \"approved\",\n \"rejected\",\n \"queued\",\n \"dispatched\",\n \"stalled\",\n \"succeeded\",\n \"failed\",\n \"needs_human\",\n \"cancelled\",\n \"settled\",\n \"verifying\",\n \"ready\",\n \"merged\",\n \"deployed\",\n \"rolled_out\",\n \"rolled_back\",\n] as const;\n\n/** Phases the standard loop uses. Any vocabulary value is valid. */\nexport const standardReceiptPhases = [\n \"approval\",\n \"budget\",\n \"dispatch\",\n \"implementation\",\n \"verification\",\n \"pull_request\",\n \"cleanup\",\n] as const;\n\n/** Kinds the standard loop writes: the standard task kinds plus \"change\". */\nexport const standardReceiptKinds = [...standardTaskKinds, \"change\"] as const;\n\nexport const receiptStateSchema = vocabularySchema.describe(\n \"What happened, e.g. dispatched, settled, merged, or a custom event name.\",\n);\n\nexport const receiptPhaseSchema = vocabularySchema.describe(\n \"Where in the process it happened, e.g. dispatch or verification.\",\n);\n\nexport const receiptKindSchema = vocabularySchema.describe(\n \"What the receipt is about: a task kind, change, or a custom kind.\",\n);\n\nexport const costSchema = z.strictObject({\n totalUsd: usdSchema,\n});\n\nexport const receiptSchema = z\n .strictObject({\n schemaVersion: schemaVersionSchema,\n receiptId: receiptIdSchema,\n repositoryIds: repositoryIdsSchema.describe(\"Repositories the recorded event concerns.\"),\n taskId: taskIdSchema.optional(),\n changeId: changeIdSchema.optional(),\n kind: receiptKindSchema,\n state: receiptStateSchema,\n phase: receiptPhaseSchema.optional(),\n reason: z\n .string()\n .min(1)\n .max(2000)\n .optional()\n .describe(\"Why it happened. Scrubbed and truncated; never secrets.\"),\n attempt: z.number().int().min(1).describe(\"Attempt the event belongs to.\"),\n cost: costSchema.optional().describe(\"Measured cost. Settled receipts only.\"),\n decidedBy: z\n .string()\n .min(1)\n .optional()\n .describe(\"Human who made the decision. Change and approval receipts only.\"),\n recordedAt: isoDateTimeSchema,\n })\n .superRefine((receipt, ctx) => {\n if (receipt.state === \"settled\" && receipt.cost === undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"cost\"],\n message: \"settled receipts require cost\",\n });\n }\n if (receipt.state !== \"settled\" && receipt.cost !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"cost\"],\n message: \"cost is only valid on settled receipts\",\n });\n }\n if (\n receipt.decidedBy !== undefined &&\n receipt.kind !== \"change\" &&\n receipt.state !== \"approved\" &&\n receipt.state !== \"rejected\"\n ) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"decidedBy\"],\n message: \"decidedBy is only valid on change and approval receipts\",\n });\n }\n });\n\nexport type ReceiptState = z.infer<typeof receiptStateSchema>;\nexport type ReceiptPhase = z.infer<typeof receiptPhaseSchema>;\nexport type ReceiptKind = z.infer<typeof receiptKindSchema>;\nexport type Cost = z.infer<typeof costSchema>;\nexport type Receipt = z.infer<typeof receiptSchema>;\n","import { z } from \"zod\";\nimport { communicationEventSchema } from \"./communication\";\nimport { isoDateTimeSchema, schemaVersionSchema } from \"./common\";\nimport { outboxIdSchema } from \"./id\";\n\nexport const outboxStateSchema = z\n .enum([\"pending\", \"delivering\", \"delivered\"])\n .describe(\"Durable connector delivery state.\");\n\nexport const outboxMessageSchema = z.strictObject({\n schemaVersion: schemaVersionSchema,\n id: outboxIdSchema,\n event: communicationEventSchema.describe(\"Immutable provider-neutral delivery payload.\"),\n state: outboxStateSchema,\n attempt: z.number().int().nonnegative(),\n availableAt: isoDateTimeSchema,\n leaseUntil: isoDateTimeSchema.optional(),\n deliveredAt: isoDateTimeSchema.optional(),\n lastError: z.string().min(1).max(2000).optional(),\n createdAt: isoDateTimeSchema,\n updatedAt: isoDateTimeSchema,\n});\n\nexport type OutboxMessage = z.infer<typeof outboxMessageSchema>;\n\nexport const outboxQueueSchema = z.strictObject({\n schemaVersion: schemaVersionSchema,\n id: z.string().regex(/^communication-[0-9a-f]$/u),\n messages: z.array(outboxMessageSchema),\n updatedAt: isoDateTimeSchema,\n});\n\nexport type OutboxQueue = z.infer<typeof outboxQueueSchema>;\n","import { z } from \"zod\";\nimport {\n isoDateTimeSchema,\n replyToSchema,\n schemaVersionSchema,\n vocabularySchema,\n} from \"./common\";\nimport { repositoryIdSchema, signalIdSchema } from \"./id\";\n\n/** Sources used by the standard connectors. Any vocabulary value is valid. */\nexport const standardSignalSources = [\n \"github_issue\",\n \"github_pr\",\n \"github_pr_comment\",\n \"slack\",\n \"human\",\n \"github_ci_failure\",\n \"vercel_deploy_failure\",\n \"security_scan\",\n \"investigation\",\n \"api\",\n] as const;\n\nexport const signalSourceSchema = vocabularySchema.describe(\n \"What produced the signal, e.g. github_issue or a custom connector's own name.\",\n);\n\nexport const signalOutcomeSchema = z\n .enum([\"pending\", \"accepted\", \"duplicate\", \"unactionable\", \"low_confidence\", \"ignored\"])\n .describe(\"Triage outcome. A signal starts pending and is decided exactly once.\");\n\nexport const signalSchema = z\n .strictObject({\n schemaVersion: schemaVersionSchema,\n id: signalIdSchema.describe(\"Signal id, derived from source and deliveryId.\"),\n repositoryId: repositoryIdSchema.describe(\"Repository the signal is about.\"),\n source: signalSourceSchema,\n deliveryId: z\n .string()\n .min(1)\n .describe(\"Provider idempotency key; a redelivered event maps to the same signal.\"),\n replyTo: replyToSchema,\n payload: z.unknown().describe(\"Provider-shaped payload. Untrusted data, never instructions.\"),\n receivedAt: isoDateTimeSchema,\n outcome: signalOutcomeSchema,\n detail: z\n .string()\n .min(1)\n .optional()\n .describe(\"Outcome nuance, e.g. severity when accepted or the duplicate-of signal id.\"),\n reason: z.string().min(1).optional().describe(\"Why the outcome was chosen.\"),\n decidedAt: isoDateTimeSchema.optional(),\n })\n .superRefine((signal, ctx) => {\n if (signal.outcome === \"pending\" && signal.decidedAt !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"decidedAt\"],\n message: \"pending signals must not carry decidedAt\",\n });\n }\n if (signal.outcome !== \"pending\" && signal.decidedAt === undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [\"decidedAt\"],\n message: \"decided signals require decidedAt\",\n });\n }\n });\n\nexport type SignalSource = z.infer<typeof signalSourceSchema>;\nexport type SignalOutcome = z.infer<typeof signalOutcomeSchema>;\nexport type Signal = z.infer<typeof signalSchema>;\n","import { z } from \"zod\";\nimport { isoDateTimeSchema, schemaVersionSchema } from \"./common\";\nimport { changeIdSchema, repositoryIdSchema, taskIdSchema } from \"./id\";\nimport { executionReferenceSchema } from \"./task\";\nimport { communicationEventSchema } from \"./communication\";\n\nexport const agentSessionIdSchema = z.string().regex(/^ses_[a-z0-9]{6,64}$/u)\n .describe(\"Stable Factory interaction ID; independent of provider session IDs.\");\n\nexport const agentSessionSchema = z.strictObject({\n schemaVersion: schemaVersionSchema,\n id: agentSessionIdSchema,\n owner: z.string().min(1).describe(\"Authenticated principal owning this interaction.\"),\n agent: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/u).describe(\"Selected application agent.\"),\n repositoryId: repositoryIdSchema.optional().describe(\"Configured repository selected for this interaction.\"),\n routeId: z.string().min(1).optional().describe(\"Declared workflow route for specialist work.\"),\n message: z.string().min(1).max(16000).describe(\"Initial request, retained for idempotent admission and recovery.\"),\n changeId: changeIdSchema.optional().describe(\"Existing change selected for this work.\"),\n taskId: taskIdSchema.optional().describe(\"Workflow-owned task; its execution reference is authoritative.\"),\n execution: executionReferenceSchema.optional().describe(\"Provider reference for taskless conversations only.\"),\n notifications: z.array(communicationEventSchema).default([]).describe(\"Durable connector deliveries, deduplicated by eventId.\"),\n createdAt: isoDateTimeSchema,\n}).refine((session) => session.taskId === undefined || session.execution === undefined, \"A session binds either a task or a conversation execution\");\n\nexport type AgentSession = z.infer<typeof agentSessionSchema>;\n","import { createHash, randomUUID } from \"node:crypto\";\nimport { isDeepStrictEqual } from \"node:util\";\nimport type { ZodType } from \"zod\";\nimport { answerEventSchema, type AnswerEvent } from \"../schema/answer\";\nimport { agentSessionSchema, type AgentSession } from \"../schema/session\";\nimport { SCHEMA_VERSION, type ReplyTo } from \"../schema/common\";\nimport { communicationEventSchema, type CommunicationEvent } from \"../schema/communication\";\nimport {\n answerIdSchema,\n outboxIdSchema,\n type AnswerId,\n type ChangeId,\n type FactoryId,\n type OutboxId,\n type RepositoryId,\n type SignalId,\n type TaskId,\n} from \"../schema/id\";\nimport { budgetSchema, type Budget } from \"../schema/budget\";\nimport { changeSchema, type Change, type ChangeState, type Level } from \"../schema/change\";\nimport { outboxMessageSchema, outboxQueueSchema, type OutboxMessage } from \"../schema/outbox\";\nimport { costSchema, receiptSchema, type Cost, type Receipt, type ReceiptState } from \"../schema/receipt\";\nimport { repositorySchema, type Repository } from \"../schema/repository\";\nimport { signalSchema, type Signal, type SignalOutcome, type SignalSource } from \"../schema/signal\";\nimport {\n taskSchema,\n type ExecutionReference,\n type Task,\n type TaskState,\n type TaskUsage,\n} from \"../schema/task\";\nimport {\n assertTransition,\n changeInitialState,\n changeTransitions,\n InvalidTransitionError,\n legalNextStates,\n signalOutcomeTransitions,\n taskInitialState,\n taskTransitions,\n} from \"../schema/transitions\";\nimport {\n RecordExistsError,\n RecordNotFoundError,\n VersionConflictError,\n type CollectionName,\n type StoreDriver,\n} from \"./driver\";\n\n/** An approval decision that does not apply to the task's current approval or state. */\nexport class ApprovalError extends Error {\n readonly taskId: TaskId;\n readonly reason: string;\n\n constructor(taskId: TaskId, reason: string) {\n super(`approval decision on \"${taskId}\" refused: ${reason}`);\n this.name = \"ApprovalError\";\n this.taskId = taskId;\n this.reason = reason;\n }\n}\n\n/** A settlement that does not apply to the task's current state. */\nexport class SettlementError extends Error {\n readonly taskId: TaskId;\n readonly reason: string;\n\n constructor(taskId: TaskId, reason: string) {\n super(`settlement on \"${taskId}\" refused: ${reason}`);\n this.name = \"SettlementError\";\n this.taskId = taskId;\n this.reason = reason;\n }\n}\n\nexport class ChangeAssociationError extends Error {\n readonly taskId: TaskId;\n readonly repositoryId: RepositoryId;\n readonly reason: string;\n\n constructor(taskId: TaskId, repositoryId: RepositoryId, reason: string) {\n super(`change for task \"${taskId}\" refused: ${reason}`);\n this.name = \"ChangeAssociationError\";\n this.taskId = taskId;\n this.repositoryId = repositoryId;\n this.reason = reason;\n }\n}\n\nexport class OutboxEventConflictError extends Error {\n constructor(eventId: string) {\n super(`outbox event \"${eventId}\" was reused with different content`);\n this.name = \"OutboxEventConflictError\";\n }\n}\n\nexport class AnswerEventConflictError extends Error {\n constructor(questionTaskId: TaskId) {\n super(`question \"${questionTaskId}\" already has a different answer event`);\n this.name = \"AnswerEventConflictError\";\n }\n}\n\nexport interface CreateSignalInput {\n repositoryId: RepositoryId;\n source: SignalSource;\n deliveryId: string;\n replyTo: ReplyTo;\n payload: unknown;\n}\n\nexport interface DecideSignalOptions {\n detail?: string;\n reason?: string;\n}\n\nexport interface CreateTaskInput {\n repositoryIds: RepositoryId[];\n kind: Task[\"kind\"];\n origin: Task[\"origin\"];\n replyTo: ReplyTo;\n /** Same key creates one task and returns it on workflow retries. */\n dedupeKey?: string;\n area?: string;\n changeId?: ChangeId;\n dependsOn?: TaskId[];\n question?: Task[\"question\"];\n /** Stamp the task as needing a human decision before dispatch. */\n approval?: \"required\";\n}\n\nexport interface ApprovalDecision {\n /** Authenticated operator making the decision. */\n by: string;\n reason?: string;\n}\n\nexport interface AnswerQuestionInput {\n questionTaskId: TaskId;\n answer: string;\n answeredBy: string;\n}\n\n// settledUsd is deliberately excluded: it is written only by tasks.settle,\n// which is receipt-first. Setting it through a transition patch would settle a\n// task with no receipt, so it is rejected at runtime as well as in the type.\n// usage is excluded likewise; only recordUsage writes it.\nexport type TaskPatch = Partial<\n Pick<Task, \"changeId\" | \"reportRef\" | \"reservedUsd\" | \"reservedAt\" | \"question\">\n>;\n\n/** One completed model step's usage, as eve's step.completed event carries it. */\nexport interface StepUsage {\n turnId: string;\n stepIndex: number;\n costUsd?: number;\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n}\n\nexport interface TaskTransitionOptions {\n patch?: TaskPatch;\n reason?: string;\n /** Required when a non-question task waits, so validation is a direct read. */\n questionTaskId?: TaskId;\n /**\n * Refuse unless the task is in this state at write time. Closes\n * check-then-act races where the transition would also be legal from the\n * state a concurrent writer moved the task into.\n */\n expectFrom?: TaskState;\n}\n\nexport interface CreateChangeInput {\n repositoryId: RepositoryId;\n taskId?: TaskId;\n groupId?: TaskId;\n prNumber: number;\n prUrl: string;\n author: string;\n risk: Level;\n confidence: Level;\n evidence: Change[\"evidence\"];\n}\n\nexport type ChangePatch = Partial<\n Pick<Change, \"confidence\" | \"evidence\" | \"decidedBy\" | \"mergeSha\">\n>;\n\nexport interface ChangeTransitionOptions {\n patch?: ChangePatch;\n reason?: string;\n}\n\nexport interface EnsureBudgetInput {\n factoryId: FactoryId;\n month: string;\n limits: Budget[\"limits\"];\n}\n\nexport interface SettleTaskOptions {\n reason?: string;\n}\n\nexport interface AppendReceiptInput {\n repositoryIds: RepositoryId[];\n taskId?: TaskId;\n changeId?: ChangeId;\n kind: string;\n state: string;\n phase?: string;\n reason?: string;\n attempt?: number;\n cost?: Cost;\n decidedBy?: string;\n /** Same key twice appends one receipt and returns the existing one. */\n dedupeKey?: string;\n}\n\nexport class SessionConflictError extends Error {}\n\nfunction sameStoredValue(left: unknown, right: unknown): boolean {\n // JSON persistence omits optional undefined fields; admission retries must compare the persisted representation.\n return isDeepStrictEqual(JSON.parse(JSON.stringify(left)), JSON.parse(JSON.stringify(right)));\n}\n\nexport interface FactoryStores {\n driverName: string;\n sessions: {\n create(input: Omit<AgentSession, \"schemaVersion\" | \"id\" | \"createdAt\" | \"execution\" | \"taskId\" | \"notifications\"> & { operationId: string }): Promise<AgentSession>;\n get(id: string): Promise<AgentSession | null>;\n list(): Promise<AgentSession[]>;\n bind(id: string, reference: { taskId: TaskId } | { execution: ExecutionReference }): Promise<AgentSession>;\n notify(event: CommunicationEvent): Promise<void>;\n };\n repositories: {\n put(repository: Repository): Promise<Repository>;\n get(id: RepositoryId): Promise<Repository | null>;\n list(): Promise<Repository[]>;\n };\n signals: {\n create(input: CreateSignalInput): Promise<Signal>;\n get(id: SignalId): Promise<Signal | null>;\n decide(id: SignalId, outcome: SignalOutcome, options?: DecideSignalOptions): Promise<Signal>;\n list(): Promise<Signal[]>;\n };\n tasks: {\n create(input: CreateTaskInput): Promise<Task>;\n get(id: TaskId): Promise<Task | null>;\n transition(id: TaskId, to: TaskState, options?: TaskTransitionOptions): Promise<Task>;\n answerQuestion(input: AnswerQuestionInput): Promise<{\n answerEvent: AnswerEvent;\n questionTask: Task;\n parentTask: Task | null;\n }>;\n /** Grant a required approval. The task stays queued; dispatch may now take it. */\n approve(id: TaskId, decision: ApprovalDecision): Promise<Task>;\n /** Deny a required approval. The task is cancelled with the reason. */\n reject(id: TaskId, decision: ApprovalDecision): Promise<Task>;\n /**\n * Record the provider's handle on the running attempt's execution, so the\n * reconciler can inspect or cancel it. Refused unless the task is running.\n */\n recordExecution(id: TaskId, execution: ExecutionReference): Promise<Task>;\n /** Add one model step's usage to the task. Idempotent per (turnId, stepIndex). Never settles. */\n recordUsage(id: TaskId, step: StepUsage): Promise<Task>;\n /**\n * Record measured cost on a terminal task. Idempotent: an already settled\n * task returns unchanged and writes no second receipt.\n */\n settle(id: TaskId, cost: Cost, options?: SettleTaskOptions): Promise<Task>;\n list(): Promise<Task[]>;\n };\n changes: {\n create(input: CreateChangeInput): Promise<Change>;\n get(id: ChangeId): Promise<Change | null>;\n transition(id: ChangeId, to: ChangeState, options?: ChangeTransitionOptions): Promise<Change>;\n list(): Promise<Change[]>;\n };\n receipts: {\n append(input: AppendReceiptInput): Promise<Receipt>;\n get(id: string): Promise<Receipt | null>;\n list(): Promise<Receipt[]>;\n };\n budgets: {\n /**\n * Insert-once per month; refreshes limits when configuration changed and\n * preserves notices. Safe under concurrent sweeps.\n */\n ensure(input: EnsureBudgetInput): Promise<Budget>;\n get(month: string): Promise<Budget | null>;\n /**\n * Write-once notice stamp. `stamped` is false when the notice was already\n * set or a concurrent stamp won, so callers notify at most once.\n */\n stampNotice(\n month: string,\n notice: \"warning\" | \"exhausted\",\n ): Promise<{ budget: Budget; stamped: boolean }>;\n };\n answers: {\n get(id: AnswerId): Promise<AnswerEvent | null>;\n };\n outbox: {\n enqueue(event: CommunicationEvent): Promise<OutboxMessage>;\n get(id: OutboxId): Promise<OutboxMessage | null>;\n claim(id: OutboxId, leaseMs?: number): Promise<OutboxMessage | null>;\n retry(id: OutboxId, attempt: number, reason: string, delayMs: number): Promise<OutboxMessage | null>;\n complete(id: OutboxId, attempt: number): Promise<OutboxMessage | null>;\n pending(limit?: number): Promise<OutboxMessage[]>;\n };\n}\n\nexport interface CreateStoresOptions {\n driver: StoreDriver;\n now?: () => string;\n}\n\nconst taskReceiptStates: Partial<Record<TaskState, ReceiptState>> = {\n queued: \"queued\",\n running: \"dispatched\",\n stalled: \"stalled\",\n succeeded: \"succeeded\",\n failed: \"failed\",\n needs_human: \"needs_human\",\n cancelled: \"cancelled\",\n};\n\nconst changeReceiptStates: Partial<Record<ChangeState, ReceiptState>> = {\n verifying: \"verifying\",\n ready: \"ready\",\n merged: \"merged\",\n deployed: \"deployed\",\n rolled_out: \"rolled_out\",\n rolled_back: \"rolled_back\",\n};\n\nfunction randomId(prefix: string): string {\n return `${prefix}_${randomUUID().replaceAll(\"-\", \"\")}`;\n}\n\nfunction derivedId(prefix: string, key: string): string {\n return `${prefix}_${createHash(\"sha256\").update(key).digest(\"hex\").slice(0, 32)}`;\n}\n\nfunction bumpsAttempt(from: TaskState, to: TaskState): boolean {\n return to === \"queued\" || (from === \"verifying\" && to === \"running\");\n}\n\nconst emptyUsage: TaskUsage = {\n costUsd: 0,\n inputTokens: 0,\n outputTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n steps: {},\n};\n\nconst unverifiedEvidence: Change[\"evidence\"] = {\n reproVerified: false,\n testsAdded: 0,\n checksGreen: false,\n attackPassed: false,\n scopeMatches: false,\n};\n\n// Integer micro-dollars, the precision settle stores, so many small steps cannot drift.\nfunction addUsd(a: number, b: number): number {\n return (Math.round(a * 1_000_000) + Math.round(b * 1_000_000)) / 1_000_000;\n}\n\nexport function createStores(options: CreateStoresOptions): FactoryStores {\n const { driver } = options;\n const now = options.now ?? (() => new Date().toISOString());\n\n async function read<T>(\n collection: CollectionName,\n id: string,\n schema: ZodType<T>,\n ): Promise<{ value: T; version: number } | null> {\n const record = await driver.get(collection, id);\n if (record === null) {\n return null;\n }\n return { value: schema.parse(record.value), version: record.version };\n }\n\n async function mustRead<T>(\n collection: CollectionName,\n id: string,\n schema: ZodType<T>,\n ): Promise<{ value: T; version: number }> {\n const record = await read(collection, id, schema);\n if (record === null) {\n throw new RecordNotFoundError(collection, id);\n }\n return record;\n }\n\n async function listAll<T>(collection: CollectionName, schema: ZodType<T>): Promise<T[]> {\n const entries = await driver.list(collection);\n return entries.map((entry) => schema.parse(entry.record.value));\n }\n\n // Receipts are append-only and their inserts are idempotent: an existing id\n // returns the stored receipt instead of writing a second one. Transition\n // receipts use ids derived from their content key and are written before\n // the entity transition persists, so a failed write leaves the transition\n // unpersisted and a retry re-runs both.\n async function insertReceipt(\n receiptId: string,\n receipt: Omit<Receipt, \"schemaVersion\" | \"receiptId\" | \"recordedAt\">,\n ): Promise<Receipt> {\n const full = receiptSchema.parse({\n ...receipt,\n schemaVersion: SCHEMA_VERSION,\n receiptId,\n recordedAt: now(),\n });\n try {\n await driver.insert(\"receipts\", receiptId, full);\n return full;\n } catch (error) {\n if (error instanceof RecordExistsError) {\n const existing = await mustRead(\"receipts\", receiptId, receiptSchema);\n return existing.value;\n }\n throw error;\n }\n }\n\n async function appendReceipt(\n key: string,\n receipt: Omit<Receipt, \"schemaVersion\" | \"receiptId\" | \"recordedAt\">,\n ): Promise<Receipt> {\n return insertReceipt(derivedId(\"rcpt\", key), receipt);\n }\n\n const stores: FactoryStores = {\n driverName: driver.name,\n\n sessions: {\n async create({ operationId, ...input }) {\n if (operationId.trim().length === 0 || operationId.length > 200) throw new Error(\"operationId must contain 1–200 characters\");\n const id = derivedId(\"ses\", JSON.stringify([input.owner, operationId]));\n const candidate = agentSessionSchema.parse({ ...input, id, schemaVersion: SCHEMA_VERSION, createdAt: now() });\n try {\n await driver.insert(\"sessions\", id, candidate);\n return candidate;\n } catch (error) {\n if (!(error instanceof RecordExistsError)) throw error;\n const existing = (await mustRead(\"sessions\", id, agentSessionSchema)).value;\n const { createdAt: _at, execution: _execution, taskId: _task, notifications: _notifications, ...intent } = existing;\n const { createdAt: _newAt, notifications: _newNotifications, ...nextIntent } = candidate;\n if (!sameStoredValue(intent, nextIntent)) throw new SessionConflictError(\"Session operationId was reused with different input\");\n return existing;\n }\n },\n async get(id) {\n return (await read(\"sessions\", id, agentSessionSchema))?.value ?? null;\n },\n list() { return listAll(\"sessions\", agentSessionSchema); },\n async bind(id, reference) {\n for (;;) {\n const existing = await mustRead(\"sessions\", id, agentSessionSchema);\n if (\"taskId\" in reference) {\n const task = (await mustRead(\"tasks\", reference.taskId, taskSchema)).value;\n if (task.origin.operator !== existing.value.owner || task.replyTo.channel !== \"api\" || task.replyTo.address !== id || task.repositoryIds[0] !== existing.value.repositoryId) {\n throw new SessionConflictError(\"Task does not belong to this session\");\n }\n }\n const previous = existing.value.taskId === undefined\n ? existing.value.execution === undefined ? undefined : { execution: existing.value.execution }\n : { taskId: existing.value.taskId };\n if (previous !== undefined) {\n if (!sameStoredValue(previous, reference)) throw new SessionConflictError(\"Session execution binding cannot be replaced\");\n return existing.value;\n }\n const next = agentSessionSchema.parse({ ...existing.value, ...reference });\n try {\n await driver.update(\"sessions\", id, next, existing.version);\n return next;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) throw error;\n }\n }\n },\n async notify(input) {\n const event = communicationEventSchema.parse(input);\n if (event.replyTo.channel !== \"api\") throw new SessionConflictError(\"Expected an API notification\");\n for (;;) {\n const record = await mustRead(\"sessions\", event.replyTo.address, agentSessionSchema);\n const existing = record.value.notifications.find((item) => item.eventId === event.eventId);\n if (existing !== undefined) {\n if (!sameStoredValue(existing, event)) throw new SessionConflictError(\"Notification eventId was reused\");\n return;\n }\n const next = agentSessionSchema.parse({ ...record.value, notifications: [...record.value.notifications, event] });\n try { await driver.update(\"sessions\", next.id, next, record.version); return; }\n catch (error) { if (!(error instanceof VersionConflictError)) throw error; }\n }\n },\n },\n\n repositories: {\n async put(repository) {\n const parsed = repositorySchema.parse(repository);\n const existing = await read(\"repositories\", parsed.id, repositorySchema);\n if (existing === null) {\n await driver.insert(\"repositories\", parsed.id, parsed);\n } else {\n await driver.update(\"repositories\", parsed.id, parsed, existing.version);\n }\n return parsed;\n },\n async get(id) {\n const record = await read(\"repositories\", id, repositorySchema);\n return record === null ? null : record.value;\n },\n list() {\n return listAll(\"repositories\", repositorySchema);\n },\n },\n\n signals: {\n async create(input) {\n const id = derivedId(\"sig\", `${input.source}:${input.deliveryId}`);\n const signal = signalSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n id,\n repositoryId: input.repositoryId,\n source: input.source,\n deliveryId: input.deliveryId,\n replyTo: input.replyTo,\n payload: input.payload,\n receivedAt: now(),\n outcome: \"pending\",\n });\n try {\n await driver.insert(\"signals\", id, signal);\n return signal;\n } catch (error) {\n if (error instanceof RecordExistsError) {\n const existing = await mustRead(\"signals\", id, signalSchema);\n return existing.value;\n }\n throw error;\n }\n },\n async get(id) {\n const record = await read(\"signals\", id, signalSchema);\n return record === null ? null : record.value;\n },\n async decide(id, outcome, decideOptions = {}) {\n const existing = await mustRead(\"signals\", id, signalSchema);\n assertTransition(signalOutcomeTransitions, existing.value.outcome, outcome);\n const next = signalSchema.parse({\n ...existing.value,\n outcome,\n detail: decideOptions.detail,\n reason: decideOptions.reason,\n decidedAt: now(),\n });\n await driver.update(\"signals\", id, next, existing.version);\n return next;\n },\n list() {\n return listAll(\"signals\", signalSchema);\n },\n },\n\n tasks: {\n async create(input) {\n const timestamp = now();\n const id = input.dedupeKey === undefined\n ? randomId(\"task\")\n : derivedId(\"task\", input.dedupeKey);\n const task = taskSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n id,\n repositoryIds: input.repositoryIds,\n kind: input.kind,\n area: input.area,\n state: taskInitialState,\n approval: input.approval,\n origin: input.origin,\n dependsOn: input.dependsOn,\n replyTo: input.replyTo,\n attempt: 1,\n question: input.question,\n changeId: input.changeId,\n createdAt: timestamp,\n updatedAt: timestamp,\n });\n try {\n await driver.insert(\"tasks\", task.id, task);\n return task;\n } catch (error) {\n if (input.dedupeKey !== undefined && error instanceof RecordExistsError) {\n const existing = await mustRead(\"tasks\", task.id, taskSchema);\n return existing.value;\n }\n throw error;\n }\n },\n async approve(id, decision) {\n const existing = await mustRead(\"tasks\", id, taskSchema);\n const task = existing.value;\n if (task.approval !== \"required\") {\n throw new ApprovalError(id, `approval is ${task.approval ?? \"not required\"}`);\n }\n if (task.state !== \"queued\") {\n throw new ApprovalError(id, `task is ${task.state}, not queued`);\n }\n const next = taskSchema.parse({ ...task, approval: \"granted\", updatedAt: now() });\n if (next.repositoryIds !== undefined) {\n await appendReceipt(`task:${id}:approved:${next.attempt}`, {\n repositoryIds: next.repositoryIds,\n taskId: id,\n kind: next.kind,\n state: \"approved\",\n phase: \"approval\",\n reason: decision.reason,\n attempt: next.attempt,\n decidedBy: decision.by,\n });\n }\n await driver.update(\"tasks\", id, next, existing.version);\n return next;\n },\n async reject(id, decision) {\n const existing = await mustRead(\"tasks\", id, taskSchema);\n const task = existing.value;\n if (task.approval !== \"required\") {\n throw new ApprovalError(id, `approval is ${task.approval ?? \"not required\"}`);\n }\n if (task.state !== \"queued\") {\n throw new ApprovalError(id, `task is ${task.state}, not queued`);\n }\n const next = taskSchema.parse({\n ...task,\n approval: \"denied\",\n state: \"cancelled\",\n updatedAt: now(),\n });\n if (next.repositoryIds !== undefined) {\n await appendReceipt(`task:${id}:rejected:${next.attempt}`, {\n repositoryIds: next.repositoryIds,\n taskId: id,\n kind: next.kind,\n state: \"rejected\",\n phase: \"approval\",\n reason: decision.reason,\n attempt: next.attempt,\n decidedBy: decision.by,\n });\n await appendReceipt(`task:${id}:cancelled:${next.attempt}`, {\n repositoryIds: next.repositoryIds,\n taskId: id,\n kind: next.kind,\n state: \"cancelled\",\n reason: decision.reason ?? `rejected by ${decision.by}`,\n attempt: next.attempt,\n });\n }\n await driver.update(\"tasks\", id, next, existing.version);\n return next;\n },\n async recordExecution(id, execution) {\n const existing = await mustRead(\"tasks\", id, taskSchema);\n const task = existing.value;\n if (task.state !== \"running\") {\n throw new InvalidTransitionError(task.state, \"running\", legalNextStates(taskTransitions, task.state));\n }\n const timestamp = now();\n const next = taskSchema.parse({\n ...task,\n execution,\n lastProgressAt: timestamp,\n updatedAt: timestamp,\n });\n await driver.update(\"tasks\", id, next, existing.version);\n return next;\n },\n async recordUsage(id, step) {\n // A version conflict means another writer bumped the row, not that\n // this step was counted; retry until the mark shows it or we land.\n for (;;) {\n const existing = await mustRead(\"tasks\", id, taskSchema);\n const task = existing.value;\n const usage = task.usage ?? emptyUsage;\n const recordedIndex = usage.steps[step.turnId];\n if (recordedIndex !== undefined && step.stepIndex <= recordedIndex) {\n return task;\n }\n const timestamp = now();\n const next = taskSchema.parse({\n ...task,\n lastProgressAt: timestamp,\n usage: {\n costUsd: addUsd(usage.costUsd, step.costUsd ?? 0),\n inputTokens: usage.inputTokens + (step.inputTokens ?? 0),\n outputTokens: usage.outputTokens + (step.outputTokens ?? 0),\n cacheReadTokens: usage.cacheReadTokens + (step.cacheReadTokens ?? 0),\n cacheWriteTokens: usage.cacheWriteTokens + (step.cacheWriteTokens ?? 0),\n steps: { ...usage.steps, [step.turnId]: step.stepIndex },\n },\n updatedAt: timestamp,\n });\n try {\n await driver.update(\"tasks\", id, next, existing.version);\n return next;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) {\n throw error;\n }\n }\n }\n },\n async settle(id, cost, settleOptions = {}) {\n const existing = await mustRead(\"tasks\", id, taskSchema);\n const task = existing.value;\n // A task settles once. Re-execution cost after an operator retry is\n // not separately metered; that is the unresolved multi-attempt\n // accounting decision, deferred to its own change.\n if (task.settledUsd !== undefined) {\n return task;\n }\n if (task.state !== \"succeeded\" && task.state !== \"failed\" && task.state !== \"cancelled\") {\n throw new SettlementError(id, `task is ${task.state}, not terminal`);\n }\n // Validate before normalizing: arithmetic would coerce null or a\n // negative amount into a valid-looking zero, so the schema check must\n // see the raw input first. Then round to the ledger's micro-dollar\n // precision so the receipt and settledUsd carry the same value.\n const validated = costSchema.parse(cost);\n const normalized = { totalUsd: Math.round(validated.totalUsd * 1_000_000) / 1_000_000 };\n // The receipt is written first, keyed by task and attempt (not by\n // cost), and is immutable, so it is the authority: a retry after a\n // lost task write (a measured settlement, then the zero-settle sweep)\n // finds the first receipt and records THAT cost, keeping receipt and\n // settledUsd in agreement.\n let recorded = normalized;\n if (task.repositoryIds !== undefined) {\n const receipt = await appendReceipt(`task:${id}:settled:${task.attempt}`, {\n repositoryIds: task.repositoryIds,\n taskId: id,\n changeId: task.changeId,\n kind: task.kind,\n state: \"settled\",\n phase: \"budget\",\n reason: settleOptions.reason,\n attempt: task.attempt,\n cost: normalized,\n });\n recorded = receipt.cost ?? normalized;\n }\n const next = taskSchema.parse({ ...task, settledUsd: recorded.totalUsd, updatedAt: now() });\n await driver.update(\"tasks\", id, next, existing.version);\n return next;\n },\n async get(id) {\n const record = await read(\"tasks\", id, taskSchema);\n return record === null ? null : record.value;\n },\n async answerQuestion(input) {\n const question = await mustRead(\"tasks\", input.questionTaskId, taskSchema);\n if (question.value.kind !== \"question\" || question.value.question === undefined) {\n throw new Error(`task ${input.questionTaskId} is not a question`);\n }\n if (question.value.state !== \"needs_human\" && question.value.state !== \"succeeded\") {\n throw new Error(`question task ${input.questionTaskId} is ${question.value.state}, not waiting`);\n }\n const questionDetails = question.value.question;\n const id = answerIdSchema.parse(derivedId(\"ans\", input.questionTaskId));\n const candidate = answerEventSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n id,\n questionTaskId: input.questionTaskId,\n parentTaskId: question.value.origin.parentTaskId,\n repositoryIds: question.value.repositoryIds,\n replyTo: question.value.replyTo,\n question: questionDetails.text,\n answer: input.answer,\n answeredBy: input.answeredBy,\n recordedAt: now(),\n });\n let answerEvent = candidate;\n try {\n await driver.insert(\"answers\", id, candidate);\n } catch (error) {\n if (!(error instanceof RecordExistsError)) throw error;\n const existing = await mustRead(\"answers\", id, answerEventSchema);\n const { recordedAt: _existingAt, ...existingIntent } = existing.value;\n const { recordedAt: _candidateAt, ...candidateIntent } = candidate;\n if (!isDeepStrictEqual(existingIntent, candidateIntent)) {\n throw new AnswerEventConflictError(input.questionTaskId);\n }\n answerEvent = existing.value;\n }\n\n let parentTask: Task | null = null;\n if (answerEvent.parentTaskId !== undefined) {\n parentTask = await stores.tasks.get(answerEvent.parentTaskId);\n if (parentTask === null) {\n throw new Error(`parent task ${answerEvent.parentTaskId} does not exist`);\n }\n for (;;) {\n const parent = await mustRead(\"tasks\", answerEvent.parentTaskId, taskSchema);\n if (parent.value.answerEventIds?.includes(answerEvent.id) === true) {\n parentTask = parent.value;\n break;\n }\n const projected = taskSchema.parse({\n ...parent.value,\n answerEventIds: [...(parent.value.answerEventIds ?? []), answerEvent.id],\n updatedAt: now(),\n });\n try {\n await driver.update(\"tasks\", parent.value.id, projected, parent.version);\n parentTask = projected;\n break;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) throw error;\n }\n }\n if (parentTask.state === \"needs_human\") {\n parentTask = await stores.tasks.transition(parentTask.id, \"queued\", {\n reason: `question ${answerEvent.questionTaskId} answered by ${answerEvent.answeredBy}`,\n });\n }\n }\n\n let questionTask = await mustRead(\"tasks\", input.questionTaskId, taskSchema).then(\n (record) => record.value,\n );\n if (questionTask.state === \"needs_human\") {\n questionTask = await stores.tasks.transition(questionTask.id, \"succeeded\", {\n patch: {\n question: {\n ...questionDetails,\n answer: answerEvent.answer,\n answeredBy: answerEvent.answeredBy,\n },\n },\n reason: \"question answered through Foreman\",\n });\n } else if (\n questionTask.state !== \"succeeded\" ||\n questionTask.question?.answer !== answerEvent.answer ||\n questionTask.question.answeredBy !== answerEvent.answeredBy\n ) {\n throw new Error(`question task ${questionTask.id} is ${questionTask.state}, not waiting`);\n }\n return { answerEvent, questionTask, parentTask };\n },\n async transition(id, to, transitionOptions = {}) {\n if (transitionOptions.patch !== undefined && \"settledUsd\" in transitionOptions.patch) {\n throw new SettlementError(id, \"settledUsd is set only by settle, not a transition\");\n }\n if (transitionOptions.patch !== undefined && \"usage\" in transitionOptions.patch) {\n throw new SettlementError(id, \"usage is set only by recordUsage, not a transition\");\n }\n const existing = await mustRead(\"tasks\", id, taskSchema);\n if (\n transitionOptions.expectFrom !== undefined &&\n existing.value.state !== transitionOptions.expectFrom\n ) {\n throw new InvalidTransitionError(\n existing.value.state,\n to,\n legalNextStates(taskTransitions, existing.value.state),\n );\n }\n assertTransition(taskTransitions, existing.value.state, to);\n if (to === \"needs_human\" && existing.value.kind !== \"question\") {\n if (transitionOptions.questionTaskId === undefined) {\n throw new Error(\n `task ${id} cannot enter needs_human without a QuestionTask id`,\n );\n }\n const question = await mustRead(\"tasks\", transitionOptions.questionTaskId, taskSchema);\n if (\n question.value.kind !== \"question\" ||\n question.value.state !== \"needs_human\" ||\n question.value.origin.parentTaskId !== id\n ) {\n throw new Error(`task ${id} cannot enter needs_human for question ${question.value.id}`);\n }\n }\n const bumps = bumpsAttempt(existing.value.state, to);\n const timestamp = now();\n // A new attempt gets a new execution; stall stamps describe only the\n // stalled state; running starts the progress clock.\n const {\n stalledAt: _stalledAt,\n stalledReason: _stalledReason,\n questionTaskId: _questionTaskId,\n ...cleared\n } = existing.value;\n const next = taskSchema.parse({\n ...cleared,\n ...(bumps ? { execution: undefined } : {}),\n ...transitionOptions.patch,\n ...(to === \"needs_human\" && existing.value.kind !== \"question\"\n ? { questionTaskId: transitionOptions.questionTaskId }\n : {}),\n ...(to === \"stalled\" ? { stalledAt: timestamp, stalledReason: transitionOptions.reason } : {}),\n ...(to === \"running\" ? { lastProgressAt: timestamp } : {}),\n state: to,\n attempt: bumps ? existing.value.attempt + 1 : existing.value.attempt,\n updatedAt: timestamp,\n });\n const receiptState = taskReceiptStates[to];\n if (receiptState !== undefined && next.repositoryIds !== undefined) {\n // The key is derived from every receipt-bearing field of the\n // transition, so a crash retry of the same write dedupes while a\n // different intent (a different change or reason produced by a\n // later write at the same state and attempt) gets its own receipt.\n // A lost write's orphan receipt can never stand in for a different\n // one, so it cannot poison a genuine transition's evidence.\n await appendReceipt(\n JSON.stringify([\n \"task\",\n id,\n receiptState,\n next.attempt,\n next.changeId ?? null,\n transitionOptions.reason ?? null,\n ]),\n {\n repositoryIds: next.repositoryIds,\n taskId: id,\n changeId: next.changeId,\n kind: next.kind,\n state: receiptState,\n reason: transitionOptions.reason,\n attempt: next.attempt,\n },\n );\n }\n await driver.update(\"tasks\", id, next, existing.version);\n return next;\n },\n list() {\n return listAll(\"tasks\", taskSchema);\n },\n },\n\n changes: {\n async create(input) {\n const timestamp = now();\n const id = derivedId(\"chg\", `${input.repositoryId}:github-pr:${input.prNumber}`);\n const change = changeSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n id,\n repositoryId: input.repositoryId,\n taskId: input.taskId,\n groupId: input.groupId,\n prNumber: input.prNumber,\n prUrl: input.prUrl,\n author: input.author,\n risk: input.risk,\n confidence: input.confidence,\n evidence: input.evidence,\n state: changeInitialState,\n createdAt: timestamp,\n updatedAt: timestamp,\n });\n await mustRead(\"repositories\", change.repositoryId, repositorySchema);\n if (change.taskId !== undefined) {\n const task = (await mustRead(\"tasks\", change.taskId, taskSchema)).value;\n if (task.kind !== \"code_change\") {\n throw new ChangeAssociationError(\n change.taskId,\n change.repositoryId,\n \"changes can only be produced by code_change tasks\",\n );\n }\n const taskRepositoryId = task.repositoryIds[0];\n if (taskRepositoryId !== change.repositoryId) {\n throw new ChangeAssociationError(\n change.taskId,\n change.repositoryId,\n `repository \"${change.repositoryId}\" does not match task repository \"${taskRepositoryId}\"`,\n );\n }\n }\n try {\n await driver.insert(\"changes\", change.id, change);\n return change;\n } catch (error) {\n if (error instanceof RecordExistsError) {\n const existing = await mustRead(\"changes\", change.id, changeSchema);\n return existing.value;\n }\n throw error;\n }\n },\n async get(id) {\n const record = await read(\"changes\", id, changeSchema);\n return record === null ? null : record.value;\n },\n async transition(id, to, transitionOptions = {}) {\n const existing = await mustRead(\"changes\", id, changeSchema);\n assertTransition(changeTransitions, existing.value.state, to);\n const invalidated = existing.value.state === \"ready\" && to === \"verifying\";\n const next = changeSchema.parse({\n ...existing.value,\n ...transitionOptions.patch,\n ...(invalidated ? { confidence: \"low\", evidence: unverifiedEvidence } : {}),\n state: to,\n updatedAt: now(),\n });\n const receiptState = changeReceiptStates[to];\n if (receiptState !== undefined) {\n await appendReceipt(`change:${id}:${receiptState}`, {\n repositoryIds: [next.repositoryId],\n taskId: next.taskId,\n changeId: id,\n kind: \"change\",\n state: receiptState,\n reason: transitionOptions.reason,\n attempt: 1,\n decidedBy: next.decidedBy,\n });\n }\n await driver.update(\"changes\", id, next, existing.version);\n return next;\n },\n list() {\n return listAll(\"changes\", changeSchema);\n },\n },\n\n receipts: {\n append(input) {\n const { dedupeKey, attempt, ...fields } = input;\n const receiptId =\n dedupeKey === undefined ? randomId(\"rcpt\") : derivedId(\"rcpt\", `custom:${dedupeKey}`);\n return insertReceipt(receiptId, { ...fields, attempt: attempt ?? 1 });\n },\n async get(id) {\n const record = await read(\"receipts\", id, receiptSchema);\n return record === null ? null : record.value;\n },\n list() {\n return listAll(\"receipts\", receiptSchema);\n },\n },\n\n budgets: {\n async ensure(input) {\n const budget = budgetSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n factoryId: input.factoryId,\n month: input.month,\n limits: input.limits,\n notices: {},\n });\n try {\n await driver.insert(\"budgets\", input.month, budget);\n return budget;\n } catch (error) {\n if (!(error instanceof RecordExistsError)) {\n throw error;\n }\n }\n const existing = await mustRead(\"budgets\", input.month, budgetSchema);\n const refreshed = budgetSchema.parse({ ...existing.value, limits: input.limits });\n if (JSON.stringify(refreshed) === JSON.stringify(existing.value)) {\n return existing.value;\n }\n try {\n await driver.update(\"budgets\", input.month, refreshed, existing.version);\n return refreshed;\n } catch (error) {\n if (error instanceof VersionConflictError) {\n const latest = await mustRead(\"budgets\", input.month, budgetSchema);\n return latest.value;\n }\n throw error;\n }\n },\n async get(month) {\n const record = await read(\"budgets\", month, budgetSchema);\n return record === null ? null : record.value;\n },\n async stampNotice(month, notice) {\n const field = notice === \"warning\" ? \"warningAt\" : \"exhaustedAt\";\n // A version conflict does not mean this notice was stamped: a limits\n // refresh or the other notice also bumps the row. Retry until the\n // notice is actually present or our write lands, so `stamped: false`\n // always means \"someone else stamped it\" and the caller never\n // delivers a notice twice. The loop terminates because every conflict\n // proves another write completed, and the budget row receives only\n // notice stamps and limits refreshes.\n for (;;) {\n const existing = await mustRead(\"budgets\", month, budgetSchema);\n if (existing.value.notices[field] !== undefined) {\n return { budget: existing.value, stamped: false };\n }\n const next = budgetSchema.parse({\n ...existing.value,\n notices: { ...existing.value.notices, [field]: now() },\n });\n try {\n await driver.update(\"budgets\", month, next, existing.version);\n return { budget: next, stamped: true };\n } catch (error) {\n if (!(error instanceof VersionConflictError)) {\n throw error;\n }\n }\n }\n },\n },\n answers: {\n async get(id) {\n const record = await read(\"answers\", id, answerEventSchema);\n return record?.value ?? null;\n },\n },\n outbox: {\n async enqueue(input) {\n const event = communicationEventSchema.parse(input);\n const id = outboxIdSchema.parse(derivedId(\"out\", event.eventId));\n const delivered = await read(\"outboxDeliveries\", id, outboxMessageSchema);\n if (delivered !== null) {\n if (!isDeepStrictEqual(delivered.value.event, event)) {\n throw new OutboxEventConflictError(event.eventId);\n }\n return delivered.value;\n }\n const queueId = `communication-${id.slice(4, 5)}`;\n for (;;) {\n const existing = await read(\"outboxQueues\", queueId, outboxQueueSchema);\n const duplicate = existing?.value.messages.find((message) => message.id === id);\n if (duplicate !== undefined) {\n if (!isDeepStrictEqual(duplicate.event, event)) {\n throw new OutboxEventConflictError(event.eventId);\n }\n return duplicate;\n }\n const timestamp = now();\n const message = outboxMessageSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n id,\n event,\n state: \"pending\",\n attempt: 0,\n availableAt: timestamp,\n createdAt: timestamp,\n updatedAt: timestamp,\n });\n const queue = outboxQueueSchema.parse({\n schemaVersion: SCHEMA_VERSION,\n id: queueId,\n messages: [...(existing?.value.messages ?? []), message],\n updatedAt: timestamp,\n });\n try {\n if (existing === null) await driver.insert(\"outboxQueues\", queueId, queue);\n else await driver.update(\"outboxQueues\", queueId, queue, existing.version);\n return message;\n } catch (error) {\n if (!(error instanceof RecordExistsError) && !(error instanceof VersionConflictError)) {\n throw error;\n }\n }\n }\n },\n async get(id) {\n const delivered = await read(\"outboxDeliveries\", id, outboxMessageSchema);\n if (delivered !== null) return delivered.value;\n const queueId = `communication-${id.slice(4, 5)}`;\n const queue = await read(\"outboxQueues\", queueId, outboxQueueSchema);\n return queue?.value.messages.find((message) => message.id === id) ?? null;\n },\n async claim(id, leaseMs = 60_000) {\n if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0) {\n throw new Error(\"outbox leaseMs must be a positive safe integer\");\n }\n const queueId = `communication-${id.slice(4, 5)}`;\n for (;;) {\n const queue = await mustRead(\"outboxQueues\", queueId, outboxQueueSchema);\n const index = queue.value.messages.findIndex((message) => message.id === id);\n if (index < 0) return null;\n if (await read(\"outboxDeliveries\", id, outboxMessageSchema) !== null) {\n const messages = queue.value.messages.filter((message) => message.id !== id);\n try {\n await driver.update(\n \"outboxQueues\",\n queueId,\n outboxQueueSchema.parse({ ...queue.value, messages, updatedAt: now() }),\n queue.version,\n );\n return null;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) throw error;\n continue;\n }\n }\n const message = queue.value.messages[index]!;\n const timestamp = now();\n const eligible =\n (message.state === \"pending\" && message.availableAt <= timestamp) ||\n (message.state === \"delivering\" &&\n message.leaseUntil !== undefined &&\n message.leaseUntil <= timestamp);\n if (!eligible) return null;\n const next = outboxMessageSchema.parse({\n ...message,\n state: \"delivering\",\n attempt: message.attempt + 1,\n leaseUntil: new Date(Date.parse(timestamp) + leaseMs).toISOString(),\n updatedAt: timestamp,\n });\n const messages = [...queue.value.messages];\n messages[index] = next;\n try {\n await driver.update(\n \"outboxQueues\",\n queueId,\n outboxQueueSchema.parse({ ...queue.value, messages, updatedAt: timestamp }),\n queue.version,\n );\n return next;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) throw error;\n }\n }\n },\n async retry(id, attempt, reason, delayMs) {\n if (!Number.isSafeInteger(delayMs) || delayMs < 0) {\n throw new Error(\"outbox delayMs must be a nonnegative safe integer\");\n }\n const queueId = `communication-${id.slice(4, 5)}`;\n for (;;) {\n const queue = await mustRead(\"outboxQueues\", queueId, outboxQueueSchema);\n const index = queue.value.messages.findIndex((message) => message.id === id);\n if (index < 0) return null;\n const message = queue.value.messages[index]!;\n if (message.state !== \"delivering\" || message.attempt !== attempt) return null;\n const timestamp = now();\n const { leaseUntil: _leaseUntil, ...leased } = message;\n const next = outboxMessageSchema.parse({\n ...leased,\n state: \"pending\",\n availableAt: new Date(Date.parse(timestamp) + delayMs).toISOString(),\n lastError: reason.trim().slice(0, 2000) || \"delivery failed\",\n updatedAt: timestamp,\n });\n const messages = [...queue.value.messages];\n messages[index] = next;\n try {\n await driver.update(\n \"outboxQueues\",\n queueId,\n outboxQueueSchema.parse({ ...queue.value, messages, updatedAt: timestamp }),\n queue.version,\n );\n return next;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) throw error;\n }\n }\n },\n async complete(id, attempt) {\n const queueId = `communication-${id.slice(4, 5)}`;\n let delivered = await read(\"outboxDeliveries\", id, outboxMessageSchema);\n for (;;) {\n const queue = await mustRead(\"outboxQueues\", queueId, outboxQueueSchema);\n const index = queue.value.messages.findIndex((message) => message.id === id);\n if (index < 0) return delivered?.value ?? null;\n const message = queue.value.messages[index]!;\n const timestamp = now();\n if (delivered === null) {\n if (message.state !== \"delivering\" || message.attempt !== attempt) return null;\n const { leaseUntil: _leaseUntil, lastError: _lastError, ...leased } = message;\n const next = outboxMessageSchema.parse({\n ...leased,\n state: \"delivered\",\n deliveredAt: timestamp,\n updatedAt: timestamp,\n });\n try {\n await driver.insert(\"outboxDeliveries\", id, next);\n delivered = { value: next, version: 1 };\n } catch (error) {\n if (!(error instanceof RecordExistsError)) throw error;\n delivered = await mustRead(\"outboxDeliveries\", id, outboxMessageSchema);\n if (!isDeepStrictEqual(delivered.value.event, message.event)) {\n throw new OutboxEventConflictError(message.event.eventId);\n }\n }\n }\n const messages = queue.value.messages.filter((candidate) => candidate.id !== id);\n try {\n await driver.update(\n \"outboxQueues\",\n queueId,\n outboxQueueSchema.parse({ ...queue.value, messages, updatedAt: timestamp }),\n queue.version,\n );\n return delivered.value;\n } catch (error) {\n if (!(error instanceof VersionConflictError)) throw error;\n }\n }\n },\n async pending(limit = 100) {\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"outbox pending limit must be a positive safe integer\");\n }\n const queues = await Promise.all(\n \"0123456789abcdef\".split(\"\").map((shard) =>\n read(\"outboxQueues\", `communication-${shard}`, outboxQueueSchema)\n ),\n );\n const timestamp = now();\n return queues\n .flatMap((queue) => queue?.value.messages ?? [])\n .filter((message) =>\n (message.state === \"pending\" && message.availableAt <= timestamp) ||\n (message.state === \"delivering\" &&\n message.leaseUntil !== undefined &&\n message.leaseUntil <= timestamp)\n )\n .sort((a, b) => a.createdAt.localeCompare(b.createdAt))\n .slice(0, limit);\n },\n },\n };\n return stores;\n}\n"],"mappings":";;;;;;;;;;AAIA,MAAa,oBAAoB,EAAE,aAAa;CAC9C,eAAe;CACf,IAAI;CACJ,gBAAgB;CAChB,c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