@vercel/factory 0.0.12 → 0.0.13

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 (33) hide show
  1. package/dist/approval-CwhTP1XB.mjs +269 -0
  2. package/dist/approval-CwhTP1XB.mjs.map +1 -0
  3. package/dist/blob/index.d.mts +1 -1
  4. package/dist/build-factory.d.mts +1 -1
  5. package/dist/build-factory.mjs +1 -1
  6. package/dist/change-CzEAoFVE.mjs +620 -0
  7. package/dist/change-CzEAoFVE.mjs.map +1 -0
  8. package/dist/connectors/slack.d.mts +4 -4
  9. package/dist/connectors/slack.mjs +81 -30
  10. package/dist/connectors/slack.mjs.map +1 -1
  11. package/dist/{approval-CIXB8IF8.d.mts → dispatch-B77cuPxh.d.mts} +290 -99
  12. package/dist/{driver-CrZsy7sm.d.mts → driver-BJutB0PE.d.mts} +2 -2
  13. package/dist/driver-Bbd25rNM.mjs.map +1 -1
  14. package/dist/eve/index.d.mts +546 -120
  15. package/dist/eve/index.mjs +358 -82
  16. package/dist/eve/index.mjs.map +1 -1
  17. package/dist/{factory-config-ifd3JxiU.mjs → factory-config-BJcjsPKl.mjs} +42 -5
  18. package/dist/factory-config-BJcjsPKl.mjs.map +1 -0
  19. package/dist/{factory-config-Bu4mklm9.d.mts → factory-config-D2yU3G0c.d.mts} +21 -2
  20. package/dist/{github-wThBfbm-.d.mts → github-DXsxboUL.d.mts} +25 -2
  21. package/dist/github.d.mts +2 -2
  22. package/dist/github.mjs +47 -1
  23. package/dist/github.mjs.map +1 -1
  24. package/dist/index.d.mts +119 -59
  25. package/dist/index.mjs +289 -330
  26. package/dist/index.mjs.map +1 -1
  27. package/dist/postgres/index.d.mts +1 -1
  28. package/package.json +1 -1
  29. package/dist/approval-DdvEKLiE.mjs +0 -132
  30. package/dist/approval-DdvEKLiE.mjs.map +0 -1
  31. package/dist/change-CFNGXVqD.mjs +0 -230
  32. package/dist/change-CFNGXVqD.mjs.map +0 -1
  33. package/dist/factory-config-ifd3JxiU.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"change-CzEAoFVE.mjs","names":[],"sources":["../src/budget.ts","../src/coordination.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 { ReplyTo } from \"./schema/common\";\nimport type { RepositoryId, SignalId, TaskId } from \"./schema/id\";\nimport type { Task } from \"./schema/task\";\nimport { RecordNotFoundError } from \"./store/driver\";\nimport type { FactoryStores } from \"./store/engine\";\n\ninterface CreateCoordinationInputBase {\n repositoryIds: readonly [RepositoryId, RepositoryId, ...RepositoryId[]];\n replyTo: ReplyTo;\n /** Same key recreates neither the parent nor its repository-scoped children. */\n dedupeKey?: string;\n}\n\nexport type CreateCoordinationInput = CreateCoordinationInputBase &\n ({ signalId: SignalId; operator?: never } | { operator: string; signalId?: never });\n\nexport interface CoordinationPlan {\n parent: Task;\n children: readonly Task[];\n}\n\nexport type CoordinationReconciliation =\n | { status: \"pending\"; parent: Task; children: readonly Task[] }\n | { status: \"succeeded\" | \"failed\"; transitioned: boolean; parent: Task; children: readonly Task[] };\n\nexport interface ReconcileCoordinationOptions {\n present(input: {\n status: \"succeeded\" | \"failed\";\n parent: Task;\n children: readonly Task[];\n }): Promise<void>;\n}\n\n/** Create one non-executable parent and one independently executable child per repository. */\nexport async function createCoordination(\n stores: FactoryStores,\n input: CreateCoordinationInput,\n): Promise<CoordinationPlan> {\n const repositoryIds = [...new Set(input.repositoryIds)];\n if (repositoryIds.length < 2) {\n throw new Error(\"coordination requires at least two distinct repositories\");\n }\n const parent = await stores.tasks.create({\n repositoryIds,\n kind: \"coordination\",\n origin: input.signalId === undefined ? { operator: input.operator } : { signalId: input.signalId },\n replyTo: input.replyTo,\n dedupeKey: input.dedupeKey,\n });\n const running = parent.state === \"queued\"\n ? await stores.tasks.transition(parent.id, \"running\", {\n reason: \"repository-scoped child tasks created\",\n })\n : parent;\n const children = await Promise.all(\n repositoryIds.map((repositoryId) =>\n stores.tasks.create({\n repositoryIds: [repositoryId],\n kind: \"code_change\",\n origin: { parentTaskId: parent.id },\n replyTo: input.replyTo,\n dedupeKey: input.dedupeKey === undefined ? undefined : `${input.dedupeKey}:${repositoryId}`,\n }),\n ),\n );\n return { parent: running, children };\n}\n\n/** Reconcile a coordination parent from its direct children without ever dispatching the parent. */\nexport async function reconcileCoordination(\n stores: FactoryStores,\n parentTaskId: TaskId,\n options: ReconcileCoordinationOptions,\n): Promise<CoordinationReconciliation> {\n const parent = await stores.tasks.get(parentTaskId);\n if (parent === null) throw new RecordNotFoundError(\"tasks\", parentTaskId);\n if (parent.kind !== \"coordination\") {\n throw new Error(`task ${parentTaskId} is ${parent.kind}, not coordination`);\n }\n const children = (await stores.tasks.list()).filter(\n (task) => task.origin.parentTaskId === parentTaskId,\n );\n if (children.length !== parent.repositoryIds.length) {\n return { status: \"pending\", parent, children };\n }\n if (parent.state === \"succeeded\" || parent.state === \"failed\") {\n return { status: parent.state, transitioned: false, parent, children };\n }\n if (children.some((child) => child.state === \"failed\" || child.state === \"cancelled\")) {\n await options.present({ status: \"failed\", parent, children });\n const failed = await stores.tasks.transition(parent.id, \"failed\", {\n reason: \"one or more repository tasks failed\",\n });\n return { status: \"failed\", transitioned: true, parent: failed, children };\n }\n if (!children.every((child) => child.state === \"succeeded\")) {\n return { status: \"pending\", parent, children };\n }\n await options.present({ status: \"succeeded\", parent, children });\n await stores.tasks.transition(parent.id, \"verifying\", {\n reason: \"all repository tasks succeeded\",\n });\n const succeeded = await stores.tasks.transition(parent.id, \"succeeded\", {\n reason: \"aggregate multi-repository handoff is ready\",\n });\n return { status: \"succeeded\", transitioned: true, parent: succeeded, children };\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: \"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,SAAS,SAAS,KAAqB;CACrC,OAAO,KAAK,MAAM,MAAM,GAAS;AACnC;;;;;;;;AASA,SAAgB,qBAAqB,OAAwB,OAAuB;CAClF,IAAI,cAAc;CAClB,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,cAAc,KAAK,cAAc,KAAK,SAAS,MAAM,OACvD;EAEF,eAAe,SAAS,KAAK,cAAc,KAAK,eAAe,CAAC;CAClE;CACA,OAAO,cAAc;AACvB;;;;;;AASA,SAAgB,WACd,UACA,QACS;CACT,OAAO,SAAS,QAAQ,IAAI,SAAS,OAAO,qBAAqB,KAAK,SAAS,OAAO,QAAQ;AAChG;AAEA,SAAgB,aACd,UACA,QACc;CACd,IAAI,CAAC,WAAW,UAAU,MAAM,GAC9B,OAAO;CAIT,IAAI,SAAS,QAAQ,IAAI,OAAO,SAAS,OAAO,QAAQ,IAAI,OAAO,gBACjE,OAAO;CAET,OAAO;AACT;AAEA,MAAM,uCAAuB,IAAI,IAAmB;CAAC;CAAa;CAAU;AAAW,CAAC;;;;;;;AAkBxF,eAAsB,iBACpB,QACA,UAA8B,CAAC,GACH;CAC5B,MAAM,WAAW,QAAQ,gBAAgB,MAAM;CAC/C,MAAM,SAAS,QAAQ,8BAAc,IAAI,KAAK,GAAA,CAAI,CAAC,CAAC,QAAQ;CAC5D,MAAM,UAAwC,CAAC;CAC/C,KAA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Eve's Slack continuation token into its channel and thread target. */
28
28
  declare function parseSlackReplyAddress(address: string): SlackReplyTarget;
29
- /** Render a provider-neutral communication event as plain Slack text. */
29
+ /** Render a provider-neutral communication event as Slack mrkdwn. */
30
30
  declare function renderSlackCommunicationEvent(input: CommunicationEvent): string;
31
31
  /** Bind Slack rendering and delivery to the channel-neutral communication contract. */
32
32
  declare function createSlackCommunicationAdapter(options: SlackCommunicationAdapterOptions): SlackCommunicationAdapter;
@@ -69,11 +69,11 @@ type SlackRepositoriesSelection = {
69
69
  } | {
70
70
  status: "required";
71
71
  };
72
- /** Select every explicitly named configured repository, preserving configuration order. */
72
+ /** Select every named configured repository, preserving configuration order. */
73
73
  declare function selectSlackRepositories(text: string, repositories: readonly string[]): SlackRepositoriesSelection;
74
74
  /**
75
- * Select the only configured repository, or require an explicit owner/name
76
- * when a Slack surface fronts more than one repository.
75
+ * Select the only configured repository, or match a full slug, unique short
76
+ * name, or GitHub repository URL when a Slack surface fronts multiple repositories.
77
77
  */
78
78
  declare function selectSlackRepository(text: string, repositories: readonly string[]): SlackRepositorySelection;
79
79
  //#endregion
@@ -30,6 +30,18 @@ const slackOwnerOutcomes = /* @__PURE__ */ new Set([
30
30
  "budget_warning",
31
31
  "budget_exhausted"
32
32
  ]);
33
+ function escapeSlackText(value) {
34
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
35
+ }
36
+ function slackLink(url, label) {
37
+ try {
38
+ const parsed = new URL(url);
39
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
40
+ return `<${escapeSlackText(parsed.toString())}|${escapeSlackText(label)}>`;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
33
45
  /** Parse Eve's Slack continuation token into its channel and thread target. */
34
46
  function parseSlackReplyAddress(address) {
35
47
  const separator = address.indexOf(":");
@@ -41,20 +53,35 @@ function parseSlackReplyAddress(address) {
41
53
  threadTs
42
54
  };
43
55
  }
44
- /** Render a provider-neutral communication event as plain Slack text. */
56
+ /** Render a provider-neutral communication event as Slack mrkdwn. */
45
57
  function renderSlackCommunicationEvent(input) {
46
58
  const event = communicationEventSchema.parse(input);
47
- const headline = slackOutcomeLabels[event.outcome];
48
- const details = slackDetailFields.flatMap((field) => {
59
+ const headline = `*${slackOutcomeLabels[event.outcome]}*`;
60
+ const details = new Map(slackDetailFields.flatMap((field) => {
49
61
  const value = event.data[field];
50
- return typeof value === "string" && value.trim() !== "" ? [value.trim()] : [];
51
- });
62
+ return typeof value === "string" && value.trim() !== "" ? [[field, value.trim()]] : [];
63
+ }));
64
+ const primaryField = [
65
+ "title",
66
+ "question",
67
+ "requestedAction"
68
+ ].find((field) => details.has(field));
69
+ const primary = primaryField === void 0 ? void 0 : details.get(primaryField);
70
+ const url = details.get("url");
71
+ const linkedPrimary = primary !== void 0 && url !== void 0 ? slackLink(url, primary) : null;
72
+ if (primaryField !== void 0) details.delete(primaryField);
73
+ if (linkedPrimary !== null) details.delete("url");
74
+ const detailLines = [.../* @__PURE__ */ new Set([...linkedPrimary !== null ? [linkedPrimary] : primary === void 0 ? [] : [escapeSlackText(primary)], ...[...details.values()].map(escapeSlackText)])];
52
75
  const lists = slackListFields.flatMap((field) => {
53
76
  const value = event.data[field];
54
77
  if (!Array.isArray(value)) return [];
55
- return value.flatMap((item) => typeof item === "string" && item.trim() !== "" ? [`- ${item.trim()}`] : []);
78
+ return value.flatMap((item) => typeof item === "string" && item.trim() !== "" ? [`• ${escapeSlackText(item.trim())}`] : []);
56
79
  });
57
- const text = [headline, .../* @__PURE__ */ new Set([...details, ...lists])].join("\n");
80
+ const text = [
81
+ headline,
82
+ ...detailLines,
83
+ ...lists.length === 0 ? [] : [lists.join("\n")]
84
+ ].join("\n\n");
58
85
  return text.length <= slackTextLimit ? text : `${text.slice(0, 11999)}…`;
59
86
  }
60
87
  function slackClientMessageId(eventId) {
@@ -110,43 +137,67 @@ function normalizeSlackMessage(event) {
110
137
  payload: event.payload
111
138
  };
112
139
  }
113
- /** Select every explicitly named configured repository, preserving configuration order. */
114
- function selectSlackRepositories(text, repositories) {
140
+ function escapedPattern(value) {
141
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
142
+ }
143
+ function isDelimitedTextMentioned(text, value) {
144
+ return new RegExp(`(^|[^a-z0-9._/-])${escapedPattern(value)}($|[^a-z0-9._/-])`, "i").test(text);
145
+ }
146
+ function isRepositoryReferenceMentioned(text, slug) {
147
+ if (isDelimitedTextMentioned(text, slug)) return true;
148
+ return new RegExp(`https?://github\\.com/${escapedPattern(slug)}(?:\\.git)?/?(?=$|[\\s?#|>)\\],.!])`, "i").test(text);
149
+ }
150
+ function repositoryName(slug) {
151
+ return slug.slice(slug.lastIndexOf("/") + 1);
152
+ }
153
+ function resolveSlackRepositoryMentions(text, repositories) {
115
154
  const normalized = [...new Set(repositories.map((slug) => slug.toLowerCase()))];
116
- if (normalized.length === 1) return {
155
+ const entries = normalized.map((slug) => ({
156
+ slug,
157
+ name: repositoryName(slug)
158
+ }));
159
+ const counts = /* @__PURE__ */ new Map();
160
+ for (const { name } of entries) counts.set(name, (counts.get(name) ?? 0) + 1);
161
+ const mentionedNames = new Set([...counts.keys()].filter((name) => isDelimitedTextMentioned(text, name)));
162
+ const matches = new Set(entries.flatMap(({ slug, name }) => isRepositoryReferenceMentioned(text, slug) || counts.get(name) === 1 && mentionedNames.has(name) ? [slug] : []));
163
+ const ambiguous = new Set(entries.flatMap(({ slug, name }) => counts.get(name) !== 1 && mentionedNames.has(name) ? [slug] : []));
164
+ return {
165
+ repositories: normalized,
166
+ matches: normalized.filter((slug) => matches.has(slug)),
167
+ ambiguous: normalized.filter((slug) => ambiguous.has(slug)),
168
+ candidates: normalized.filter((slug) => matches.has(slug) || ambiguous.has(slug))
169
+ };
170
+ }
171
+ /** Select every named configured repository, preserving configuration order. */
172
+ function selectSlackRepositories(text, repositories) {
173
+ const mentions = resolveSlackRepositoryMentions(text, repositories);
174
+ if (mentions.repositories.length === 1) return {
117
175
  status: "selected",
118
- repositorySlugs: [normalized[0]]
176
+ repositorySlugs: [mentions.repositories[0]]
119
177
  };
120
- const matches = normalized.filter((slug) => {
121
- const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
122
- return new RegExp(`(^|[^a-z0-9._/-])${escaped}($|[^a-z0-9._/-])`, "i").test(text);
123
- });
124
- return matches.length === 0 ? { status: "required" } : {
178
+ if (mentions.ambiguous.length > 0) return { status: "required" };
179
+ return mentions.matches.length === 0 ? { status: "required" } : {
125
180
  status: "selected",
126
- repositorySlugs: [matches[0], ...matches.slice(1)]
181
+ repositorySlugs: [mentions.matches[0], ...mentions.matches.slice(1)]
127
182
  };
128
183
  }
129
184
  /**
130
- * Select the only configured repository, or require an explicit owner/name
131
- * when a Slack surface fronts more than one repository.
185
+ * Select the only configured repository, or match a full slug, unique short
186
+ * name, or GitHub repository URL when a Slack surface fronts multiple repositories.
132
187
  */
133
188
  function selectSlackRepository(text, repositories) {
134
- const normalized = [...new Set(repositories.map((slug) => slug.toLowerCase()))];
135
- if (normalized.length === 1) return {
189
+ const mentions = resolveSlackRepositoryMentions(text, repositories);
190
+ if (mentions.repositories.length === 1) return {
136
191
  status: "selected",
137
- repositorySlug: normalized[0]
192
+ repositorySlug: mentions.repositories[0]
138
193
  };
139
- const matches = normalized.filter((slug) => {
140
- const escaped = slug.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
141
- return new RegExp(`(^|[^a-z0-9._/-])${escaped}($|[^a-z0-9._/-])`, "i").test(text);
142
- });
143
- if (matches.length === 1) return {
194
+ if (mentions.candidates.length === 1) return {
144
195
  status: "selected",
145
- repositorySlug: matches[0]
196
+ repositorySlug: mentions.candidates[0]
146
197
  };
147
- if (matches.length > 1) return {
198
+ if (mentions.candidates.length > 1) return {
148
199
  status: "ambiguous",
149
- repositorySlugs: matches
200
+ repositorySlugs: mentions.candidates
150
201
  };
151
202
  return { status: "required" };
152
203
  }
@@ -1 +1 @@
1
- {"version":3,"file":"slack.mjs","names":[],"sources":["../../src/connectors/slack.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n communicationEventSchema,\n type CommunicationAdapter,\n type CommunicationEvent,\n type CommunicationOutcome,\n type NormalizedSignal,\n} from \"./index\";\n\nconst slackOutcomeLabels: Record<CommunicationOutcome, string> = {\n accepted: \"Request accepted\",\n started: \"Work started\",\n succeeded: \"Work completed\",\n failed: \"Work failed\",\n needs_human: \"Human action required\",\n question: \"Question requires an answer\",\n digest: \"Factory digest\",\n rolled_back: \"Change rolled back\",\n budget_warning: \"Factory budget warning\",\n budget_exhausted: \"Factory budget exhausted\",\n message: \"Factory update\",\n};\n\nconst slackDetailFields = [\"title\", \"message\", \"summary\", \"question\", \"requestedAction\", \"reason\", \"url\"] as const;\nconst slackListFields = [\"items\", \"options\"] as const;\nconst slackTextLimit = 12_000;\nconst slackOwnerOutcomes = new Set<CommunicationOutcome>([\n \"digest\",\n \"budget_warning\",\n \"budget_exhausted\",\n]);\n\nexport interface SlackCommunicationDelivery {\n eventId: string;\n clientMessageId: string;\n text: string;\n target:\n | { type: \"owner\" }\n | { type: \"thread\"; channelId: string; threadTs: string };\n}\n\nexport interface SlackCommunicationAdapter extends CommunicationAdapter {\n readonly channel: \"slack\";\n render(event: CommunicationEvent): string;\n}\n\nexport interface SlackCommunicationAdapterOptions {\n send(delivery: SlackCommunicationDelivery): Promise<void>;\n render?: (event: CommunicationEvent) => string;\n}\n\nexport interface SlackReplyTarget {\n channelId: string;\n threadTs: string;\n}\n\n/** Parse Eve's Slack continuation token into its channel and thread target. */\nexport function parseSlackReplyAddress(address: string): SlackReplyTarget {\n const separator = address.indexOf(\":\");\n const channelId = address.slice(0, separator);\n const threadTs = address.slice(separator + 1);\n if (separator <= 0 || !/^[A-Z][A-Z0-9]+$/.test(channelId) || !/^\\d+\\.\\d+$/.test(threadTs)) {\n throw new Error(`Invalid Slack reply address: ${address}.`);\n }\n return { channelId, threadTs };\n}\n\n/** Render a provider-neutral communication event as plain Slack text. */\nexport function renderSlackCommunicationEvent(input: CommunicationEvent): string {\n const event = communicationEventSchema.parse(input);\n const headline = slackOutcomeLabels[event.outcome];\n const details = slackDetailFields.flatMap((field) => {\n const value = event.data[field];\n return typeof value === \"string\" && value.trim() !== \"\" ? [value.trim()] : [];\n });\n const lists = slackListFields.flatMap((field) => {\n const value = event.data[field];\n if (!Array.isArray(value)) return [];\n return value.flatMap((item) =>\n typeof item === \"string\" && item.trim() !== \"\" ? [`- ${item.trim()}`] : []\n );\n });\n const text = [headline, ...new Set([...details, ...lists])].join(\"\\n\");\n return text.length <= slackTextLimit ? text : `${text.slice(0, slackTextLimit - 1)}…`;\n}\n\nfunction slackClientMessageId(eventId: string): string {\n const digest = createHash(\"sha256\").update(eventId).digest(\"hex\").slice(0, 32);\n return [\n digest.slice(0, 8),\n digest.slice(8, 12),\n digest.slice(12, 16),\n digest.slice(16, 20),\n digest.slice(20),\n ].join(\"-\");\n}\n\n/** Bind Slack rendering and delivery to the channel-neutral communication contract. */\nexport function createSlackCommunicationAdapter(\n options: SlackCommunicationAdapterOptions,\n): SlackCommunicationAdapter {\n const render = options.render ?? renderSlackCommunicationEvent;\n return Object.freeze({\n channel: \"slack\" as const,\n render,\n async deliver(input: CommunicationEvent): Promise<void> {\n const event = communicationEventSchema.parse(input);\n if (event.replyTo.channel !== \"slack\") {\n throw new Error(`Slack communication adapter cannot deliver to ${event.replyTo.channel}.`);\n }\n const target = slackOwnerOutcomes.has(event.outcome)\n ? { type: \"owner\" as const }\n : { type: \"thread\" as const, ...parseSlackReplyAddress(event.replyTo.address) };\n await options.send({\n eventId: event.eventId,\n clientMessageId: slackClientMessageId(event.eventId),\n text: render(event),\n target,\n });\n },\n });\n}\n\nexport interface SlackMessageEvent {\n teamId: string;\n channelId: string;\n messageTs: string;\n threadTs: string;\n actorId: string;\n text: string;\n replyAddress: string;\n repositorySlugs: readonly [string, ...string[]];\n payload: unknown;\n}\n\nexport interface SlackMessageSignal extends NormalizedSignal<\"slack\"> {\n repositorySlugs: readonly [string, ...string[]];\n message: {\n teamId: string;\n channelId: string;\n messageTs: string;\n threadTs: string;\n actorId: string;\n text: string;\n };\n}\n\n/** Normalize an Eve-verified Slack message after the caller resolves its repositories. */\nexport function normalizeSlackMessage(event: SlackMessageEvent): SlackMessageSignal {\n return {\n source: \"slack\",\n deliveryId: `${event.teamId}:${event.channelId}:${event.messageTs}`,\n repositorySlugs: [\n event.repositorySlugs[0].toLowerCase(),\n ...event.repositorySlugs.slice(1).map((slug) => slug.toLowerCase()),\n ],\n replyTo: { channel: \"slack\", address: event.replyAddress },\n message: {\n teamId: event.teamId,\n channelId: event.channelId,\n messageTs: event.messageTs,\n threadTs: event.threadTs,\n actorId: event.actorId,\n text: event.text,\n },\n payload: event.payload,\n };\n}\n\nexport type SlackRepositorySelection =\n | { status: \"selected\"; repositorySlug: string }\n | { status: \"required\" }\n | { status: \"ambiguous\"; repositorySlugs: readonly string[] };\n\nexport type SlackRepositoriesSelection =\n | { status: \"selected\"; repositorySlugs: readonly [string, ...string[]] }\n | { status: \"required\" };\n\n/** Select every explicitly named configured repository, preserving configuration order. */\nexport function selectSlackRepositories(\n text: string,\n repositories: readonly string[],\n): SlackRepositoriesSelection {\n const normalized = [...new Set(repositories.map((slug) => slug.toLowerCase()))];\n if (normalized.length === 1) {\n return { status: \"selected\", repositorySlugs: [normalized[0]!] };\n }\n const matches = normalized.filter((slug) => {\n const escaped = slug.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(^|[^a-z0-9._/-])${escaped}($|[^a-z0-9._/-])`, \"i\").test(text);\n });\n return matches.length === 0\n ? { status: \"required\" }\n : { status: \"selected\", repositorySlugs: [matches[0]!, ...matches.slice(1)] };\n}\n\n/**\n * Select the only configured repository, or require an explicit owner/name\n * when a Slack surface fronts more than one repository.\n */\nexport function selectSlackRepository(\n text: string,\n repositories: readonly string[],\n): SlackRepositorySelection {\n const normalized = [...new Set(repositories.map((slug) => slug.toLowerCase()))];\n if (normalized.length === 1) {\n return { status: \"selected\", repositorySlug: normalized[0]! };\n }\n\n const matches = normalized.filter((slug) => {\n const escaped = slug.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(^|[^a-z0-9._/-])${escaped}($|[^a-z0-9._/-])`, \"i\").test(text);\n });\n if (matches.length === 1) {\n return { status: \"selected\", repositorySlug: matches[0]! };\n }\n if (matches.length > 1) {\n return { status: \"ambiguous\", repositorySlugs: matches };\n }\n return { status: \"required\" };\n}\n"],"mappings":";;;AASA,MAAM,qBAA2D;CAC/D,UAAU;CACV,SAAS;CACT,WAAW;CACX,QAAQ;CACR,aAAa;CACb,UAAU;CACV,QAAQ;CACR,aAAa;CACb,gBAAgB;CAChB,kBAAkB;CAClB,SAAS;AACX;AAEA,MAAM,oBAAoB;CAAC;CAAS;CAAW;CAAW;CAAY;CAAmB;CAAU;AAAK;AACxG,MAAM,kBAAkB,CAAC,SAAS,SAAS;AAC3C,MAAM,iBAAiB;AACvB,MAAM,qCAAqB,IAAI,IAA0B;CACvD;CACA;CACA;AACF,CAAC;;AA2BD,SAAgB,uBAAuB,SAAmC;CACxE,MAAM,YAAY,QAAQ,QAAQ,GAAG;CACrC,MAAM,YAAY,QAAQ,MAAM,GAAG,SAAS;CAC5C,MAAM,WAAW,QAAQ,MAAM,YAAY,CAAC;CAC5C,IAAI,aAAa,KAAK,CAAC,mBAAmB,KAAK,SAAS,KAAK,CAAC,aAAa,KAAK,QAAQ,GACtF,MAAM,IAAI,MAAM,gCAAgC,QAAQ,EAAE;CAE5D,OAAO;EAAE;EAAW;CAAS;AAC/B;;AAGA,SAAgB,8BAA8B,OAAmC;CAC/E,MAAM,QAAQ,yBAAyB,MAAM,KAAK;CAClD,MAAM,WAAW,mBAAmB,MAAM;CAC1C,MAAM,UAAU,kBAAkB,SAAS,UAAU;EACnD,MAAM,QAAQ,MAAM,KAAK;EACzB,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,KAA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CAAC,CAAC,CAAC;CAC9E,IAAI,WAAW,WAAW,GACxB,OAAO;EAAE,QAAQ;EAAY,gBAAgB,WAAW;CAAI;CAG9D,MAAM,UAAU,WAAW,QAAQ,SAAS;EAC1C,MAAM,UAAU,KAAK,QAAQ,uBAAuB,MAAM;EAC1D,OAAO,IAAI,OAAO,oBAAoB,QAAQ,oBAAoB,GAAG,CAAC,CAAC,KAAK,IAAI;CAClF,CAAC;CACD,IAAI,QAAQ,WAAW,GACrB,OAAO;EAAE,QAAQ;EAAY,gBAAgB,QAAQ;CAAI;CAE3D,IAAI,QAAQ,SAAS,GACnB,OAAO;EAAE,QAAQ;EAAa,iBAAiB;CAAQ;CAEzD,OAAO,EAAE,QAAQ,WAAW;AAC9B"}
1
+ {"version":3,"file":"slack.mjs","names":[],"sources":["../../src/connectors/slack.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport {\n communicationEventSchema,\n type CommunicationAdapter,\n type CommunicationEvent,\n type CommunicationOutcome,\n type NormalizedSignal,\n} from \"./index\";\n\nconst slackOutcomeLabels: Record<CommunicationOutcome, string> = {\n accepted: \"Request accepted\",\n started: \"Work started\",\n succeeded: \"Work completed\",\n failed: \"Work failed\",\n needs_human: \"Human action required\",\n question: \"Question requires an answer\",\n digest: \"Factory digest\",\n rolled_back: \"Change rolled back\",\n budget_warning: \"Factory budget warning\",\n budget_exhausted: \"Factory budget exhausted\",\n message: \"Factory update\",\n};\n\nconst slackDetailFields = [\"title\", \"message\", \"summary\", \"question\", \"requestedAction\", \"reason\", \"url\"] as const;\nconst slackListFields = [\"items\", \"options\"] as const;\nconst slackTextLimit = 12_000;\nconst slackOwnerOutcomes = new Set<CommunicationOutcome>([\n \"digest\",\n \"budget_warning\",\n \"budget_exhausted\",\n]);\n\nfunction escapeSlackText(value: string): string {\n return value.replaceAll(\"&\", \"&amp;\").replaceAll(\"<\", \"&lt;\").replaceAll(\">\", \"&gt;\");\n}\n\nfunction slackLink(url: string, label: string): string | null {\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") return null;\n return `<${escapeSlackText(parsed.toString())}|${escapeSlackText(label)}>`;\n } catch {\n return null;\n }\n}\n\nexport interface SlackCommunicationDelivery {\n eventId: string;\n clientMessageId: string;\n text: string;\n target:\n | { type: \"owner\" }\n | { type: \"thread\"; channelId: string; threadTs: string };\n}\n\nexport interface SlackCommunicationAdapter extends CommunicationAdapter {\n readonly channel: \"slack\";\n render(event: CommunicationEvent): string;\n}\n\nexport interface SlackCommunicationAdapterOptions {\n send(delivery: SlackCommunicationDelivery): Promise<void>;\n render?: (event: CommunicationEvent) => string;\n}\n\nexport interface SlackReplyTarget {\n channelId: string;\n threadTs: string;\n}\n\n/** Parse Eve's Slack continuation token into its channel and thread target. */\nexport function parseSlackReplyAddress(address: string): SlackReplyTarget {\n const separator = address.indexOf(\":\");\n const channelId = address.slice(0, separator);\n const threadTs = address.slice(separator + 1);\n if (separator <= 0 || !/^[A-Z][A-Z0-9]+$/.test(channelId) || !/^\\d+\\.\\d+$/.test(threadTs)) {\n throw new Error(`Invalid Slack reply address: ${address}.`);\n }\n return { channelId, threadTs };\n}\n\n/** Render a provider-neutral communication event as Slack mrkdwn. */\nexport function renderSlackCommunicationEvent(input: CommunicationEvent): string {\n const event = communicationEventSchema.parse(input);\n const headline = `*${slackOutcomeLabels[event.outcome]}*`;\n const details = new Map(slackDetailFields.flatMap((field) => {\n const value = event.data[field];\n return typeof value === \"string\" && value.trim() !== \"\" ? [[field, value.trim()] as const] : [];\n }));\n const primaryField = ([\"title\", \"question\", \"requestedAction\"] as const)\n .find((field) => details.has(field));\n const primary = primaryField === undefined ? undefined : details.get(primaryField);\n const url = details.get(\"url\");\n const linkedPrimary = primary !== undefined && url !== undefined ? slackLink(url, primary) : null;\n if (primaryField !== undefined) details.delete(primaryField);\n if (linkedPrimary !== null) details.delete(\"url\");\n\n const detailLines = [...new Set([\n ...(linkedPrimary !== null ? [linkedPrimary] : primary === undefined ? [] : [escapeSlackText(primary)]),\n ...[...details.values()].map(escapeSlackText),\n ])];\n const lists = slackListFields.flatMap((field) => {\n const value = event.data[field];\n if (!Array.isArray(value)) return [];\n return value.flatMap((item) =>\n typeof item === \"string\" && item.trim() !== \"\" ? [`• ${escapeSlackText(item.trim())}`] : []\n );\n });\n const text = [headline, ...detailLines, ...(lists.length === 0 ? [] : [lists.join(\"\\n\")])]\n .join(\"\\n\\n\");\n return text.length <= slackTextLimit ? text : `${text.slice(0, slackTextLimit - 1)}…`;\n}\n\nfunction slackClientMessageId(eventId: string): string {\n const digest = createHash(\"sha256\").update(eventId).digest(\"hex\").slice(0, 32);\n return [\n digest.slice(0, 8),\n digest.slice(8, 12),\n digest.slice(12, 16),\n digest.slice(16, 20),\n digest.slice(20),\n ].join(\"-\");\n}\n\n/** Bind Slack rendering and delivery to the channel-neutral communication contract. */\nexport function createSlackCommunicationAdapter(\n options: SlackCommunicationAdapterOptions,\n): SlackCommunicationAdapter {\n const render = options.render ?? renderSlackCommunicationEvent;\n return Object.freeze({\n channel: \"slack\" as const,\n render,\n async deliver(input: CommunicationEvent): Promise<void> {\n const event = communicationEventSchema.parse(input);\n if (event.replyTo.channel !== \"slack\") {\n throw new Error(`Slack communication adapter cannot deliver to ${event.replyTo.channel}.`);\n }\n const target = slackOwnerOutcomes.has(event.outcome)\n ? { type: \"owner\" as const }\n : { type: \"thread\" as const, ...parseSlackReplyAddress(event.replyTo.address) };\n await options.send({\n eventId: event.eventId,\n clientMessageId: slackClientMessageId(event.eventId),\n text: render(event),\n target,\n });\n },\n });\n}\n\nexport interface SlackMessageEvent {\n teamId: string;\n channelId: string;\n messageTs: string;\n threadTs: string;\n actorId: string;\n text: string;\n replyAddress: string;\n repositorySlugs: readonly [string, ...string[]];\n payload: unknown;\n}\n\nexport interface SlackMessageSignal extends NormalizedSignal<\"slack\"> {\n repositorySlugs: readonly [string, ...string[]];\n message: {\n teamId: string;\n channelId: string;\n messageTs: string;\n threadTs: string;\n actorId: string;\n text: string;\n };\n}\n\n/** Normalize an Eve-verified Slack message after the caller resolves its repositories. */\nexport function normalizeSlackMessage(event: SlackMessageEvent): SlackMessageSignal {\n return {\n source: \"slack\",\n deliveryId: `${event.teamId}:${event.channelId}:${event.messageTs}`,\n repositorySlugs: [\n event.repositorySlugs[0].toLowerCase(),\n ...event.repositorySlugs.slice(1).map((slug) => slug.toLowerCase()),\n ],\n replyTo: { channel: \"slack\", address: event.replyAddress },\n message: {\n teamId: event.teamId,\n channelId: event.channelId,\n messageTs: event.messageTs,\n threadTs: event.threadTs,\n actorId: event.actorId,\n text: event.text,\n },\n payload: event.payload,\n };\n}\n\nexport type SlackRepositorySelection =\n | { status: \"selected\"; repositorySlug: string }\n | { status: \"required\" }\n | { status: \"ambiguous\"; repositorySlugs: readonly string[] };\n\nexport type SlackRepositoriesSelection =\n | { status: \"selected\"; repositorySlugs: readonly [string, ...string[]] }\n | { status: \"required\" };\n\nfunction escapedPattern(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction isDelimitedTextMentioned(text: string, value: string): boolean {\n return new RegExp(\n `(^|[^a-z0-9._/-])${escapedPattern(value)}($|[^a-z0-9._/-])`,\n \"i\",\n ).test(text);\n}\n\nfunction isRepositoryReferenceMentioned(text: string, slug: string): boolean {\n if (isDelimitedTextMentioned(text, slug)) return true;\n return new RegExp(\n `https?://github\\\\.com/${escapedPattern(slug)}(?:\\\\.git)?/?(?=$|[\\\\s?#|>)\\\\],.!])`,\n \"i\",\n ).test(text);\n}\n\nfunction repositoryName(slug: string): string {\n return slug.slice(slug.lastIndexOf(\"/\") + 1);\n}\n\ninterface SlackRepositoryMentions {\n repositories: readonly string[];\n matches: readonly string[];\n ambiguous: readonly string[];\n candidates: readonly string[];\n}\n\nfunction resolveSlackRepositoryMentions(\n text: string,\n repositories: readonly string[],\n): SlackRepositoryMentions {\n const normalized = [...new Set(repositories.map((slug) => slug.toLowerCase()))];\n const entries = normalized.map((slug) => ({ slug, name: repositoryName(slug) }));\n const counts = new Map<string, number>();\n for (const { name } of entries) {\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n const mentionedNames = new Set(\n [...counts.keys()].filter((name) => isDelimitedTextMentioned(text, name)),\n );\n const matches = new Set(entries.flatMap(({ slug, name }) =>\n isRepositoryReferenceMentioned(text, slug) || (\n counts.get(name) === 1 && mentionedNames.has(name)\n )\n ? [slug]\n : []\n ));\n const ambiguous = new Set(entries.flatMap(({ slug, name }) =>\n counts.get(name) !== 1 && mentionedNames.has(name) ? [slug] : []\n ));\n\n return {\n repositories: normalized,\n matches: normalized.filter((slug) => matches.has(slug)),\n ambiguous: normalized.filter((slug) => ambiguous.has(slug)),\n candidates: normalized.filter((slug) => matches.has(slug) || ambiguous.has(slug)),\n };\n}\n\n/** Select every named configured repository, preserving configuration order. */\nexport function selectSlackRepositories(\n text: string,\n repositories: readonly string[],\n): SlackRepositoriesSelection {\n const mentions = resolveSlackRepositoryMentions(text, repositories);\n if (mentions.repositories.length === 1) {\n return { status: \"selected\", repositorySlugs: [mentions.repositories[0]!] };\n }\n if (mentions.ambiguous.length > 0) return { status: \"required\" };\n return mentions.matches.length === 0\n ? { status: \"required\" }\n : {\n status: \"selected\",\n repositorySlugs: [mentions.matches[0]!, ...mentions.matches.slice(1)],\n };\n}\n\n/**\n * Select the only configured repository, or match a full slug, unique short\n * name, or GitHub repository URL when a Slack surface fronts multiple repositories.\n */\nexport function selectSlackRepository(\n text: string,\n repositories: readonly string[],\n): SlackRepositorySelection {\n const mentions = resolveSlackRepositoryMentions(text, repositories);\n if (mentions.repositories.length === 1) {\n return { status: \"selected\", repositorySlug: mentions.repositories[0]! };\n }\n if (mentions.candidates.length === 1) {\n return { status: \"selected\", repositorySlug: mentions.candidates[0]! };\n }\n if (mentions.candidates.length > 1) {\n return { status: \"ambiguous\", repositorySlugs: mentions.candidates };\n }\n return { status: \"required\" };\n}\n"],"mappings":";;;AASA,MAAM,qBAA2D;CAC/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