@mastra/factory 0.13.0-alpha.9 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +232 -10
  2. package/dist/auth.d.ts +2 -0
  3. package/dist/auth.d.ts.map +1 -1
  4. package/dist/auth.js +29 -4
  5. package/dist/auth.js.map +1 -1
  6. package/dist/boards/define-board.d.ts +36 -2
  7. package/dist/boards/define-board.d.ts.map +1 -1
  8. package/dist/boards/define-board.js +58 -1
  9. package/dist/boards/define-board.js.map +1 -1
  10. package/dist/boards/index.d.ts +4 -2
  11. package/dist/boards/index.d.ts.map +1 -1
  12. package/dist/boards/index.js +2 -1
  13. package/dist/boards/index.js.map +1 -1
  14. package/dist/boards/relocate.d.ts +17 -0
  15. package/dist/boards/relocate.d.ts.map +1 -0
  16. package/dist/boards/relocate.js +53 -0
  17. package/dist/boards/relocate.js.map +1 -0
  18. package/dist/boards/review.d.ts +1 -1
  19. package/dist/boards/review.d.ts.map +1 -1
  20. package/dist/boards/review.js +17 -4
  21. package/dist/boards/review.js.map +1 -1
  22. package/dist/boards/semantics.d.ts +28 -0
  23. package/dist/boards/semantics.d.ts.map +1 -0
  24. package/dist/boards/semantics.js +41 -0
  25. package/dist/boards/semantics.js.map +1 -0
  26. package/dist/boards/work-tool-rules.d.ts +8 -0
  27. package/dist/boards/work-tool-rules.d.ts.map +1 -0
  28. package/dist/boards/work-tool-rules.js +20 -0
  29. package/dist/boards/work-tool-rules.js.map +1 -0
  30. package/dist/boards/work.d.ts +1 -1
  31. package/dist/boards/work.d.ts.map +1 -1
  32. package/dist/boards/work.js +13 -0
  33. package/dist/boards/work.js.map +1 -1
  34. package/dist/capabilities/intake.d.ts +2 -0
  35. package/dist/capabilities/intake.d.ts.map +1 -1
  36. package/dist/factory.d.ts +5 -6
  37. package/dist/factory.d.ts.map +1 -1
  38. package/dist/factory.js +41 -12
  39. package/dist/factory.js.map +1 -1
  40. package/dist/integrations/base.d.ts +7 -4
  41. package/dist/integrations/base.d.ts.map +1 -1
  42. package/dist/integrations/github/default-rules.d.ts +2 -2
  43. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  44. package/dist/integrations/github/default-rules.js +2 -2
  45. package/dist/integrations/github/default-rules.js.map +1 -1
  46. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  47. package/dist/integrations/github/issue-reconciler.js +4 -3
  48. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  49. package/dist/integrations/github/rules.d.ts +6 -2
  50. package/dist/integrations/github/rules.d.ts.map +1 -1
  51. package/dist/integrations/github/rules.js +96 -15
  52. package/dist/integrations/github/rules.js.map +1 -1
  53. package/dist/integrations/github/sandbox.d.ts +6 -3
  54. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  55. package/dist/integrations/github/sandbox.js +21 -2
  56. package/dist/integrations/github/sandbox.js.map +1 -1
  57. package/dist/integrations/issue-reconciler.d.ts +2 -0
  58. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  59. package/dist/integrations/issue-reconciler.js +1 -3
  60. package/dist/integrations/issue-reconciler.js.map +1 -1
  61. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  62. package/dist/integrations/linear/agent-tools.js.map +1 -1
  63. package/dist/integrations/linear/default-rules.d.ts +2 -2
  64. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  65. package/dist/integrations/linear/default-rules.js +2 -2
  66. package/dist/integrations/linear/default-rules.js.map +1 -1
  67. package/dist/integrations/linear/integration.js +1 -0
  68. package/dist/integrations/linear/integration.js.map +1 -1
  69. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  70. package/dist/integrations/linear/issue-reconciler.js +9 -4
  71. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  72. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  73. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  74. package/dist/integrations/linear/routes.d.ts.map +1 -1
  75. package/dist/integrations/linear/routes.js +19 -26
  76. package/dist/integrations/linear/routes.js.map +1 -1
  77. package/dist/integrations/linear/rules.d.ts +7 -2
  78. package/dist/integrations/linear/rules.d.ts.map +1 -1
  79. package/dist/integrations/linear/rules.js +20 -8
  80. package/dist/integrations/linear/rules.js.map +1 -1
  81. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  82. package/dist/integrations/platform/api-client.js +25 -4
  83. package/dist/integrations/platform/api-client.js.map +1 -1
  84. package/dist/integrations/platform/github/integration.d.ts +1 -0
  85. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  86. package/dist/integrations/platform/github/integration.js +5 -0
  87. package/dist/integrations/platform/github/integration.js.map +1 -1
  88. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  89. package/dist/integrations/platform/linear/integration.js +5 -2
  90. package/dist/integrations/platform/linear/integration.js.map +1 -1
  91. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +8 -0
  92. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +1 -0
  93. package/dist/integrations/slack/emoji-shortcodes.generated.js +1985 -0
  94. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +1 -0
  95. package/dist/integrations/slack/emoji.d.ts +3 -0
  96. package/dist/integrations/slack/emoji.d.ts.map +1 -0
  97. package/dist/integrations/slack/emoji.js +12 -0
  98. package/dist/integrations/slack/emoji.js.map +1 -0
  99. package/dist/integrations/slack/integration.js +1 -1
  100. package/dist/integrations/slack/integration.js.map +1 -1
  101. package/dist/integrations/slack/slack.d.ts.map +1 -1
  102. package/dist/integrations/slack/slack.js +16 -2
  103. package/dist/integrations/slack/slack.js.map +1 -1
  104. package/dist/routes/attention-activity.d.ts +2 -3
  105. package/dist/routes/attention-activity.d.ts.map +1 -1
  106. package/dist/routes/attention-activity.js +12 -3
  107. package/dist/routes/attention-activity.js.map +1 -1
  108. package/dist/routes/attention-parked.d.ts +22 -0
  109. package/dist/routes/attention-parked.d.ts.map +1 -0
  110. package/dist/routes/attention-parked.js +136 -0
  111. package/dist/routes/attention-parked.js.map +1 -0
  112. package/dist/routes/attention-providers.js +8 -8
  113. package/dist/routes/attention-providers.js.map +1 -1
  114. package/dist/routes/attention.d.ts +2 -0
  115. package/dist/routes/attention.d.ts.map +1 -1
  116. package/dist/routes/attention.js +47 -118
  117. package/dist/routes/attention.js.map +1 -1
  118. package/dist/routes/contracts.d.ts +627 -0
  119. package/dist/routes/contracts.d.ts.map +1 -0
  120. package/dist/routes/contracts.js +468 -0
  121. package/dist/routes/contracts.js.map +1 -0
  122. package/dist/routes/intake.d.ts +18 -0
  123. package/dist/routes/intake.d.ts.map +1 -1
  124. package/dist/routes/intake.js +265 -15
  125. package/dist/routes/intake.js.map +1 -1
  126. package/dist/routes/projects.d.ts.map +1 -1
  127. package/dist/routes/projects.js +26 -76
  128. package/dist/routes/projects.js.map +1 -1
  129. package/dist/routes/supervisor.d.ts +2 -0
  130. package/dist/routes/supervisor.d.ts.map +1 -1
  131. package/dist/routes/supervisor.js +7 -6
  132. package/dist/routes/supervisor.js.map +1 -1
  133. package/dist/routes/surface.d.ts +7 -4
  134. package/dist/routes/surface.d.ts.map +1 -1
  135. package/dist/routes/surface.js +17 -11
  136. package/dist/routes/surface.js.map +1 -1
  137. package/dist/routes/telemetry.d.ts +13 -0
  138. package/dist/routes/telemetry.d.ts.map +1 -0
  139. package/dist/routes/telemetry.js +60 -0
  140. package/dist/routes/telemetry.js.map +1 -0
  141. package/dist/routes/work-items.d.ts +3 -3
  142. package/dist/routes/work-items.d.ts.map +1 -1
  143. package/dist/routes/work-items.js +134 -250
  144. package/dist/routes/work-items.js.map +1 -1
  145. package/dist/rules/dispatch-errors.d.ts +2 -2
  146. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  147. package/dist/rules/dispatch-errors.js +10 -6
  148. package/dist/rules/dispatch-errors.js.map +1 -1
  149. package/dist/rules/dispatcher.d.ts +9 -2
  150. package/dist/rules/dispatcher.d.ts.map +1 -1
  151. package/dist/rules/dispatcher.js +76 -23
  152. package/dist/rules/dispatcher.js.map +1 -1
  153. package/dist/rules/index.d.ts +4 -5
  154. package/dist/rules/index.d.ts.map +1 -1
  155. package/dist/rules/index.js +3 -4
  156. package/dist/rules/processor.d.ts +3 -3
  157. package/dist/rules/processor.d.ts.map +1 -1
  158. package/dist/rules/processor.js +24 -31
  159. package/dist/rules/processor.js.map +1 -1
  160. package/dist/rules/resolve.d.ts +1 -3
  161. package/dist/rules/resolve.d.ts.map +1 -1
  162. package/dist/rules/resolve.js +1 -4
  163. package/dist/rules/resolve.js.map +1 -1
  164. package/dist/rules/start-coordinator.d.ts.map +1 -1
  165. package/dist/rules/start-coordinator.js +3 -1
  166. package/dist/rules/start-coordinator.js.map +1 -1
  167. package/dist/rules/tools.d.ts.map +1 -1
  168. package/dist/rules/tools.js +20 -10
  169. package/dist/rules/tools.js.map +1 -1
  170. package/dist/rules/transition-service.d.ts +7 -7
  171. package/dist/rules/transition-service.d.ts.map +1 -1
  172. package/dist/rules/transition-service.js +21 -25
  173. package/dist/rules/transition-service.js.map +1 -1
  174. package/dist/rules/types.d.ts +16 -11
  175. package/dist/rules/types.d.ts.map +1 -1
  176. package/dist/rules/types.js.map +1 -1
  177. package/dist/rules/validation.d.ts +12 -2
  178. package/dist/rules/validation.d.ts.map +1 -1
  179. package/dist/rules/validation.js +29 -20
  180. package/dist/rules/validation.js.map +1 -1
  181. package/dist/session/live-sessions.d.ts +33 -3
  182. package/dist/session/live-sessions.d.ts.map +1 -1
  183. package/dist/session/live-sessions.js +67 -5
  184. package/dist/session/live-sessions.js.map +1 -1
  185. package/dist/storage/domains/intake/base.d.ts +54 -1
  186. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  187. package/dist/storage/domains/intake/base.js +136 -4
  188. package/dist/storage/domains/intake/base.js.map +1 -1
  189. package/dist/storage/domains/work-items/base.d.ts +22 -7
  190. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  191. package/dist/storage/domains/work-items/base.js +41 -26
  192. package/dist/storage/domains/work-items/base.js.map +1 -1
  193. package/dist/supervisor/health-worker.d.ts +2 -0
  194. package/dist/supervisor/health-worker.d.ts.map +1 -1
  195. package/dist/supervisor/health-worker.js +3 -1
  196. package/dist/supervisor/health-worker.js.map +1 -1
  197. package/dist/supervisor/health.d.ts +12 -14
  198. package/dist/supervisor/health.d.ts.map +1 -1
  199. package/dist/supervisor/health.js +24 -52
  200. package/dist/supervisor/health.js.map +1 -1
  201. package/dist/supervisor/instructions.d.ts +1 -1
  202. package/dist/supervisor/instructions.d.ts.map +1 -1
  203. package/dist/supervisor/instructions.js +10 -8
  204. package/dist/supervisor/instructions.js.map +1 -1
  205. package/dist/supervisor/read-tools.d.ts +2 -0
  206. package/dist/supervisor/read-tools.d.ts.map +1 -1
  207. package/dist/supervisor/read-tools.js +2 -2
  208. package/dist/supervisor/read-tools.js.map +1 -1
  209. package/dist/supervisor/write-tools.d.ts.map +1 -1
  210. package/dist/supervisor/write-tools.js +6 -4
  211. package/dist/supervisor/write-tools.js.map +1 -1
  212. package/dist/telemetry-types.d.ts +7 -0
  213. package/dist/telemetry-types.d.ts.map +1 -0
  214. package/dist/telemetry-types.js +24 -0
  215. package/dist/telemetry-types.js.map +1 -0
  216. package/dist/telemetry.d.ts +9 -0
  217. package/dist/telemetry.d.ts.map +1 -0
  218. package/dist/telemetry.js +47 -0
  219. package/dist/telemetry.js.map +1 -0
  220. package/dist/work-item-branch.d.ts +2 -0
  221. package/dist/work-item-branch.d.ts.map +1 -1
  222. package/dist/work-item-branch.js +6 -1
  223. package/dist/work-item-branch.js.map +1 -1
  224. package/dist/workspace.d.ts.map +1 -1
  225. package/dist/workspace.js +3 -1
  226. package/dist/workspace.js.map +1 -1
  227. package/factory-skills/configure-factory-rules/SKILL.md +30 -10
  228. package/package.json +12 -10
  229. package/dist/rules/defaults.d.ts +0 -9
  230. package/dist/rules/defaults.d.ts.map +0 -1
  231. package/dist/rules/defaults.js +0 -50
  232. package/dist/rules/defaults.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["#attentionChanged","#db","#countRows","#withProjectRelationTransaction","#claimLeases","#renewLease","#completeLease","#failLease","#listWithOps","#retryAttentionReceiptWrite","#setAttentionReceiptWithOps","#attentionSourceIsCurrent","#settleProposedDecision","#resolveFailedDecision","#upsert","#purgeRuleState","#purgeFeedState"],"sources":["../../../../src/storage/domains/work-items/base.ts"],"sourcesContent":["/**\n * Factory work-items storage domain.\n *\n * Work items belong to a first-class Factory project. External intake items use\n * a provider-neutral source reference; manual work items have no source.\n * Stage history is server-owned, while session and metadata patches merge\n * atomically so concurrent actors do not overwrite each other. The authoritative\n * Factory transition path keeps one exclusive current stage per item.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\nimport { isTerminalFactoryRuleStage } from '../../../rules/types.js';\nimport type { FactoryTriageType } from '../../../rules/types.js';\nimport type { FactoryHealthFinding } from '../../../supervisor/health.js';\nimport {\n WORK_ITEM_ACTIVITY_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_COMMENTS_SCHEMA,\n} from '../comments/schema.js';\n\nexport type WorkItemStage = string;\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n if (value && typeof value === 'object') {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value) ?? 'null';\n}\n\nexport function factoryDecisionHash(decision: Record<string, unknown>): string {\n return createHash('sha256').update(stableJson(decision)).digest('hex');\n}\n\nexport interface ExternalWorkItemSource {\n integrationId: string;\n type: string;\n /**\n * The tenant on the platform, never ours: a Slack team (`T0ABC…`), a Discord\n * guild. Scopes the key, because a platform id such as a channel or a message\n * `ts` is only unique inside the workspace that issued it.\n */\n workspaceId?: string;\n externalId: string;\n url?: string;\n}\n\n/** Dispatcher upsert idempotency token — server bookkeeping, dropped from the read wire. */\nexport const FACTORY_RULE_MATERIALIZATION_KEY = 'factoryRuleMaterializationKey';\nexport const FACTORY_PULL_REQUEST_RECONCILIATION_KEY = 'factoryPullRequestReconciliation';\n\nexport interface WorkItemStageEntry {\n stage: WorkItemStage;\n enteredAt: string;\n exitedAt?: string;\n by: string;\n /**\n * Actor that closed this entry; absent on entries written before exit\n * stamping existed — treat as human.\n */\n exitedBy?: string;\n}\n\n/**\n * Whether an actor id marks a move an agent run performed: the binding id the\n * transition tool stamps (`agent:*`), or the rule that fires off a bound run's\n * tool result (see `factory/rules/processor.ts`).\n *\n * Deliberately narrower than \"not a human\": the poller stamps\n * `factory-rule-dispatcher` / `github:*` on every card it syncs from the\n * upstream repo, so counting those as machine work reports the repo's activity\n * as the Factory's and pins any such ratio near 100%.\n */\nexport function isAgentActor(by: string | undefined): boolean {\n if (by === undefined) return false;\n return by.startsWith('agent:') || by === 'factory-tool-result-rule';\n}\n\nexport interface WorkItemSessionRef {\n sessionId: string;\n branch: string;\n threadId: string;\n startedBy: string;\n}\n\nexport interface FactoryRuleIngressRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n identity: string;\n triggerType: string;\n transitionId: string;\n result: Record<string, unknown>;\n createdAt: Date;\n}\n\nexport interface CommitFactoryRuleEvaluationInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n ingress: { identity: string; triggerType: string };\n ruleSetVersion: string;\n expectedRevision: number | null;\n actor: Record<string, unknown> | null;\n outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string };\n decisions: Record<string, unknown>[];\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n now: Date;\n}\n\nexport type CommitFactoryRuleEvaluationResult =\n | { status: 'committed'; result: Record<string, unknown> }\n | { status: 'replayed'; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface FactoryToolResultCursorRecord {\n bindingId: string;\n orgId: string;\n factoryProjectId: string;\n lastMessageId: string;\n lastMessageCreatedAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryRuleEvaluationRecord {\n id: string;\n ingressId: string;\n workItemId: string | null;\n ruleSetVersion: string;\n expectedRevision: number | null;\n outcome: 'accepted' | 'rejected';\n code: string | null;\n reason: string | null;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n createdAt: Date;\n}\n\n/** `proposed` is parked awaiting approval; `dismissed` is human, `superseded` is automatic. */\nexport type FactoryDispatchStatus =\n | 'pending'\n | 'proposed'\n | 'dismissed'\n | 'superseded'\n | 'leased'\n | 'retry'\n | 'succeeded'\n | 'failed';\n\nconst FACTORY_DISPATCH_FAILURE_CODES = [\n 'session_unavailable',\n 'source_control_missing',\n 'source_repository_missing',\n 'unsupported_provider_item',\n 'notification_delivery_failed',\n 'plan_awaiting_approval',\n 'run_awaiting_input',\n 'repository_git_missing',\n 'repository_egress_blocked',\n 'repository_clone_failed',\n 'repository_pull_failed',\n 'repository_push_failed',\n 'repository_commit_failed',\n 'repository_cli_missing',\n 'repository_pr_failed',\n 'unknown',\n] as const;\n\nexport type FactoryDispatchFailureCode = (typeof FACTORY_DISPATCH_FAILURE_CODES)[number];\n\nfunction isFactoryDispatchFailureCode(value: unknown): value is FactoryDispatchFailureCode {\n return FACTORY_DISPATCH_FAILURE_CODES.some(code => code === value);\n}\n\nexport interface FactoryDeferredDecisionPageInput {\n orgId: string;\n factoryProjectId: string;\n statuses?: FactoryDispatchStatus[];\n before?: { createdAt: Date; id: string };\n limit: number;\n}\n\nexport interface FactoryDeferredDecisionPage {\n decisions: FactoryDeferredDecisionRecord[];\n hasMore: boolean;\n}\n\nexport interface FactoryDecisionStatusPageInput {\n orgId: string;\n factoryProjectId: string;\n status: FactoryDispatchStatus;\n before?: { occurredAt: Date; id: string };\n limit: number;\n}\n\nexport interface FactoryDeferredDecisionRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n evaluationId: string;\n workItemId: string | null;\n idempotencyKey: string;\n effectOrdinal: number;\n effectHash: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n actor: Record<string, unknown> | null;\n decision: Record<string, unknown>;\n status: FactoryDispatchStatus;\n attempts: number;\n deliveryGeneration: number;\n failureOccurrence: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n failureCode: FactoryDispatchFailureCode | null;\n /** When a human released this run; set once, so the gate never parks it again. */\n approvedAt: Date | null;\n /** Who released this run — the run is attributed to them, not the repo connector. */\n approvedBy: string | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type FactoryAttentionKind =\n | 'automation-failed'\n | 'automation-proposed'\n | 'mention'\n | 'activity'\n | 'supervisor-finding';\nexport type FactoryAttentionReceiptState = 'read' | 'archived';\n\nexport interface FactorySupervisorFindingRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n findingKey: string;\n occurrence: number;\n finding: Record<string, unknown>;\n openedAt: Date;\n updatedAt: Date;\n resolvedAt: Date | null;\n}\nexport type FactoryAttentionReceiptAction = 'read' | 'archive' | 'restore';\n\nexport interface FactoryAttentionIdentity {\n kind: FactoryAttentionKind;\n sourceId: string;\n occurrence: number;\n}\n\nexport interface FactoryAttentionReceiptRecord extends FactoryAttentionIdentity {\n id: string;\n orgId: string;\n factoryProjectId: string;\n userId: string;\n state: FactoryAttentionReceiptState;\n readAt: Date;\n archivedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface SetAttentionReceiptInput {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n identity: FactoryAttentionIdentity;\n action: FactoryAttentionReceiptAction;\n now: Date;\n}\n\nexport function factoryDecisionAttentionIdentity(\n decisionId: string,\n failureOccurrence: number,\n): FactoryAttentionIdentity {\n return { kind: 'automation-failed', sourceId: decisionId, occurrence: failureOccurrence };\n}\n\nexport function factoryProposalAttentionIdentity(decisionId: string): FactoryAttentionIdentity {\n return { kind: 'automation-proposed', sourceId: decisionId, occurrence: 0 };\n}\n\n// A settled proposal is settled for everyone, so its receipts go for everyone.\nfunction proposalReceiptFilter(orgId: string, factoryProjectId: string, decisionId: string) {\n const identity = factoryProposalAttentionIdentity(decisionId);\n return {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: identity.kind,\n source_id: identity.sourceId,\n occurrence: identity.occurrence,\n };\n}\n\nexport function factoryMentionAttentionIdentity(commentId: string): FactoryAttentionIdentity {\n return { kind: 'mention', sourceId: commentId, occurrence: 0 };\n}\n\n/** Collapsed per work item, so the occurrence is what a new comment bumps. */\nexport function factoryActivityAttentionIdentity(workItemId: string, occurrence: number): FactoryAttentionIdentity {\n return { kind: 'activity', sourceId: workItemId, occurrence };\n}\n\nexport function factorySupervisorFindingAttentionIdentity(\n findingKey: string,\n occurrence: number,\n): FactoryAttentionIdentity {\n return { kind: 'supervisor-finding', sourceId: findingKey, occurrence };\n}\n\nexport function factoryAttentionKey(factoryProjectId: string, identity: FactoryAttentionIdentity): string {\n return `factory:${factoryProjectId}:attention:${identity.kind}:${identity.sourceId}:${identity.occurrence}`;\n}\n\nexport interface FactoryRunBindingSessionAddress {\n factoryProjectId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n}\n\nexport interface FactoryRunBindingAddress extends FactoryRunBindingSessionAddress {\n orgId: string;\n}\n\nexport interface RevokeFactoryRunBindingInput {\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n revokedAt: Date;\n}\n\nexport interface RevokeStaleFactoryRunBindingsInput {\n /** Active bindings created before this instant are revoked regardless of item state. */\n olderThan: Date;\n now: Date;\n}\n\n/**\n * Stages in which a bound run can still act on its work item. Mirrors the\n * non-terminal subset of `FACTORY_RULE_STAGES` (rules/types.ts); bindings for\n * items outside these stages are dead weight in the reconcile walk.\n */\nconst ACTIVE_RUN_BINDING_STAGES: ReadonlySet<string> = new Set(['intake', 'triage', 'planning', 'execute', 'review']);\n\nexport interface RevokeFactoryRunBindingsForWorkItemInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n revokedAt: Date;\n}\n\nexport interface FactoryRunBindingRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n status: 'active' | 'revoked';\n createdAt: Date;\n revokedAt: Date | null;\n}\n\nexport interface FactoryPendingStartRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n kickoffKey: string;\n message: string | null;\n status: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n failureCode: FactoryDispatchFailureCode | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryLeaseClaimInput {\n ownerId: string;\n now: Date;\n leaseExpiresAt: Date;\n limit: number;\n}\n\nexport interface FactoryLeaseIdentity {\n id: string;\n orgId: string;\n factoryProjectId: string;\n ownerId: string;\n}\n\nexport interface FactoryDispatchFailureInput extends FactoryLeaseIdentity {\n now: Date;\n availableAt: Date;\n lastError: string;\n failureCode: FactoryDispatchFailureCode;\n terminal: boolean;\n advanceDeliveryGeneration?: boolean;\n}\n\nexport interface CommitFactoryTransitionInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n expectedRevision: number;\n destinationStage: string;\n actorId: string;\n ingress: { identity: string; triggerType: string; transitionId: string };\n ruleSetVersion: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string };\n /** Arm or disarm autonomy in the same revision-checked update that commits the transition. */\n autonomy?: 'arm' | 'disarm';\n /** Consent-bearing actor behind the flip; their id pre-approves the runs this transition queues. */\n consentedBy?: string;\n /** Triage classification reported by an authenticated triage binding. */\n triageType?: FactoryTriageType;\n /** Record the person's acceptance of this item in the same revision-checked update; a no-op once set. */\n accept?: boolean;\n}\n\nexport type CommitFactoryTransitionResult =\n | { status: 'committed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'replayed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface PrepareFactoryRunStartInput {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n workItem: { id?: string; input: CreateWorkItemInput };\n role: string;\n session: WorkItemSessionInput;\n resourceId: string;\n kickoffKey: string;\n kickoffMessage: string | null;\n}\n\nexport interface PrepareFactoryRunStartResult {\n item: WorkItemRow;\n binding: FactoryRunBindingRecord;\n pendingStart: FactoryPendingStartRecord;\n replayed: boolean;\n}\n\n/** Session ref as accepted from clients — `startedBy` is stamped server-side. */\nexport interface WorkItemSessionInput {\n sessionId: string;\n branch: string;\n threadId: string;\n}\n\nexport type WorkItemSessions = Record<string, WorkItemSessionRef>;\n\nexport interface WorkItemRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n board: string | null;\n externalSource: ExternalWorkItemSource | null;\n parentWorkItemId: string | null;\n title: string;\n stages: WorkItemStage[];\n stageHistory: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n /** Authoritative verdict written by the bound triage run. */\n triageType: FactoryTriageType | null;\n /**\n * When a person first committed this item to the Factory, by starting a run\n * on it or releasing one that was proposed. Projects that withhold auto-run\n * are asking to decide what the Factory picks up, not to approve each step of\n * work they already asked for, so runs on an armed item skip the gate.\n */\n autonomyArmedAt: Date | null;\n /**\n * When a person chose to run this item hands-off: the dispatcher answers its\n * parked plans even while the project's Auto-approve plans switch is off.\n */\n plansPreapprovedAt: Date | null;\n /**\n * When a person first moved this item out of Intake/Triage into working\n * stages. Non-bug items wait for that gesture; once it is recorded the\n * agents may advance the item through Planning and Execute on their own.\n */\n acceptedAt: Date | null;\n /** Denormalized feed counters, maintained by the comments domain via recount. */\n commentCount: number;\n /** Bumps on every feed mutation (create/edit/delete) — the clients' change hint. */\n feedActivityAt: Date | null;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemInput {\n board?: string;\n externalSource?: ExternalWorkItemSource | null;\n parentWorkItemId?: string | null;\n title: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface UpdateWorkItemInput {\n board?: string;\n parentWorkItemId?: string | null;\n title?: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n /** The person chose a hands-off run: stamped once, so a second grant never moves it. */\n plansPreapproved?: true;\n}\n\nexport interface WorkItemPriorState {\n stages: WorkItemStage[];\n sessionRoles: string[];\n}\n\nexport interface UpsertWorkItemResult {\n item: WorkItemRow;\n created: boolean;\n previous: WorkItemPriorState;\n}\n\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board: { type: 'text', nullable: true },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n triage_type: { type: 'text', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n {\n // The unique index leads with `factory_project_id`, so it cannot serve a\n // lookup by the key alone — which is what a platform message has.\n name: 'work_items_source_key_idx',\n columns: ['source_key'],\n },\n ],\n};\n\ninterface WorkItemDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board: string | null;\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n parent_work_item_id: string | null;\n title: string;\n stages: WorkItemStage[];\n stage_history: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n triage_type: FactoryTriageType | null;\n autonomy_armed_at: Date | null;\n plans_preapproved_at: Date | null;\n accepted_at: Date | null;\n comment_count: number;\n feed_activity_at: Date | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n}\n\n/**\n * The one shape a platform id takes in a lookup key, for cards and for the\n * comments mirrored off them alike: whoever writes a second builder reopens the\n * cross-workspace collision the `workspaceId` is here to close.\n */\nexport function externalSourceKey(source: ExternalWorkItemSource | null | undefined): string | null {\n if (!source) return null;\n const workspace = source.workspaceId ? `${source.workspaceId}:` : '';\n return `${source.integrationId}:${source.type}:${workspace}${source.externalId}`;\n}\n\nfunction toWorkItem(row: WorkItemDbRow): WorkItemRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n board: row.board ?? null,\n externalSource: row.external_source,\n parentWorkItemId: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stageHistory: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n triageType: row.triage_type ?? null,\n autonomyArmedAt: row.autonomy_armed_at ?? null,\n plansPreapprovedAt: row.plans_preapproved_at ?? null,\n acceptedAt: row.accepted_at ?? null,\n commentCount: row.comment_count ?? 0,\n feedActivityAt: row.feed_activity_at ?? null,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nconst toRow = toWorkItem;\n\nfunction patchColumns(changes: Partial<WorkItemRow>): Partial<WorkItemDbRow> {\n return {\n ...(changes.board !== undefined ? { board: changes.board } : {}),\n ...(changes.parentWorkItemId !== undefined ? { parent_work_item_id: changes.parentWorkItemId } : {}),\n ...(changes.title !== undefined ? { title: changes.title } : {}),\n ...(changes.stages !== undefined ? { stages: changes.stages } : {}),\n ...(changes.stageHistory !== undefined ? { stage_history: changes.stageHistory } : {}),\n ...(changes.sessions !== undefined ? { sessions: changes.sessions } : {}),\n ...(changes.metadata !== undefined ? { metadata: changes.metadata } : {}),\n ...(changes.triageType !== undefined ? { triage_type: changes.triageType } : {}),\n ...(changes.autonomyArmedAt !== undefined ? { autonomy_armed_at: changes.autonomyArmedAt } : {}),\n ...(changes.acceptedAt !== undefined ? { accepted_at: changes.acceptedAt } : {}),\n ...(changes.revision !== undefined ? { revision: changes.revision } : {}),\n ...(changes.updatedAt !== undefined ? { updated_at: changes.updatedAt } : {}),\n };\n}\n\nfunction emptyPrior(): WorkItemPriorState {\n return { stages: [], sessionRoles: [] };\n}\n\nfunction priorState(row: WorkItemDbRow): WorkItemPriorState {\n return { stages: row.stages, sessionRoles: Object.keys(row.sessions) };\n}\n\nexport class WorkItemRelationError extends Error {\n readonly code = 'invalid_work_item_relation';\n}\n\nexport class WorkItemUpdateConflictError extends Error {\n readonly code = 'work_item_update_conflict';\n\n constructor(readonly reason: 'board' | 'revision') {\n super(`Work item ${reason} precondition failed`);\n }\n}\n\nexport function validateParentRelation(\n projectItems: WorkItemRow[],\n itemId: string | undefined,\n parentWorkItemId: string | null,\n): void {\n if (parentWorkItemId === null) return;\n const byId = new Map(projectItems.map(item => [item.id, item]));\n const parent = byId.get(parentWorkItemId);\n if (!parent) throw new WorkItemRelationError('Related work item not found in this project.');\n if (itemId === parentWorkItemId) throw new WorkItemRelationError('A work item cannot relate to itself.');\n\n const visited = new Set<string>();\n let cursor: WorkItemRow | undefined = parent;\n while (cursor?.parentWorkItemId) {\n if (cursor.parentWorkItemId === itemId) {\n throw new WorkItemRelationError('This relationship would create a cycle.');\n }\n if (visited.has(cursor.id)) throw new WorkItemRelationError('The related work item chain contains a cycle.');\n visited.add(cursor.id);\n cursor = byId.get(cursor.parentWorkItemId);\n }\n}\n\n/**\n * Diff `oldStages` → `newStages` and return the updated history: exited stages\n * get `exitedAt` + `exitedBy` stamped on their open entry, entered stages get\n * a new entry.\n */\nexport function applyStageTransition(\n history: WorkItemStageEntry[],\n oldStages: WorkItemStage[],\n newStages: WorkItemStage[],\n by: string,\n now: Date,\n): WorkItemStageEntry[] {\n const timestamp = now.toISOString();\n const next = history.map(entry => ({ ...entry }));\n for (const stage of oldStages) {\n if (newStages.includes(stage)) continue;\n for (let i = next.length - 1; i >= 0; i--) {\n const entry = next[i]!;\n if (entry.stage === stage && entry.exitedAt === undefined) {\n entry.exitedAt = timestamp;\n entry.exitedBy = by;\n break;\n }\n }\n }\n for (const stage of newStages) {\n if (!oldStages.includes(stage)) next.push({ stage, enteredAt: timestamp, by });\n }\n return next;\n}\n\nexport function stampSessions(sessions: Record<string, WorkItemSessionInput>, by: string): WorkItemSessions {\n return Object.fromEntries(Object.entries(sessions).map(([role, session]) => [role, { ...session, startedBy: by }]));\n}\n\nfunction applyUpdate({\n current,\n userId,\n input,\n}: {\n current: WorkItemDbRow;\n userId: string;\n input: UpdateWorkItemInput;\n}): Partial<WorkItemDbRow> {\n const now = new Date();\n return {\n ...(input.board !== undefined ? { board: input.board } : {}),\n ...(input.parentWorkItemId !== undefined ? { parent_work_item_id: input.parentWorkItemId } : {}),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.stages !== undefined\n ? {\n stages: input.stages,\n stage_history: applyStageTransition(current.stage_history, current.stages, input.stages, userId, now),\n }\n : {}),\n ...(input.sessions !== undefined\n ? { sessions: { ...current.sessions, ...stampSessions(input.sessions, userId) } }\n : {}),\n ...(input.metadata !== undefined\n ? { metadata: input.metadata === null ? null : { ...(current.metadata ?? {}), ...input.metadata } }\n : {}),\n ...(input.plansPreapproved && !current.plans_preapproved_at ? { plans_preapproved_at: now } : {}),\n revision: current.revision + 1,\n updated_at: now,\n };\n}\nconst ATTENTION_RECEIPT_QUERY_BATCH_SIZE = 200;\nconst ATTENTION_RECEIPT_WRITE_BATCH_SIZE = 25;\n\nconst projectRelationLocks = new Map<string, Promise<unknown>>();\n\nfunction withInProcessProjectLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = projectRelationLocks.get(key) ?? Promise.resolve();\n const result = previous.then(fn, fn);\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n projectRelationLocks.set(key, tail);\n void tail.then(() => {\n if (projectRelationLocks.get(key) === tail) projectRelationLocks.delete(key);\n });\n return result;\n}\n\n/** Source key a decision materializes, used to purge governance rows when the item is deleted. */\nfunction decisionSourceKey(decision: unknown): string | null {\n if (typeof decision !== 'object' || decision === null) return null;\n const record = decision as Record<string, unknown>;\n if (record.type !== 'upsertLinkedWorkItem' || typeof record.sourceKey !== 'string') return null;\n return record.sourceKey;\n}\n\nfunction deferredDecisionType(decision: FactoryDeferredDecisionRecord): string | undefined {\n return typeof decision.decision.type === 'string' ? decision.decision.type : undefined;\n}\n\nfunction ingressWasAccepted(row: GovernanceDbRow | null): boolean {\n if (!row || typeof row.result !== 'object' || row.result === null || Array.isArray(row.result)) return false;\n return 'status' in row.result && row.result.status === 'accepted';\n}\n\nconst FACTORY_GOVERNANCE_SCHEMAS: CollectionSchema[] = [\n {\n name: 'factory_rule_ingress',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n identity: { type: 'text' },\n trigger_type: { type: 'text' },\n transition_id: { type: 'text' },\n result: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_rule_ingress_tenant_identity_unique', columns: ['org_id', 'factory_project_id', 'identity'] },\n ],\n },\n {\n name: 'factory_rule_evaluations',\n columns: {\n id: { type: 'uuid-pk' },\n ingress_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n rule_set_version: { type: 'text' },\n expected_revision: { type: 'integer', nullable: true },\n outcome: { type: 'text' },\n code: { type: 'text', nullable: true },\n reason: { type: 'text', nullable: true },\n causal_chain: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_deferred_decisions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n evaluation_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n source_key: { type: 'text', nullable: true },\n idempotency_key: { type: 'text' },\n effect_ordinal: { type: 'integer' },\n effect_hash: { type: 'text' },\n causal_chain: { type: 'json' },\n actor: { type: 'json', nullable: true },\n decision: { type: 'json' },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n delivery_generation: { type: 'integer', default: 0 },\n failure_occurrence: { type: 'integer', default: 0 },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n failure_code: { type: 'text', nullable: true },\n approved_at: { type: 'timestamp', nullable: true },\n approved_by: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_deferred_decisions_tenant_key_unique',\n columns: ['org_id', 'factory_project_id', 'idempotency_key'],\n },\n ],\n indexes: [\n { name: 'factory_deferred_decisions_claim_idx', columns: ['status', 'created_at'] },\n {\n name: 'factory_deferred_decisions_tenant_status_created_idx',\n columns: ['org_id', 'factory_project_id', 'status', 'created_at', 'id'],\n },\n {\n name: 'factory_deferred_decisions_tenant_status_failed_idx',\n columns: ['org_id', 'factory_project_id', 'status', 'updated_at', 'id'],\n },\n ],\n },\n {\n name: 'factory_supervisor_findings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n finding_key: { type: 'text' },\n occurrence: { type: 'integer' },\n finding: { type: 'json' },\n opened_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n resolved_at: { type: 'timestamp', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_supervisor_findings_project_key_unique',\n columns: ['org_id', 'factory_project_id', 'finding_key'],\n },\n ],\n indexes: [\n {\n name: 'factory_supervisor_findings_project_open_idx',\n columns: ['org_id', 'factory_project_id', 'resolved_at', 'updated_at', 'id'],\n },\n ],\n },\n {\n name: 'factory_attention_receipts',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n user_id: { type: 'text' },\n kind: { type: 'text' },\n source_id: { type: 'text' },\n occurrence: { type: 'integer' },\n state: { type: 'text' },\n read_at: { type: 'timestamp' },\n archived_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_attention_receipts_user_source_unique',\n columns: ['org_id', 'factory_project_id', 'user_id', 'kind', 'source_id', 'occurrence'],\n },\n ],\n indexes: [\n {\n name: 'factory_attention_receipts_user_state_idx',\n columns: ['org_id', 'factory_project_id', 'user_id', 'state'],\n },\n {\n name: 'factory_attention_receipts_source_idx',\n columns: ['org_id', 'factory_project_id', 'kind', 'source_id', 'occurrence'],\n },\n ],\n },\n {\n name: 'factory_run_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n role: { type: 'text' },\n thread_id: { type: 'text' },\n resource_id: { type: 'text' },\n session_id: { type: 'text' },\n branch: { type: 'text' },\n status: { type: 'text' },\n created_at: { type: 'timestamp' },\n revoked_at: { type: 'timestamp', nullable: true },\n },\n indexes: [\n // Exact-address lookups run on every processor message; status filter is\n // applied on top of the address columns.\n {\n name: 'factory_run_bindings_session_idx',\n columns: ['factory_project_id', 'thread_id', 'resource_id', 'session_id'],\n },\n // Restart reconciler enumerates active bindings across all tenants.\n { name: 'factory_run_bindings_status_idx', columns: ['status'] },\n ],\n },\n {\n name: 'factory_tool_result_cursors',\n columns: {\n binding_id: { type: 'text', primaryKey: true },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n last_message_id: { type: 'text' },\n last_message_created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_pending_starts',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n binding_id: { type: 'text' },\n kickoff_key: { type: 'text' },\n message: { type: 'text', nullable: true },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n failure_code: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_pending_starts_tenant_kickoff_unique',\n columns: ['org_id', 'factory_project_id', 'kickoff_key'],\n },\n ],\n indexes: [{ name: 'factory_pending_starts_claim_idx', columns: ['status', 'created_at'] }],\n },\n];\n\ninterface GovernanceDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n created_at: Date;\n [key: string]: unknown;\n}\n\nfunction toBinding(row: GovernanceDbRow): FactoryRunBindingRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n workItemId: String(row.work_item_id),\n role: String(row.role),\n threadId: String(row.thread_id),\n resourceId: String(row.resource_id),\n sessionId: String(row.session_id),\n branch: String(row.branch),\n status: row.status as FactoryRunBindingRecord['status'],\n createdAt: row.created_at,\n revokedAt: (row.revoked_at as Date | null) ?? null,\n };\n}\nfunction toDeferredDecision(row: GovernanceDbRow): FactoryDeferredDecisionRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n evaluationId: String(row.evaluation_id),\n workItemId: row.work_item_id === null || row.work_item_id === undefined ? null : String(row.work_item_id),\n idempotencyKey: String(row.idempotency_key),\n effectOrdinal: Number(row.effect_ordinal),\n effectHash: String(row.effect_hash),\n causalChain: (row.causal_chain as FactoryDeferredDecisionRecord['causalChain']) ?? [],\n actor: (row.actor as Record<string, unknown> | null) ?? null,\n decision: row.decision as Record<string, unknown>,\n status: row.status as FactoryDispatchStatus,\n attempts: Number(row.attempts),\n deliveryGeneration: Number(row.delivery_generation ?? 0),\n failureOccurrence: Number(row.failure_occurrence ?? 0),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n failureCode: isFactoryDispatchFailureCode(row.failure_code) ? row.failure_code : null,\n approvedAt: (row.approved_at as Date | null) ?? null,\n approvedBy: (row.approved_by as string | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\nfunction attentionReceiptKind(value: unknown): FactoryAttentionKind {\n if (\n value === 'automation-failed' ||\n value === 'automation-proposed' ||\n value === 'mention' ||\n value === 'activity' ||\n value === 'supervisor-finding'\n ) {\n return value;\n }\n throw new Error(`Unsupported attention receipt kind '${String(value)}'.`);\n}\n\nfunction toSupervisorFinding(row: GovernanceDbRow): FactorySupervisorFindingRecord {\n return {\n id: row.id,\n orgId: String(row.org_id),\n factoryProjectId: String(row.factory_project_id),\n findingKey: String(row.finding_key),\n occurrence: Number(row.occurrence),\n finding: row.finding as Record<string, unknown>,\n openedAt: row.opened_at as Date,\n updatedAt: row.updated_at as Date,\n resolvedAt: (row.resolved_at as Date | null) ?? null,\n };\n}\n\nfunction attentionReceiptState(value: unknown): FactoryAttentionReceiptState {\n if (value === 'read' || value === 'archived') return value;\n throw new Error(`Unsupported attention receipt state '${String(value)}'.`);\n}\n\nfunction toAttentionReceipt(row: GovernanceDbRow): FactoryAttentionReceiptRecord {\n if (typeof row.source_id !== 'string' || !row.source_id) {\n throw new Error('Attention receipt source_id must be a non-empty string.');\n }\n const occurrence = Number(row.occurrence);\n if (!Number.isSafeInteger(occurrence) || occurrence < 0) {\n throw new Error('Attention receipt occurrence must be a non-negative safe integer.');\n }\n if (!(row.read_at instanceof Date)) throw new Error('Attention receipt read_at must be a timestamp.');\n const archivedAt = row.archived_at;\n if (archivedAt !== null && archivedAt !== undefined && !(archivedAt instanceof Date)) {\n throw new Error('Attention receipt archived_at must be a timestamp or null.');\n }\n if (!(row.created_at instanceof Date)) throw new Error('Attention receipt created_at must be a timestamp.');\n if (!(row.updated_at instanceof Date)) throw new Error('Attention receipt updated_at must be a timestamp.');\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n userId: String(row.user_id),\n kind: attentionReceiptKind(row.kind),\n sourceId: row.source_id,\n occurrence,\n state: attentionReceiptState(row.state),\n readAt: row.read_at,\n archivedAt: archivedAt ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\nfunction toPendingStart(row: GovernanceDbRow): FactoryPendingStartRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n bindingId: String(row.binding_id),\n kickoffKey: String(row.kickoff_key),\n message: (row.message as string | null) ?? null,\n status: row.status as FactoryPendingStartRecord['status'],\n attempts: Number(row.attempts),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n failureCode: (row.failure_code as FactoryDispatchFailureCode | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\n\n/** The project whose attention list a write just changed. */\nexport interface FactoryAttentionScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport class WorkItemsStorage extends FactoryStorageDomain {\n #attentionChanged: (scope: FactoryAttentionScope) => void = () => {};\n\n constructor() {\n super('work-items');\n }\n\n /**\n * Wired once at boot. Every write below that changes what this project's\n * attention list projects announces it here — the one place a new such write\n * has to remember, since clients stop polling while their stream is up.\n */\n onAttentionChanged(listener: (scope: FactoryAttentionScope) => void): void {\n this.#attentionChanged = listener;\n }\n\n async init(): Promise<void> {\n // The comment schemas are co-registered so the delete cascade below can\n // purge feed rows regardless of domain init order.\n await this.ensureCollections([\n WORK_ITEMS_SCHEMA,\n ...FACTORY_GOVERNANCE_SCHEMAS,\n WORK_ITEM_COMMENTS_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_ACTIVITY_SCHEMA,\n ]);\n await this.repairLegacyAttentionState();\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_items', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #countRows(collection: string, where: CollectionWhere): Promise<number> {\n const count = this.#db.count;\n if (!count) throw new Error('[WorkItemsStorage] storage backend does not support collection counts.');\n return count.call(this.#db, collection, where);\n }\n\n async syncSupervisorFindings(input: {\n orgId: string;\n factoryProjectId: string;\n findings: FactoryHealthFinding[];\n now: Date;\n }): Promise<void> {\n const changed = await this.#withProjectRelationTransaction(input.orgId, input.factoryProjectId, async ops => {\n let changed = false;\n const existingOpen = await ops.findMany<GovernanceDbRow>('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n resolved_at: null,\n });\n const currentKeys = new Set(input.findings.map(finding => finding.id));\n for (const row of existingOpen) {\n if (!currentKeys.has(String(row.finding_key))) {\n await ops.updateAtomic<GovernanceDbRow>(\n 'factory_supervisor_findings',\n { id: row.id, resolved_at: null },\n () => ({ resolved_at: input.now, updated_at: input.now }),\n );\n changed = true;\n }\n }\n const openByKey = new Map(existingOpen.map(row => [String(row.finding_key), row]));\n for (const finding of input.findings) {\n const row =\n openByKey.get(finding.id) ??\n (await ops.findOne<GovernanceDbRow>('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n finding_key: finding.id,\n }));\n if (!row) {\n await ops.insertOne<GovernanceDbRow>('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n finding_key: finding.id,\n occurrence: 0,\n finding,\n opened_at: input.now,\n updated_at: input.now,\n resolved_at: null,\n });\n changed = true;\n continue;\n }\n const reopening = row.resolved_at !== null;\n const findingChanged = stableJson(row.finding) !== stableJson(finding);\n if (!reopening && !findingChanged) continue;\n await ops.updateAtomic<GovernanceDbRow>('factory_supervisor_findings', { id: row.id }, current => ({\n finding,\n occurrence: Number(current.occurrence) + (current.resolved_at !== null ? 1 : 0),\n opened_at: current.resolved_at !== null ? input.now : current.opened_at,\n updated_at: input.now,\n resolved_at: null,\n }));\n changed = true;\n }\n return changed;\n });\n if (changed) this.#attentionChanged?.({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n }\n\n async listSupervisorFindingPage(input: {\n orgId: string;\n factoryProjectId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<{ rows: FactorySupervisorFindingRecord[]; hasMore: boolean }> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_supervisor_findings',\n { org_id: input.orgId, factory_project_id: input.factoryProjectId, resolved_at: null },\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.occurredAt, input.before.id] } } : {}),\n },\n );\n return { rows: rows.slice(0, input.limit).map(toSupervisorFinding), hasMore: rows.length > input.limit };\n }\n\n async countOpenSupervisorFindings(input: { orgId: string; factoryProjectId: string }): Promise<number> {\n return this.#countRows('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n resolved_at: null,\n });\n }\n\n async #withProjectRelationTransaction<T>(\n orgId: string,\n factoryProjectId: string,\n fn: (ops: FactoryStorageOps) => Promise<T>,\n ): Promise<T> {\n const key = `work-items:${orgId}:${factoryProjectId}`;\n return withInProcessProjectLock(key, () => this.storage.withTransaction(fn, { isolationLevel: 'serializable' }));\n }\n\n async #claimLeases<T>(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryLeaseClaimInput,\n map: (row: GovernanceDbRow) => T,\n ): Promise<T[]> {\n const claim = () =>\n this.storage.withTransaction(async ops => {\n // Bounded candidate window: only rows in claimable/expirable statuses,\n // oldest first. Terminal rows (sent/succeeded/failed) accumulate over a\n // deployment's lifetime and must never be scanned per dispatch tick.\n const candidates = await ops.findMany<GovernanceDbRow>(\n table,\n { status: { in: ['pending', 'retry', 'leased'] } },\n { orderBy: [['created_at', 'asc']], limit: Math.max(input.limit * 5, 50) },\n );\n const claimed: T[] = [];\n for (const candidate of candidates) {\n if (claimed.length >= input.limit) break;\n const availableAt = new Date(candidate.available_at as Date | string).getTime();\n const leaseExpiresAt = candidate.lease_expires_at\n ? new Date(candidate.lease_expires_at as Date | string).getTime()\n : 0;\n const claimable =\n (candidate.status === 'pending' || candidate.status === 'retry') && availableAt <= input.now.getTime();\n const expired = candidate.status === 'leased' && leaseExpiresAt <= input.now.getTime();\n if (!claimable && !expired) continue;\n let didClaim = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(table, { id: candidate.id }, current => {\n const currentAvailable = new Date(current.available_at as Date | string).getTime();\n const currentExpiry = current.lease_expires_at\n ? new Date(current.lease_expires_at as Date | string).getTime()\n : 0;\n const currentClaimable =\n (current.status === 'pending' || current.status === 'retry') && currentAvailable <= input.now.getTime();\n const currentExpired = current.status === 'leased' && currentExpiry <= input.now.getTime();\n if (!currentClaimable && !currentExpired) return null;\n didClaim = true;\n return {\n status: 'leased',\n attempts: Number(current.attempts) + 1,\n lease_owner: input.ownerId,\n lease_expires_at: input.leaseExpiresAt,\n updated_at: input.now,\n };\n });\n if (didClaim && row) claimed.push(map(row));\n }\n return claimed;\n });\n return claim();\n }\n\n async #renewLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n leaseExpiresAt: Date,\n ): Promise<boolean> {\n let renewed = false;\n await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n renewed = true;\n return { lease_expires_at: leaseExpiresAt, updated_at: new Date() };\n },\n );\n return renewed;\n }\n\n async #completeLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<GovernanceDbRow | null> {\n let completed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n completed = true;\n return {\n status: table === 'factory_pending_starts' ? 'sent' : 'succeeded',\n lease_owner: null,\n lease_expires_at: null,\n completed_at: now,\n updated_at: now,\n };\n },\n );\n return completed ? row : null;\n }\n\n async #failLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryDispatchFailureInput,\n ): Promise<GovernanceDbRow | null> {\n let failed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: input.id, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== input.ownerId) return null;\n failed = true;\n return {\n status: input.terminal ? 'failed' : 'retry',\n ...(table === 'factory_deferred_decisions' && !input.terminal && input.advanceDeliveryGeneration !== false\n ? { delivery_generation: Number(current.delivery_generation ?? 0) + 1 }\n : {}),\n available_at: input.availableAt,\n lease_owner: null,\n lease_expires_at: null,\n last_error: input.lastError,\n failure_code: input.failureCode,\n completed_at: input.terminal ? input.now : null,\n ...(table === 'factory_deferred_decisions' && input.terminal\n ? { failure_occurrence: Number(current.failure_occurrence ?? 0) + 1 }\n : {}),\n updated_at: input.now,\n };\n },\n );\n return failed ? row : null;\n }\n\n async #listWithOps(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<WorkItemRow[]> {\n const rows = await ops.findMany<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n },\n );\n return rows.map(toWorkItem);\n }\n\n /**\n * List the org's work items for a project, newest first. Ordered on `created_at` with an id\n * tiebreak so the order is stable: `updated_at` moves under every write, which makes it useless\n * as a cursor and non-deterministic for the callers that iterate this list.\n */\n async list({ orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }): Promise<WorkItemRow[]> {\n return this.#listWithOps(this.#db, orgId, factoryProjectId);\n }\n\n async listByIds({\n orgId,\n factoryProjectId,\n ids,\n }: {\n orgId: string;\n factoryProjectId: string;\n ids: string[];\n }): Promise<WorkItemRow[]> {\n if (ids.length === 0) return [];\n const rows = await this.#db.findMany<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n id: { in: [...new Set(ids)] },\n });\n return rows.map(toWorkItem);\n }\n\n /**\n * Strip every ref to a retired session; matching happens in app code because\n * `findMany` cannot reach inside the `sessions` JSON column.\n * ponytail: org-wide scan per session delete; JSON-path query if it measures.\n */\n async clearSessionReferences({ orgId, sessionId }: { orgId: string; sessionId: string }): Promise<number> {\n const rows = await this.#db.findMany<WorkItemDbRow>('work_items', { org_id: orgId });\n const holding = rows.filter(row => Object.values(row.sessions).some(ref => ref.sessionId === sessionId));\n let cleared = 0;\n for (const row of holding) {\n let changed = false;\n await this.#db.updateAtomic<WorkItemDbRow>('work_items', { id: row.id }, current => {\n const kept = Object.entries(current.sessions).filter(([, ref]) => ref.sessionId !== sessionId);\n if (kept.length === Object.keys(current.sessions).length) return null;\n changed = true;\n return { sessions: Object.fromEntries(kept), revision: current.revision + 1, updated_at: new Date() };\n });\n if (changed) cleared += 1;\n }\n return cleared;\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n return row ? toWorkItem(row) : null;\n }\n\n /**\n * Resolve the card a platform thread created, given only its external source.\n * Bare of org/project because an inbound platform message carries neither: an\n * unlinked sender has no tenant. Tenant safety rides on the key's\n * `workspaceId` instead. Ambiguous matches resolve to nothing, not a guess.\n */\n async getBySource(source: ExternalWorkItemSource): Promise<WorkItemRow | null> {\n const rows = await this.#db.findMany<WorkItemDbRow>('work_items', { source_key: externalSourceKey(source) });\n return rows.length === 1 ? toWorkItem(rows[0]!) : null;\n }\n\n async getForProject(orgId: string, factoryProjectId: string, id: string): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', {\n id,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row ? toRow(row) : null;\n }\n\n async getTransitionResultByIngress(\n orgId: string,\n factoryProjectId: string,\n identity: string,\n ): Promise<Record<string, unknown> | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n identity,\n });\n return (row?.result as Record<string, unknown> | undefined) ?? null;\n }\n\n async commitTransition(input: CommitFactoryTransitionInput): Promise<CommitFactoryTransitionResult> {\n const commit = (): Promise<CommitFactoryTransitionResult> =>\n this.storage.withTransaction<CommitFactoryTransitionResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior)\n return {\n status: 'replayed',\n item: await this.getForProject(input.orgId, input.factoryProjectId, input.workItemId),\n result: prior.result as Record<string, unknown>,\n };\n\n const now = new Date();\n let item: WorkItemRow | null = null;\n let code: string | null = null;\n let reason: string | null = null;\n let result: Record<string, unknown>;\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n },\n row => {\n const existing = toRow(row);\n item = existing;\n if (existing.revision !== input.expectedRevision) {\n code = 'stale';\n reason = 'The work item changed before this transition committed.';\n return null;\n }\n if (input.evaluation.outcome === 'rejected') {\n code = input.evaluation.code;\n reason = input.evaluation.reason;\n return null;\n }\n const arm = input.autonomy === 'arm' && !existing.autonomyArmedAt;\n const disarm = input.autonomy === 'disarm' && existing.autonomyArmedAt !== null;\n const accept = input.accept === true && !existing.acceptedAt;\n const triageType = existing.triageType ?? input.triageType ?? null;\n const classified = triageType !== existing.triageType;\n if (existing.stages.length === 1 && existing.stages[0] === input.destinationStage) {\n // Classification is part of a terminal handoff, so unlike an\n // autonomy flip alone it is a revisioned work-item change.\n return arm || disarm || accept || classified\n ? patchColumns({\n ...(arm ? { autonomyArmedAt: now } : {}),\n ...(disarm ? { autonomyArmedAt: null } : {}),\n ...(accept ? { acceptedAt: now } : {}),\n ...(classified ? { triageType, revision: existing.revision + 1, updatedAt: now } : {}),\n })\n : null;\n }\n return patchColumns({\n ...(arm ? { autonomyArmedAt: now } : {}),\n ...(disarm ? { autonomyArmedAt: null } : {}),\n ...(accept ? { acceptedAt: now } : {}),\n ...(classified ? { triageType } : {}),\n stages: [input.destinationStage],\n stageHistory: applyStageTransition(\n existing.stageHistory,\n existing.stages,\n [input.destinationStage],\n input.actorId,\n now,\n ),\n revision: existing.revision + 1,\n updatedAt: now,\n });\n },\n );\n if (updated) item = toRow(updated);\n if (!item) {\n code = input.evaluation.outcome === 'rejected' ? input.evaluation.code : 'invalid_transition';\n reason = input.evaluation.outcome === 'rejected' ? input.evaluation.reason : 'Work item not found.';\n }\n const outcome: 'accepted' | 'rejected' =\n item && code === null && input.evaluation.outcome === 'accepted' ? 'accepted' : 'rejected';\n result =\n outcome === 'accepted'\n ? {\n status: 'accepted',\n transitionId: input.ingress.transitionId,\n itemId: item!.id,\n revision: item!.revision,\n stage: input.destinationStage,\n decisions: input.evaluation.outcome === 'accepted' ? input.evaluation.decisions : [],\n }\n : { status: 'rejected', transitionId: input.ingress.transitionId, itemId: input.workItemId, code, reason };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.transitionId,\n result,\n created_at: now,\n });\n if (item) {\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item.id,\n rule_set_version: input.ruleSetVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: now,\n });\n if (outcome === 'accepted' && input.evaluation.outcome === 'accepted') {\n for (const [index, decision] of input.evaluation.decisions.entries()) {\n // Consent pre-approves only the runs this same commit queues.\n const approvedBy = decision.type === 'invokeSkill' ? (input.consentedBy ?? null) : null;\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item.id,\n source_key: decisionSourceKey(decision),\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: index,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: null,\n decision,\n status: 'pending',\n attempts: 0,\n delivery_generation: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n approved_at: approvedBy ? now : null,\n approved_by: approvedBy,\n completed_at: null,\n created_at: new Date(now.getTime() + index),\n updated_at: now,\n });\n }\n }\n }\n return { status: 'committed', item, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async commitRuleEvaluation(input: CommitFactoryRuleEvaluationInput): Promise<CommitFactoryRuleEvaluationResult> {\n const commit = () =>\n this.storage.withTransaction<CommitFactoryRuleEvaluationResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior) {\n const result = prior.result as Record<string, unknown>;\n const decisions = Array.isArray(result.decisions) ? result.decisions : [];\n const evaluation = await ops.findOne<GovernanceDbRow>('factory_rule_evaluations', { ingress_id: prior.id });\n for (const decision of decisions) {\n if (\n !evaluation ||\n !decision ||\n typeof decision !== 'object' ||\n (decision as Record<string, unknown>).type !== 'upsertLinkedWorkItem' ||\n typeof (decision as Record<string, unknown>).sourceKey !== 'string' ||\n typeof (decision as Record<string, unknown>).idempotencyKey !== 'string'\n ) {\n continue;\n }\n const materialization = decision as Record<string, unknown> & { sourceKey: string; idempotencyKey: string };\n const item = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: materialization.sourceKey,\n });\n if (item) continue;\n await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n idempotency_key: materialization.idempotencyKey,\n },\n current =>\n current.status === 'succeeded'\n ? {\n status: 'retry',\n attempts: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n updated_at: input.now,\n }\n : null,\n );\n }\n return { status: 'replayed' as const, result };\n }\n const itemRow = input.workItemId\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : null;\n if (input.workItemId !== null && !itemRow) return { status: 'missing' as const };\n const item = itemRow ? toRow(itemRow) : null;\n const stale = item !== null && item.revision !== input.expectedRevision;\n const outcome = stale ? 'rejected' : input.outcome.status;\n const code = stale ? 'stale' : (input.outcome.code ?? null);\n const reason = stale\n ? 'The work item changed before this rule evaluation committed.'\n : (input.outcome.reason ?? null);\n const decisions = outcome === 'accepted' ? input.decisions : [];\n const result = {\n status: outcome,\n itemId: item?.id ?? null,\n revision: item?.revision ?? null,\n code,\n reason,\n decisions,\n };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.identity,\n result,\n created_at: input.now,\n });\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item?.id ?? null,\n rule_set_version: input.ruleSetVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: input.now,\n });\n for (const [effectOrdinal, decision] of decisions.entries()) {\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item?.id ?? null,\n source_key: decisionSourceKey(decision),\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: effectOrdinal,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: input.actor,\n decision,\n status: 'pending',\n attempts: 0,\n delivery_generation: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: new Date(input.now.getTime() + effectOrdinal),\n updated_at: input.now,\n });\n }\n return { status: 'committed' as const, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async getToolResultCursor(\n orgId: string,\n factoryProjectId: string,\n bindingId: string,\n ): Promise<FactoryToolResultCursorRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_tool_result_cursors', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n binding_id: bindingId,\n });\n return row\n ? {\n bindingId: String(row.binding_id),\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n lastMessageId: String(row.last_message_id),\n lastMessageCreatedAt: row.last_message_created_at as Date,\n updatedAt: row.updated_at as Date,\n }\n : null;\n }\n\n async advanceToolResultCursor(cursor: FactoryToolResultCursorRecord): Promise<void> {\n const current = await this.getToolResultCursor(cursor.orgId, cursor.factoryProjectId, cursor.bindingId);\n if (current && current.lastMessageCreatedAt > cursor.lastMessageCreatedAt) return;\n await this.#db.upsertOne<GovernanceDbRow>('factory_tool_result_cursors', ['binding_id'], {\n binding_id: cursor.bindingId,\n org_id: cursor.orgId,\n factory_project_id: cursor.factoryProjectId,\n last_message_id: cursor.lastMessageId,\n last_message_created_at: cursor.lastMessageCreatedAt,\n updated_at: cursor.updatedAt,\n });\n }\n\n async listDeferredDecisions(orgId: string, factoryProjectId: string): Promise<FactoryDeferredDecisionRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toDeferredDecision);\n }\n\n /** Read a bounded newest-first status page without exposing another tenant. */\n async listDeferredDecisionPage(input: FactoryDeferredDecisionPageInput): Promise<FactoryDeferredDecisionPage> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n ...(input.statuses ? { status: { in: input.statuses } } : {}),\n },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.createdAt, input.before.id] } } : {}),\n },\n );\n return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };\n }\n\n /** Newest-parked-first keyset over one status, on the `updated_at` the status was stamped. */\n async listDecisionPageByStatus(input: FactoryDecisionStatusPageInput): Promise<FactoryDeferredDecisionPage> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n status: input.status,\n },\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.occurredAt, input.before.id] } } : {}),\n },\n );\n return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };\n }\n\n async countDeferredDecisionsByStatuses({\n orgId,\n factoryProjectId,\n statuses,\n }: {\n orgId: string;\n factoryProjectId: string;\n statuses: FactoryDispatchStatus[];\n }): Promise<number> {\n return this.#countRows('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n status: { in: statuses },\n });\n }\n\n async getDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_deferred_decisions', {\n id: decisionId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row ? toDeferredDecision(row) : null;\n }\n\n async listAttentionReceipts({\n orgId,\n factoryProjectId,\n userId,\n identities,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n identities: FactoryAttentionIdentity[];\n }): Promise<FactoryAttentionReceiptRecord[]> {\n if (identities.length === 0) return [];\n const requested = new Set(\n identities.map(identity => `${identity.kind}\\0${identity.sourceId}\\0${identity.occurrence}`),\n );\n const sourceIds = [...new Set(identities.map(identity => identity.sourceId))];\n const kinds = [...new Set(identities.map(identity => identity.kind))];\n const receipts: FactoryAttentionReceiptRecord[] = [];\n for (let index = 0; index < sourceIds.length; index += ATTENTION_RECEIPT_QUERY_BATCH_SIZE) {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n user_id: userId,\n kind: { in: kinds },\n source_id: { in: sourceIds.slice(index, index + ATTENTION_RECEIPT_QUERY_BATCH_SIZE) },\n });\n receipts.push(\n ...rows\n .map(toAttentionReceipt)\n .filter(receipt => requested.has(`${receipt.kind}\\0${receipt.sourceId}\\0${receipt.occurrence}`)),\n );\n }\n return receipts;\n }\n\n async countAttentionReceipts({\n orgId,\n factoryProjectId,\n userId,\n kind,\n state,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n kind: FactoryAttentionKind;\n state?: FactoryAttentionReceiptState;\n }): Promise<number> {\n return this.#countRows('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n user_id: userId,\n kind,\n ...(state ? { state } : {}),\n });\n }\n\n async deleteAttentionReceipts({\n orgId,\n factoryProjectId,\n userId,\n identities,\n }: {\n orgId: string;\n factoryProjectId: string;\n /** Restrict to one user's receipts (a removed mention must keep other users' read state). */\n userId?: string;\n identities: FactoryAttentionIdentity[];\n }): Promise<void> {\n const unique = [\n ...new Map(\n identities.map(identity => [`${identity.kind}\\0${identity.sourceId}\\0${identity.occurrence}`, identity]),\n ).values(),\n ];\n for (let index = 0; index < unique.length; index += ATTENTION_RECEIPT_WRITE_BATCH_SIZE) {\n await Promise.all(\n unique.slice(index, index + ATTENTION_RECEIPT_WRITE_BATCH_SIZE).map(identity =>\n this.#db.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(userId ? { user_id: userId } : {}),\n kind: identity.kind,\n source_id: identity.sourceId,\n occurrence: identity.occurrence,\n }),\n ),\n );\n }\n }\n\n async setAttentionReceipt(input: SetAttentionReceiptInput): Promise<FactoryAttentionReceiptRecord | null> {\n return this.#retryAttentionReceiptWrite(() =>\n this.storage.withTransaction(ops => this.#setAttentionReceiptWithOps(ops, input)),\n );\n }\n\n async #retryAttentionReceiptWrite<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return write();\n }\n }\n\n /**\n * Per-kind currency predicate: a receipt may only target a source that still\n * projects an attention item FOR THIS USER — otherwise the route answers\n * 409. Without the mention-row check, any member could write receipts\n * against arbitrary comment ids and permanently skew their own badge math.\n */\n async #attentionSourceIsCurrent(\n ops: FactoryStorageOps,\n {\n orgId,\n factoryProjectId,\n userId,\n identity,\n }: { orgId: string; factoryProjectId: string; userId: string; identity: FactoryAttentionIdentity },\n ): Promise<boolean> {\n if (identity.kind === 'automation-failed') {\n let currentOccurrence = false;\n const decision = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: identity.sourceId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n currentOccurrence =\n current.status === 'failed' && Number(current.failure_occurrence ?? 0) === identity.occurrence;\n return null;\n },\n );\n return Boolean(decision) && currentOccurrence;\n }\n if (identity.kind === 'automation-proposed') {\n let parked = false;\n const decision = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: identity.sourceId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n parked = current.status === 'proposed' && identity.occurrence === 0;\n return null;\n },\n );\n return Boolean(decision) && parked;\n }\n if (identity.kind === 'activity') {\n // Occurrence-exact: a bump since the read makes that receipt stale, and\n // the route answers 409. Scoped to this user or every badge would skew.\n const activity = await ops.findOne('work_item_activity', {\n work_item_id: identity.sourceId,\n participant_id: userId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n occurrence: identity.occurrence,\n });\n return activity !== null;\n }\n if (identity.kind === 'supervisor-finding') {\n const finding = await ops.findOne('factory_supervisor_findings', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n finding_key: identity.sourceId,\n occurrence: identity.occurrence,\n resolved_at: null,\n });\n return finding !== null;\n }\n if (identity.occurrence !== 0) return false;\n const mention = await ops.findOne('work_item_comment_mentions', {\n comment_id: identity.sourceId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n mentioned_kind: 'user',\n mentioned_id: userId,\n });\n if (!mention) return false;\n const comment = await ops.findOne('work_item_comments', {\n id: identity.sourceId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n deleted_at: null,\n });\n return comment !== null;\n }\n\n async #setAttentionReceiptWithOps(\n ops: FactoryStorageOps,\n { orgId, factoryProjectId, userId, identity, action, now }: SetAttentionReceiptInput,\n ): Promise<FactoryAttentionReceiptRecord | null> {\n if (!(await this.#attentionSourceIsCurrent(ops, { orgId, factoryProjectId, userId, identity }))) return null;\n\n const where = {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n user_id: userId,\n kind: identity.kind,\n source_id: identity.sourceId,\n occurrence: identity.occurrence,\n };\n const existing = await ops.findOne<GovernanceDbRow>('factory_attention_receipts', where);\n if (!existing) {\n return toAttentionReceipt(\n await ops.insertOne<GovernanceDbRow>('factory_attention_receipts', {\n ...where,\n state: action === 'archive' ? 'archived' : 'read',\n read_at: now,\n archived_at: action === 'archive' ? now : null,\n created_at: now,\n updated_at: now,\n }),\n );\n }\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_attention_receipts',\n { id: existing.id, ...where },\n current => {\n const preserveArchive = action === 'read' && current.state === 'archived';\n const archived = action === 'archive' || preserveArchive;\n return {\n state: archived ? 'archived' : 'read',\n read_at: current.read_at,\n archived_at: action === 'archive' ? now : archived ? (current.archived_at ?? now) : null,\n updated_at: now,\n };\n },\n );\n return row ? toAttentionReceipt(row) : null;\n }\n\n async markAttentionReceiptsRead({\n orgId,\n factoryProjectId,\n userId,\n identities,\n now,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n identities: FactoryAttentionIdentity[];\n now: Date;\n }): Promise<void> {\n const uniqueIdentities = [\n ...new Map(\n identities.map(identity => [`${identity.kind}\\0${identity.sourceId}\\0${identity.occurrence}`, identity]),\n ).values(),\n ];\n for (let index = 0; index < uniqueIdentities.length; index += ATTENTION_RECEIPT_WRITE_BATCH_SIZE) {\n const batch = uniqueIdentities.slice(index, index + ATTENTION_RECEIPT_WRITE_BATCH_SIZE);\n await this.#retryAttentionReceiptWrite(() =>\n this.storage.withTransaction(async ops => {\n for (const identity of batch) {\n await this.#setAttentionReceiptWithOps(ops, {\n orgId,\n factoryProjectId,\n userId,\n identity,\n action: 'read',\n now,\n });\n }\n }),\n );\n }\n }\n\n async claimDeferredDecisions(input: FactoryLeaseClaimInput): Promise<FactoryDeferredDecisionRecord[]> {\n return this.#claimLeases('factory_deferred_decisions', input, toDeferredDecision);\n }\n\n async renewDeferredDecisionLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_deferred_decisions', identity, leaseExpiresAt);\n }\n\n async completeDeferredDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#completeLease('factory_deferred_decisions', identity, now);\n return row ? toDeferredDecision(row) : null;\n }\n\n async failDeferredDecision(input: FactoryDispatchFailureInput): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#failLease('factory_deferred_decisions', input);\n if (!row) return null;\n const record = toDeferredDecision(row);\n // A retryable failure surfaces nothing; only a terminal one mints an item.\n if (input.terminal) this.#attentionChanged(record);\n return record;\n }\n\n /** Park a claimed effect for human approval; the dispatcher never claims `proposed` rows. */\n async proposeDeferredDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n let proposed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n proposed = true;\n return {\n status: 'proposed',\n // The claim that parked it spent no effect, so it costs no attempt.\n attempts: 0,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now,\n };\n },\n );\n if (!proposed || !row) return null;\n const record = toDeferredDecision(row);\n this.#attentionChanged(record);\n return record;\n }\n\n /**\n * Release an approved effect back to the dispatcher; only `proposed` rows are\n * approvable. Approval is a person taking the item on, so the item's autonomy\n * is armed in the same transaction — a crash cannot release the run while\n * leaving its follow-up work parked for re-approval.\n */\n async approveDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n approvedBy?: string,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const approved = await this.storage.withTransaction(async ops => {\n let settled = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'proposed') return null;\n settled = true;\n return {\n status: 'pending',\n attempts: 0,\n available_at: now,\n approved_at: now,\n approved_by: approvedBy ?? null,\n updated_at: now,\n };\n },\n );\n if (!settled || !row) return null;\n const record = toDeferredDecision(row);\n await ops.deleteMany('factory_attention_receipts', proposalReceiptFilter(orgId, factoryProjectId, decisionId));\n if (record.workItemId) {\n await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id: record.workItemId }, current =>\n current.autonomy_armed_at ? null : { autonomy_armed_at: now },\n );\n }\n return record;\n });\n if (approved) this.#attentionChanged(approved);\n return approved;\n }\n\n /** Retire a proposal nobody wants: `dismissed` is terminal, so the run never happens. */\n async dismissDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n return this.#settleProposedDecision(\n { orgId, factoryProjectId, decisionId },\n { status: 'dismissed', updated_at: now, completed_at: now },\n );\n }\n\n /**\n * Automatically retire proposed or failed work that a newer run or terminal\n * work-item state has overtaken. Human dismissal remains `dismissed`.\n */\n async supersedeDecisionsForWorkItem(input: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role?: string;\n supersededAt: Date;\n }): Promise<FactoryDeferredDecisionRecord[]> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n status: { in: ['proposed', 'failed'] },\n });\n const superseded: FactoryDeferredDecisionRecord[] = [];\n for (const row of rows) {\n const decision = toDeferredDecision(row);\n if (input.role !== undefined && decision.decision.role !== input.role) continue;\n const record =\n decision.status === 'proposed'\n ? await this.#settleProposedDecision(\n {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n decisionId: decision.id,\n },\n { status: 'superseded', updated_at: input.supersededAt, completed_at: input.supersededAt },\n )\n : await this.#resolveFailedDecision({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n decisionId: decision.id,\n status: 'superseded',\n now: input.supersededAt,\n });\n if (record) superseded.push(record);\n }\n return superseded;\n }\n\n async #settleProposedDecision(\n { orgId, factoryProjectId, decisionId }: { orgId: string; factoryProjectId: string; decisionId: string },\n patch: Partial<GovernanceDbRow>,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const settled = await this.storage.withTransaction(async ops => {\n let updated = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'proposed') return null;\n updated = true;\n return patch;\n },\n );\n if (!updated || !row) return null;\n await ops.deleteMany('factory_attention_receipts', proposalReceiptFilter(orgId, factoryProjectId, decisionId));\n return toDeferredDecision(row);\n });\n if (settled) this.#attentionChanged(settled);\n return settled;\n }\n\n async #resolveFailedDecision({\n orgId,\n factoryProjectId,\n decisionId,\n status,\n now,\n }: {\n orgId: string;\n factoryProjectId: string;\n decisionId: string;\n status: 'succeeded' | 'superseded';\n now: Date;\n }): Promise<FactoryDeferredDecisionRecord | null> {\n const resolved = await this.storage.withTransaction(async ops => {\n let resolved = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'failed') return null;\n resolved = true;\n return { status, updated_at: now };\n },\n );\n if (!resolved || !row) return null;\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'automation-failed',\n source_id: decisionId,\n occurrence: Number(row.failure_occurrence ?? 0),\n });\n return toDeferredDecision(row);\n });\n if (resolved) this.#attentionChanged(resolved);\n return resolved;\n }\n\n async supersedeTerminalDecisionsForWorkItem(input: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n supersededAt: Date;\n }): Promise<void> {\n await this.supersedeDecisionsForWorkItem(input);\n }\n\n async repairLegacyAttentionState(): Promise<void> {\n let cursor: { values: Array<Date | string> } | undefined;\n const inspectedWorkItems = new Set<string>();\n while (true) {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { status: { in: ['failed', 'proposed'] } },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n limit: ATTENTION_RECEIPT_QUERY_BATCH_SIZE + 1,\n ...(cursor ? { cursor } : {}),\n },\n );\n const page = rows.slice(0, ATTENTION_RECEIPT_QUERY_BATCH_SIZE);\n for (const row of page) {\n const decision = toDeferredDecision(row);\n if (\n decision.status === 'failed' &&\n decision.failureOccurrence === 0 &&\n deferredDecisionType(decision) === 'transition'\n ) {\n const ingress = await this.#db.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: decision.orgId,\n factory_project_id: decision.factoryProjectId,\n identity: `decision:${decision.idempotencyKey}`,\n });\n if (ingressWasAccepted(ingress)) {\n await this.#resolveFailedDecision({\n orgId: decision.orgId,\n factoryProjectId: decision.factoryProjectId,\n decisionId: decision.id,\n status: 'succeeded',\n now: new Date(),\n });\n continue;\n }\n }\n if (!decision.workItemId) continue;\n const itemKey = `${decision.orgId}\\0${decision.factoryProjectId}\\0${decision.workItemId}`;\n if (inspectedWorkItems.has(itemKey)) continue;\n inspectedWorkItems.add(itemKey);\n const item = await this.get({ orgId: decision.orgId, id: decision.workItemId });\n if (!item || !isTerminalFactoryRuleStage(item.stages)) continue;\n await this.supersedeDecisionsForWorkItem({\n orgId: decision.orgId,\n factoryProjectId: decision.factoryProjectId,\n workItemId: decision.workItemId,\n supersededAt: new Date(),\n });\n }\n const last = page.at(-1);\n if (rows.length <= ATTENTION_RECEIPT_QUERY_BATCH_SIZE || !last) return;\n if (!(last.created_at instanceof Date)) throw new Error('Deferred decision created_at is not a timestamp.');\n cursor = { values: [last.created_at, last.id] };\n }\n }\n\n /** Requeue the same idempotent terminal effect; non-failed decisions are never rerun. */\n async retryDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const retriedRecord = await this.storage.withTransaction(async ops => {\n let retried = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'failed') return null;\n retried = true;\n return {\n status: 'retry',\n attempts: 0,\n delivery_generation: Number(current.delivery_generation ?? 0) + 1,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n failure_code: null,\n completed_at: null,\n updated_at: now,\n };\n },\n );\n if (!retried || !row) return null;\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'automation-failed',\n source_id: decisionId,\n occurrence: Number(row.failure_occurrence ?? 0),\n });\n return toDeferredDecision(row);\n });\n if (retriedRecord) this.#attentionChanged(retriedRecord);\n return retriedRecord;\n }\n\n /** Resolve exact active agent authority; partial session matches never authorize. */\n async findActiveRunBinding(address: FactoryRunBindingAddress): Promise<FactoryRunBindingRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: address.orgId,\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n status: 'active',\n });\n return row ? toBinding(row) : null;\n }\n\n /**\n * Recover the active binding for a thread when session state lost\n * `factoryProjectId` (e.g. crash-resume recreated the session empty).\n * Ambiguous matches across factory projects never authorize.\n */\n async findActiveRunBindingByThread(input: {\n orgId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n }): Promise<FactoryRunBindingRecord | null> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n thread_id: input.threadId,\n resource_id: input.resourceId,\n session_id: input.sessionId,\n status: 'active',\n });\n if (new Set(rows.map(row => row.factory_project_id)).size !== 1) return null;\n const row = rows.sort((left, right) => right.created_at.getTime() - left.created_at.getTime())[0];\n return row ? toBinding(row) : null;\n }\n\n /** Resolve exact bound-session state for processor awareness; ambiguous cross-tenant matches return null. */\n async findRunBindingBySession(address: FactoryRunBindingSessionAddress): Promise<FactoryRunBindingRecord | null> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n });\n if (new Set(rows.map(row => row.org_id)).size !== 1) return null;\n const row = rows.sort((left, right) => {\n if (left.status === 'active' && right.status !== 'active') return -1;\n if (right.status === 'active' && left.status !== 'active') return 1;\n return right.created_at.getTime() - left.created_at.getTime();\n })[0];\n return row ? toBinding(row) : null;\n }\n\n /** Revoke one exact tenant-scoped binding. */\n async revokeRunBinding(input: RevokeFactoryRunBindingInput): Promise<FactoryRunBindingRecord | null> {\n let revoked = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_run_bindings',\n { id: input.bindingId, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'active') return null;\n revoked = true;\n return { status: 'revoked', revoked_at: input.revokedAt };\n },\n );\n return revoked && row ? toBinding(row) : null;\n }\n\n /**\n * Revoke every active binding for one work item (all roles). Called from\n * terminal-stage cleanup so completed items stop paying the reconcile walk.\n * Returns the number of bindings revoked.\n */\n async revokeRunBindingsForWorkItem(input: RevokeFactoryRunBindingsForWorkItemInput): Promise<number> {\n return this.#db.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n status: 'active',\n },\n { status: 'revoked', revoked_at: input.revokedAt },\n );\n }\n\n /**\n * Revoke leaked/legacy active bindings: older than `olderThan`, or whose\n * work item is gone, malformed, or already terminal. Terminal-stage cleanup\n * handles bindings go-forward; this sweep drains anything that slipped past\n * it. Returns the number of bindings revoked.\n */\n async revokeStaleRunBindings(input: RevokeStaleFactoryRunBindingsInput): Promise<number> {\n const bindings = await this.listActiveRunBindings();\n const itemCache = new Map<string, WorkItemRow | null>();\n let revoked = 0;\n for (const binding of bindings) {\n let stale = binding.createdAt.getTime() < input.olderThan.getTime();\n if (!stale) {\n const key = `${binding.orgId}:${binding.workItemId}`;\n let item = itemCache.get(key);\n if (item === undefined) {\n item = await this.get({ orgId: binding.orgId, id: binding.workItemId });\n itemCache.set(key, item);\n }\n stale =\n !item ||\n item.stages.length !== 1 ||\n !ACTIVE_RUN_BINDING_STAGES.has(item.stages[0]!) ||\n item.factoryProjectId !== binding.factoryProjectId;\n }\n if (!stale) continue;\n const result = await this.revokeRunBinding({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n bindingId: binding.id,\n revokedAt: input.now,\n });\n if (result) revoked += 1;\n }\n return revoked;\n }\n\n /** Enumerate active bindings for the server-owned restart reconciler. */\n async listActiveRunBindings(): Promise<FactoryRunBindingRecord[]> {\n return (await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', { status: 'active' })).map(toBinding);\n }\n\n /** List binding history, optionally narrowed to one work item. */\n async listRunBindings(\n orgId: string,\n factoryProjectId: string,\n workItemId?: string,\n ): Promise<FactoryRunBindingRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_run_bindings',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(workItemId ? { work_item_id: workItemId } : {}),\n },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toBinding);\n }\n\n async listPendingStarts(orgId: string, factoryProjectId: string): Promise<FactoryPendingStartRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_pending_starts',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toPendingStart);\n }\n\n async claimPendingStarts(input: FactoryLeaseClaimInput): Promise<FactoryPendingStartRecord[]> {\n return this.#claimLeases('factory_pending_starts', input, toPendingStart);\n }\n\n async renewPendingStartLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_pending_starts', identity, leaseExpiresAt);\n }\n\n async completePendingStart(identity: FactoryLeaseIdentity, now: Date): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#completeLease('factory_pending_starts', identity, now);\n return row ? toPendingStart(row) : null;\n }\n\n async failPendingStart(input: FactoryDispatchFailureInput): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#failLease('factory_pending_starts', input);\n return row ? toPendingStart(row) : null;\n }\n\n async prepareRunStart(input: PrepareFactoryRunStartInput): Promise<PrepareFactoryRunStartResult> {\n const prepare = () =>\n this.storage.withTransaction(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n kickoff_key: input.kickoffKey,\n });\n if (prior) {\n const bindingRow = await ops.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: String(prior.binding_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n const itemRow =\n bindingRow &&\n (await ops.findOne<WorkItemDbRow>('work_items', {\n id: String(bindingRow.work_item_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n }));\n if (!bindingRow || !itemRow) throw new Error('Factory start replay references missing state.');\n return {\n item: toRow(itemRow),\n binding: toBinding(bindingRow),\n pendingStart: toPendingStart(prior),\n replayed: true,\n };\n }\n const now = new Date();\n const create = input.workItem.input;\n let row = input.workItem.id\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItem.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : externalSourceKey(create.externalSource)\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: externalSourceKey(create.externalSource),\n })\n : null;\n let item: WorkItemRow;\n if (row) {\n row = await ops.updateAtomic<WorkItemDbRow>('work_items', { id: row.id }, current => {\n // Stamp only the starting role — `applyUpdate` merges sessions, so\n // other roles keep their own session and `startedBy` (#22254).\n return applyUpdate({ current, userId: input.userId, input: { sessions: { [input.role]: input.session } } });\n });\n item = toRow(row!);\n } else {\n if (create.parentWorkItemId)\n validateParentRelation(\n (\n await ops.findMany<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n ).map(toRow),\n undefined,\n create.parentWorkItemId,\n );\n row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n created_by: input.userId,\n factory_project_id: input.factoryProjectId,\n board: create.board ?? null,\n external_source: create.externalSource ?? null,\n source_key: externalSourceKey(create.externalSource),\n parent_work_item_id: create.parentWorkItemId ?? null,\n title: create.title,\n stages: create.stages ?? [],\n stage_history: applyStageTransition([], [], create.stages ?? [], input.userId, now),\n sessions: stampSessions({ [input.role]: input.session }, input.userId),\n metadata: create.metadata ?? null,\n revision: 1,\n created_at: now,\n updated_at: now,\n });\n item = toRow(row);\n }\n await ops.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n thread_id: input.session.threadId,\n resource_id: input.resourceId,\n session_id: input.session.sessionId,\n status: 'active',\n },\n { status: 'revoked', revoked_at: now },\n );\n await ops.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n status: 'active',\n },\n { status: 'revoked', revoked_at: now },\n );\n const bindingRow = await ops.insertOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n thread_id: input.session.threadId,\n resource_id: input.resourceId,\n session_id: input.session.sessionId,\n branch: input.session.branch,\n status: 'active',\n created_at: now,\n revoked_at: null,\n });\n const pendingRow = await ops.insertOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n binding_id: bindingRow.id,\n kickoff_key: input.kickoffKey,\n message: input.kickoffMessage,\n status: 'pending',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n failure_code: null,\n completed_at: null,\n created_at: now,\n updated_at: now,\n });\n return { item, binding: toBinding(bindingRow), pendingStart: toPendingStart(pendingRow), replayed: false };\n });\n // A losing preparer can hit two distinct unique violations back to back:\n // first on the work item's `source_key`, then on the pending start's\n // `kickoff_key` (when the winner commits its pending row between our\n // attempts). Each retry re-reads, so one extra attempt converges on replay.\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n return await prepare();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n }\n\n async markPendingStart(\n bindingId: string,\n status: 'sent' | 'failed',\n lastError?: string,\n ): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_pending_starts',\n { binding_id: bindingId },\n () => ({ status, last_error: lastError ?? null, updated_at: new Date() }),\n );\n return row ? toPendingStart(row) : null;\n }\n\n /**\n * Create a work item, reusing the existing record when `sourceKey` already\n * has one for the project (acting twice on the same issue must not duplicate\n * the card). On reuse the provided stages replace the current ones (with the\n * transition recorded in history) and sessions/metadata are merged in. The\n * result discriminates insert from reuse so callers can audit the actual\n * outcome.\n */\n async upsert(params: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n }): Promise<UpsertWorkItemResult> {\n const run = (ops: FactoryStorageOps) => this.#upsert(params, ops);\n const execute = () =>\n params.input.parentWorkItemId\n ? this.#withProjectRelationTransaction(params.orgId, params.factoryProjectId, run)\n : run(this.#db);\n try {\n return await execute();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return execute();\n }\n }\n\n async #upsert(\n {\n orgId,\n userId,\n factoryProjectId,\n input,\n reuseMode = 'update',\n }: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n },\n ops: FactoryStorageOps,\n ): Promise<UpsertWorkItemResult> {\n const key = externalSourceKey(input.externalSource);\n const reuse = async (): Promise<UpsertWorkItemResult | null> => {\n if (!key) return null;\n const existing = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: key,\n });\n if (!existing) return null;\n if (reuseMode === 'preserve') {\n const item = toWorkItem(existing);\n return { created: false, item, previous: priorState(existing) };\n }\n\n let previous = emptyPrior();\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId, source_key: key },\n async current => {\n previous = priorState(current);\n const fullPatch = input.parentWorkItemId === null ? { ...input, parentWorkItemId: undefined } : input;\n const patch: UpdateWorkItemInput =\n reuseMode === 'non-stage'\n ? {\n title: input.title,\n parentWorkItemId: input.parentWorkItemId ?? undefined,\n metadata: input.metadata,\n }\n : fullPatch;\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return {\n board: reuseMode === 'non-stage' ? current.board : (input.board ?? current.board ?? null),\n external_source: input.externalSource ?? null,\n ...applyUpdate({ current, userId, input: patch }),\n };\n },\n );\n return updated ? { item: toWorkItem(updated), created: false, previous } : null;\n };\n\n const reused = await reuse();\n if (reused) return reused;\n\n const now = new Date();\n const stages = input.stages ?? ['intake'];\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n undefined,\n input.parentWorkItemId ?? null,\n );\n const row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n board: input.board ?? null,\n external_source: input.externalSource ?? null,\n source_key: key,\n parent_work_item_id: input.parentWorkItemId ?? null,\n title: input.title,\n stages,\n stage_history: stages.map(stage => ({ stage, enteredAt: now.toISOString(), by: userId })),\n sessions: stampSessions(input.sessions ?? {}, userId),\n metadata: input.metadata ?? null,\n revision: 1,\n created_by: userId,\n created_at: now,\n updated_at: now,\n });\n return { item: toWorkItem(row), created: true, previous: emptyPrior() };\n }\n\n async setParentWorkItemIfMissing({\n orgId,\n id,\n userId,\n parentWorkItemId,\n }: {\n orgId: string;\n id: string;\n userId: string;\n parentWorkItemId: string;\n }): Promise<WorkItemRow | null> {\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const row = await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id }, async current => {\n if (current.parent_work_item_id !== null) return current;\n validateParentRelation(\n await this.#listWithOps(ops, orgId, current.factory_project_id),\n current.id,\n parentWorkItemId,\n );\n return applyUpdate({ current, userId, input: { parentWorkItemId } });\n });\n return row ? toWorkItem(row) : null;\n });\n }\n\n async update({\n orgId,\n id,\n userId,\n patch,\n expectedRevision,\n expectedBoard,\n }: {\n orgId: string;\n id: string;\n userId: string;\n patch: UpdateWorkItemInput;\n expectedRevision?: number;\n expectedBoard?: string | null;\n }): Promise<{ item: WorkItemRow; previous: WorkItemPriorState } | null> {\n const run = async (ops: FactoryStorageOps) => {\n let previous = emptyPrior();\n const row = await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id }, async current => {\n previous = priorState(current);\n if (expectedBoard !== undefined && current.board !== expectedBoard) {\n throw new WorkItemUpdateConflictError('board');\n }\n if (expectedRevision !== undefined && current.revision !== expectedRevision) {\n throw new WorkItemUpdateConflictError('revision');\n }\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, current.factory_project_id),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return applyUpdate({ current, userId, input: patch });\n });\n return row ? { item: toWorkItem(row), previous } : null;\n };\n\n if (patch.parentWorkItemId === undefined) return run(this.#db);\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, run);\n }\n\n /**\n * Drop the governance rows that materialized a source key so a deleted work item\n * is not resurrected by the prior-ingress replay path on the next intake poll.\n */\n async #purgeRuleState(\n ops: FactoryStorageOps,\n { orgId, factoryProjectId, sourceKey }: { orgId: string; factoryProjectId: string; sourceKey: string },\n ): Promise<void> {\n const decisions = await ops.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: sourceKey,\n });\n if (decisions.length === 0) return;\n\n const evaluationIds = [...new Set(decisions.map(decision => String(decision.evaluation_id)))];\n const ingressIds = new Set<string>();\n for (const evaluationId of evaluationIds) {\n const evaluation = await ops.findOne<GovernanceDbRow>('factory_rule_evaluations', { id: evaluationId });\n if (evaluation) ingressIds.add(String(evaluation.ingress_id));\n }\n\n const decisionIds = decisions.map(decision => decision.id);\n for (let index = 0; index < decisionIds.length; index += ATTENTION_RECEIPT_QUERY_BATCH_SIZE) {\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'automation-failed',\n source_id: { in: decisionIds.slice(index, index + ATTENTION_RECEIPT_QUERY_BATCH_SIZE) },\n });\n }\n\n await ops.deleteMany('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: sourceKey,\n });\n for (const evaluationId of evaluationIds) {\n await ops.deleteMany('factory_rule_evaluations', { id: evaluationId });\n }\n for (const ingressId of ingressIds) {\n const remaining = await ops.findMany<GovernanceDbRow>('factory_rule_evaluations', { ingress_id: ingressId });\n if (remaining.length === 0) await ops.deleteMany('factory_rule_ingress', { id: ingressId });\n }\n }\n\n /**\n * Feed rows die with their work item: orphan mention rows would keep\n * projecting attention items that deep-link to a card that no longer exists.\n */\n async #purgeFeedState(\n ops: FactoryStorageOps,\n { orgId, factoryProjectId, workItemId }: { orgId: string; factoryProjectId: string; workItemId: string },\n ): Promise<void> {\n // Paged harvest: this runs inside the delete transaction and a long-lived\n // item can carry thousands of comments — never materialize them all.\n const where = { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId };\n while (true) {\n const comments = await ops.findMany<{ id: string } & Record<string, unknown>>('work_item_comments', where, {\n limit: ATTENTION_RECEIPT_QUERY_BATCH_SIZE,\n });\n if (comments.length === 0) break;\n const commentIds = comments.map(comment => comment.id);\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'mention',\n source_id: { in: commentIds },\n });\n await ops.deleteMany('work_item_comments', { ...where, id: { in: commentIds } });\n if (comments.length < ATTENTION_RECEIPT_QUERY_BATCH_SIZE) break;\n }\n await ops.deleteMany('work_item_comment_mentions', where);\n // Activity is keyed on the item, so one statement covers every occurrence\n // and every participant.\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'activity',\n source_id: workItemId,\n });\n await ops.deleteMany('work_item_activity', where);\n }\n\n async delete({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n\n const removed = await this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const existing = await ops.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!existing) return null;\n const deleted = await ops.deleteMany('work_items', { org_id: orgId, id });\n if (deleted === 0) return null;\n await this.#purgeFeedState(ops, { orgId, factoryProjectId: existing.factory_project_id, workItemId: id });\n if (existing.source_key) {\n await this.#purgeRuleState(ops, {\n orgId,\n factoryProjectId: existing.factory_project_id,\n sourceKey: existing.source_key,\n });\n }\n await ops.updateMany(\n 'work_items',\n { org_id: orgId, parent_work_item_id: id },\n { parent_work_item_id: null, updated_at: new Date() },\n );\n return toWorkItem(existing);\n });\n if (removed) this.#attentionChanged(removed);\n return removed;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAyBA,SAAS,WAAW,OAAwB;CAC1C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG,EAAE;CACrE,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAgC,CAAC,CACxD,MAAM,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,KAAK,CAAC,CAAC,CACpD,KAAK,CAAC,KAAK,WAAW,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,WAAW,KAAK,GAAG,CAAC,CACpE,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEA,SAAgB,oBAAoB,UAA2C;CAC7E,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,WAAW,QAAQ,CAAC,CAAC,CAAC,OAAO,KAAK;AACvE;;AAgBA,MAAa,mCAAmC;AAChD,MAAa,0CAA0C;;;;;;;;;;;AAwBvD,SAAgB,aAAa,IAAiC;CAC5D,IAAI,OAAO,KAAA,GAAW,OAAO;CAC7B,OAAO,GAAG,WAAW,QAAQ,KAAK,OAAO;AAC3C;AAwEA,MAAM,iCAAiC;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,SAAS,6BAA6B,OAAqD;CACzF,OAAO,+BAA+B,MAAK,SAAQ,SAAS,KAAK;AACnE;AAqGA,SAAgB,iCACd,YACA,mBAC0B;CAC1B,OAAO;EAAE,MAAM;EAAqB,UAAU;EAAY,YAAY;CAAkB;AAC1F;AAEA,SAAgB,iCAAiC,YAA8C;CAC7F,OAAO;EAAE,MAAM;EAAuB,UAAU;EAAY,YAAY;CAAE;AA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AAoC;EAC5D;EACA,MAAM,IAAI,WAAW,8BAA8B,KAAK;EAGxD,MAAM,IAAI,WAAW,8BAA8B;GACjD,QAAQ;GACR,oBAAoB;GACpB,MAAM;GACN,WAAW;EACb,CAAC;EACD,MAAM,IAAI,WAAW,sBAAsB,KAAK;CAClD;CAEA,MAAM,OAAO,EAAE,OAAO,MAAkE;EACtF,MAAM,YAAY,MAAM,KAAKf,IAAI,QAAuB,cAAc;GAAE,QAAQ;GAAO;EAAG,CAAC;EAC3F,IAAI,CAAC,WAAW,OAAO;EAEvB,MAAM,UAAU,MAAM,KAAKE,gCAAgC,OAAO,UAAU,oBAAoB,OAAM,QAAO;GAC3G,MAAM,WAAW,MAAM,IAAI,QAAuB,cAAc;IAAE,QAAQ;IAAO;GAAG,CAAC;GACrF,IAAI,CAAC,UAAU,OAAO;GAEtB,IAAI,MADkB,IAAI,WAAW,cAAc;IAAE,QAAQ;IAAO;GAAG,CAAC,MACxD,GAAG,OAAO;GAC1B,MAAM,KAAKa,gBAAgB,KAAK;IAAE;IAAO,kBAAkB,SAAS;IAAoB,YAAY;GAAG,CAAC;GACxG,IAAI,SAAS,YACX,MAAM,KAAKD,gBAAgB,KAAK;IAC9B;IACA,kBAAkB,SAAS;IAC3B,WAAW,SAAS;GACtB,CAAC;GAEH,MAAM,IAAI,WACR,cACA;IAAE,QAAQ;IAAO,qBAAqB;GAAG,GACzC;IAAE,qBAAqB;IAAM,4BAAY,IAAI,KAAK;GAAE,CACtD;GACA,OAAO,WAAW,QAAQ;EAC5B,CAAC;EACD,IAAI,SAAS,KAAKf,kBAAkB,OAAO;EAC3C,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"base.js","names":["#attentionChanged","#isTerminal","#db","#countRows","#withProjectRelationTransaction","#claimLeases","#renewLease","#completeLease","#failLease","#listWithOps","#retryAttentionReceiptWrite","#setAttentionReceiptWithOps","#attentionSourceIsCurrent","#settleProposedDecision","#resolveFailedDecision","#upsert","#purgeRuleState","#purgeFeedState"],"sources":["../../../../src/storage/domains/work-items/base.ts"],"sourcesContent":["/**\n * Factory work-items storage domain.\n *\n * Work items belong to a first-class Factory project. External intake items use\n * a provider-neutral source reference; manual work items have no source.\n * Stage history is server-owned, while session and metadata patches merge\n * atomically so concurrent actors do not overwrite each other. The authoritative\n * Factory transition path keeps one exclusive current stage per item.\n */\n\nimport { createHash } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, CollectionWhere, FactoryStorageOps } from '@mastra/core/storage';\nimport type { FactoryTriageType } from '../../../rules/types.js';\nimport type { FactoryHealthFinding } from '../../../supervisor/health.js';\nimport {\n WORK_ITEM_ACTIVITY_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_COMMENTS_SCHEMA,\n} from '../comments/schema.js';\n\nexport type WorkItemStage = string;\n\nfunction stableJson(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(',')}]`;\n if (value && typeof value === 'object') {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)\n .join(',')}}`;\n }\n return JSON.stringify(value) ?? 'null';\n}\n\nexport function factoryDecisionHash(decision: Record<string, unknown>): string {\n return createHash('sha256').update(stableJson(decision)).digest('hex');\n}\n\nexport interface ExternalWorkItemSource {\n integrationId: string;\n type: string;\n /**\n * The tenant on the platform, never ours: a Slack team (`T0ABC…`), a Discord\n * guild. Scopes the key, because a platform id such as a channel or a message\n * `ts` is only unique inside the workspace that issued it.\n */\n workspaceId?: string;\n externalId: string;\n url?: string;\n}\n\n/** Dispatcher upsert idempotency token — server bookkeeping, dropped from the read wire. */\nexport const FACTORY_RULE_MATERIALIZATION_KEY = 'factoryRuleMaterializationKey';\nexport const FACTORY_PULL_REQUEST_RECONCILIATION_KEY = 'factoryPullRequestReconciliation';\n\nexport interface WorkItemStageEntry {\n stage: WorkItemStage;\n enteredAt: string;\n exitedAt?: string;\n by: string;\n /**\n * Actor that closed this entry; absent on entries written before exit\n * stamping existed — treat as human.\n */\n exitedBy?: string;\n}\n\n/**\n * Whether an actor id marks a move an agent run performed: the binding id the\n * transition tool stamps (`agent:*`), or the rule that fires off a bound run's\n * tool result (see `factory/rules/processor.ts`).\n *\n * Deliberately narrower than \"not a human\": the poller stamps\n * `factory-rule-dispatcher` / `github:*` on every card it syncs from the\n * upstream repo, so counting those as machine work reports the repo's activity\n * as the Factory's and pins any such ratio near 100%.\n */\nexport function isAgentActor(by: string | undefined): boolean {\n if (by === undefined) return false;\n return by.startsWith('agent:') || by === 'factory-tool-result-rule';\n}\n\nexport interface WorkItemSessionRef {\n sessionId: string;\n branch: string;\n threadId: string;\n startedBy: string;\n}\n\nexport interface FactoryRuleIngressRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n identity: string;\n triggerType: string;\n transitionId: string;\n result: Record<string, unknown>;\n createdAt: Date;\n}\n\nexport interface CommitFactoryRuleEvaluationInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n ingress: { identity: string; triggerType: string };\n configVersion: string;\n expectedRevision: number | null;\n actor: Record<string, unknown> | null;\n outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string };\n decisions: Record<string, unknown>[];\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n now: Date;\n}\n\nexport type CommitFactoryRuleEvaluationResult =\n | { status: 'committed'; result: Record<string, unknown> }\n | { status: 'replayed'; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface FactoryToolResultCursorRecord {\n bindingId: string;\n orgId: string;\n factoryProjectId: string;\n lastMessageId: string;\n lastMessageCreatedAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryRuleEvaluationRecord {\n id: string;\n ingressId: string;\n workItemId: string | null;\n configVersion: string;\n expectedRevision: number | null;\n outcome: 'accepted' | 'rejected';\n code: string | null;\n reason: string | null;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n createdAt: Date;\n}\n\n/** `proposed` is parked awaiting approval; `dismissed` is human, `superseded` is automatic. */\nexport type FactoryDispatchStatus =\n | 'pending'\n | 'proposed'\n | 'dismissed'\n | 'superseded'\n | 'leased'\n | 'retry'\n | 'succeeded'\n | 'failed';\n\nconst FACTORY_DISPATCH_FAILURE_CODES = [\n 'session_unavailable',\n 'source_control_missing',\n 'source_repository_missing',\n 'unsupported_provider_item',\n 'notification_delivery_failed',\n 'run_overdue',\n 'repository_git_missing',\n 'repository_egress_blocked',\n 'repository_clone_failed',\n 'repository_pull_failed',\n 'repository_push_failed',\n 'repository_commit_failed',\n 'repository_cli_missing',\n 'repository_pr_failed',\n 'unknown',\n] as const;\n\n/** Written until a pause stopped counting as a failure; stored rows still read through them. */\nconst RETIRED_FACTORY_DISPATCH_FAILURE_CODES = ['plan_awaiting_approval', 'run_awaiting_input'] as const;\n\nconst STORED_FACTORY_DISPATCH_FAILURE_CODES = [\n ...FACTORY_DISPATCH_FAILURE_CODES,\n ...RETIRED_FACTORY_DISPATCH_FAILURE_CODES,\n] as const;\n\nexport type FactoryDispatchFailureCode = (typeof FACTORY_DISPATCH_FAILURE_CODES)[number];\nexport type StoredFactoryDispatchFailureCode = (typeof STORED_FACTORY_DISPATCH_FAILURE_CODES)[number];\n\nfunction isStoredFactoryDispatchFailureCode(value: unknown): value is StoredFactoryDispatchFailureCode {\n return STORED_FACTORY_DISPATCH_FAILURE_CODES.some(code => code === value);\n}\n\nexport interface FactoryDeferredDecisionPageInput {\n orgId: string;\n factoryProjectId: string;\n statuses?: FactoryDispatchStatus[];\n before?: { createdAt: Date; id: string };\n limit: number;\n}\n\nexport interface FactoryDeferredDecisionPage {\n decisions: FactoryDeferredDecisionRecord[];\n hasMore: boolean;\n}\n\nexport interface FactoryDecisionStatusPageInput {\n orgId: string;\n factoryProjectId: string;\n status: FactoryDispatchStatus;\n before?: { occurredAt: Date; id: string };\n limit: number;\n}\n\nexport interface FactoryDeferredDecisionRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n evaluationId: string;\n workItemId: string | null;\n idempotencyKey: string;\n effectOrdinal: number;\n effectHash: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n actor: Record<string, unknown> | null;\n decision: Record<string, unknown>;\n status: FactoryDispatchStatus;\n attempts: number;\n deliveryGeneration: number;\n failureOccurrence: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n failureCode: StoredFactoryDispatchFailureCode | null;\n /** When a human released this run; set once, so the gate never parks it again. */\n approvedAt: Date | null;\n /** Who released this run — the run is attributed to them, not the repo connector. */\n approvedBy: string | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport type FactoryAttentionKind =\n | 'automation-failed'\n | 'automation-proposed'\n | 'mention'\n | 'activity'\n | 'supervisor-finding'\n | 'agent-waiting';\nexport type FactoryAttentionReceiptState = 'read' | 'archived';\n\nexport interface FactorySupervisorFindingRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n findingKey: string;\n occurrence: number;\n finding: Record<string, unknown>;\n openedAt: Date;\n updatedAt: Date;\n resolvedAt: Date | null;\n}\nexport type FactoryAttentionReceiptAction = 'read' | 'archive' | 'restore';\n\nexport interface FactoryAttentionIdentity {\n kind: FactoryAttentionKind;\n sourceId: string;\n occurrence: number;\n}\n\nexport interface FactoryAttentionReceiptRecord extends FactoryAttentionIdentity {\n id: string;\n orgId: string;\n factoryProjectId: string;\n userId: string;\n state: FactoryAttentionReceiptState;\n readAt: Date;\n archivedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\ninterface SetAttentionReceiptInput {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n identity: FactoryAttentionIdentity;\n action: FactoryAttentionReceiptAction;\n now: Date;\n}\n\nexport function factoryDecisionAttentionIdentity(\n decisionId: string,\n failureOccurrence: number,\n): FactoryAttentionIdentity {\n return { kind: 'automation-failed', sourceId: decisionId, occurrence: failureOccurrence };\n}\n\nexport function factoryProposalAttentionIdentity(decisionId: string): FactoryAttentionIdentity {\n return { kind: 'automation-proposed', sourceId: decisionId, occurrence: 0 };\n}\n\n// A settled proposal is settled for everyone, so its receipts go for everyone.\nfunction proposalReceiptFilter(orgId: string, factoryProjectId: string, decisionId: string) {\n const identity = factoryProposalAttentionIdentity(decisionId);\n return {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: identity.kind,\n source_id: identity.sourceId,\n occurrence: identity.occurrence,\n };\n}\n\nexport function factoryMentionAttentionIdentity(commentId: string): FactoryAttentionIdentity {\n return { kind: 'mention', sourceId: commentId, occurrence: 0 };\n}\n\n/** Collapsed per work item, so the occurrence is what a new comment bumps. */\nexport function factoryActivityAttentionIdentity(workItemId: string, occurrence: number): FactoryAttentionIdentity {\n return { kind: 'activity', sourceId: workItemId, occurrence };\n}\n\nexport function factorySupervisorFindingAttentionIdentity(\n findingKey: string,\n occurrence: number,\n): FactoryAttentionIdentity {\n return { kind: 'supervisor-finding', sourceId: findingKey, occurrence };\n}\n\n/** Dated by the park itself, so an answer and a new park never share a receipt. */\nexport function factoryAgentWaitingAttentionIdentity(sessionId: string, suspendedAt: number): FactoryAttentionIdentity {\n return { kind: 'agent-waiting', sourceId: sessionId, occurrence: suspendedAt };\n}\n\nexport function factoryAttentionKey(factoryProjectId: string, identity: FactoryAttentionIdentity): string {\n return `factory:${factoryProjectId}:attention:${identity.kind}:${identity.sourceId}:${identity.occurrence}`;\n}\n\nexport interface FactoryRunBindingSessionAddress {\n factoryProjectId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n}\n\nexport interface FactoryRunBindingAddress extends FactoryRunBindingSessionAddress {\n orgId: string;\n}\n\nexport interface RevokeFactoryRunBindingInput {\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n revokedAt: Date;\n}\n\nexport interface RevokeStaleFactoryRunBindingsInput {\n /** Active bindings created before this instant are revoked regardless of item state. */\n olderThan: Date;\n now: Date;\n}\n\nexport interface RevokeFactoryRunBindingsForWorkItemInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n revokedAt: Date;\n}\n\nexport interface FactoryRunBindingRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n status: 'active' | 'revoked';\n createdAt: Date;\n revokedAt: Date | null;\n}\n\nexport interface FactoryPendingStartRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n bindingId: string;\n kickoffKey: string;\n message: string | null;\n status: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n attempts: number;\n availableAt: Date;\n leaseOwner: string | null;\n leaseExpiresAt: Date | null;\n lastError: string | null;\n failureCode: StoredFactoryDispatchFailureCode | null;\n completedAt: Date | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface FactoryLeaseClaimInput {\n ownerId: string;\n now: Date;\n leaseExpiresAt: Date;\n limit: number;\n}\n\nexport interface FactoryLeaseIdentity {\n id: string;\n orgId: string;\n factoryProjectId: string;\n ownerId: string;\n}\n\nexport interface FactoryDispatchFailureInput extends FactoryLeaseIdentity {\n now: Date;\n availableAt: Date;\n lastError: string;\n failureCode: FactoryDispatchFailureCode;\n terminal: boolean;\n advanceDeliveryGeneration?: boolean;\n}\n\nexport interface CommitFactoryTransitionInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n expectedRevision: number;\n destinationStage: string;\n actorId: string;\n ingress: { identity: string; triggerType: string; transitionId: string };\n configVersion: string;\n causalChain: Array<{ ingressId: string; decisionType: string }>;\n evaluation:\n | { outcome: 'accepted'; decisions: Record<string, unknown>[] }\n | { outcome: 'rejected'; code: string; reason: string };\n /** Arm or disarm autonomy in the same revision-checked update that commits the transition. */\n autonomy?: 'arm' | 'disarm';\n /** Consent-bearing actor behind the flip; their id pre-approves the runs this transition queues. */\n consentedBy?: string;\n /** Triage classification reported by an authenticated triage binding. */\n triageType?: FactoryTriageType;\n /** Record the person's acceptance of this item in the same revision-checked update; a no-op once set. */\n accept?: boolean;\n}\n\nexport type CommitFactoryTransitionResult =\n | { status: 'committed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'replayed'; item: WorkItemRow | null; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport interface PrepareFactoryRunStartInput {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n workItem: { id?: string; input: CreateWorkItemInput };\n role: string;\n session: WorkItemSessionInput;\n resourceId: string;\n kickoffKey: string;\n kickoffMessage: string | null;\n}\n\nexport interface PrepareFactoryRunStartResult {\n item: WorkItemRow;\n binding: FactoryRunBindingRecord;\n pendingStart: FactoryPendingStartRecord;\n replayed: boolean;\n}\n\n/** Session ref as accepted from clients — `startedBy` is stamped server-side. */\nexport interface WorkItemSessionInput {\n sessionId: string;\n branch: string;\n threadId: string;\n}\n\nexport type WorkItemSessions = Record<string, WorkItemSessionRef>;\n\nexport interface WorkItemRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n board: string | null;\n externalSource: ExternalWorkItemSource | null;\n parentWorkItemId: string | null;\n title: string;\n stages: WorkItemStage[];\n stageHistory: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n /** Authoritative verdict written by the bound triage run. */\n triageType: FactoryTriageType | null;\n /**\n * When a person first committed this item to the Factory, by starting a run\n * on it or releasing one that was proposed. Projects that withhold auto-run\n * are asking to decide what the Factory picks up, not to approve each step of\n * work they already asked for, so runs on an armed item skip the gate.\n */\n autonomyArmedAt: Date | null;\n /**\n * When a person chose to run this item hands-off: the dispatcher answers its\n * parked plans even while the project's Auto-approve plans switch is off.\n */\n plansPreapprovedAt: Date | null;\n /**\n * When a person first moved this item out of Intake/Triage into working\n * stages. Non-bug items wait for that gesture; once it is recorded the\n * agents may advance the item through Planning and Execute on their own.\n */\n acceptedAt: Date | null;\n /** Denormalized feed counters, maintained by the comments domain via recount. */\n commentCount: number;\n /** Bumps on every feed mutation (create/edit/delete) — the clients' change hint. */\n feedActivityAt: Date | null;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemInput {\n board?: string;\n externalSource?: ExternalWorkItemSource | null;\n parentWorkItemId?: string | null;\n title: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface UpdateWorkItemInput {\n board?: string;\n parentWorkItemId?: string | null;\n title?: string;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n /** The person chose a hands-off run: stamped once, so a second grant never moves it. */\n plansPreapproved?: true;\n}\n\nexport interface WorkItemPriorState {\n stages: WorkItemStage[];\n sessionRoles: string[];\n}\n\nexport interface UpsertWorkItemResult {\n item: WorkItemRow;\n created: boolean;\n previous: WorkItemPriorState;\n}\n\nexport const WORK_ITEMS_SCHEMA: CollectionSchema = {\n name: 'work_items',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board: { type: 'text', nullable: true },\n external_source: { type: 'json', nullable: true },\n source_key: { type: 'text', nullable: true },\n parent_work_item_id: { type: 'text', nullable: true },\n title: { type: 'text' },\n stages: { type: 'json' },\n stage_history: { type: 'json' },\n sessions: { type: 'json' },\n metadata: { type: 'json', nullable: true },\n triage_type: { type: 'text', nullable: true },\n autonomy_armed_at: { type: 'timestamp', nullable: true },\n plans_preapproved_at: { type: 'timestamp', nullable: true },\n accepted_at: { type: 'timestamp', nullable: true },\n comment_count: { type: 'integer', default: 0 },\n feed_activity_at: { type: 'timestamp', nullable: true },\n revision: { type: 'integer', default: 1 },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'work_items_project_source_key_unique',\n columns: ['factory_project_id', 'source_key'],\n },\n ],\n indexes: [\n {\n name: 'work_items_org_project_created_at_id_idx',\n columns: ['org_id', 'factory_project_id', 'created_at', 'id'],\n },\n {\n name: 'work_items_project_parent_idx',\n columns: ['org_id', 'factory_project_id', 'parent_work_item_id'],\n },\n {\n // The unique index leads with `factory_project_id`, so it cannot serve a\n // lookup by the key alone — which is what a platform message has.\n name: 'work_items_source_key_idx',\n columns: ['source_key'],\n },\n ],\n};\n\ninterface WorkItemDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board: string | null;\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n parent_work_item_id: string | null;\n title: string;\n stages: WorkItemStage[];\n stage_history: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n triage_type: FactoryTriageType | null;\n autonomy_armed_at: Date | null;\n plans_preapproved_at: Date | null;\n accepted_at: Date | null;\n comment_count: number;\n feed_activity_at: Date | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n}\n\n/**\n * The one shape a platform id takes in a lookup key, for cards and for the\n * comments mirrored off them alike: whoever writes a second builder reopens the\n * cross-workspace collision the `workspaceId` is here to close.\n */\nexport function externalSourceKey(source: ExternalWorkItemSource | null | undefined): string | null {\n if (!source) return null;\n const workspace = source.workspaceId ? `${source.workspaceId}:` : '';\n return `${source.integrationId}:${source.type}:${workspace}${source.externalId}`;\n}\n\nfunction toWorkItem(row: WorkItemDbRow): WorkItemRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n board: row.board ?? null,\n externalSource: row.external_source,\n parentWorkItemId: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stageHistory: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n triageType: row.triage_type ?? null,\n autonomyArmedAt: row.autonomy_armed_at ?? null,\n plansPreapprovedAt: row.plans_preapproved_at ?? null,\n acceptedAt: row.accepted_at ?? null,\n commentCount: row.comment_count ?? 0,\n feedActivityAt: row.feed_activity_at ?? null,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nconst toRow = toWorkItem;\n\nfunction patchColumns(changes: Partial<WorkItemRow>): Partial<WorkItemDbRow> {\n return {\n ...(changes.board !== undefined ? { board: changes.board } : {}),\n ...(changes.parentWorkItemId !== undefined ? { parent_work_item_id: changes.parentWorkItemId } : {}),\n ...(changes.title !== undefined ? { title: changes.title } : {}),\n ...(changes.stages !== undefined ? { stages: changes.stages } : {}),\n ...(changes.stageHistory !== undefined ? { stage_history: changes.stageHistory } : {}),\n ...(changes.sessions !== undefined ? { sessions: changes.sessions } : {}),\n ...(changes.metadata !== undefined ? { metadata: changes.metadata } : {}),\n ...(changes.triageType !== undefined ? { triage_type: changes.triageType } : {}),\n ...(changes.autonomyArmedAt !== undefined ? { autonomy_armed_at: changes.autonomyArmedAt } : {}),\n ...(changes.acceptedAt !== undefined ? { accepted_at: changes.acceptedAt } : {}),\n ...(changes.revision !== undefined ? { revision: changes.revision } : {}),\n ...(changes.updatedAt !== undefined ? { updated_at: changes.updatedAt } : {}),\n };\n}\n\nfunction emptyPrior(): WorkItemPriorState {\n return { stages: [], sessionRoles: [] };\n}\n\nfunction priorState(row: WorkItemDbRow): WorkItemPriorState {\n return { stages: row.stages, sessionRoles: Object.keys(row.sessions) };\n}\n\nexport class WorkItemRelationError extends Error {\n readonly code = 'invalid_work_item_relation';\n}\n\nexport class WorkItemUpdateConflictError extends Error {\n readonly code = 'work_item_update_conflict';\n\n constructor(readonly reason: 'board' | 'revision') {\n super(`Work item ${reason} precondition failed`);\n }\n}\n\nexport function validateParentRelation(\n projectItems: WorkItemRow[],\n itemId: string | undefined,\n parentWorkItemId: string | null,\n): void {\n if (parentWorkItemId === null) return;\n const byId = new Map(projectItems.map(item => [item.id, item]));\n const parent = byId.get(parentWorkItemId);\n if (!parent) throw new WorkItemRelationError('Related work item not found in this project.');\n if (itemId === parentWorkItemId) throw new WorkItemRelationError('A work item cannot relate to itself.');\n\n const visited = new Set<string>();\n let cursor: WorkItemRow | undefined = parent;\n while (cursor?.parentWorkItemId) {\n if (cursor.parentWorkItemId === itemId) {\n throw new WorkItemRelationError('This relationship would create a cycle.');\n }\n if (visited.has(cursor.id)) throw new WorkItemRelationError('The related work item chain contains a cycle.');\n visited.add(cursor.id);\n cursor = byId.get(cursor.parentWorkItemId);\n }\n}\n\n/**\n * Diff `oldStages` → `newStages` and return the updated history: exited stages\n * get `exitedAt` + `exitedBy` stamped on their open entry, entered stages get\n * a new entry.\n */\nexport function applyStageTransition(\n history: WorkItemStageEntry[],\n oldStages: WorkItemStage[],\n newStages: WorkItemStage[],\n by: string,\n now: Date,\n): WorkItemStageEntry[] {\n const timestamp = now.toISOString();\n const next = history.map(entry => ({ ...entry }));\n for (const stage of oldStages) {\n if (newStages.includes(stage)) continue;\n for (let i = next.length - 1; i >= 0; i--) {\n const entry = next[i]!;\n if (entry.stage === stage && entry.exitedAt === undefined) {\n entry.exitedAt = timestamp;\n entry.exitedBy = by;\n break;\n }\n }\n }\n for (const stage of newStages) {\n if (!oldStages.includes(stage)) next.push({ stage, enteredAt: timestamp, by });\n }\n return next;\n}\n\nexport function stampSessions(sessions: Record<string, WorkItemSessionInput>, by: string): WorkItemSessions {\n return Object.fromEntries(Object.entries(sessions).map(([role, session]) => [role, { ...session, startedBy: by }]));\n}\n\nfunction applyUpdate({\n current,\n userId,\n input,\n}: {\n current: WorkItemDbRow;\n userId: string;\n input: UpdateWorkItemInput;\n}): Partial<WorkItemDbRow> {\n const now = new Date();\n return {\n ...(input.board !== undefined ? { board: input.board } : {}),\n ...(input.parentWorkItemId !== undefined ? { parent_work_item_id: input.parentWorkItemId } : {}),\n ...(input.title !== undefined ? { title: input.title } : {}),\n ...(input.stages !== undefined\n ? {\n stages: input.stages,\n stage_history: applyStageTransition(current.stage_history, current.stages, input.stages, userId, now),\n }\n : {}),\n ...(input.sessions !== undefined\n ? { sessions: { ...current.sessions, ...stampSessions(input.sessions, userId) } }\n : {}),\n ...(input.metadata !== undefined\n ? { metadata: input.metadata === null ? null : { ...(current.metadata ?? {}), ...input.metadata } }\n : {}),\n ...(input.plansPreapproved && !current.plans_preapproved_at ? { plans_preapproved_at: now } : {}),\n revision: current.revision + 1,\n updated_at: now,\n };\n}\nconst ATTENTION_RECEIPT_QUERY_BATCH_SIZE = 200;\nconst ATTENTION_RECEIPT_WRITE_BATCH_SIZE = 25;\n\nconst projectRelationLocks = new Map<string, Promise<unknown>>();\n\nfunction withInProcessProjectLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = projectRelationLocks.get(key) ?? Promise.resolve();\n const result = previous.then(fn, fn);\n const tail = result.then(\n () => undefined,\n () => undefined,\n );\n projectRelationLocks.set(key, tail);\n void tail.then(() => {\n if (projectRelationLocks.get(key) === tail) projectRelationLocks.delete(key);\n });\n return result;\n}\n\n/** Source key a decision materializes, used to purge governance rows when the item is deleted. */\nfunction decisionSourceKey(decision: unknown): string | null {\n if (typeof decision !== 'object' || decision === null) return null;\n const record = decision as Record<string, unknown>;\n if (record.type !== 'upsertLinkedWorkItem' || typeof record.sourceKey !== 'string') return null;\n return record.sourceKey;\n}\n\nfunction deferredDecisionType(decision: FactoryDeferredDecisionRecord): string | undefined {\n return typeof decision.decision.type === 'string' ? decision.decision.type : undefined;\n}\n\nfunction ingressWasAccepted(row: GovernanceDbRow | null): boolean {\n if (!row || typeof row.result !== 'object' || row.result === null || Array.isArray(row.result)) return false;\n return 'status' in row.result && row.result.status === 'accepted';\n}\n\nconst FACTORY_GOVERNANCE_SCHEMAS: CollectionSchema[] = [\n {\n name: 'factory_rule_ingress',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n identity: { type: 'text' },\n trigger_type: { type: 'text' },\n transition_id: { type: 'text' },\n result: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_rule_ingress_tenant_identity_unique', columns: ['org_id', 'factory_project_id', 'identity'] },\n ],\n },\n {\n name: 'factory_rule_evaluations',\n columns: {\n id: { type: 'uuid-pk' },\n ingress_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n rule_set_version: { type: 'text' },\n expected_revision: { type: 'integer', nullable: true },\n outcome: { type: 'text' },\n code: { type: 'text', nullable: true },\n reason: { type: 'text', nullable: true },\n causal_chain: { type: 'json' },\n created_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_deferred_decisions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n evaluation_id: { type: 'text' },\n work_item_id: { type: 'text', nullable: true },\n source_key: { type: 'text', nullable: true },\n idempotency_key: { type: 'text' },\n effect_ordinal: { type: 'integer' },\n effect_hash: { type: 'text' },\n causal_chain: { type: 'json' },\n actor: { type: 'json', nullable: true },\n decision: { type: 'json' },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n delivery_generation: { type: 'integer', default: 0 },\n failure_occurrence: { type: 'integer', default: 0 },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n failure_code: { type: 'text', nullable: true },\n approved_at: { type: 'timestamp', nullable: true },\n approved_by: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_deferred_decisions_tenant_key_unique',\n columns: ['org_id', 'factory_project_id', 'idempotency_key'],\n },\n ],\n indexes: [\n { name: 'factory_deferred_decisions_claim_idx', columns: ['status', 'created_at'] },\n {\n name: 'factory_deferred_decisions_tenant_status_created_idx',\n columns: ['org_id', 'factory_project_id', 'status', 'created_at', 'id'],\n },\n {\n name: 'factory_deferred_decisions_tenant_status_failed_idx',\n columns: ['org_id', 'factory_project_id', 'status', 'updated_at', 'id'],\n },\n ],\n },\n {\n name: 'factory_supervisor_findings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n finding_key: { type: 'text' },\n occurrence: { type: 'integer' },\n finding: { type: 'json' },\n opened_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n resolved_at: { type: 'timestamp', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_supervisor_findings_project_key_unique',\n columns: ['org_id', 'factory_project_id', 'finding_key'],\n },\n ],\n indexes: [\n {\n name: 'factory_supervisor_findings_project_open_idx',\n columns: ['org_id', 'factory_project_id', 'resolved_at', 'updated_at', 'id'],\n },\n ],\n },\n {\n name: 'factory_attention_receipts',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n user_id: { type: 'text' },\n kind: { type: 'text' },\n source_id: { type: 'text' },\n // A park's occurrence is its epoch-ms stamp, past what INTEGER holds.\n occurrence: { type: 'bigint' },\n state: { type: 'text' },\n read_at: { type: 'timestamp' },\n archived_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_attention_receipts_user_source_unique',\n columns: ['org_id', 'factory_project_id', 'user_id', 'kind', 'source_id', 'occurrence'],\n },\n ],\n indexes: [\n {\n name: 'factory_attention_receipts_user_state_idx',\n columns: ['org_id', 'factory_project_id', 'user_id', 'state'],\n },\n {\n name: 'factory_attention_receipts_source_idx',\n columns: ['org_id', 'factory_project_id', 'kind', 'source_id', 'occurrence'],\n },\n ],\n },\n {\n name: 'factory_run_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n work_item_id: { type: 'text' },\n role: { type: 'text' },\n thread_id: { type: 'text' },\n resource_id: { type: 'text' },\n session_id: { type: 'text' },\n branch: { type: 'text' },\n status: { type: 'text' },\n created_at: { type: 'timestamp' },\n revoked_at: { type: 'timestamp', nullable: true },\n },\n indexes: [\n // Exact-address lookups run on every processor message; status filter is\n // applied on top of the address columns.\n {\n name: 'factory_run_bindings_session_idx',\n columns: ['factory_project_id', 'thread_id', 'resource_id', 'session_id'],\n },\n // Restart reconciler enumerates active bindings across all tenants.\n { name: 'factory_run_bindings_status_idx', columns: ['status'] },\n ],\n },\n {\n name: 'factory_tool_result_cursors',\n columns: {\n binding_id: { type: 'text', primaryKey: true },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n last_message_id: { type: 'text' },\n last_message_created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n },\n {\n name: 'factory_pending_starts',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n binding_id: { type: 'text' },\n kickoff_key: { type: 'text' },\n message: { type: 'text', nullable: true },\n status: { type: 'text' },\n attempts: { type: 'integer' },\n available_at: { type: 'timestamp' },\n lease_owner: { type: 'text', nullable: true },\n lease_expires_at: { type: 'timestamp', nullable: true },\n last_error: { type: 'text', nullable: true },\n failure_code: { type: 'text', nullable: true },\n completed_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n {\n name: 'factory_pending_starts_tenant_kickoff_unique',\n columns: ['org_id', 'factory_project_id', 'kickoff_key'],\n },\n ],\n indexes: [{ name: 'factory_pending_starts_claim_idx', columns: ['status', 'created_at'] }],\n },\n];\n\ninterface GovernanceDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n created_at: Date;\n [key: string]: unknown;\n}\n\nfunction toBinding(row: GovernanceDbRow): FactoryRunBindingRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n workItemId: String(row.work_item_id),\n role: String(row.role),\n threadId: String(row.thread_id),\n resourceId: String(row.resource_id),\n sessionId: String(row.session_id),\n branch: String(row.branch),\n status: row.status as FactoryRunBindingRecord['status'],\n createdAt: row.created_at,\n revokedAt: (row.revoked_at as Date | null) ?? null,\n };\n}\nfunction toDeferredDecision(row: GovernanceDbRow): FactoryDeferredDecisionRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n evaluationId: String(row.evaluation_id),\n workItemId: row.work_item_id === null || row.work_item_id === undefined ? null : String(row.work_item_id),\n idempotencyKey: String(row.idempotency_key),\n effectOrdinal: Number(row.effect_ordinal),\n effectHash: String(row.effect_hash),\n causalChain: (row.causal_chain as FactoryDeferredDecisionRecord['causalChain']) ?? [],\n actor: (row.actor as Record<string, unknown> | null) ?? null,\n decision: row.decision as Record<string, unknown>,\n status: row.status as FactoryDispatchStatus,\n attempts: Number(row.attempts),\n deliveryGeneration: Number(row.delivery_generation ?? 0),\n failureOccurrence: Number(row.failure_occurrence ?? 0),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n failureCode: isStoredFactoryDispatchFailureCode(row.failure_code) ? row.failure_code : null,\n approvedAt: (row.approved_at as Date | null) ?? null,\n approvedBy: (row.approved_by as string | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\nfunction attentionReceiptKind(value: unknown): FactoryAttentionKind {\n if (\n value === 'automation-failed' ||\n value === 'automation-proposed' ||\n value === 'mention' ||\n value === 'activity' ||\n value === 'supervisor-finding' ||\n value === 'agent-waiting'\n ) {\n return value;\n }\n throw new Error(`Unsupported attention receipt kind '${String(value)}'.`);\n}\n\nfunction toSupervisorFinding(row: GovernanceDbRow): FactorySupervisorFindingRecord {\n return {\n id: row.id,\n orgId: String(row.org_id),\n factoryProjectId: String(row.factory_project_id),\n findingKey: String(row.finding_key),\n occurrence: Number(row.occurrence),\n finding: row.finding as Record<string, unknown>,\n openedAt: row.opened_at as Date,\n updatedAt: row.updated_at as Date,\n resolvedAt: (row.resolved_at as Date | null) ?? null,\n };\n}\n\nfunction attentionReceiptState(value: unknown): FactoryAttentionReceiptState {\n if (value === 'read' || value === 'archived') return value;\n throw new Error(`Unsupported attention receipt state '${String(value)}'.`);\n}\n\nfunction toAttentionReceipt(row: GovernanceDbRow): FactoryAttentionReceiptRecord {\n if (typeof row.source_id !== 'string' || !row.source_id) {\n throw new Error('Attention receipt source_id must be a non-empty string.');\n }\n const occurrence = Number(row.occurrence);\n if (!Number.isSafeInteger(occurrence) || occurrence < 0) {\n throw new Error('Attention receipt occurrence must be a non-negative safe integer.');\n }\n if (!(row.read_at instanceof Date)) throw new Error('Attention receipt read_at must be a timestamp.');\n const archivedAt = row.archived_at;\n if (archivedAt !== null && archivedAt !== undefined && !(archivedAt instanceof Date)) {\n throw new Error('Attention receipt archived_at must be a timestamp or null.');\n }\n if (!(row.created_at instanceof Date)) throw new Error('Attention receipt created_at must be a timestamp.');\n if (!(row.updated_at instanceof Date)) throw new Error('Attention receipt updated_at must be a timestamp.');\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n userId: String(row.user_id),\n kind: attentionReceiptKind(row.kind),\n sourceId: row.source_id,\n occurrence,\n state: attentionReceiptState(row.state),\n readAt: row.read_at,\n archivedAt: archivedAt ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\nfunction toPendingStart(row: GovernanceDbRow): FactoryPendingStartRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n bindingId: String(row.binding_id),\n kickoffKey: String(row.kickoff_key),\n message: (row.message as string | null) ?? null,\n status: row.status as FactoryPendingStartRecord['status'],\n attempts: Number(row.attempts),\n availableAt: row.available_at as Date,\n leaseOwner: (row.lease_owner as string | null) ?? null,\n leaseExpiresAt: (row.lease_expires_at as Date | null) ?? null,\n lastError: (row.last_error as string | null) ?? null,\n failureCode: (row.failure_code as FactoryDispatchFailureCode | null) ?? null,\n completedAt: (row.completed_at as Date | null) ?? null,\n createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\n\n/** The project whose attention list a write just changed. */\nexport interface FactoryAttentionScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport class WorkItemsStorage extends FactoryStorageDomain {\n #attentionChanged: (scope: FactoryAttentionScope) => void = () => {};\n // Storage does not know boards. Until the host says which phases are terminal,\n // no card counts as finished, so the boot sweep never supersedes on a guess.\n #isTerminal: (item: WorkItemRow) => boolean = () => false;\n\n constructor() {\n super('work-items');\n }\n\n /**\n * Wired once at boot. Every write below that changes what this project's\n * attention list projects announces it here — the one place a new such write\n * has to remember, since clients stop polling while their stream is up.\n */\n onAttentionChanged(listener: (scope: FactoryAttentionScope) => void): void {\n this.#attentionChanged = listener;\n }\n\n /**\n * Wired once at boot, before `init()`. Tells the legacy attention sweep and\n * the stale-binding sweep which cards sit in a phase their installed board\n * declares terminal.\n */\n useTerminalPhasePredicate(isTerminal: (item: WorkItemRow) => boolean): void {\n this.#isTerminal = isTerminal;\n }\n\n async init(): Promise<void> {\n // The comment schemas are co-registered so the delete cascade below can\n // purge feed rows regardless of domain init order.\n await this.ensureCollections([\n WORK_ITEMS_SCHEMA,\n ...FACTORY_GOVERNANCE_SCHEMAS,\n WORK_ITEM_COMMENTS_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_ACTIVITY_SCHEMA,\n ]);\n await this.repairLegacyAttentionState();\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_items', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async #countRows(collection: string, where: CollectionWhere): Promise<number> {\n const count = this.#db.count;\n if (!count) throw new Error('[WorkItemsStorage] storage backend does not support collection counts.');\n return count.call(this.#db, collection, where);\n }\n\n async syncSupervisorFindings(input: {\n orgId: string;\n factoryProjectId: string;\n findings: FactoryHealthFinding[];\n now: Date;\n }): Promise<void> {\n const changed = await this.#withProjectRelationTransaction(input.orgId, input.factoryProjectId, async ops => {\n let changed = false;\n const existingOpen = await ops.findMany<GovernanceDbRow>('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n resolved_at: null,\n });\n const currentKeys = new Set(input.findings.map(finding => finding.id));\n for (const row of existingOpen) {\n if (!currentKeys.has(String(row.finding_key))) {\n await ops.updateAtomic<GovernanceDbRow>(\n 'factory_supervisor_findings',\n { id: row.id, resolved_at: null },\n () => ({ resolved_at: input.now, updated_at: input.now }),\n );\n changed = true;\n }\n }\n const openByKey = new Map(existingOpen.map(row => [String(row.finding_key), row]));\n for (const finding of input.findings) {\n const row =\n openByKey.get(finding.id) ??\n (await ops.findOne<GovernanceDbRow>('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n finding_key: finding.id,\n }));\n if (!row) {\n await ops.insertOne<GovernanceDbRow>('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n finding_key: finding.id,\n occurrence: 0,\n finding,\n opened_at: input.now,\n updated_at: input.now,\n resolved_at: null,\n });\n changed = true;\n continue;\n }\n const reopening = row.resolved_at !== null;\n const findingChanged = stableJson(row.finding) !== stableJson(finding);\n if (!reopening && !findingChanged) continue;\n await ops.updateAtomic<GovernanceDbRow>('factory_supervisor_findings', { id: row.id }, current => ({\n finding,\n occurrence: Number(current.occurrence) + (current.resolved_at !== null ? 1 : 0),\n opened_at: current.resolved_at !== null ? input.now : current.opened_at,\n updated_at: input.now,\n resolved_at: null,\n }));\n changed = true;\n }\n return changed;\n });\n if (changed) this.#attentionChanged?.({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n }\n\n async listSupervisorFindingPage(input: {\n orgId: string;\n factoryProjectId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<{ rows: FactorySupervisorFindingRecord[]; hasMore: boolean }> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_supervisor_findings',\n { org_id: input.orgId, factory_project_id: input.factoryProjectId, resolved_at: null },\n {\n orderBy: [\n ['opened_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.occurredAt, input.before.id] } } : {}),\n },\n );\n return { rows: rows.slice(0, input.limit).map(toSupervisorFinding), hasMore: rows.length > input.limit };\n }\n\n async countOpenSupervisorFindings(input: { orgId: string; factoryProjectId: string }): Promise<number> {\n return this.#countRows('factory_supervisor_findings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n resolved_at: null,\n });\n }\n\n async #withProjectRelationTransaction<T>(\n orgId: string,\n factoryProjectId: string,\n fn: (ops: FactoryStorageOps) => Promise<T>,\n ): Promise<T> {\n const key = `work-items:${orgId}:${factoryProjectId}`;\n return withInProcessProjectLock(key, () => this.storage.withTransaction(fn, { isolationLevel: 'serializable' }));\n }\n\n async #claimLeases<T>(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryLeaseClaimInput,\n map: (row: GovernanceDbRow) => T,\n ): Promise<T[]> {\n const claim = () =>\n this.storage.withTransaction(async ops => {\n // Bounded candidate window: only rows in claimable/expirable statuses,\n // oldest first. Terminal rows (sent/succeeded/failed) accumulate over a\n // deployment's lifetime and must never be scanned per dispatch tick.\n const candidates = await ops.findMany<GovernanceDbRow>(\n table,\n { status: { in: ['pending', 'retry', 'leased'] } },\n { orderBy: [['created_at', 'asc']], limit: Math.max(input.limit * 5, 50) },\n );\n const claimed: T[] = [];\n for (const candidate of candidates) {\n if (claimed.length >= input.limit) break;\n const availableAt = new Date(candidate.available_at as Date | string).getTime();\n const leaseExpiresAt = candidate.lease_expires_at\n ? new Date(candidate.lease_expires_at as Date | string).getTime()\n : 0;\n const claimable =\n (candidate.status === 'pending' || candidate.status === 'retry') && availableAt <= input.now.getTime();\n const expired = candidate.status === 'leased' && leaseExpiresAt <= input.now.getTime();\n if (!claimable && !expired) continue;\n let didClaim = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(table, { id: candidate.id }, current => {\n const currentAvailable = new Date(current.available_at as Date | string).getTime();\n const currentExpiry = current.lease_expires_at\n ? new Date(current.lease_expires_at as Date | string).getTime()\n : 0;\n const currentClaimable =\n (current.status === 'pending' || current.status === 'retry') && currentAvailable <= input.now.getTime();\n const currentExpired = current.status === 'leased' && currentExpiry <= input.now.getTime();\n if (!currentClaimable && !currentExpired) return null;\n didClaim = true;\n return {\n status: 'leased',\n attempts: Number(current.attempts) + 1,\n lease_owner: input.ownerId,\n lease_expires_at: input.leaseExpiresAt,\n updated_at: input.now,\n };\n });\n if (didClaim && row) claimed.push(map(row));\n }\n return claimed;\n });\n return claim();\n }\n\n async #renewLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n leaseExpiresAt: Date,\n ): Promise<boolean> {\n let renewed = false;\n await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n renewed = true;\n return { lease_expires_at: leaseExpiresAt, updated_at: new Date() };\n },\n );\n return renewed;\n }\n\n async #completeLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<GovernanceDbRow | null> {\n let completed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n completed = true;\n return {\n status: table === 'factory_pending_starts' ? 'sent' : 'succeeded',\n lease_owner: null,\n lease_expires_at: null,\n completed_at: now,\n updated_at: now,\n };\n },\n );\n return completed ? row : null;\n }\n\n async #failLease(\n table: 'factory_deferred_decisions' | 'factory_pending_starts',\n input: FactoryDispatchFailureInput,\n ): Promise<GovernanceDbRow | null> {\n let failed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n table,\n { id: input.id, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== input.ownerId) return null;\n failed = true;\n return {\n status: input.terminal ? 'failed' : 'retry',\n ...(table === 'factory_deferred_decisions' && !input.terminal && input.advanceDeliveryGeneration !== false\n ? { delivery_generation: Number(current.delivery_generation ?? 0) + 1 }\n : {}),\n available_at: input.availableAt,\n lease_owner: null,\n lease_expires_at: null,\n last_error: input.lastError,\n failure_code: input.failureCode,\n completed_at: input.terminal ? input.now : null,\n ...(table === 'factory_deferred_decisions' && input.terminal\n ? { failure_occurrence: Number(current.failure_occurrence ?? 0) + 1 }\n : {}),\n updated_at: input.now,\n };\n },\n );\n return failed ? row : null;\n }\n\n async #listWithOps(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<WorkItemRow[]> {\n const rows = await ops.findMany<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n },\n );\n return rows.map(toWorkItem);\n }\n\n /**\n * List the org's work items for a project, newest first. Ordered on `created_at` with an id\n * tiebreak so the order is stable: `updated_at` moves under every write, which makes it useless\n * as a cursor and non-deterministic for the callers that iterate this list.\n */\n async list({ orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }): Promise<WorkItemRow[]> {\n return this.#listWithOps(this.#db, orgId, factoryProjectId);\n }\n\n async listByIds({\n orgId,\n factoryProjectId,\n ids,\n }: {\n orgId: string;\n factoryProjectId: string;\n ids: string[];\n }): Promise<WorkItemRow[]> {\n if (ids.length === 0) return [];\n const rows = await this.#db.findMany<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n id: { in: [...new Set(ids)] },\n });\n return rows.map(toWorkItem);\n }\n\n /**\n * Strip every ref to a retired session; matching happens in app code because\n * `findMany` cannot reach inside the `sessions` JSON column.\n * ponytail: org-wide scan per session delete; JSON-path query if it measures.\n */\n async clearSessionReferences({ orgId, sessionId }: { orgId: string; sessionId: string }): Promise<number> {\n const rows = await this.#db.findMany<WorkItemDbRow>('work_items', { org_id: orgId });\n const holding = rows.filter(row => Object.values(row.sessions).some(ref => ref.sessionId === sessionId));\n let cleared = 0;\n for (const row of holding) {\n let changed = false;\n await this.#db.updateAtomic<WorkItemDbRow>('work_items', { id: row.id }, current => {\n const kept = Object.entries(current.sessions).filter(([, ref]) => ref.sessionId !== sessionId);\n if (kept.length === Object.keys(current.sessions).length) return null;\n changed = true;\n return { sessions: Object.fromEntries(kept), revision: current.revision + 1, updated_at: new Date() };\n });\n if (changed) cleared += 1;\n }\n return cleared;\n }\n\n async getByProjectSource({\n orgId,\n factoryProjectId,\n source,\n }: {\n orgId: string;\n factoryProjectId: string;\n source: ExternalWorkItemSource;\n }): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: externalSourceKey(source),\n });\n return row ? toWorkItem(row) : null;\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n return row ? toWorkItem(row) : null;\n }\n\n /**\n * Resolve the card a platform thread created, given only its external source.\n * Bare of org/project because an inbound platform message carries neither: an\n * unlinked sender has no tenant. Tenant safety rides on the key's\n * `workspaceId` instead. Ambiguous matches resolve to nothing, not a guess.\n */\n async getBySource(source: ExternalWorkItemSource): Promise<WorkItemRow | null> {\n const rows = await this.#db.findMany<WorkItemDbRow>('work_items', { source_key: externalSourceKey(source) });\n return rows.length === 1 ? toWorkItem(rows[0]!) : null;\n }\n\n async getForProject(orgId: string, factoryProjectId: string, id: string): Promise<WorkItemRow | null> {\n const row = await this.#db.findOne<WorkItemDbRow>('work_items', {\n id,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row ? toRow(row) : null;\n }\n\n async getTransitionResultByIngress(\n orgId: string,\n factoryProjectId: string,\n identity: string,\n ): Promise<Record<string, unknown> | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n identity,\n });\n return (row?.result as Record<string, unknown> | undefined) ?? null;\n }\n\n async commitTransition(input: CommitFactoryTransitionInput): Promise<CommitFactoryTransitionResult> {\n const commit = (): Promise<CommitFactoryTransitionResult> =>\n this.storage.withTransaction<CommitFactoryTransitionResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior)\n return {\n status: 'replayed',\n item: await this.getForProject(input.orgId, input.factoryProjectId, input.workItemId),\n result: prior.result as Record<string, unknown>,\n };\n\n const now = new Date();\n let item: WorkItemRow | null = null;\n let code: string | null = null;\n let reason: string | null = null;\n let result: Record<string, unknown>;\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n },\n row => {\n const existing = toRow(row);\n item = existing;\n if (existing.revision !== input.expectedRevision) {\n code = 'stale';\n reason = 'The work item changed before this transition committed.';\n return null;\n }\n if (input.evaluation.outcome === 'rejected') {\n code = input.evaluation.code;\n reason = input.evaluation.reason;\n return null;\n }\n const arm = input.autonomy === 'arm' && !existing.autonomyArmedAt;\n const disarm = input.autonomy === 'disarm' && existing.autonomyArmedAt !== null;\n const accept = input.accept === true && !existing.acceptedAt;\n const triageType = existing.triageType ?? input.triageType ?? null;\n const classified = triageType !== existing.triageType;\n if (existing.stages.length === 1 && existing.stages[0] === input.destinationStage) {\n // Classification is part of a terminal handoff, so unlike an\n // autonomy flip alone it is a revisioned work-item change.\n return arm || disarm || accept || classified\n ? patchColumns({\n ...(arm ? { autonomyArmedAt: now } : {}),\n ...(disarm ? { autonomyArmedAt: null } : {}),\n ...(accept ? { acceptedAt: now } : {}),\n ...(classified ? { triageType, revision: existing.revision + 1, updatedAt: now } : {}),\n })\n : null;\n }\n return patchColumns({\n ...(arm ? { autonomyArmedAt: now } : {}),\n ...(disarm ? { autonomyArmedAt: null } : {}),\n ...(accept ? { acceptedAt: now } : {}),\n ...(classified ? { triageType } : {}),\n stages: [input.destinationStage],\n stageHistory: applyStageTransition(\n existing.stageHistory,\n existing.stages,\n [input.destinationStage],\n input.actorId,\n now,\n ),\n revision: existing.revision + 1,\n updatedAt: now,\n });\n },\n );\n if (updated) item = toRow(updated);\n if (!item) {\n code = input.evaluation.outcome === 'rejected' ? input.evaluation.code : 'invalid_transition';\n reason = input.evaluation.outcome === 'rejected' ? input.evaluation.reason : 'Work item not found.';\n }\n const outcome: 'accepted' | 'rejected' =\n item && code === null && input.evaluation.outcome === 'accepted' ? 'accepted' : 'rejected';\n result =\n outcome === 'accepted'\n ? {\n status: 'accepted',\n transitionId: input.ingress.transitionId,\n itemId: item!.id,\n revision: item!.revision,\n stage: input.destinationStage,\n decisions: input.evaluation.outcome === 'accepted' ? input.evaluation.decisions : [],\n }\n : { status: 'rejected', transitionId: input.ingress.transitionId, itemId: input.workItemId, code, reason };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.transitionId,\n result,\n created_at: now,\n });\n if (item) {\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item.id,\n rule_set_version: input.configVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: now,\n });\n if (outcome === 'accepted' && input.evaluation.outcome === 'accepted') {\n for (const [index, decision] of input.evaluation.decisions.entries()) {\n // Consent pre-approves only the runs this same commit queues.\n const approvedBy = decision.type === 'invokeSkill' ? (input.consentedBy ?? null) : null;\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item.id,\n source_key: decisionSourceKey(decision),\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: index,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: null,\n decision,\n status: 'pending',\n attempts: 0,\n delivery_generation: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n approved_at: approvedBy ? now : null,\n approved_by: approvedBy,\n completed_at: null,\n created_at: new Date(now.getTime() + index),\n updated_at: now,\n });\n }\n }\n }\n return { status: 'committed', item, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async commitRuleEvaluation(input: CommitFactoryRuleEvaluationInput): Promise<CommitFactoryRuleEvaluationResult> {\n const commit = () =>\n this.storage.withTransaction<CommitFactoryRuleEvaluationResult>(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n });\n if (prior) {\n const result = prior.result as Record<string, unknown>;\n const decisions = Array.isArray(result.decisions) ? result.decisions : [];\n const evaluation = await ops.findOne<GovernanceDbRow>('factory_rule_evaluations', { ingress_id: prior.id });\n for (const decision of decisions) {\n if (\n !evaluation ||\n !decision ||\n typeof decision !== 'object' ||\n (decision as Record<string, unknown>).type !== 'upsertLinkedWorkItem' ||\n typeof (decision as Record<string, unknown>).sourceKey !== 'string' ||\n typeof (decision as Record<string, unknown>).idempotencyKey !== 'string'\n ) {\n continue;\n }\n const materialization = decision as Record<string, unknown> & { sourceKey: string; idempotencyKey: string };\n const item = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: materialization.sourceKey,\n });\n if (item) continue;\n await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n idempotency_key: materialization.idempotencyKey,\n },\n current =>\n current.status === 'succeeded'\n ? {\n status: 'retry',\n attempts: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n updated_at: input.now,\n }\n : null,\n );\n }\n return { status: 'replayed' as const, result };\n }\n const itemRow = input.workItemId\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : null;\n if (input.workItemId !== null && !itemRow) return { status: 'missing' as const };\n const item = itemRow ? toRow(itemRow) : null;\n const stale = item !== null && item.revision !== input.expectedRevision;\n const outcome = stale ? 'rejected' : input.outcome.status;\n const code = stale ? 'stale' : (input.outcome.code ?? null);\n const reason = stale\n ? 'The work item changed before this rule evaluation committed.'\n : (input.outcome.reason ?? null);\n const decisions = outcome === 'accepted' ? input.decisions : [];\n const result = {\n status: outcome,\n itemId: item?.id ?? null,\n revision: item?.revision ?? null,\n code,\n reason,\n decisions,\n };\n const ingress = await ops.insertOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n identity: input.ingress.identity,\n trigger_type: input.ingress.triggerType,\n transition_id: input.ingress.identity,\n result,\n created_at: input.now,\n });\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n work_item_id: item?.id ?? null,\n rule_set_version: input.configVersion,\n expected_revision: input.expectedRevision,\n outcome,\n code,\n reason,\n causal_chain: input.causalChain,\n created_at: input.now,\n });\n for (const [effectOrdinal, decision] of decisions.entries()) {\n await ops.insertOne<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n evaluation_id: evaluation.id,\n work_item_id: item?.id ?? null,\n source_key: decisionSourceKey(decision),\n idempotency_key: String(decision.idempotencyKey),\n effect_ordinal: effectOrdinal,\n effect_hash: factoryDecisionHash(decision),\n causal_chain: input.causalChain,\n actor: input.actor,\n decision,\n status: 'pending',\n attempts: 0,\n delivery_generation: 0,\n available_at: input.now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n completed_at: null,\n created_at: new Date(input.now.getTime() + effectOrdinal),\n updated_at: input.now,\n });\n }\n return { status: 'committed' as const, result };\n });\n try {\n return await commit();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return commit();\n }\n }\n\n async getToolResultCursor(\n orgId: string,\n factoryProjectId: string,\n bindingId: string,\n ): Promise<FactoryToolResultCursorRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_tool_result_cursors', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n binding_id: bindingId,\n });\n return row\n ? {\n bindingId: String(row.binding_id),\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n lastMessageId: String(row.last_message_id),\n lastMessageCreatedAt: row.last_message_created_at as Date,\n updatedAt: row.updated_at as Date,\n }\n : null;\n }\n\n async advanceToolResultCursor(cursor: FactoryToolResultCursorRecord): Promise<void> {\n const current = await this.getToolResultCursor(cursor.orgId, cursor.factoryProjectId, cursor.bindingId);\n if (current && current.lastMessageCreatedAt > cursor.lastMessageCreatedAt) return;\n await this.#db.upsertOne<GovernanceDbRow>('factory_tool_result_cursors', ['binding_id'], {\n binding_id: cursor.bindingId,\n org_id: cursor.orgId,\n factory_project_id: cursor.factoryProjectId,\n last_message_id: cursor.lastMessageId,\n last_message_created_at: cursor.lastMessageCreatedAt,\n updated_at: cursor.updatedAt,\n });\n }\n\n async listDeferredDecisions(orgId: string, factoryProjectId: string): Promise<FactoryDeferredDecisionRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toDeferredDecision);\n }\n\n /** Read a bounded newest-first status page without exposing another tenant. */\n async listDeferredDecisionPage(input: FactoryDeferredDecisionPageInput): Promise<FactoryDeferredDecisionPage> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n ...(input.statuses ? { status: { in: input.statuses } } : {}),\n },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.createdAt, input.before.id] } } : {}),\n },\n );\n return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };\n }\n\n /** Newest-parked-first keyset over one status, on the `updated_at` the status was stamped. */\n async listDecisionPageByStatus(input: FactoryDecisionStatusPageInput): Promise<FactoryDeferredDecisionPage> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n status: input.status,\n },\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: input.limit + 1,\n ...(input.before ? { cursor: { values: [input.before.occurredAt, input.before.id] } } : {}),\n },\n );\n return { decisions: rows.slice(0, input.limit).map(toDeferredDecision), hasMore: rows.length > input.limit };\n }\n\n async countDeferredDecisionsByStatuses({\n orgId,\n factoryProjectId,\n statuses,\n }: {\n orgId: string;\n factoryProjectId: string;\n statuses: FactoryDispatchStatus[];\n }): Promise<number> {\n return this.#countRows('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n status: { in: statuses },\n });\n }\n\n async getDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_deferred_decisions', {\n id: decisionId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n });\n return row ? toDeferredDecision(row) : null;\n }\n\n async listAttentionReceipts({\n orgId,\n factoryProjectId,\n userId,\n identities,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n identities: FactoryAttentionIdentity[];\n }): Promise<FactoryAttentionReceiptRecord[]> {\n if (identities.length === 0) return [];\n const requested = new Set(\n identities.map(identity => `${identity.kind}\\0${identity.sourceId}\\0${identity.occurrence}`),\n );\n const sourceIds = [...new Set(identities.map(identity => identity.sourceId))];\n const kinds = [...new Set(identities.map(identity => identity.kind))];\n const receipts: FactoryAttentionReceiptRecord[] = [];\n for (let index = 0; index < sourceIds.length; index += ATTENTION_RECEIPT_QUERY_BATCH_SIZE) {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n user_id: userId,\n kind: { in: kinds },\n source_id: { in: sourceIds.slice(index, index + ATTENTION_RECEIPT_QUERY_BATCH_SIZE) },\n });\n receipts.push(\n ...rows\n .map(toAttentionReceipt)\n .filter(receipt => requested.has(`${receipt.kind}\\0${receipt.sourceId}\\0${receipt.occurrence}`)),\n );\n }\n return receipts;\n }\n\n async countAttentionReceipts({\n orgId,\n factoryProjectId,\n userId,\n kind,\n state,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n kind: FactoryAttentionKind;\n state?: FactoryAttentionReceiptState;\n }): Promise<number> {\n return this.#countRows('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n user_id: userId,\n kind,\n ...(state ? { state } : {}),\n });\n }\n\n async deleteAttentionReceipts({\n orgId,\n factoryProjectId,\n userId,\n identities,\n }: {\n orgId: string;\n factoryProjectId: string;\n /** Restrict to one user's receipts (a removed mention must keep other users' read state). */\n userId?: string;\n identities: FactoryAttentionIdentity[];\n }): Promise<void> {\n const unique = [\n ...new Map(\n identities.map(identity => [`${identity.kind}\\0${identity.sourceId}\\0${identity.occurrence}`, identity]),\n ).values(),\n ];\n for (let index = 0; index < unique.length; index += ATTENTION_RECEIPT_WRITE_BATCH_SIZE) {\n await Promise.all(\n unique.slice(index, index + ATTENTION_RECEIPT_WRITE_BATCH_SIZE).map(identity =>\n this.#db.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(userId ? { user_id: userId } : {}),\n kind: identity.kind,\n source_id: identity.sourceId,\n occurrence: identity.occurrence,\n }),\n ),\n );\n }\n }\n\n async setAttentionReceipt(input: SetAttentionReceiptInput): Promise<FactoryAttentionReceiptRecord | null> {\n return this.#retryAttentionReceiptWrite(() =>\n this.storage.withTransaction(ops => this.#setAttentionReceiptWithOps(ops, input)),\n );\n }\n\n async #retryAttentionReceiptWrite<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return write();\n }\n }\n\n /**\n * Per-kind currency predicate: a receipt may only target a source that still\n * projects an attention item FOR THIS USER — otherwise the route answers\n * 409. Without the mention-row check, any member could write receipts\n * against arbitrary comment ids and permanently skew their own badge math.\n */\n async #attentionSourceIsCurrent(\n ops: FactoryStorageOps,\n {\n orgId,\n factoryProjectId,\n userId,\n identity,\n }: { orgId: string; factoryProjectId: string; userId: string; identity: FactoryAttentionIdentity },\n ): Promise<boolean> {\n if (identity.kind === 'automation-failed') {\n let currentOccurrence = false;\n const decision = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: identity.sourceId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n currentOccurrence =\n current.status === 'failed' && Number(current.failure_occurrence ?? 0) === identity.occurrence;\n return null;\n },\n );\n return Boolean(decision) && currentOccurrence;\n }\n if (identity.kind === 'automation-proposed') {\n let parked = false;\n const decision = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: identity.sourceId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n parked = current.status === 'proposed' && identity.occurrence === 0;\n return null;\n },\n );\n return Boolean(decision) && parked;\n }\n // A parked session has no row here; the route checks it against the live registry.\n if (identity.kind === 'agent-waiting') return true;\n if (identity.kind === 'activity') {\n // Occurrence-exact: a bump since the read makes that receipt stale, and\n // the route answers 409. Scoped to this user or every badge would skew.\n const activity = await ops.findOne('work_item_activity', {\n work_item_id: identity.sourceId,\n participant_id: userId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n occurrence: identity.occurrence,\n });\n return activity !== null;\n }\n if (identity.kind === 'supervisor-finding') {\n const finding = await ops.findOne('factory_supervisor_findings', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n finding_key: identity.sourceId,\n occurrence: identity.occurrence,\n resolved_at: null,\n });\n return finding !== null;\n }\n if (identity.occurrence !== 0) return false;\n const mention = await ops.findOne('work_item_comment_mentions', {\n comment_id: identity.sourceId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n mentioned_kind: 'user',\n mentioned_id: userId,\n });\n if (!mention) return false;\n const comment = await ops.findOne('work_item_comments', {\n id: identity.sourceId,\n org_id: orgId,\n factory_project_id: factoryProjectId,\n deleted_at: null,\n });\n return comment !== null;\n }\n\n async #setAttentionReceiptWithOps(\n ops: FactoryStorageOps,\n { orgId, factoryProjectId, userId, identity, action, now }: SetAttentionReceiptInput,\n ): Promise<FactoryAttentionReceiptRecord | null> {\n if (!(await this.#attentionSourceIsCurrent(ops, { orgId, factoryProjectId, userId, identity }))) return null;\n\n const where = {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n user_id: userId,\n kind: identity.kind,\n source_id: identity.sourceId,\n occurrence: identity.occurrence,\n };\n const existing = await ops.findOne<GovernanceDbRow>('factory_attention_receipts', where);\n if (!existing) {\n return toAttentionReceipt(\n await ops.insertOne<GovernanceDbRow>('factory_attention_receipts', {\n ...where,\n state: action === 'archive' ? 'archived' : 'read',\n read_at: now,\n archived_at: action === 'archive' ? now : null,\n created_at: now,\n updated_at: now,\n }),\n );\n }\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_attention_receipts',\n { id: existing.id, ...where },\n current => {\n const preserveArchive = action === 'read' && current.state === 'archived';\n const archived = action === 'archive' || preserveArchive;\n return {\n state: archived ? 'archived' : 'read',\n read_at: current.read_at,\n archived_at: action === 'archive' ? now : archived ? (current.archived_at ?? now) : null,\n updated_at: now,\n };\n },\n );\n return row ? toAttentionReceipt(row) : null;\n }\n\n async markAttentionReceiptsRead({\n orgId,\n factoryProjectId,\n userId,\n identities,\n now,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n identities: FactoryAttentionIdentity[];\n now: Date;\n }): Promise<void> {\n const uniqueIdentities = [\n ...new Map(\n identities.map(identity => [`${identity.kind}\\0${identity.sourceId}\\0${identity.occurrence}`, identity]),\n ).values(),\n ];\n for (let index = 0; index < uniqueIdentities.length; index += ATTENTION_RECEIPT_WRITE_BATCH_SIZE) {\n const batch = uniqueIdentities.slice(index, index + ATTENTION_RECEIPT_WRITE_BATCH_SIZE);\n await this.#retryAttentionReceiptWrite(() =>\n this.storage.withTransaction(async ops => {\n for (const identity of batch) {\n await this.#setAttentionReceiptWithOps(ops, {\n orgId,\n factoryProjectId,\n userId,\n identity,\n action: 'read',\n now,\n });\n }\n }),\n );\n }\n }\n\n async claimDeferredDecisions(input: FactoryLeaseClaimInput): Promise<FactoryDeferredDecisionRecord[]> {\n return this.#claimLeases('factory_deferred_decisions', input, toDeferredDecision);\n }\n\n async renewDeferredDecisionLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_deferred_decisions', identity, leaseExpiresAt);\n }\n\n async completeDeferredDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#completeLease('factory_deferred_decisions', identity, now);\n return row ? toDeferredDecision(row) : null;\n }\n\n async failDeferredDecision(input: FactoryDispatchFailureInput): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#failLease('factory_deferred_decisions', input);\n if (!row) return null;\n const record = toDeferredDecision(row);\n // A retryable failure surfaces nothing; only a terminal one mints an item.\n if (input.terminal) this.#attentionChanged(record);\n return record;\n }\n\n /** Park a claimed effect for human approval; the dispatcher never claims `proposed` rows. */\n async proposeDeferredDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n let proposed = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: identity.id, org_id: identity.orgId, factory_project_id: identity.factoryProjectId },\n current => {\n if (current.status !== 'leased' || current.lease_owner !== identity.ownerId) return null;\n proposed = true;\n return {\n status: 'proposed',\n // The claim that parked it spent no effect, so it costs no attempt.\n attempts: 0,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now,\n };\n },\n );\n if (!proposed || !row) return null;\n const record = toDeferredDecision(row);\n this.#attentionChanged(record);\n return record;\n }\n\n /**\n * Release an approved effect back to the dispatcher; only `proposed` rows are\n * approvable. Approval is a person taking the item on, so the item's autonomy\n * is armed in the same transaction — a crash cannot release the run while\n * leaving its follow-up work parked for re-approval.\n */\n async approveDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n approvedBy?: string,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const approved = await this.storage.withTransaction(async ops => {\n let settled = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'proposed') return null;\n settled = true;\n return {\n status: 'pending',\n attempts: 0,\n available_at: now,\n approved_at: now,\n approved_by: approvedBy ?? null,\n updated_at: now,\n };\n },\n );\n if (!settled || !row) return null;\n const record = toDeferredDecision(row);\n await ops.deleteMany('factory_attention_receipts', proposalReceiptFilter(orgId, factoryProjectId, decisionId));\n if (record.workItemId) {\n await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id: record.workItemId }, current =>\n current.autonomy_armed_at ? null : { autonomy_armed_at: now },\n );\n }\n return record;\n });\n if (approved) this.#attentionChanged(approved);\n return approved;\n }\n\n /** Retire a proposal nobody wants: `dismissed` is terminal, so the run never happens. */\n async dismissDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n return this.#settleProposedDecision(\n { orgId, factoryProjectId, decisionId },\n { status: 'dismissed', updated_at: now, completed_at: now },\n );\n }\n\n /**\n * Automatically retire proposed or failed work that a newer run or terminal\n * work-item state has overtaken. Human dismissal remains `dismissed`.\n */\n async supersedeDecisionsForWorkItem(input: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n role?: string;\n supersededAt: Date;\n }): Promise<FactoryDeferredDecisionRecord[]> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n status: { in: ['proposed', 'failed'] },\n });\n const superseded: FactoryDeferredDecisionRecord[] = [];\n for (const row of rows) {\n const decision = toDeferredDecision(row);\n if (input.role !== undefined && decision.decision.role !== input.role) continue;\n const record =\n decision.status === 'proposed'\n ? await this.#settleProposedDecision(\n {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n decisionId: decision.id,\n },\n { status: 'superseded', updated_at: input.supersededAt, completed_at: input.supersededAt },\n )\n : await this.#resolveFailedDecision({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n decisionId: decision.id,\n status: 'superseded',\n now: input.supersededAt,\n });\n if (record) superseded.push(record);\n }\n return superseded;\n }\n\n async #settleProposedDecision(\n { orgId, factoryProjectId, decisionId }: { orgId: string; factoryProjectId: string; decisionId: string },\n patch: Partial<GovernanceDbRow>,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const settled = await this.storage.withTransaction(async ops => {\n let updated = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'proposed') return null;\n updated = true;\n return patch;\n },\n );\n if (!updated || !row) return null;\n await ops.deleteMany('factory_attention_receipts', proposalReceiptFilter(orgId, factoryProjectId, decisionId));\n return toDeferredDecision(row);\n });\n if (settled) this.#attentionChanged(settled);\n return settled;\n }\n\n async #resolveFailedDecision({\n orgId,\n factoryProjectId,\n decisionId,\n status,\n now,\n }: {\n orgId: string;\n factoryProjectId: string;\n decisionId: string;\n status: 'succeeded' | 'superseded';\n now: Date;\n }): Promise<FactoryDeferredDecisionRecord | null> {\n const resolved = await this.storage.withTransaction(async ops => {\n let resolved = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'failed') return null;\n resolved = true;\n return { status, updated_at: now };\n },\n );\n if (!resolved || !row) return null;\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'automation-failed',\n source_id: decisionId,\n occurrence: Number(row.failure_occurrence ?? 0),\n });\n return toDeferredDecision(row);\n });\n if (resolved) this.#attentionChanged(resolved);\n return resolved;\n }\n\n async supersedeTerminalDecisionsForWorkItem(input: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n supersededAt: Date;\n }): Promise<void> {\n await this.supersedeDecisionsForWorkItem(input);\n }\n\n async repairLegacyAttentionState(): Promise<void> {\n let cursor: { values: Array<Date | string> } | undefined;\n const inspectedWorkItems = new Set<string>();\n while (true) {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { status: { in: ['failed', 'proposed'] } },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n limit: ATTENTION_RECEIPT_QUERY_BATCH_SIZE + 1,\n ...(cursor ? { cursor } : {}),\n },\n );\n const page = rows.slice(0, ATTENTION_RECEIPT_QUERY_BATCH_SIZE);\n for (const row of page) {\n const decision = toDeferredDecision(row);\n if (\n decision.status === 'failed' &&\n decision.failureOccurrence === 0 &&\n deferredDecisionType(decision) === 'transition'\n ) {\n const ingress = await this.#db.findOne<GovernanceDbRow>('factory_rule_ingress', {\n org_id: decision.orgId,\n factory_project_id: decision.factoryProjectId,\n identity: `decision:${decision.idempotencyKey}`,\n });\n if (ingressWasAccepted(ingress)) {\n await this.#resolveFailedDecision({\n orgId: decision.orgId,\n factoryProjectId: decision.factoryProjectId,\n decisionId: decision.id,\n status: 'succeeded',\n now: new Date(),\n });\n continue;\n }\n }\n if (!decision.workItemId) continue;\n const itemKey = `${decision.orgId}\\0${decision.factoryProjectId}\\0${decision.workItemId}`;\n if (inspectedWorkItems.has(itemKey)) continue;\n inspectedWorkItems.add(itemKey);\n const item = await this.get({ orgId: decision.orgId, id: decision.workItemId });\n if (!item || !this.#isTerminal(item)) continue;\n await this.supersedeDecisionsForWorkItem({\n orgId: decision.orgId,\n factoryProjectId: decision.factoryProjectId,\n workItemId: decision.workItemId,\n supersededAt: new Date(),\n });\n }\n const last = page.at(-1);\n if (rows.length <= ATTENTION_RECEIPT_QUERY_BATCH_SIZE || !last) return;\n if (!(last.created_at instanceof Date)) throw new Error('Deferred decision created_at is not a timestamp.');\n cursor = { values: [last.created_at, last.id] };\n }\n }\n\n /** Requeue the same idempotent terminal effect; non-failed decisions are never rerun. */\n async retryDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const retriedRecord = await this.storage.withTransaction(async ops => {\n let retried = false;\n const row = await ops.updateAtomic<GovernanceDbRow>(\n 'factory_deferred_decisions',\n { id: decisionId, org_id: orgId, factory_project_id: factoryProjectId },\n current => {\n if (current.status !== 'failed') return null;\n retried = true;\n return {\n status: 'retry',\n attempts: 0,\n delivery_generation: Number(current.delivery_generation ?? 0) + 1,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n failure_code: null,\n completed_at: null,\n updated_at: now,\n };\n },\n );\n if (!retried || !row) return null;\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'automation-failed',\n source_id: decisionId,\n occurrence: Number(row.failure_occurrence ?? 0),\n });\n return toDeferredDecision(row);\n });\n if (retriedRecord) this.#attentionChanged(retriedRecord);\n return retriedRecord;\n }\n\n /** Resolve exact active agent authority; partial session matches never authorize. */\n async findActiveRunBinding(address: FactoryRunBindingAddress): Promise<FactoryRunBindingRecord | null> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: address.orgId,\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n status: 'active',\n });\n return row ? toBinding(row) : null;\n }\n\n /**\n * Recover the active binding for a thread when session state lost\n * `factoryProjectId` (e.g. crash-resume recreated the session empty).\n * Ambiguous matches across factory projects never authorize.\n */\n async findActiveRunBindingByThread(input: {\n orgId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n }): Promise<FactoryRunBindingRecord | null> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n thread_id: input.threadId,\n resource_id: input.resourceId,\n session_id: input.sessionId,\n status: 'active',\n });\n if (new Set(rows.map(row => row.factory_project_id)).size !== 1) return null;\n const row = rows.sort((left, right) => right.created_at.getTime() - left.created_at.getTime())[0];\n return row ? toBinding(row) : null;\n }\n\n /** Resolve exact bound-session state for processor awareness; ambiguous cross-tenant matches return null. */\n async findRunBindingBySession(address: FactoryRunBindingSessionAddress): Promise<FactoryRunBindingRecord | null> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n factory_project_id: address.factoryProjectId,\n thread_id: address.threadId,\n resource_id: address.resourceId,\n session_id: address.sessionId,\n });\n if (new Set(rows.map(row => row.org_id)).size !== 1) return null;\n const row = rows.sort((left, right) => {\n if (left.status === 'active' && right.status !== 'active') return -1;\n if (right.status === 'active' && left.status !== 'active') return 1;\n return right.created_at.getTime() - left.created_at.getTime();\n })[0];\n return row ? toBinding(row) : null;\n }\n\n /** Revoke one exact tenant-scoped binding. */\n async revokeRunBinding(input: RevokeFactoryRunBindingInput): Promise<FactoryRunBindingRecord | null> {\n let revoked = false;\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_run_bindings',\n { id: input.bindingId, org_id: input.orgId, factory_project_id: input.factoryProjectId },\n current => {\n if (current.status !== 'active') return null;\n revoked = true;\n return { status: 'revoked', revoked_at: input.revokedAt };\n },\n );\n return revoked && row ? toBinding(row) : null;\n }\n\n /**\n * Revoke every active binding for one work item (all roles). Called from\n * terminal-stage cleanup so completed items stop paying the reconcile walk.\n * Returns the number of bindings revoked.\n */\n async revokeRunBindingsForWorkItem(input: RevokeFactoryRunBindingsForWorkItemInput): Promise<number> {\n return this.#db.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n status: 'active',\n },\n { status: 'revoked', revoked_at: input.revokedAt },\n );\n }\n\n /**\n * Revoke leaked/legacy active bindings: older than `olderThan`, or whose\n * work item is gone, malformed, or already terminal. Terminal-stage cleanup\n * handles bindings go-forward; this sweep drains anything that slipped past\n * it. Returns the number of bindings revoked.\n */\n async revokeStaleRunBindings(input: RevokeStaleFactoryRunBindingsInput): Promise<number> {\n const bindings = await this.listActiveRunBindings();\n const itemCache = new Map<string, WorkItemRow | null>();\n let revoked = 0;\n for (const binding of bindings) {\n let stale = binding.createdAt.getTime() < input.olderThan.getTime();\n if (!stale) {\n const key = `${binding.orgId}:${binding.workItemId}`;\n let item = itemCache.get(key);\n if (item === undefined) {\n item = await this.get({ orgId: binding.orgId, id: binding.workItemId });\n itemCache.set(key, item);\n }\n // Terminal-ness comes from the installed board via the host-wired\n // predicate; an unknown board or phase is never treated as finished.\n stale =\n !item ||\n item.stages.length !== 1 ||\n this.#isTerminal(item) ||\n item.factoryProjectId !== binding.factoryProjectId;\n }\n if (!stale) continue;\n const result = await this.revokeRunBinding({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n bindingId: binding.id,\n revokedAt: input.now,\n });\n if (result) revoked += 1;\n }\n return revoked;\n }\n\n /** Enumerate active bindings for the server-owned restart reconciler. */\n async listActiveRunBindings(): Promise<FactoryRunBindingRecord[]> {\n return (await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', { status: 'active' })).map(toBinding);\n }\n\n /** List binding history, optionally narrowed to one work item. */\n async listRunBindings(\n orgId: string,\n factoryProjectId: string,\n workItemId?: string,\n ): Promise<FactoryRunBindingRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_run_bindings',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(workItemId ? { work_item_id: workItemId } : {}),\n },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toBinding);\n }\n\n async listPendingStarts(orgId: string, factoryProjectId: string): Promise<FactoryPendingStartRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_pending_starts',\n { org_id: orgId, factory_project_id: factoryProjectId },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toPendingStart);\n }\n\n async claimPendingStarts(input: FactoryLeaseClaimInput): Promise<FactoryPendingStartRecord[]> {\n return this.#claimLeases('factory_pending_starts', input, toPendingStart);\n }\n\n async renewPendingStartLease(identity: FactoryLeaseIdentity, leaseExpiresAt: Date): Promise<boolean> {\n return this.#renewLease('factory_pending_starts', identity, leaseExpiresAt);\n }\n\n async completePendingStart(identity: FactoryLeaseIdentity, now: Date): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#completeLease('factory_pending_starts', identity, now);\n return row ? toPendingStart(row) : null;\n }\n\n async failPendingStart(input: FactoryDispatchFailureInput): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#failLease('factory_pending_starts', input);\n return row ? toPendingStart(row) : null;\n }\n\n async prepareRunStart(input: PrepareFactoryRunStartInput): Promise<PrepareFactoryRunStartResult> {\n const prepare = () =>\n this.storage.withTransaction(async ops => {\n const prior = await ops.findOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n kickoff_key: input.kickoffKey,\n });\n if (prior) {\n const bindingRow = await ops.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: String(prior.binding_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n const itemRow =\n bindingRow &&\n (await ops.findOne<WorkItemDbRow>('work_items', {\n id: String(bindingRow.work_item_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n }));\n if (!bindingRow || !itemRow) throw new Error('Factory start replay references missing state.');\n return {\n item: toRow(itemRow),\n binding: toBinding(bindingRow),\n pendingStart: toPendingStart(prior),\n replayed: true,\n };\n }\n const now = new Date();\n const create = input.workItem.input;\n let row = input.workItem.id\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n id: input.workItem.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : externalSourceKey(create.externalSource)\n ? await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: externalSourceKey(create.externalSource),\n })\n : null;\n let item: WorkItemRow;\n if (row) {\n row = await ops.updateAtomic<WorkItemDbRow>('work_items', { id: row.id }, current => {\n // Stamp only the starting role — `applyUpdate` merges sessions, so\n // other roles keep their own session and `startedBy` (#22254).\n return applyUpdate({ current, userId: input.userId, input: { sessions: { [input.role]: input.session } } });\n });\n item = toRow(row!);\n } else {\n if (create.parentWorkItemId)\n validateParentRelation(\n (\n await ops.findMany<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n ).map(toRow),\n undefined,\n create.parentWorkItemId,\n );\n row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: input.orgId,\n created_by: input.userId,\n factory_project_id: input.factoryProjectId,\n board: create.board ?? null,\n external_source: create.externalSource ?? null,\n source_key: externalSourceKey(create.externalSource),\n parent_work_item_id: create.parentWorkItemId ?? null,\n title: create.title,\n stages: create.stages ?? [],\n stage_history: applyStageTransition([], [], create.stages ?? [], input.userId, now),\n sessions: stampSessions({ [input.role]: input.session }, input.userId),\n metadata: create.metadata ?? null,\n revision: 1,\n created_at: now,\n updated_at: now,\n });\n item = toRow(row);\n }\n await ops.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n thread_id: input.session.threadId,\n resource_id: input.resourceId,\n session_id: input.session.sessionId,\n status: 'active',\n },\n { status: 'revoked', revoked_at: now },\n );\n await ops.updateMany(\n 'factory_run_bindings',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n status: 'active',\n },\n { status: 'revoked', revoked_at: now },\n );\n const bindingRow = await ops.insertOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: item.id,\n role: input.role,\n thread_id: input.session.threadId,\n resource_id: input.resourceId,\n session_id: input.session.sessionId,\n branch: input.session.branch,\n status: 'active',\n created_at: now,\n revoked_at: null,\n });\n const pendingRow = await ops.insertOne<GovernanceDbRow>('factory_pending_starts', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n binding_id: bindingRow.id,\n kickoff_key: input.kickoffKey,\n message: input.kickoffMessage,\n status: 'pending',\n attempts: 0,\n available_at: now,\n lease_owner: null,\n lease_expires_at: null,\n last_error: null,\n failure_code: null,\n completed_at: null,\n created_at: now,\n updated_at: now,\n });\n return { item, binding: toBinding(bindingRow), pendingStart: toPendingStart(pendingRow), replayed: false };\n });\n // A losing preparer can hit two distinct unique violations back to back:\n // first on the work item's `source_key`, then on the pending start's\n // `kickoff_key` (when the winner commits its pending row between our\n // attempts). Each retry re-reads, so one extra attempt converges on replay.\n let lastError: unknown;\n for (let attempt = 0; attempt < 3; attempt++) {\n try {\n return await prepare();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n lastError = error;\n }\n }\n throw lastError;\n }\n\n async markPendingStart(\n bindingId: string,\n status: 'sent' | 'failed',\n lastError?: string,\n ): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_pending_starts',\n { binding_id: bindingId },\n () => ({ status, last_error: lastError ?? null, updated_at: new Date() }),\n );\n return row ? toPendingStart(row) : null;\n }\n\n /**\n * Create a work item, reusing the existing record when `sourceKey` already\n * has one for the project (acting twice on the same issue must not duplicate\n * the card). On reuse the provided stages replace the current ones (with the\n * transition recorded in history) and sessions/metadata are merged in. The\n * result discriminates insert from reuse so callers can audit the actual\n * outcome.\n */\n async upsert(params: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n }): Promise<UpsertWorkItemResult> {\n const run = (ops: FactoryStorageOps) => this.#upsert(params, ops);\n const execute = () =>\n params.input.parentWorkItemId\n ? this.#withProjectRelationTransaction(params.orgId, params.factoryProjectId, run)\n : run(this.#db);\n try {\n return await execute();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return execute();\n }\n }\n\n async #upsert(\n {\n orgId,\n userId,\n factoryProjectId,\n input,\n reuseMode = 'update',\n }: {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n reuseMode?: 'update' | 'preserve' | 'non-stage';\n },\n ops: FactoryStorageOps,\n ): Promise<UpsertWorkItemResult> {\n const key = externalSourceKey(input.externalSource);\n const reuse = async (): Promise<UpsertWorkItemResult | null> => {\n if (!key) return null;\n const existing = await ops.findOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: key,\n });\n if (!existing) return null;\n if (reuseMode === 'preserve') {\n const item = toWorkItem(existing);\n return { created: false, item, previous: priorState(existing) };\n }\n\n let previous = emptyPrior();\n const updated = await ops.updateAtomic<WorkItemDbRow>(\n 'work_items',\n { org_id: orgId, factory_project_id: factoryProjectId, source_key: key },\n async current => {\n previous = priorState(current);\n const fullPatch = input.parentWorkItemId === null ? { ...input, parentWorkItemId: undefined } : input;\n const patch: UpdateWorkItemInput =\n reuseMode === 'non-stage'\n ? {\n title: input.title,\n parentWorkItemId: input.parentWorkItemId ?? undefined,\n metadata: input.metadata,\n }\n : fullPatch;\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return {\n board: reuseMode === 'non-stage' ? current.board : (input.board ?? current.board ?? null),\n external_source: input.externalSource ?? null,\n ...applyUpdate({ current, userId, input: patch }),\n };\n },\n );\n return updated ? { item: toWorkItem(updated), created: false, previous } : null;\n };\n\n const reused = await reuse();\n if (reused) return reused;\n\n const now = new Date();\n const stages = input.stages ?? ['intake'];\n validateParentRelation(\n await this.#listWithOps(ops, orgId, factoryProjectId),\n undefined,\n input.parentWorkItemId ?? null,\n );\n const row = await ops.insertOne<WorkItemDbRow>('work_items', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n board: input.board ?? null,\n external_source: input.externalSource ?? null,\n source_key: key,\n parent_work_item_id: input.parentWorkItemId ?? null,\n title: input.title,\n stages,\n stage_history: stages.map(stage => ({ stage, enteredAt: now.toISOString(), by: userId })),\n sessions: stampSessions(input.sessions ?? {}, userId),\n metadata: input.metadata ?? null,\n revision: 1,\n created_by: userId,\n created_at: now,\n updated_at: now,\n });\n return { item: toWorkItem(row), created: true, previous: emptyPrior() };\n }\n\n async setParentWorkItemIfMissing({\n orgId,\n id,\n userId,\n parentWorkItemId,\n }: {\n orgId: string;\n id: string;\n userId: string;\n parentWorkItemId: string;\n }): Promise<WorkItemRow | null> {\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const row = await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id }, async current => {\n if (current.parent_work_item_id !== null) return current;\n validateParentRelation(\n await this.#listWithOps(ops, orgId, current.factory_project_id),\n current.id,\n parentWorkItemId,\n );\n return applyUpdate({ current, userId, input: { parentWorkItemId } });\n });\n return row ? toWorkItem(row) : null;\n });\n }\n\n async update({\n orgId,\n id,\n userId,\n patch,\n expectedRevision,\n expectedBoard,\n }: {\n orgId: string;\n id: string;\n userId: string;\n patch: UpdateWorkItemInput;\n expectedRevision?: number;\n expectedBoard?: string | null;\n }): Promise<{ item: WorkItemRow; previous: WorkItemPriorState } | null> {\n const run = async (ops: FactoryStorageOps) => {\n let previous = emptyPrior();\n const row = await ops.updateAtomic<WorkItemDbRow>('work_items', { org_id: orgId, id }, async current => {\n previous = priorState(current);\n if (expectedBoard !== undefined && current.board !== expectedBoard) {\n throw new WorkItemUpdateConflictError('board');\n }\n if (expectedRevision !== undefined && current.revision !== expectedRevision) {\n throw new WorkItemUpdateConflictError('revision');\n }\n if (patch.parentWorkItemId !== undefined) {\n validateParentRelation(\n await this.#listWithOps(ops, orgId, current.factory_project_id),\n current.id,\n patch.parentWorkItemId,\n );\n }\n return applyUpdate({ current, userId, input: patch });\n });\n return row ? { item: toWorkItem(row), previous } : null;\n };\n\n if (patch.parentWorkItemId === undefined) return run(this.#db);\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, run);\n }\n\n /**\n * Drop the governance rows that materialized a source key so a deleted work item\n * is not resurrected by the prior-ingress replay path on the next intake poll.\n */\n async #purgeRuleState(\n ops: FactoryStorageOps,\n { orgId, factoryProjectId, sourceKey }: { orgId: string; factoryProjectId: string; sourceKey: string },\n ): Promise<void> {\n const decisions = await ops.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: sourceKey,\n });\n if (decisions.length === 0) return;\n\n const evaluationIds = [...new Set(decisions.map(decision => String(decision.evaluation_id)))];\n const ingressIds = new Set<string>();\n for (const evaluationId of evaluationIds) {\n const evaluation = await ops.findOne<GovernanceDbRow>('factory_rule_evaluations', { id: evaluationId });\n if (evaluation) ingressIds.add(String(evaluation.ingress_id));\n }\n\n const decisionIds = decisions.map(decision => decision.id);\n for (let index = 0; index < decisionIds.length; index += ATTENTION_RECEIPT_QUERY_BATCH_SIZE) {\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'automation-failed',\n source_id: { in: decisionIds.slice(index, index + ATTENTION_RECEIPT_QUERY_BATCH_SIZE) },\n });\n }\n\n await ops.deleteMany('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: sourceKey,\n });\n for (const evaluationId of evaluationIds) {\n await ops.deleteMany('factory_rule_evaluations', { id: evaluationId });\n }\n for (const ingressId of ingressIds) {\n const remaining = await ops.findMany<GovernanceDbRow>('factory_rule_evaluations', { ingress_id: ingressId });\n if (remaining.length === 0) await ops.deleteMany('factory_rule_ingress', { id: ingressId });\n }\n }\n\n /**\n * Feed rows die with their work item: orphan mention rows would keep\n * projecting attention items that deep-link to a card that no longer exists.\n */\n async #purgeFeedState(\n ops: FactoryStorageOps,\n { orgId, factoryProjectId, workItemId }: { orgId: string; factoryProjectId: string; workItemId: string },\n ): Promise<void> {\n // Paged harvest: this runs inside the delete transaction and a long-lived\n // item can carry thousands of comments — never materialize them all.\n const where = { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId };\n while (true) {\n const comments = await ops.findMany<{ id: string } & Record<string, unknown>>('work_item_comments', where, {\n limit: ATTENTION_RECEIPT_QUERY_BATCH_SIZE,\n });\n if (comments.length === 0) break;\n const commentIds = comments.map(comment => comment.id);\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'mention',\n source_id: { in: commentIds },\n });\n await ops.deleteMany('work_item_comments', { ...where, id: { in: commentIds } });\n if (comments.length < ATTENTION_RECEIPT_QUERY_BATCH_SIZE) break;\n }\n await ops.deleteMany('work_item_comment_mentions', where);\n // Activity is keyed on the item, so one statement covers every occurrence\n // and every participant.\n await ops.deleteMany('factory_attention_receipts', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n kind: 'activity',\n source_id: workItemId,\n });\n await ops.deleteMany('work_item_activity', where);\n }\n\n async delete({ orgId, id }: { orgId: string; id: string }): Promise<WorkItemRow | null> {\n const candidate = await this.#db.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!candidate) return null;\n\n const removed = await this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const existing = await ops.findOne<WorkItemDbRow>('work_items', { org_id: orgId, id });\n if (!existing) return null;\n const deleted = await ops.deleteMany('work_items', { org_id: orgId, id });\n if (deleted === 0) return null;\n await this.#purgeFeedState(ops, { orgId, factoryProjectId: existing.factory_project_id, workItemId: id });\n if (existing.source_key) {\n await this.#purgeRuleState(ops, {\n orgId,\n factoryProjectId: existing.factory_project_id,\n sourceKey: existing.source_key,\n });\n }\n await ops.updateMany(\n 'work_items',\n { org_id: orgId, parent_work_item_id: id },\n { parent_work_item_id: null, updated_at: new Date() },\n );\n return toWorkItem(existing);\n });\n if (removed) this.#attentionChanged(removed);\n return removed;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAwBA,SAAS,WAAW,OAAwB;CAC1C,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,IAAI,MAAM,IAAI,UAAU,CAAC,CAAC,KAAK,GAAG,EAAE;CACrE,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,IAAI,OAAO,QAAQ,KAAgC,CAAC,CACxD,MAAM,CAAC,OAAO,CAAC,WAAW,KAAK,cAAc,KAAK,CAAC,CAAC,CACpD,KAAK,CAAC,KAAK,WAAW,GAAG,KAAK,UAAU,GAAG,EAAE,GAAG,WAAW,KAAK,GAAG,CAAC,CACpE,KAAK,GAAG,EAAE;CAEf,OAAO,KAAK,UAAU,KAAK,KAAK;AAClC;AAEA,SAAgB,oBAAoB,UAA2C;CAC7E,OAAO,WAAW,QAAQ,CA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