@mastra/factory 0.29.0-alpha.4 → 0.29.0-alpha.5

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 (315) hide show
  1. package/README.md +119 -60
  2. package/dist/boards/board-events.d.ts +89 -9
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +176 -13
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts.map +1 -1
  7. package/dist/boards/board-writes.js +14 -1
  8. package/dist/boards/board-writes.js.map +1 -1
  9. package/dist/boards/busy-card.d.ts +11 -0
  10. package/dist/boards/busy-card.d.ts.map +1 -0
  11. package/dist/boards/busy-card.js +15 -0
  12. package/dist/boards/busy-card.js.map +1 -0
  13. package/dist/boards/card-facts.d.ts.map +1 -1
  14. package/dist/boards/card-facts.js +18 -4
  15. package/dist/boards/card-facts.js.map +1 -1
  16. package/dist/boards/index.d.ts +2 -1
  17. package/dist/boards/index.d.ts.map +1 -1
  18. package/dist/boards/index.js +3 -2
  19. package/dist/boards/intake-dry-run.d.ts +109 -0
  20. package/dist/boards/intake-dry-run.d.ts.map +1 -0
  21. package/dist/boards/intake-dry-run.js +158 -0
  22. package/dist/boards/intake-dry-run.js.map +1 -0
  23. package/dist/boards/intake-lookup.d.ts +32 -0
  24. package/dist/boards/intake-lookup.d.ts.map +1 -0
  25. package/dist/boards/intake-lookup.js +12 -0
  26. package/dist/boards/intake-lookup.js.map +1 -0
  27. package/dist/boards/intake-order.d.ts +32 -0
  28. package/dist/boards/intake-order.d.ts.map +1 -0
  29. package/dist/boards/intake-order.js +60 -0
  30. package/dist/boards/intake-order.js.map +1 -0
  31. package/dist/boards/intake-routing.d.ts +246 -35
  32. package/dist/boards/intake-routing.d.ts.map +1 -1
  33. package/dist/boards/intake-routing.js +437 -52
  34. package/dist/boards/intake-routing.js.map +1 -1
  35. package/dist/boards/reroute.d.ts +7 -3
  36. package/dist/boards/reroute.d.ts.map +1 -1
  37. package/dist/boards/reroute.js +21 -4
  38. package/dist/boards/reroute.js.map +1 -1
  39. package/dist/boards/semantics.d.ts +8 -28
  40. package/dist/boards/semantics.d.ts.map +1 -1
  41. package/dist/boards/semantics.js +7 -39
  42. package/dist/boards/semantics.js.map +1 -1
  43. package/dist/boards/work-routes.d.ts +31 -11
  44. package/dist/boards/work-routes.d.ts.map +1 -1
  45. package/dist/boards/work-routes.js +104 -20
  46. package/dist/boards/work-routes.js.map +1 -1
  47. package/dist/factory.d.ts +27 -1
  48. package/dist/factory.d.ts.map +1 -1
  49. package/dist/factory.js +31 -9
  50. package/dist/factory.js.map +1 -1
  51. package/dist/integrations/base.d.ts +9 -0
  52. package/dist/integrations/base.d.ts.map +1 -1
  53. package/dist/integrations/dependabot/rules.js +1 -1
  54. package/dist/integrations/dependabot/rules.js.map +1 -1
  55. package/dist/integrations/github/default-rules.d.ts +22 -1
  56. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  57. package/dist/integrations/github/default-rules.js +23 -5
  58. package/dist/integrations/github/default-rules.js.map +1 -1
  59. package/dist/integrations/github/intake-lookup.d.ts +16 -0
  60. package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
  61. package/dist/integrations/github/intake-lookup.js +76 -0
  62. package/dist/integrations/github/intake-lookup.js.map +1 -0
  63. package/dist/integrations/github/integration.d.ts +19 -5
  64. package/dist/integrations/github/integration.d.ts.map +1 -1
  65. package/dist/integrations/github/integration.js +21 -6
  66. package/dist/integrations/github/integration.js.map +1 -1
  67. package/dist/integrations/github/review-status-reporter.js +1 -1
  68. package/dist/integrations/github/routes.d.ts.map +1 -1
  69. package/dist/integrations/github/routes.js +14 -2
  70. package/dist/integrations/github/routes.js.map +1 -1
  71. package/dist/integrations/github/rules.d.ts +12 -1
  72. package/dist/integrations/github/rules.d.ts.map +1 -1
  73. package/dist/integrations/github/rules.js +218 -30
  74. package/dist/integrations/github/rules.js.map +1 -1
  75. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  76. package/dist/integrations/github/sandbox.js +30 -4
  77. package/dist/integrations/github/sandbox.js.map +1 -1
  78. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  79. package/dist/integrations/gitlab/default-rules.js +19 -3
  80. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  81. package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
  82. package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
  83. package/dist/integrations/gitlab/intake-lookup.js +85 -0
  84. package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
  85. package/dist/integrations/gitlab/integration.d.ts +5 -0
  86. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  87. package/dist/integrations/gitlab/integration.js +21 -1
  88. package/dist/integrations/gitlab/integration.js.map +1 -1
  89. package/dist/integrations/gitlab/rules.d.ts +20 -0
  90. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  91. package/dist/integrations/gitlab/rules.js +108 -12
  92. package/dist/integrations/gitlab/rules.js.map +1 -1
  93. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  94. package/dist/integrations/incidentio/rules.js +14 -4
  95. package/dist/integrations/incidentio/rules.js.map +1 -1
  96. package/dist/integrations/jira/rules.d.ts.map +1 -1
  97. package/dist/integrations/jira/rules.js +12 -2
  98. package/dist/integrations/jira/rules.js.map +1 -1
  99. package/dist/integrations/linear/rules.d.ts.map +1 -1
  100. package/dist/integrations/linear/rules.js +13 -2
  101. package/dist/integrations/linear/rules.js.map +1 -1
  102. package/dist/integrations/platform/github/event-worker.js +9 -1
  103. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  104. package/dist/integrations/platform/github/integration.d.ts +6 -6
  105. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  106. package/dist/integrations/platform/github/integration.js +22 -3
  107. package/dist/integrations/platform/github/integration.js.map +1 -1
  108. package/dist/integrations/pull-request-head.d.ts +1 -1
  109. package/dist/integrations/pull-request-head.d.ts.map +1 -1
  110. package/dist/integrations/pull-request-head.js +5 -0
  111. package/dist/integrations/pull-request-head.js.map +1 -1
  112. package/dist/integrations/vanta/rules.js +1 -1
  113. package/dist/integrations/vanta/rules.js.map +1 -1
  114. package/dist/routes/board-snapshot.d.ts +8 -1
  115. package/dist/routes/board-snapshot.d.ts.map +1 -1
  116. package/dist/routes/board-snapshot.js +33 -7
  117. package/dist/routes/board-snapshot.js.map +1 -1
  118. package/dist/routes/boards.js.map +1 -1
  119. package/dist/routes/config.d.ts +6 -0
  120. package/dist/routes/config.d.ts.map +1 -1
  121. package/dist/routes/config.js +5 -2
  122. package/dist/routes/config.js.map +1 -1
  123. package/dist/routes/contracts.d.ts +1258 -0
  124. package/dist/routes/contracts.d.ts.map +1 -1
  125. package/dist/routes/contracts.js +586 -13
  126. package/dist/routes/contracts.js.map +1 -1
  127. package/dist/routes/intake-check.d.ts +92 -0
  128. package/dist/routes/intake-check.d.ts.map +1 -0
  129. package/dist/routes/intake-check.js +322 -0
  130. package/dist/routes/intake-check.js.map +1 -0
  131. package/dist/routes/intake-routes.d.ts +10 -2
  132. package/dist/routes/intake-routes.d.ts.map +1 -1
  133. package/dist/routes/intake-routes.js +292 -11
  134. package/dist/routes/intake-routes.js.map +1 -1
  135. package/dist/routes/mastra-gateway.d.ts.map +1 -1
  136. package/dist/routes/mastra-gateway.js +3 -2
  137. package/dist/routes/mastra-gateway.js.map +1 -1
  138. package/dist/routes/project-sessions.d.ts +49 -0
  139. package/dist/routes/project-sessions.d.ts.map +1 -0
  140. package/dist/routes/project-sessions.js +93 -0
  141. package/dist/routes/project-sessions.js.map +1 -0
  142. package/dist/routes/run-queue.d.ts +6 -6
  143. package/dist/routes/run-queue.d.ts.map +1 -1
  144. package/dist/routes/run-queue.js +28 -8
  145. package/dist/routes/run-queue.js.map +1 -1
  146. package/dist/routes/session-rows.d.ts +30 -0
  147. package/dist/routes/session-rows.d.ts.map +1 -0
  148. package/dist/routes/session-rows.js +98 -0
  149. package/dist/routes/session-rows.js.map +1 -0
  150. package/dist/routes/source-control-sessions.d.ts +4 -5
  151. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  152. package/dist/routes/source-control-sessions.js +8 -87
  153. package/dist/routes/source-control-sessions.js.map +1 -1
  154. package/dist/routes/surface.d.ts +13 -1
  155. package/dist/routes/surface.d.ts.map +1 -1
  156. package/dist/routes/surface.js +24 -26
  157. package/dist/routes/surface.js.map +1 -1
  158. package/dist/routes/work-item-starters.d.ts +1 -0
  159. package/dist/routes/work-item-starters.d.ts.map +1 -1
  160. package/dist/routes/work-item-starters.js +14 -2
  161. package/dist/routes/work-item-starters.js.map +1 -1
  162. package/dist/routes/work-items.d.ts +13 -0
  163. package/dist/routes/work-items.d.ts.map +1 -1
  164. package/dist/routes/work-items.js +87 -34
  165. package/dist/routes/work-items.js.map +1 -1
  166. package/dist/rules/dispatch-errors.js +1 -1
  167. package/dist/rules/dispatch-errors.js.map +1 -1
  168. package/dist/rules/dispatcher.d.ts +39 -7
  169. package/dist/rules/dispatcher.d.ts.map +1 -1
  170. package/dist/rules/dispatcher.js +361 -122
  171. package/dist/rules/dispatcher.js.map +1 -1
  172. package/dist/rules/event-rules.d.ts +69 -1
  173. package/dist/rules/event-rules.d.ts.map +1 -1
  174. package/dist/rules/event-rules.js +151 -5
  175. package/dist/rules/event-rules.js.map +1 -1
  176. package/dist/rules/review-source-tool.js +1 -1
  177. package/dist/rules/rule-group.d.ts +18 -1
  178. package/dist/rules/rule-group.d.ts.map +1 -1
  179. package/dist/rules/rule-group.js +52 -8
  180. package/dist/rules/rule-group.js.map +1 -1
  181. package/dist/rules/run-bearing.d.ts +8 -0
  182. package/dist/rules/run-bearing.d.ts.map +1 -0
  183. package/dist/rules/run-bearing.js +11 -0
  184. package/dist/rules/run-bearing.js.map +1 -0
  185. package/dist/rules/start-coordinator.d.ts +2 -3
  186. package/dist/rules/start-coordinator.d.ts.map +1 -1
  187. package/dist/rules/start-coordinator.js +26 -34
  188. package/dist/rules/start-coordinator.js.map +1 -1
  189. package/dist/rules/tools.js +2 -1
  190. package/dist/rules/tools.js.map +1 -1
  191. package/dist/rules/transition-service.d.ts +16 -0
  192. package/dist/rules/transition-service.d.ts.map +1 -1
  193. package/dist/rules/transition-service.js +34 -10
  194. package/dist/rules/transition-service.js.map +1 -1
  195. package/dist/rules/types.d.ts +18 -5
  196. package/dist/rules/types.d.ts.map +1 -1
  197. package/dist/rules/types.js +2 -1
  198. package/dist/rules/types.js.map +1 -1
  199. package/dist/rules/update-fold.d.ts +32 -0
  200. package/dist/rules/update-fold.d.ts.map +1 -0
  201. package/dist/rules/update-fold.js +60 -0
  202. package/dist/rules/update-fold.js.map +1 -0
  203. package/dist/rules/validation.d.ts.map +1 -1
  204. package/dist/rules/validation.js +54 -6
  205. package/dist/rules/validation.js.map +1 -1
  206. package/dist/session/resource-migration.d.ts.map +1 -1
  207. package/dist/session/resource-migration.js +2 -3
  208. package/dist/session/resource-migration.js.map +1 -1
  209. package/dist/session/run-audit.d.ts +9 -0
  210. package/dist/session/run-audit.d.ts.map +1 -1
  211. package/dist/session/run-audit.js +9 -1
  212. package/dist/session/run-audit.js.map +1 -1
  213. package/dist/session/self-review-gate.d.ts +26 -2
  214. package/dist/session/self-review-gate.d.ts.map +1 -1
  215. package/dist/session/self-review-gate.js +60 -10
  216. package/dist/session/self-review-gate.js.map +1 -1
  217. package/dist/session/session-row-query.d.ts +25 -0
  218. package/dist/session/session-row-query.d.ts.map +1 -0
  219. package/dist/session/session-row-query.js +47 -0
  220. package/dist/session/session-row-query.js.map +1 -0
  221. package/dist/session/session-row-status.d.ts +16 -0
  222. package/dist/session/session-row-status.d.ts.map +1 -0
  223. package/dist/session/session-row-status.js +14 -0
  224. package/dist/session/session-row-status.js.map +1 -0
  225. package/dist/session/session-row-view.d.ts +14 -0
  226. package/dist/session/session-row-view.d.ts.map +1 -0
  227. package/dist/session/session-row-view.js +125 -0
  228. package/dist/session/session-row-view.js.map +1 -0
  229. package/dist/session/session-rows.d.ts +46 -0
  230. package/dist/session/session-rows.d.ts.map +1 -0
  231. package/dist/session/session-rows.js +232 -0
  232. package/dist/session/session-rows.js.map +1 -0
  233. package/dist/session/session-threads.d.ts.map +1 -1
  234. package/dist/session/session-threads.js +1 -0
  235. package/dist/session/session-threads.js.map +1 -1
  236. package/dist/session/source-control-tools.d.ts +14 -7
  237. package/dist/session/source-control-tools.d.ts.map +1 -1
  238. package/dist/session/source-control-tools.js +10 -2
  239. package/dist/session/source-control-tools.js.map +1 -1
  240. package/dist/session/work-item-repository.d.ts +44 -0
  241. package/dist/session/work-item-repository.d.ts.map +1 -1
  242. package/dist/session/work-item-repository.js +80 -1
  243. package/dist/session/work-item-repository.js.map +1 -1
  244. package/dist/session/work-item-state-processor.d.ts.map +1 -1
  245. package/dist/session/work-item-state-processor.js +44 -8
  246. package/dist/session/work-item-state-processor.js.map +1 -1
  247. package/dist/storage/domains/audit/actions.d.ts +2 -1
  248. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  249. package/dist/storage/domains/audit/actions.js +3 -1
  250. package/dist/storage/domains/audit/actions.js.map +1 -1
  251. package/dist/storage/domains/boards/base.d.ts +162 -14
  252. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  253. package/dist/storage/domains/boards/base.js +415 -41
  254. package/dist/storage/domains/boards/base.js.map +1 -1
  255. package/dist/storage/domains/boards/schemas.d.ts +6 -0
  256. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  257. package/dist/storage/domains/boards/schemas.js +95 -1
  258. package/dist/storage/domains/boards/schemas.js.map +1 -1
  259. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  260. package/dist/storage/domains/projects/base.js +19 -10
  261. package/dist/storage/domains/projects/base.js.map +1 -1
  262. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  263. package/dist/storage/domains/source-control/base.js +5 -2
  264. package/dist/storage/domains/source-control/base.js.map +1 -1
  265. package/dist/storage/domains/work-items/base.d.ts +48 -17
  266. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  267. package/dist/storage/domains/work-items/base.js +128 -75
  268. package/dist/storage/domains/work-items/base.js.map +1 -1
  269. package/dist/storage/domains/work-items/cards.d.ts +3 -2
  270. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  271. package/dist/storage/domains/work-items/cards.js +4 -2
  272. package/dist/storage/domains/work-items/cards.js.map +1 -1
  273. package/dist/storage/probed-list.d.ts +11 -0
  274. package/dist/storage/probed-list.d.ts.map +1 -0
  275. package/dist/storage/probed-list.js +52 -0
  276. package/dist/storage/probed-list.js.map +1 -0
  277. package/dist/tools/audit-events-tool.d.ts +2 -2
  278. package/dist/tools/read-tools.d.ts +0 -3
  279. package/dist/tools/read-tools.d.ts.map +1 -1
  280. package/dist/tools/read-tools.js +4 -42
  281. package/dist/tools/read-tools.js.map +1 -1
  282. package/dist/tools/session-tools.d.ts.map +1 -1
  283. package/dist/tools/session-tools.js +5 -9
  284. package/dist/tools/session-tools.js.map +1 -1
  285. package/dist/tools/work-item-tools.d.ts +3 -0
  286. package/dist/tools/work-item-tools.d.ts.map +1 -1
  287. package/dist/tools/work-item-tools.js +8 -4
  288. package/dist/tools/work-item-tools.js.map +1 -1
  289. package/dist/work-item-branch.d.ts +4 -0
  290. package/dist/work-item-branch.d.ts.map +1 -1
  291. package/dist/work-item-branch.js +7 -1
  292. package/dist/work-item-branch.js.map +1 -1
  293. package/dist/work-items/card-context-sessions.d.ts +50 -0
  294. package/dist/work-items/card-context-sessions.d.ts.map +1 -0
  295. package/dist/work-items/card-context-sessions.js +84 -0
  296. package/dist/work-items/card-context-sessions.js.map +1 -0
  297. package/dist/work-items/change-requests.d.ts +87 -0
  298. package/dist/work-items/change-requests.d.ts.map +1 -0
  299. package/dist/work-items/change-requests.js +134 -0
  300. package/dist/work-items/change-requests.js.map +1 -0
  301. package/dist/work-items/create-work-item.d.ts +7 -2
  302. package/dist/work-items/create-work-item.d.ts.map +1 -1
  303. package/dist/work-items/create-work-item.js +44 -13
  304. package/dist/work-items/create-work-item.js.map +1 -1
  305. package/dist/work-items/list-related-cards.d.ts.map +1 -1
  306. package/dist/work-items/list-related-cards.js +1 -1
  307. package/dist/work-items/list-related-cards.js.map +1 -1
  308. package/dist/work-items/providers/github.d.ts.map +1 -1
  309. package/dist/work-items/providers/github.js +1 -0
  310. package/dist/work-items/providers/github.js.map +1 -1
  311. package/factory-skills/factory-build/SKILL.md +1 -1
  312. package/factory-skills/factory-plan/SKILL.md +5 -3
  313. package/factory-skills/factory-self-review/SKILL.md +2 -0
  314. package/factory-skills/factory-triage/SKILL.md +1 -1
  315. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"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 { factoryDispatchFailureMetadata } from '../../../rules/dispatch-errors.js';\nimport { externalSourceForWorkItem, FACTORY_TRIAGE_TYPES } from '../../../rules/types.js';\nimport type { FactoryTriageType, WorkItemSource } from '../../../rules/types.js';\nimport { splitCardMetadata, workItemProviderAdapter } from '../../../work-items/providers/index.js';\nimport {\n copyLegacyRows,\n migrateWorkItemSplit,\n readLegacyWatermark,\n readWorkItemSplitMarker,\n recordWorkItemSplitComplete,\n} from '../../../work-items/split-migration.js';\nimport type { LegacyWatermark, WorkItemSplitReport } from '../../../work-items/split-migration.js';\nimport { ensureLegacyCollections } from '../../legacy-collections.js';\nimport {\n BoardScopes,\n bumpBoardVersions,\n CARD_TABLES,\n DECISION_TABLES,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n readBoardVersion,\n trackBoardWrites,\n} from './board-version.js';\nimport type { BoardScope } from './board-version.js';\nimport { Cards, splitCardRows } from './cards.js';\nimport { LEASE_TABLES, trackClaimableWrites } from './claimable-work.js';\nimport type { FactoryClaimableWorkScope } from './claimable-work.js';\nimport {\n LEGACY_REST_PHASE,\n LEGACY_REVIEW_BOARD,\n LEGACY_TRIAGE_PHASE,\n LEGACY_WORK_BOARD,\n readReviewBoardInUse,\n releaseLegacyReviewCards,\n} from './legacy-review.js';\nimport type { ReviewBoardInUse, ReviewBoardScope } from './legacy-review.js';\nimport type {\n WorkItemRow as ProviderWorkItemRow,\n WorkItemDbRecord,\n WorkItemSourceDbRecord,\n WorkItemSourceRow,\n} from './work-item-schema.js';\nimport {\n primarySource,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n WORK_ITEMS_SCHEMA,\n} from './work-item-schema.js';\n\nexport type { FactoryClaimableWorkScope } from './claimable-work.js';\n\nexport type WorkItemStage = string;\n\n/** Freeze `value` and everything reachable from it, so shared cache entries cannot be written to. */\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const entry of Object.values(value)) deepFreeze(entry);\n }\n return value;\n}\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\nfunction isWorkItemSource(value: unknown): value is WorkItemSource {\n return (\n value === 'github-issue' ||\n value === 'github-pr' ||\n value === 'linear-issue' ||\n value === 'jira-issue' ||\n value === 'incidentio-follow-up' ||\n value === 'github-dependabot-alert' ||\n value === 'vanta-vulnerability' ||\n value === 'detail-finding' ||\n value === 'manual'\n );\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 CommitFactoryRuleEvaluationInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n ingress: { identity: 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 /** Consent-bearing actor behind the evaluation; their id pre-approves the skill runs it queues. */\n consentedBy?: string;\n}\n\nexport type CommitFactoryRuleEvaluationResult =\n | { status: 'committed'; result: Record<string, unknown> }\n | { status: 'replayed'; result: Record<string, unknown> }\n | { status: 'missing' }\n /** The work item's revision moved; nothing was persisted, so the caller may re-read and retry. */\n | { status: 'stale' };\n\nexport interface FactoryToolResultCursorRecord {\n bindingId: string;\n orgId: string;\n factoryProjectId: string;\n lastMessageCreatedAt: Date;\n updatedAt: 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 'source_repository_ambiguous',\n 'unsupported_provider_item',\n 'notification_delivery_failed',\n 'run_terminal_event_missing',\n 'run_incomplete',\n 'skill_delivery_ambiguous',\n 'run_overdue',\n 'repository_git_missing',\n 'repository_sandbox_unresponsive',\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 'run_configuration_invalid',\n 'run_credentials_unavailable',\n 'run_user_unauthenticated',\n 'factory_org_key_missing',\n 'run_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 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 = 'automation-failed' | 'automation-proposed' | 'agent-waiting';\nexport type FactoryAttentionReceiptState = 'read' | 'archived';\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\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, unless `keep` exempts them. */\n olderThan: Date;\n now: Date;\n /** Exempts an over-age binding from the age test only; the item-state checks still apply. */\n keep?: (binding: FactoryRunBindingRecord) => Promise<boolean>;\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 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 FactoryDeferredDecisionClaimInput extends FactoryLeaseClaimInput {\n /** Restrict the claim by decision payload; rejected rows are never leased. */\n decisionFilter?: (decision: Record<string, unknown>) => boolean;\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; transitionId: 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: Card | null; result: Record<string, unknown> }\n | { status: 'replayed'; item: Card | null; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport class FactoryRunBindingSupersededError extends Error {\n constructor() {\n super('Factory run binding was superseded before preparation.');\n }\n}\n\nexport interface PrepareFactoryRunStartInput {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n workItem: { id?: string; input: CreateWorkItemInput };\n role: string;\n /** Only recover this binding if it still owns the role when the transaction starts. */\n expectedBindingId?: string;\n session: WorkItemSessionInput;\n resourceId: string;\n kickoffKey: string;\n kickoffMessage: string | null;\n}\n\nexport interface PrepareFactoryRunStartResult {\n item: Card;\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 Card extends BoardItemRow {\n workItem: ProviderWorkItemRow;\n externalSource: ExternalWorkItemSource | null;\n parentWorkItemId: string | null;\n title: string;\n /** What the card is about, in the words of whoever filed it; handed to agent runs at kickoff. */\n description: string | null;\n}\n\nexport interface BoardItemRow {\n workItemId: string;\n parentBoardItemId: string | null;\n id: string;\n orgId: string;\n factoryProjectId: string;\n board: string | null;\n stages: WorkItemStage[];\n stageHistory: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n /** When the card last changed. A reader that keeps the board tells its copy of the card by it. */\n changedAt?: Date | 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. Boards whose phases don't start\n * on their own 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 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 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 description?: string | null;\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 description?: string | null;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface WorkItemPriorState {\n stages: WorkItemStage[];\n sessionRoles: string[];\n}\n\nexport interface UpsertWorkItemResult {\n item: Card;\n created: boolean;\n previous: WorkItemPriorState;\n}\n\nexport const FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_subscriptions',\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 session_id: { type: 'text' },\n thread_id: { type: 'text' },\n resource_id: { type: 'text' },\n user_id: { type: 'text' },\n reason: { type: 'text' },\n created_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_work_item_subscriptions_item_session_unique', columns: ['work_item_id', 'session_id'] },\n ],\n indexes: [\n {\n name: 'factory_work_item_subscriptions_session_idx',\n columns: ['org_id', 'factory_project_id', 'session_id'],\n },\n ],\n};\n\n/** Why a session follows a work item: it filed it, moved it, started a role on it, or asked to. */\nexport type WorkItemSubscriptionReason = 'created' | 'moved' | 'started' | 'subscribed';\n\n/** A session following a work item, so it hears what happens to it. */\nexport interface WorkItemSubscription {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n sessionId: string;\n threadId: string;\n resourceId: string;\n userId: string;\n reason: WorkItemSubscriptionReason;\n createdAt: Date;\n}\n\nexport interface SubscribeToWorkItemInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n sessionId: string;\n threadId: string;\n resourceId: string;\n userId: string;\n reason: WorkItemSubscriptionReason;\n}\n\ninterface WorkItemSubscriptionDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n session_id: string;\n thread_id: string;\n resource_id: string;\n user_id: string;\n reason: WorkItemSubscriptionReason;\n created_at: Date;\n}\n\nfunction toWorkItemSubscription(row: WorkItemSubscriptionDbRow): WorkItemSubscription {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n workItemId: row.work_item_id,\n sessionId: row.session_id,\n threadId: row.thread_id,\n resourceId: row.resource_id,\n userId: row.user_id,\n reason: row.reason,\n createdAt: row.created_at,\n };\n}\n\nexport interface WorkItemDbRow extends Record<string, unknown> {\n work_item?: WorkItemDbRecord;\n work_item_sources?: WorkItemSourceDbRecord[];\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 claim_key: string | null;\n parent_work_item_id: string | null;\n title: string;\n description: string | null;\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 revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n changed_at?: Date | null;\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 toSource(source: WorkItemSourceDbRecord): WorkItemSourceRow {\n return {\n id: source.id,\n workItemId: source.work_item_id,\n provider: source.provider,\n integrationId: source.integration_id,\n sourceType: source.source_type,\n workspaceId: source.workspace_id,\n externalId: source.external_id,\n sourceKey: source.source_key,\n key: source.key,\n url: source.url,\n state: source.state,\n labels: source.labels,\n author: source.author,\n metadata: source.metadata,\n revision: source.revision,\n syncedAt: source.synced_at,\n createdAt: source.created_at,\n updatedAt: source.updated_at,\n };\n}\n\nfunction toWorkItem(row: WorkItemDbRow): Card {\n const fallback = row.work_item ? null : splitCardRows(row, { workItemId: row.id });\n const work = row.work_item ?? fallback!.workItem;\n const sources = (row.work_item_sources ?? (fallback?.source ? [fallback.source] : [])).map(toSource);\n const source = primarySource({ workItem: { sources } });\n return {\n workItem: {\n sources,\n id: work.id,\n orgId: work.org_id,\n factoryProjectId: work.factory_project_id,\n provider: source?.provider ?? 'factory',\n externalId: source?.externalId ?? row.id,\n key: source?.key ?? null,\n url: source?.url ?? null,\n title: work.title,\n state: source?.state ?? null,\n labels: source?.labels ?? [],\n author: source?.author ?? null,\n parentWorkItemId: work.parent_work_item_id,\n metadata: source?.metadata ?? null,\n revision: work.revision,\n syncedAt: source?.syncedAt ?? null,\n createdAt: work.created_at,\n updatedAt: work.updated_at,\n },\n workItemId: work.id,\n parentBoardItemId: row.parent_work_item_id,\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 description: row.description ?? null,\n stages: row.stages,\n stageHistory: row.stage_history,\n sessions: row.sessions,\n metadata: splitCardMetadata(row.metadata, workItemProviderAdapter(row.external_source).providerMetadataKeys).board,\n triageType: row.triage_type ?? null,\n autonomyArmedAt: row.autonomy_armed_at ?? null,\n acceptedAt: row.accepted_at ?? null,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n changedAt: row.changed_at ?? null,\n };\n}\n\nconst toRow = toWorkItem;\n\nfunction patchColumns(changes: Partial<Card>): 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.description !== undefined ? { description: changes.description } : {}),\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 WorkItemSplitModeError extends Error {}\n\nconst OPEN_PASS_PAGE_SIZE = 500;\n\nfunction logSplit(line: string): void {\n console.info(`[factory] ${line}`);\n}\n\nfunction sameWatermark(a: LegacyWatermark | null, b: LegacyWatermark): boolean {\n return a !== null && a.id === b.id && new Date(a.updatedAt).getTime() === new Date(b.updatedAt).getTime();\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\n/** The source a caller tried to attach already belongs to another work item in the project. */\nexport class WorkItemSourceConflictError extends Error {\n readonly code = 'work_item_source_conflict';\n\n constructor(readonly ownerWorkItemId: string) {\n super(`The source already belongs to work item ${ownerWorkItemId}.`);\n }\n}\n\nexport function validateParentRelation(\n projectItems: Card[],\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: Card | 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 now = new Date(),\n}: {\n current: WorkItemDbRow;\n userId: string;\n input: UpdateWorkItemInput;\n now?: Date;\n}): Partial<WorkItemDbRow> {\n const metadata = input.metadata ? { ...input.metadata } : input.metadata;\n const reconciliation = current.metadata?.[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n // Clearing an absent reconciliation marker must not invalidate pending rules.\n if (\n metadata?.[FACTORY_PULL_REQUEST_RECONCILIATION_KEY] === null &&\n reconciliation !== 'merged' &&\n reconciliation !== 'closed' &&\n reconciliation !== null\n ) {\n delete metadata[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n }\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.description !== undefined ? { description: input.description } : {}),\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 ...(metadata !== undefined\n ? { metadata: metadata === null ? null : { ...(current.metadata ?? {}), ...metadata } }\n : {}),\n revision: current.revision + 1,\n updated_at: now,\n };\n}\n/** Stage-history actor for the one-time move of cards held for triage acceptance. */\nexport const HELD_CARD_SWEEP_ACTOR = 'factory-held-card-sweep';\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 decisionRowPayload(decision: unknown): Record<string, unknown> {\n const parsed = typeof decision === 'string' ? safeJsonParse(decision) : decision;\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\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 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 created_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_rule_evaluations_ingress_idx', columns: ['ingress_id'] }],\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 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 name: 'factory_deferred_decisions_tenant_evaluation_idx',\n columns: ['org_id', 'factory_project_id', 'evaluation_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 {\n name: 'factory_run_bindings_org_thread_idx',\n columns: ['org_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_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 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 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 (value === 'automation-failed' || value === 'automation-proposed' || value === 'agent-waiting') {\n return value;\n }\n throw new Error(`Unsupported attention receipt kind '${String(value)}'.`);\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 createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\n\n/** The project whose board a committed card or decision write just changed. */\nexport type FactoryBoardScope = Required<BoardScope>;\n\n/** A safety net, not the invalidation path: bounds how long a missed version bump or a stuck read can last. */\nconst LIST_CACHE_TTL_MS = 60_000;\nconst LIST_CACHE_MAX_PROJECTS = 100;\nconst LIST_DELTA_CLOCK_SKEW_MS = 5_000;\n\ntype WorkItemSourceSyncPatch = Partial<\n Pick<WorkItemSourceRow, 'state' | 'labels' | 'author' | 'url' | 'key' | 'metadata'>\n>;\n\nexport class WorkItemsStorage extends FactoryStorageDomain {\n /** Last full card list per project, valid while the project's board version is unchanged. */\n /** `takenAt` is the last full read; `readFrom` when the latest read, full or delta, began. */\n readonly #listCache = new Map<string, { version: string; takenAt: number; readFrom: number; items: Card[] }>();\n // Joined only at the same board version: a poll after a write must not join a read begun before it.\n readonly #listInFlight = new Map<string, { version: string; startedAt: number; items: Promise<Card[]> }>();\n #boardChanged: (scope: FactoryBoardScope) => void = () => {};\n readonly #claimableWorkListeners = new Set<(scope: FactoryClaimableWorkScope) => void>();\n // Storage does not know boards: no card counts as finished until the host wires the predicate.\n #isTerminal: (item: Card) => boolean = () => false;\n\n #legacyMode = false;\n /**\n * Legacy cards this replica may still have to copy. While pending, lookups by id or source\n * copy a missed card on demand; `since` limits the passes to rows written after the last\n * finished pass.\n */\n #split: { pending: boolean; since: LegacyWatermark | null } = { pending: false, since: null };\n\n get legacyMode(): boolean {\n return this.#legacyMode;\n }\n\n get legacyBackfillPending(): boolean {\n return this.#split.pending;\n }\n\n /** Projects found not to use the Review board; once redundant it stays so, with no card left to reopen on it. */\n readonly #reviewRedundant = new Set<string>();\n\n #ownReviewBoard: ReviewBoardInUse | undefined;\n\n /**\n * Tells cards apart from the retired Review board's: where `owned` answers true the project has\n * a board of its own under `review`, and the cards stored on it are that board's.\n */\n useOwnReviewBoard(owned: ReviewBoardInUse): void {\n this.#ownReviewBoard = owned;\n }\n\n /** {@link reviewBoardInUse} through `ops`, so a caller inside a transaction reads within it. */\n readonly #reviewInUse: ReviewBoardInUse = async (ops, scope) => {\n // Asked every time: a project can make or delete a board of its own under `review` at any moment.\n if (await this.#ownReviewBoard?.(ops, scope)) return true;\n const key = `${scope.orgId}\\0${scope.factoryProjectId}`;\n if (this.#reviewRedundant.has(key)) return false;\n const inUse = await readReviewBoardInUse(ops, scope, {\n split: !this.#legacyMode,\n // Legacy cards not copied yet still count.\n legacy: this.#legacyMode || this.#split.pending,\n });\n if (!inUse) this.#reviewRedundant.add(key);\n return inUse;\n };\n\n /**\n * Whether cards stored on `review` stay there: the project has a board of its own under that\n * key, or still uses the retired Review board (it holds a card stored on Review that isn't Done\n * or Canceled) and keeps it. In any other project Review is redundant and its cards read as Work.\n */\n reviewBoardInUse(scope: ReviewBoardScope): Promise<boolean> {\n return this.#reviewInUse(this.#db, scope);\n }\n\n /**\n * Leaves `review` to a board about to take it: stores the Work placement of the cards the\n * retired Review board left there, through `ops`, so it happens in the board write's\n * transaction. See {@link releaseLegacyReviewCards} for `open`.\n */\n async releaseReviewCards(\n ops: FactoryStorageOps,\n scope: ReviewBoardScope,\n { open }: { open: 'refuse' | 'move' },\n ): Promise<void> {\n const rewritten = await releaseLegacyReviewCards(\n ops,\n scope,\n // Legacy cards not copied yet still count.\n { split: !this.#legacyMode, legacy: this.#legacyMode || this.#split.pending },\n open,\n );\n // An open card that moved was listed on Review until now.\n if (rewritten > 0) await bumpBoardVersions(ops, [scope]);\n }\n\n constructor() {\n super('work-items');\n }\n\n /**\n * Wired once at boot. Fires after a committed write changes what a board shows of a card\n * or a deferred decision, so open boards refetch instead of polling.\n */\n onBoardChanged(listener: (scope: FactoryBoardScope) => void): void {\n this.#boardChanged = listener;\n }\n\n /**\n * Fires after any committed write leaves a pending start or deferred decision\n * `pending` or `retry`, so an idle dispatcher can wake instead of polling.\n * Listeners run after the write has committed, so a listener that throws is\n * logged and skipped rather than failing the write or the other listeners.\n * Returns a function that removes the listener.\n */\n onClaimableWork(listener: (scope: FactoryClaimableWorkScope) => void): () => void {\n this.#claimableWorkListeners.add(listener);\n return () => this.#claimableWorkListeners.delete(listener);\n }\n\n #claimableWork(scope: FactoryClaimableWorkScope): void {\n for (const listener of this.#claimableWorkListeners) {\n try {\n listener(scope);\n } catch (error) {\n console.error('[factory] claimable-work listener failed', error instanceof Error ? error.message : error);\n }\n }\n }\n\n /**\n * When the next pending start or deferred decision becomes claimable: the earliest\n * `available_at` of a queued row, or `lease_expires_at` of a leased one (a crashed\n * dispatcher's lease is reclaimed once it lapses). `null` when nothing is queued or leased.\n * May be in the past when work is already due.\n */\n async nextClaimableAt(): Promise<Date | null> {\n const earliest = async (table: string, status: string | { in: string[] }, column: string) => {\n const [row] = await this.#db.findMany<GovernanceDbRow>(\n table,\n { status },\n { orderBy: [[column, 'asc']], limit: 1 },\n );\n const value = row?.[column];\n return value ? new Date(value as Date | string).getTime() : undefined;\n };\n const times = await Promise.all(\n LEASE_TABLES.flatMap(table => [\n earliest(table, { in: ['pending', 'retry'] }, 'available_at'),\n earliest(table, 'leased', 'lease_expires_at'),\n ]),\n );\n const due = times.filter((time): time is number => time !== undefined);\n return due.length ? new Date(Math.min(...due)) : null;\n }\n\n /** Tells the stale-binding sweep which cards sit in a phase their installed board declares terminal. */\n useTerminalPhasePredicate(isTerminal: (item: Card) => boolean): void {\n this.#isTerminal = isTerminal;\n }\n\n async init(): Promise<void> {\n this.#legacyMode = process.env.MASTRA_FACTORY_WORK_ITEM_SPLIT === 'dry-run';\n // Pre-split cards and the split's progress marker exist only on databases an earlier release\n // wrote cards to; dry-run mode serves from the pre-split table, so it always needs it.\n const legacySchemas = [WORK_ITEMS_SCHEMA, FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA];\n let hasLegacyCards = true;\n if (this.#legacyMode) await this.ensureCollections(legacySchemas);\n else hasLegacyCards = await ensureLegacyCollections(this.storage, legacySchemas);\n await this.ensureCollections([\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n ...FACTORY_GOVERNANCE_SCHEMAS,\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA,\n ]);\n if (this.#legacyMode && (await super.ops.findOne(FACTORY_BOARD_ITEMS_SCHEMA.name, {}))) {\n throw new WorkItemSplitModeError(\n 'MASTRA_FACTORY_WORK_ITEM_SPLIT=dry-run cannot serve a database with migrated board items.',\n );\n }\n if (this.#legacyMode) {\n this.#split = { pending: false, since: null };\n await migrateWorkItemSplit(this.storage, { dryRun: true, ops: super.ops, log: logSplit });\n return;\n }\n if (!hasLegacyCards) {\n this.#split = { pending: false, since: null };\n return;\n }\n const [marker, newest] = await Promise.all([readWorkItemSplitMarker(super.ops), readLegacyWatermark(super.ops)]);\n const finished = !newest || (marker !== null && sameWatermark(marker.watermark, newest));\n // The factory copies open cards once boards load, and the rest in the background.\n this.#split = { pending: !finished, since: marker?.watermark ?? null };\n }\n\n /**\n * Copy the legacy cards `isTerminal` rejects, before Factory serves. Terminal cards are left\n * to `backfillLegacyCards`. A no-op once the split finished.\n */\n async migrateOpenLegacyCards(\n isTerminal: (card: Card) => boolean | Promise<boolean>,\n ): Promise<WorkItemSplitReport | null> {\n if (this.#legacyMode || !this.#split.pending) return null;\n return migrateWorkItemSplit(this.storage, {\n ops: super.ops,\n since: this.#split.since,\n // Mostly unchanged rows on a re-boot: larger pages mean fewer round trips.\n pageSize: OPEN_PASS_PAGE_SIZE,\n include: async row => !(await isTerminal(toWorkItem(row))),\n label: 'boot pass',\n log: logSplit,\n });\n }\n\n /**\n * Copy every remaining legacy card, then record the newest legacy row seen before the pass\n * began, so later boots skip rows up to it. Skipped cards are logged and count as done: they\n * conflict with newer split state and a rescan would only skip them again.\n */\n async backfillLegacyCards({ signal }: { signal?: AbortSignal } = {}): Promise<WorkItemSplitReport | null> {\n if (this.#legacyMode || !this.#split.pending) return null;\n // Captured first: a legacy write during the pass sorts after it and is rescanned next boot.\n const watermark = await readLegacyWatermark(super.ops);\n const report = await migrateWorkItemSplit(this.storage, {\n ops: super.ops,\n since: this.#split.since,\n signal,\n label: 'background pass',\n log: logSplit,\n });\n if (!report.aborted) {\n await recordWorkItemSplitComplete(super.ops, watermark);\n this.#split = { pending: false, since: watermark };\n }\n return report;\n }\n\n /**\n * Copy the legacy cards filed for these external records, so a lookup that matches on `list()`\n * finds them. A no-op once the split finished.\n */\n async copyLegacyCards({\n orgId,\n factoryProjectId,\n sources,\n }: {\n orgId: string;\n factoryProjectId: string;\n sources: readonly ExternalWorkItemSource[];\n }): Promise<void> {\n if (this.#legacyMode || !this.#split.pending || !sources.length) return;\n const sourceKeys = new Set(sources.map(source => externalSourceKey(source)!));\n await this.#cards(this.#db, { transaction: false }).findMany({\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: { in: [...sourceKeys] },\n });\n }\n\n /**\n * Card row access. While legacy cards remain uncopied, a lookup that misses copies the card:\n * inside the caller's transaction when `ops` is one (a nested transaction would deadlock\n * LibSQL), else in a transaction of its own.\n */\n #cards(ops: FactoryStorageOps, { transaction }: { transaction: boolean }): Cards {\n if (this.#legacyMode || !this.#split.pending) return new Cards(ops, this.#legacyMode, undefined, this.#reviewInUse);\n return new Cards(\n ops,\n false,\n {\n copy: async rows => {\n if (transaction) {\n await copyLegacyRows(ops, rows);\n return;\n }\n try {\n await this.#withTransaction(tx => copyLegacyRows(tx, rows));\n } catch (error) {\n // A concurrent first copy won (its retry lost again); the re-read finds its rows.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n },\n },\n this.#reviewInUse,\n );\n }\n\n /** Validation reads the split tables only, so a parent still in legacy is copied first. */\n async #copyLegacyParent(ops: FactoryStorageOps, orgId: string, parentId: string | null | undefined) {\n if (parentId && this.#split.pending)\n await this.#cards(ops, { transaction: true }).findOne({ org_id: orgId, id: parentId });\n }\n\n /** Refresh source evidence without changing work identity or board concurrency tokens. */\n async syncWorkItemSource(params: {\n orgId: string;\n factoryProjectId: string;\n provider: string;\n externalId: string;\n patch: WorkItemSourceSyncPatch | ((current: WorkItemSourceDbRecord) => WorkItemSourceSyncPatch | null);\n expectedRevision?: number;\n }): Promise<void> {\n await this.#withTransaction(async ops => {\n await this.#syncWorkItemSource(ops, params);\n });\n }\n\n async #syncWorkItemSource(\n ops: FactoryStorageOps,\n {\n orgId,\n factoryProjectId,\n provider,\n externalId,\n patch,\n expectedRevision,\n }: Parameters<WorkItemsStorage['syncWorkItemSource']>[0],\n ): Promise<Date | undefined> {\n const where = { org_id: orgId, factory_project_id: factoryProjectId, provider, external_id: externalId };\n const source = await ops.findOne<WorkItemSourceDbRecord>(FACTORY_WORK_ITEM_SOURCES_SCHEMA.name, where);\n const card = source && { work_item_id: source.work_item_id };\n // Lock the card's row before its source, the order every card write takes them in.\n if (card) await ops.updateAtomic(FACTORY_BOARD_ITEMS_SCHEMA.name, card, () => null);\n let synced = false;\n await ops.updateAtomic<WorkItemSourceDbRecord>(\n FACTORY_WORK_ITEM_SOURCES_SCHEMA.name,\n { org_id: orgId, factory_project_id: factoryProjectId, provider, external_id: externalId },\n current => {\n if (expectedRevision !== undefined && current.revision !== expectedRevision) {\n throw new WorkItemUpdateConflictError('revision');\n }\n const next = typeof patch === 'function' ? patch(current) : patch;\n if (!next) return null;\n synced = true;\n const { metadata, ...facts } = next;\n // Raw provider state can be 'closed' while normalized state is 'merged'.\n const nextMetadata =\n metadata === null\n ? null\n : {\n ...current.metadata,\n ...metadata,\n ...(next.labels !== undefined && !Object.hasOwn(metadata ?? {}, 'labels')\n ? { labels: next.labels }\n : {}),\n ...(next.state !== undefined && !Object.hasOwn(metadata ?? {}, 'state') ? { state: next.state } : {}),\n ...(next.author !== undefined && !Object.hasOwn(metadata ?? {}, 'author')\n ? { author: next.author }\n : {}),\n ...(next.key !== undefined && !Object.hasOwn(metadata ?? {}, 'identifier')\n ? { identifier: next.key }\n : {}),\n };\n return {\n ...facts,\n metadata: nextMetadata,\n revision: current.revision + 1,\n synced_at: new Date(),\n updated_at: new Date(),\n };\n },\n );\n // The card shows these facts but its own row did not move: stamp it so a board reload rereads it.\n if (!card || !synced) return undefined;\n const changed_at = new Date();\n await ops.updateMany(FACTORY_BOARD_ITEMS_SCHEMA.name, card, { changed_at });\n return changed_at;\n }\n\n /**\n * File one more external record on an existing card: a pull request on the\n * issue card it fixes. The card's primary source stays first, so the card keeps\n * reading as the issue. Attaching a source the card already holds is a no-op\n * (`attached: false`); one another card holds throws\n * {@link WorkItemSourceConflictError}. Later state for the attached record goes\n * through {@link syncWorkItemSource}, never {@link syncCard}, which writes the\n * primary source.\n */\n async attachSource({\n orgId,\n id,\n source,\n metadata,\n expectedRevision,\n }: {\n orgId: string;\n id: string;\n source: ExternalWorkItemSource;\n metadata: Record<string, unknown> | null;\n expectedRevision?: number;\n }): Promise<{ item: Card; attached: boolean } | null> {\n let result: Awaited<ReturnType<Cards['attachSource']>>;\n try {\n result = await this.#withTransaction(async ops => {\n const cards = new Cards(ops, this.#legacyMode, undefined, this.#reviewInUse);\n const attached = await cards.attachSource(\n { org_id: orgId, id },\n { external_source: source, metadata, now: new Date() },\n expectedRevision,\n );\n if (attached?.ownerWorkItemId) throw new WorkItemSourceConflictError(attached.ownerWorkItemId);\n if (attached?.revisionConflict) throw new WorkItemUpdateConflictError('revision');\n return attached;\n });\n } catch (error) {\n // A concurrent attach or upsert of the same record won the unique index.\n if (error instanceof UniqueViolationError && error.collection === FACTORY_WORK_ITEM_SOURCES_SCHEMA.name) {\n // Sources are unique per project, so another project's copy of the record is no owner here.\n const card = await new Cards(this.#db, this.#legacyMode, undefined, this.#reviewInUse).findOne({\n org_id: orgId,\n id,\n });\n const owner = card\n ? await this.#db.findOne<WorkItemSourceDbRecord>(FACTORY_WORK_ITEM_SOURCES_SCHEMA.name, {\n org_id: orgId,\n factory_project_id: card.factory_project_id,\n source_key: externalSourceKey(source),\n })\n : null;\n if (owner && card && owner.work_item_id === card.work_item?.id)\n return { item: toWorkItem(card), attached: false };\n throw new WorkItemSourceConflictError(owner?.work_item_id ?? 'unknown');\n }\n throw error;\n }\n return result ? { item: toWorkItem(result.row), attached: result.attached } : null;\n }\n\n /** Apply source facts and their process stamps in one transaction. */\n async syncCard({\n orgId,\n id,\n userId,\n patch,\n expectedSourceRevision,\n fillOnly = false,\n }: {\n orgId: string;\n id: string;\n userId: string;\n patch: { title?: string; metadata?: Record<string, unknown> | null };\n expectedSourceRevision?: number;\n fillOnly?: boolean;\n }): Promise<{ item: Card; previous: WorkItemPriorState } | null> {\n return this.#withTransaction(async ops => {\n let previous = emptyPrior();\n let stamped: Date | undefined;\n const row = await this.#cards(ops, { transaction: true }).updateAtomic({ org_id: orgId, id }, async current => {\n previous = priorState(current);\n const item = toWorkItem(current);\n const source = primarySource(item);\n if (this.#legacyMode || !source) {\n const metadata = fillOnly\n ? Object.fromEntries(\n Object.entries(patch.metadata ?? {}).filter(([key]) => current.metadata?.[key] === undefined),\n )\n : patch.metadata;\n if (fillOnly && patch.title === undefined && Object.keys(metadata ?? {}).length === 0) return null;\n return applyUpdate({ current, userId, input: { ...patch, metadata } });\n }\n const adapter = workItemProviderAdapter(item.externalSource);\n const split = splitCardMetadata(patch.metadata, adapter.providerMetadataKeys);\n if (Object.keys(split.provider ?? {}).length > 0) {\n stamped = await this.#syncWorkItemSource(ops, {\n orgId,\n factoryProjectId: item.factoryProjectId,\n provider: source.provider,\n externalId: source.externalId,\n expectedRevision: expectedSourceRevision,\n patch: currentSource => {\n const providerPatch = fillOnly\n ? Object.fromEntries(\n Object.entries(split.provider ?? {}).filter(([key]) => currentSource.metadata?.[key] === undefined),\n )\n : split.provider;\n if (fillOnly && Object.keys(providerPatch ?? {}).length === 0) return null;\n const facts = adapter.toSource(item.externalSource, { ...currentSource.metadata, ...providerPatch });\n if (!facts) throw new Error('An external source must produce provider facts.');\n return {\n key: facts.key,\n url: facts.url,\n state: facts.state,\n labels: facts.labels,\n author: facts.author,\n metadata: facts.metadata,\n };\n },\n });\n }\n const boardPatch = Object.fromEntries(\n Object.entries(split.board ?? {}).filter(([key, value]) =>\n fillOnly\n ? item.metadata?.[key] === undefined\n : JSON.stringify(item.metadata?.[key]) !== JSON.stringify(value),\n ),\n );\n if (patch.title === undefined && Object.keys(boardPatch).length === 0) return null;\n return applyUpdate({\n current,\n userId,\n input: { ...(patch.title !== undefined ? { title: patch.title } : {}), metadata: boardPatch },\n });\n });\n if (!row) return null;\n const item = toWorkItem(row);\n // `row` was read before the source's sync stamped it; a write of the card itself stamps later.\n const changedAt = stamped && !(item.changedAt && item.changedAt > stamped) ? stamped : item.changedAt;\n return { item: { ...item, changedAt }, previous };\n });\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.#withTransaction(ops => this.#cards(ops, { transaction: true }).deleteMany({}));\n await super.ops.deleteMany(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, {});\n // A project with no version row is never served from cache, so this invalidates every replica.\n await super.ops.deleteMany(FACTORY_BOARD_VERSIONS_SCHEMA.name, {});\n this.#listCache.clear();\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n protected override get ops(): FactoryStorageOps {\n const ops = super.ops;\n // Outside a transaction a resolved write has committed, so its wake can go out at once.\n const cards = trackBoardWrites(ops, CARD_TABLES, async scope => {\n await bumpBoardVersions(ops, [scope]);\n this.#announceBoard(scope);\n });\n return trackClaimableWrites(\n trackBoardWrites(cards, DECISION_TABLES, scope => this.#announceBoard(scope)),\n scope => this.#claimableWork(scope),\n );\n }\n\n /** Only legacy dry-run writes name no project, and no feed is keyed by org alone. */\n #announceBoard(scope: BoardScope): void {\n if (scope.factoryProjectId) this.#boardChanged({ orgId: scope.orgId, factoryProjectId: scope.factoryProjectId });\n }\n\n /** `storage.withTransaction`, bumping and announcing the board of every project it wrote once it commits. */\n async #withTransaction<T>(\n fn: (ops: FactoryStorageOps) => Promise<T>,\n options?: { isolationLevel?: 'serializable' },\n ): Promise<T> {\n const changed = new BoardScopes();\n const touched = new BoardScopes();\n const cardWritten = (scope: BoardScope) => {\n changed.add(scope);\n touched.add(scope);\n };\n let queued = new Map<string, FactoryClaimableWorkScope>();\n const run = () => {\n // A retried transaction starts over: wakes queued by the rolled-back attempt never committed.\n queued = new Map();\n return this.storage.withTransaction(\n ops =>\n fn(\n trackClaimableWrites(\n trackBoardWrites(trackBoardWrites(ops, CARD_TABLES, cardWritten), DECISION_TABLES, touched.add),\n scope => queued.set(`${scope.orgId}\\u0000${scope.factoryProjectId}`, scope),\n ),\n ),\n options,\n );\n };\n let result: T;\n try {\n result = await run();\n } catch (error) {\n // A first guard insert can race. Retry only after the failed transaction\n // rolls back; PostgreSQL cannot recover from a unique violation inside it.\n if (!(error instanceof UniqueViolationError) || error.collection !== FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name)\n throw error;\n result = await run();\n }\n try {\n await bumpBoardVersions(super.ops, changed.values());\n } finally {\n // Only after commit: a dispatcher woken earlier could miss the uncommitted row and go idle.\n for (const scope of queued.values()) this.#claimableWork(scope);\n }\n for (const scope of touched.values()) this.#announceBoard(scope);\n return result;\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 #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.#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 accept?: (row: GovernanceDbRow) => boolean,\n ): Promise<T[]> {\n const claim = () =>\n this.#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 where = { status: { in: ['pending', 'retry', 'leased'] } };\n const claimed: T[] = [];\n // A filtered claim widens its window past rows it rejects so matching\n // rows queued behind any size of filtered-out backlog stay reachable.\n // Unfiltered claims read one window: the first claimable rows are the\n // oldest. Ties on created_at keep the store's insertion order.\n let window = Math.max(input.limit * 5, 50);\n let scanned = 0;\n let exhausted = false;\n do {\n const page = await ops.findMany<GovernanceDbRow>(table, where, {\n orderBy: [['created_at', 'asc']],\n limit: window,\n });\n exhausted = !accept || page.length < window;\n const candidates = page.slice(scanned);\n scanned = page.length;\n window *= 4;\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 if (accept && !accept(candidate)) 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 // A new attempt starts clean: the previous attempt's cause no longer describes this one.\n ...(table === 'factory_deferred_decisions' ? { last_error: null, failure_code: null } : {}),\n updated_at: input.now,\n };\n });\n if (didClaim && row) claimed.push(map(row));\n }\n } while (!exhausted && claimed.length < input.limit);\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 status?: 'superseded',\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: status ?? (table === 'factory_pending_starts' ? 'sent' : 'succeeded'),\n lease_owner: null,\n lease_expires_at: null,\n ...(table === 'factory_deferred_decisions' ? { 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 ...(table === 'factory_deferred_decisions'\n ? {\n last_error: input.lastError,\n failure_code: input.failureCode,\n completed_at: input.terminal ? input.now : null,\n ...(input.terminal ? { failure_occurrence: Number(current.failure_occurrence ?? 0) + 1 } : {}),\n }\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<Card[]> {\n const rows = await this.#cards(ops, { transaction: true }).findMany(\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 /** The ids deleted after `from`. */\n #removedSince(scope: CollectionWhere, from: Date) {\n return super.ops.findMany<{ id: string }>(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, scope, {\n orderBy: [['deleted_at', 'asc']],\n cursor: { values: [from] },\n });\n }\n\n /**\n * `previous` updated with the cards changed or deleted since `since`. Reads from a few seconds\n * earlier so a writer whose clock runs behind this one is still caught.\n */\n async #listDelta(orgId: string, factoryProjectId: string, previous: readonly Card[], since: number): Promise<Card[]> {\n const from = new Date(since - LIST_DELTA_CLOCK_SKEW_MS);\n const scope = { org_id: orgId, factory_project_id: factoryProjectId };\n const [rows, tombstones] = await Promise.all([\n this.#cards(super.ops, { transaction: true }).findMany(scope, {\n orderBy: [['changed_at', 'asc']],\n cursor: { values: [from] },\n }),\n this.#removedSince(scope, from),\n ]);\n if (rows.length === 0 && tombstones.length === 0) return [...previous];\n const changed = new Map(rows.map(row => [row.id, toWorkItem(row)]));\n const deleted = new Set(tombstones.map(row => row.id));\n const items = previous.filter(item => !changed.has(item.id) && !deleted.has(item.id));\n for (const item of changed.values()) if (!deleted.has(item.id)) items.push(item);\n return items.sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0),\n );\n }\n\n /** The project's cards as {@link list} reads them, uncached, through `ops`: a transaction's, to read them in it. */\n async listWith(ops: FactoryStorageOps, { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }) {\n return this.#listWithOps(ops, orgId, factoryProjectId);\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<Card[]> {\n const { items, cached } = await this.#listCached(orgId, factoryProjectId);\n return cached ? structuredClone(items) : items;\n }\n\n /**\n * Same rows as {@link list}, but shared with the list cache instead of cloned: the board poll\n * reads every card of the project every few seconds, and cloning thousands of rows per poll\n * costs more than the query the cache saves. The cached cards are frozen, so a caller that\n * writes to one throws instead of changing the board every other caller sees.\n */\n async listShared({ orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }): Promise<readonly Card[]> {\n return (await this.#listCached(orgId, factoryProjectId)).items;\n }\n\n /**\n * {@link listShared} for a reader that keeps the board between reads. `cursor` names this read.\n * Sent back as `since`, it adds what moved since that read: `changed`, the listed cards written\n * since, and `removed`, the ids no longer listed. Without them only the whole list answers: no\n * cursor or one this didn't issue, or a board showing Review cards, which move without a write.\n */\n async listSharedSince(scope: { orgId: string; factoryProjectId: string; since?: string }): Promise<{\n items: readonly Card[];\n cursor?: string;\n changed?: Card[];\n removed?: string[];\n }> {\n const { items, readFrom } = await this.#listCached(scope.orgId, scope.factoryProjectId);\n if (readFrom === undefined || items.some(card => card.board === LEGACY_REVIEW_BOARD)) return { items };\n const cursor = String(readFrom);\n if (scope.since === undefined) return { items, cursor };\n // The reader holds this very list.\n if (scope.since === cursor) return { items, cursor, changed: [], removed: [] };\n // Answered from `items`, the list `cursor` names, so the two agree: a write that list doesn't\n // hold yet is left for the read that sends `cursor` back.\n const from = new Date(Number(scope.since) - LIST_DELTA_CLOCK_SKEW_MS);\n const gone = await this.#removedSince({ org_id: scope.orgId, factory_project_id: scope.factoryProjectId }, from);\n const removed = new Set(gone.map(row => row.id));\n const changed = items.filter(card => {\n removed.delete(card.id);\n return card.changedAt && new Date(card.changedAt) > from;\n });\n return { items, cursor, changed, removed: [...removed] };\n }\n\n /**\n * `cached` is true when `items` is shared with other callers, which callers that mutate must clone.\n * `readFrom` is when the read that produced a cached `items` began.\n */\n async #listCached(\n orgId: string,\n factoryProjectId: string,\n ): Promise<{ items: Card[]; cached: boolean; readFrom?: number }> {\n const key = `${orgId}\\u0000${factoryProjectId}`;\n // Read the version before the rows: a write that lands in between bumps it again afterwards,\n // so the next call refetches instead of trusting a snapshot taken before that write.\n const version = await readBoardVersion(super.ops, orgId, factoryProjectId);\n const hit = this.#listCache.get(key);\n if (version && hit?.version === version && Date.now() - hit.takenAt < LIST_CACHE_TTL_MS) {\n return { items: hit.items, cached: true, readFrom: hit.readFrom };\n }\n if (!version) {\n const items = await this.#listWithOps(super.ops, orgId, factoryProjectId);\n this.#listCache.delete(key);\n return { items, cached: false };\n }\n const inFlight = this.#listInFlight.get(key);\n if (inFlight?.version === version && Date.now() - inFlight.startedAt < LIST_CACHE_TTL_MS) {\n return { items: await inFlight.items, cached: true, readFrom: inFlight.startedAt };\n }\n const startedAt = Date.now();\n // Within the TTL a version change only needs the cards changed since the last read; the TTL\n // still forces a full read as a backstop for anything a delta could miss. A board showing\n // Review cards is read whole: closing its last open one moves the others without writing them.\n const delta =\n hit && startedAt - hit.takenAt < LIST_CACHE_TTL_MS && !hit.items.some(card => card.board === LEGACY_REVIEW_BOARD);\n const read = (\n delta\n ? this.#listDelta(orgId, factoryProjectId, hit.items, hit.readFrom)\n : this.#listWithOps(super.ops, orgId, factoryProjectId)\n ).then(deepFreeze);\n this.#listInFlight.set(key, { version, startedAt, items: read });\n try {\n const items = await read;\n if (this.#listInFlight.get(key)?.items === read) {\n this.#listCache.delete(key);\n this.#listCache.set(key, {\n version,\n takenAt: delta ? hit.takenAt : Date.now(),\n readFrom: startedAt,\n items,\n });\n if (this.#listCache.size > LIST_CACHE_MAX_PROJECTS) {\n this.#listCache.delete(this.#listCache.keys().next().value!);\n }\n }\n return { items, cached: true, readFrom: startedAt };\n } finally {\n if (this.#listInFlight.get(key)?.items === read) this.#listInFlight.delete(key);\n }\n }\n\n /**\n * The cards linked to `item` in its project, its parent and its children, newest first as\n * {@link list} orders them. Read by id and by the parent index, so the cost does not grow with\n * the board.\n */\n async listLinked({ item, limit }: { item: Card; limit: number }): Promise<Card[]> {\n const cards = this.#cards(this.#db, { transaction: false });\n const scope = { org_id: item.orgId, factory_project_id: item.factoryProjectId };\n const [parent, children] = await Promise.all([\n item.parentWorkItemId ? cards.findOne({ ...scope, id: item.parentWorkItemId }) : null,\n cards.findMany(\n { ...scope, parent_work_item_id: item.id },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n ),\n ]);\n return (parent ? [parent, ...children] : children)\n .map(toWorkItem)\n .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : -1))\n .slice(0, limit);\n }\n\n async listByIds({\n orgId,\n factoryProjectId,\n ids,\n }: {\n orgId: string;\n factoryProjectId: string;\n ids: string[];\n }): Promise<Card[]> {\n if (ids.length === 0) return [];\n const rows = await this.#cards(this.#db, { transaction: false }).findMany({\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<Pick<WorkItemDbRow, 'id' | 'sessions'> & Record<string, unknown>>(\n this.#legacyMode ? WORK_ITEMS_SCHEMA.name : FACTORY_BOARD_ITEMS_SCHEMA.name,\n { org_id: orgId },\n );\n if (this.#split.pending) {\n // An uncopied card holding the session would bring the reference back when copied; the\n // update below copies it first.\n const split = new Set(rows.map(row => row.id));\n const legacy = await this.#db.findMany<Pick<WorkItemDbRow, 'id' | 'sessions'> & Record<string, unknown>>(\n WORK_ITEMS_SCHEMA.name,\n { org_id: orgId },\n );\n rows.push(...legacy.filter(row => !split.has(row.id)));\n }\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.#withTransaction(ops =>\n this.#cards(ops, { transaction: true }).updateAtomic({ 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 );\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<Card | null> {\n const row = await this.#cards(this.#db, { transaction: false }).findOne({\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<Card | null> {\n const row = await this.#cards(this.#db, { transaction: false }).findOne({ 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<Card | null> {\n const rows = await this.#cards(this.#db, { transaction: false }).findMany({\n source_key: externalSourceKey(source),\n });\n return rows.length === 1 ? toWorkItem(rows[0]!) : null;\n }\n\n /**\n * Every card in the org that was linked from one external source, across\n * Factory projects. Source keys are unique per project, not per org, so an\n * issue whose routing moved between projects can own one card in each; intake\n * consults this before creating another.\n */\n async listBySource({ orgId, source }: { orgId: string; source: ExternalWorkItemSource }): Promise<Card[]> {\n const rows = await this.#cards(this.#db, { transaction: false }).findMany({\n org_id: orgId,\n source_key: externalSourceKey(source),\n });\n return rows.map(toWorkItem);\n }\n\n async getForProject(orgId: string, factoryProjectId: string, id: string): Promise<Card | null> {\n const row = await this.#cards(this.#db, { transaction: false }).findOne({\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 listRecordedIngress(\n orgId: string,\n factoryProjectId: string,\n identities: readonly string[],\n ): Promise<Set<string>> {\n if (identities.length === 0) return new Set();\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_rule_ingress', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n identity: { in: [...new Set(identities)] },\n });\n return new Set(rows.map(row => String(row.identity)));\n }\n\n async commitTransition(input: CommitFactoryTransitionInput): Promise<CommitFactoryTransitionResult> {\n const commit = (): Promise<CommitFactoryTransitionResult> =>\n this.#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 // Read through the transaction: on a single-connection database the\n // root client waits for this transaction, which would never finish.\n const row = await this.#cards(ops, { transaction: true }).findOne({\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n return { status: 'replayed', item: row ? toRow(row) : null, result: prior.result as Record<string, unknown> };\n }\n\n const now = new Date();\n let item: Card | null = null;\n let code: string | null = null;\n let reason: string | null = null;\n let result: Record<string, unknown>;\n const updated = await this.#cards(ops, { transaction: true }).updateAtomic(\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 // A stale revision only lost a race with another write; recording it\n // under this identity would replay the loss to every retry, so a\n // re-read at the current revision could never commit the transition.\n if (code === 'stale') return { status: 'committed', item, result };\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 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 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 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.#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 !isWorkItemSource((decision as Record<string, unknown>).source) ||\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> & {\n source: WorkItemSource;\n sourceKey: string;\n idempotencyKey: string;\n };\n const item = await this.#cards(ops, { transaction: true }).findOne({\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: externalSourceKey(\n externalSourceForWorkItem(materialization.source, materialization.sourceKey),\n ),\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 this.#cards(ops, { transaction: true }).findOne({\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 // A lost revision race is not a verdict on the event: persisting it would\n // make every redelivery replay an empty result, so record nothing.\n if (item !== null && item.revision !== input.expectedRevision) return { status: 'stale' as const };\n const outcome = input.outcome.status;\n const code = input.outcome.code ?? null;\n const reason = 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 result,\n created_at: input.now,\n });\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n created_at: input.now,\n });\n for (const [effectOrdinal, decision] of decisions.entries()) {\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 ?? null,\n source_key: decisionSourceKey(decision),\n idempotency_key: String(decision.idempotencyKey),\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 approved_at: approvedBy ? input.now : null,\n approved_by: approvedBy,\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 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_created_at: cursor.lastMessageCreatedAt,\n updated_at: cursor.updatedAt,\n });\n }\n\n async listDeferredDecisions(\n orgId: string,\n factoryProjectId: string,\n filter: { statuses?: readonly string[]; workItemId?: string } = {},\n ): Promise<FactoryDeferredDecisionRecord[]> {\n return (\n await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(filter.statuses ? { status: { in: [...filter.statuses] } } : {}),\n ...(filter.workItemId ? { work_item_id: filter.workItemId } : {}),\n },\n { orderBy: [['created_at', 'asc']] },\n )\n ).map(toDeferredDecision);\n }\n\n async listDecisionsForEvaluations(\n orgId: string,\n factoryProjectId: string,\n evaluationIds: string[],\n ): Promise<FactoryDeferredDecisionRecord[]> {\n if (evaluationIds.length === 0) return [];\n return (\n await this.#db.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n evaluation_id: { in: [...new Set(evaluationIds)] },\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.#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 return true;\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.#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: FactoryDeferredDecisionClaimInput): Promise<FactoryDeferredDecisionRecord[]> {\n const filter = input.decisionFilter;\n const accept = filter ? (row: GovernanceDbRow) => filter(decisionRowPayload(row.decision)) : undefined;\n return this.#claimLeases('factory_deferred_decisions', input, toDeferredDecision, accept);\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 /** Settle a leased decision whose card moved on before it could act: nothing ran, and nothing needs a person. */\n async supersedeLeasedDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#completeLease('factory_deferred_decisions', identity, now, 'superseded');\n return row ? toDeferredDecision(row) : null;\n }\n\n /**\n * Hand a leased decision back untouched until `availableAt`: it could not act yet and did\n * nothing, so the claim is not an attempt and leaves no error behind.\n */\n async postponeDeferredDecision(\n identity: FactoryLeaseIdentity,\n availableAt: Date,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n let postponed = 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 postponed = true;\n return {\n status: 'pending',\n attempts: Math.max(0, Number(current.attempts) - 1),\n available_at: availableAt,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now,\n };\n },\n );\n return postponed && 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 return row ? toDeferredDecision(row) : null;\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 return proposed && row ? toDeferredDecision(row) : null;\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 return this.#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 this.#cards(ops, { transaction: true }).updateAtomic({ org_id: orgId, id: record.workItemId }, current =>\n current.autonomy_armed_at ? null : { autonomy_armed_at: now },\n );\n }\n return record;\n });\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.#supersedeFailedDecision({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n decisionId: decision.id,\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 return this.#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 }\n\n async #supersedeFailedDecision({\n orgId,\n factoryProjectId,\n decisionId,\n now,\n }: {\n orgId: string;\n factoryProjectId: string;\n decisionId: string;\n now: Date;\n }): Promise<FactoryDeferredDecisionRecord | null> {\n return this.#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: 'superseded', 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 }\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 /**\n * Factory used to hold a triaged non-bug in Triage until a person accepted it.\n * Triage now sends those cards back to Intake instead, so move the ones still\n * held there, once. A card with a live run, or one that changed under us, is\n * left alone. Returns the cards moved; a second run finds none.\n */\n async returnHeldTriageCards(): Promise<Card[]> {\n // A one-time migration of rows written when Work was the only board, so it reads Work's phase\n // keys (`triage`, `intake`) by name. Cards filed before boards were recorded carry no board;\n // outside pull requests they are Work cards.\n const held = (\n await this.#cards(this.#db, { transaction: false }).findMany({\n board: { in: [LEGACY_WORK_BOARD, null] },\n triage_type: { in: FACTORY_TRIAGE_TYPES.filter(type => type !== 'bug') },\n accepted_at: null,\n })\n )\n .map(toWorkItem)\n .filter(\n item =>\n item.stages.length === 1 &&\n item.stages[0] === LEGACY_TRIAGE_PHASE &&\n (item.board === LEGACY_WORK_BOARD || item.externalSource?.type !== 'pull-request'),\n );\n if (held.length === 0) return [];\n // A binding stays active after its run ends until the stale-binding sweep, so the triage\n // run that classified the card is still bound. Only a run started since the card last\n // changed can still be working on it.\n const startedAt = new Map<string, number>();\n for (const row of await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n status: 'active',\n work_item_id: { in: held.map(item => item.id) },\n })) {\n const key = `${row.org_id}:${row.work_item_id}`;\n startedAt.set(key, Math.max(startedAt.get(key) ?? 0, new Date(row.created_at as string | Date).getTime()));\n }\n const moved: Card[] = [];\n for (const item of held) {\n if ((startedAt.get(`${item.orgId}:${item.id}`) ?? 0) >= item.updatedAt.getTime()) continue;\n // A governed transition leaves an audit row and disarms autonomy so the card\n // waits for a person; the identity makes a second replica's move a replay.\n const identity = `${HELD_CARD_SWEEP_ACTOR}:${item.id}:${item.revision}`;\n const committed = await this.commitTransition({\n orgId: item.orgId,\n factoryProjectId: item.factoryProjectId,\n workItemId: item.id,\n expectedRevision: item.revision,\n destinationStage: LEGACY_REST_PHASE,\n actorId: HELD_CARD_SWEEP_ACTOR,\n ingress: { identity, transitionId: identity },\n causalChain: [],\n evaluation: { outcome: 'accepted', decisions: [] },\n autonomy: 'disarm',\n });\n if (committed.status === 'committed' && committed.result.status === 'accepted' && committed.item) {\n moved.push(committed.item);\n }\n }\n return moved;\n }\n\n /** Requeue the same idempotent terminal effect; non-failed or non-retryable decisions are never rerun. */\n async retryDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n return this.#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 const failureCode = isStoredFactoryDispatchFailureCode(current.failure_code) ? current.failure_code : null;\n if (!factoryDispatchFailureMetadata(failureCode).canRetry) 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 }\n\n /** The binding an `agent:<bindingId>` actor names, active or revoked. Identifies; never authorizes. */\n async findRunBindingById(input: {\n orgId: string;\n factoryProjectId: string;\n id: string;\n }): Promise<FactoryRunBindingRecord | null> {\n // Actor ids are free text and the id column is a uuid on Postgres.\n if (!/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(input.id)) return null;\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: input.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n return row ? toBinding(row) : null;\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 rejectAmbiguous?: boolean;\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 const projectCount = new Set(rows.map(row => row.factory_project_id)).size;\n if (projectCount > 1 && input.rejectAmbiguous)\n throw new Error('Factory session has ambiguous active run bindings.');\n if (projectCount !== 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 /** Historical thread membership for model/billing policy only; never grants active agent authority. */\n async findRunBindingByThread(input: {\n orgId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n rejectAmbiguous?: boolean;\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 });\n const projectCount = new Set(rows.map(row => row.factory_project_id)).size;\n if (projectCount > 1 && input.rejectAmbiguous) throw new Error('Factory session has ambiguous run bindings.');\n if (projectCount !== 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 /**\n * The active binding a Factory session is serving, keyed by the session\n * alone so it resolves before the session has a live thread (e.g. when the\n * dispatcher builds the workspace for a kickoff). Ambiguous matches never\n * authorize.\n */\n async findActiveRunBindingForSession(input: {\n orgId: string;\n factoryProjectId: 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 factory_project_id: input.factoryProjectId,\n session_id: input.sessionId,\n status: 'active',\n });\n if (rows.length !== 1) return null;\n return toBinding(rows[0]!);\n }\n\n /** Whether this session was ever bound to a run, on any thread and whether or not the binding was revoked. */\n async hasRunBindingForSession(input: {\n orgId: string;\n factoryProjectId: string;\n sessionId: string;\n }): Promise<boolean> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n session_id: input.sessionId,\n });\n return 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` (unless\n * `keep` vouches for them), or whose work item is gone, malformed, or\n * already terminal. Terminal-stage cleanup handles bindings go-forward; this\n * sweep drains anything that slipped past 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, Card | null>();\n let revoked = 0;\n for (const binding of bindings) {\n let stale = binding.createdAt.getTime() < input.olderThan.getTime() && !(await input.keep?.(binding));\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 /**\n * The work items a session was ever bound to run, revoked bindings included.\n * `null` stands for a bound item that no longer loads. Empty when the session\n * never ran a work item.\n */\n async listRunBoundItems(sessionId: string): Promise<(Card | null)[]> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', { session_id: sessionId });\n const keys = new Map(rows.map(row => [`${row.org_id}:${row.work_item_id}`, row]));\n return Promise.all(\n [...keys.values()].map(row => this.get({ orgId: String(row.org_id), id: String(row.work_item_id) })),\n );\n }\n\n /**\n * Move a session's bindings from the legacy `resourceId = sessionId` onto\n * `resourceId`. Only rows still on the session id change, so a rerun is a no-op.\n */\n async moveRunBindingsToResource(input: { sessionId: string; resourceId: string }): Promise<number> {\n return this.#db.updateMany(\n 'factory_run_bindings',\n { session_id: input.sessionId, resource_id: input.sessionId },\n { resource_id: input.resourceId },\n );\n }\n\n /** List binding history, optionally narrowed to one or some work items. */\n async listRunBindings(\n orgId: string,\n factoryProjectId: string,\n workItemId?: string | string[],\n ): Promise<FactoryRunBindingRecord[]> {\n if (Array.isArray(workItemId) && workItemId.length === 0) return [];\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: Array.isArray(workItemId) ? { in: workItemId } : 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.#withTransaction(async ops => {\n if (input.expectedBindingId) {\n const workItemId = input.workItem.id;\n if (!workItemId) throw new FactoryRunBindingSupersededError();\n const expected = await ops.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: input.expectedBindingId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: workItemId,\n role: input.role,\n status: 'active',\n });\n if (!expected) throw new FactoryRunBindingSupersededError();\n }\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 this.#cards(ops, { transaction: true }).findOne({\n id: String(bindingRow.work_item_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n }));\n // Replay only a still-live binding. A prior pending row whose binding\n // was revoked (abort → stage re-entry) or whose state is gone is a\n // dead-run artifact: discard it and mint a fresh binding below. The\n // unique kickoff_key index requires removing the stale row before\n // re-inserting.\n if (bindingRow && itemRow && bindingRow.status === 'active') {\n return {\n item: toRow(itemRow),\n binding: toBinding(bindingRow),\n pendingStart: toPendingStart(prior),\n replayed: true,\n };\n }\n await ops.deleteMany('factory_pending_starts', {\n id: prior.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n }\n const now = new Date();\n const create = input.workItem.input;\n let row = input.workItem.id\n ? await this.#cards(ops, { transaction: true }).findOne({\n id: input.workItem.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : externalSourceKey(create.externalSource)\n ? await this.#cards(ops, { transaction: true }).findOne({\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: externalSourceKey(create.externalSource),\n })\n : null;\n let item: Card;\n if (row) {\n row = await this.#cards(ops, { transaction: true }).updateAtomic({ 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 // The binding below shares this clock, so a run started on an existing card\n // is never older than the card's last change.\n return applyUpdate({\n current,\n userId: input.userId,\n input: { sessions: { [input.role]: input.session } },\n now,\n });\n });\n item = toRow(row!);\n } else {\n if (create.parentWorkItemId) await this.#copyLegacyParent(ops, input.orgId, create.parentWorkItemId);\n if (create.parentWorkItemId)\n validateParentRelation(\n (\n await this.#cards(ops, { transaction: true }).findMany({\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n ).map(toRow),\n undefined,\n create.parentWorkItemId,\n );\n row = await this.#cards(ops, { transaction: true }).insertOne({\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 description: create.description ?? null,\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 // A role continuing in an earlier role's session (e.g. build after plan)\n // may open a new thread; the earlier role's agent must stop acting.\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 session_id: input.session.sessionId,\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 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(bindingId: string, status: 'sent' | 'failed'): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_pending_starts',\n { binding_id: bindingId },\n () => ({ status, 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 : this.#withTransaction(run);\n try {\n return await execute();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n // Another writer filed the same source key first; the retry reuses its card.\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 this.#cards(ops, { transaction: true }).findOne({\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: key,\n });\n if (!existing) return null;\n if (reuseMode === 'preserve') {\n return { created: false, item: toWorkItem(existing), previous: priorState(existing) };\n }\n\n let previous = emptyPrior();\n const updated = await this.#cards(ops, { transaction: true }).updateAtomic(\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 description: input.description,\n parentWorkItemId: input.parentWorkItemId ?? undefined,\n metadata: input.metadata,\n }\n : fullPatch;\n if (patch.parentWorkItemId !== undefined) {\n await this.#copyLegacyParent(ops, orgId, patch.parentWorkItemId);\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 // The card is handed to this second caller, so a concurrent creator's guarded rollback\n // must see the reuse; pending rules keep their revision.\n { touch: reuseMode === 'non-stage' },\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 // Legacy writers omit stages; they only ever filed onto the default board's resting phase.\n const stages = input.stages ?? [LEGACY_REST_PHASE];\n if (input.parentWorkItemId != null) {\n await this.#copyLegacyParent(ops, orgId, input.parentWorkItemId);\n validateParentRelation(await this.#listWithOps(ops, orgId, factoryProjectId), undefined, input.parentWorkItemId);\n }\n const row = await this.#cards(ops, { transaction: true }).insertOne({\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 description: input.description ?? null,\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<Card | null> {\n const candidate = await this.#cards(this.#db, { transaction: false }).findOne({ 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 this.#cards(ops, { transaction: true }).updateAtomic({ org_id: orgId, id }, async current => {\n if (current.parent_work_item_id !== null) return current;\n await this.#copyLegacyParent(ops, orgId, parentWorkItemId);\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: Card; previous: WorkItemPriorState } | null> {\n const run = async (ops: FactoryStorageOps) => {\n let previous = emptyPrior();\n const row = await this.#cards(ops, { transaction: true }).updateAtomic({ 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 await this.#copyLegacyParent(ops, orgId, patch.parentWorkItemId);\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 this.#withTransaction(run);\n const candidate = await this.#cards(this.#db, { transaction: false }).findOne({ 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, sourceKeys }: { orgId: string; factoryProjectId: string; sourceKeys: string[] },\n ): Promise<void> {\n const keys = [...new Set(sourceKeys)];\n const decisions = await ops.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: { in: keys },\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: { in: keys },\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 * Make a session follow a work item. Idempotent: following again keeps the\n * first subscription, including its reason (filing beats a later subscribe).\n */\n async subscribeToWorkItem(input: SubscribeToWorkItemInput): Promise<WorkItemSubscription> {\n // Subscriptions never change the board, so they skip the board-version bump.\n const ops = super.ops;\n const where = { work_item_id: input.workItemId, session_id: input.sessionId };\n const existing = await ops.findOne<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, where);\n if (existing) return toWorkItemSubscription(existing);\n try {\n const row = await ops.insertOne<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n session_id: input.sessionId,\n thread_id: input.threadId,\n resource_id: input.resourceId,\n user_id: input.userId,\n reason: input.reason,\n created_at: new Date(),\n });\n return toWorkItemSubscription(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const raced = await ops.findOne<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, where);\n if (!raced) throw error;\n return toWorkItemSubscription(raced);\n }\n }\n\n /** Stop a session following a work item. Returns whether it was following. */\n async unsubscribeFromWorkItem({\n orgId,\n workItemId,\n sessionId,\n }: {\n orgId: string;\n workItemId: string;\n sessionId: string;\n }): Promise<boolean> {\n const deleted = await super.ops.deleteMany(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, {\n org_id: orgId,\n work_item_id: workItemId,\n session_id: sessionId,\n });\n return deleted > 0;\n }\n\n /** The sessions following a work item, earliest first. */\n async listWorkItemSubscribers({\n orgId,\n workItemId,\n }: {\n orgId: string;\n workItemId: string;\n }): Promise<WorkItemSubscription[]> {\n const rows = await super.ops.findMany<WorkItemSubscriptionDbRow>(\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name,\n { org_id: orgId, work_item_id: workItemId },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n },\n );\n return rows.map(toWorkItemSubscription);\n }\n\n /** Every follow link in a Factory, earliest first: which session follows which work item. */\n async listProjectSubscriptions({\n orgId,\n factoryProjectId,\n }: {\n orgId: string;\n factoryProjectId: string;\n }): Promise<WorkItemSubscription[]> {\n const rows = await super.ops.findMany<WorkItemSubscriptionDbRow>(\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name,\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n },\n );\n return rows.map(toWorkItemSubscription);\n }\n\n /** The work items one session follows in a Factory, earliest first. */\n async listSessionSubscriptions({\n orgId,\n factoryProjectId,\n sessionId,\n }: {\n orgId: string;\n factoryProjectId: string;\n sessionId: string;\n }): Promise<WorkItemSubscription[]> {\n const rows = await super.ops.findMany<WorkItemSubscriptionDbRow>(\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name,\n { org_id: orgId, factory_project_id: factoryProjectId, session_id: sessionId },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n },\n );\n return rows.map(toWorkItemSubscription);\n }\n\n async delete({\n orgId,\n id,\n purgeRuleState = true,\n expectedRevision,\n expectedUpdatedAt,\n }: {\n orgId: string;\n id: string;\n purgeRuleState?: boolean;\n /** Deletes only while the card is still at this revision; returns `null` and keeps it otherwise. */\n expectedRevision?: number;\n /** Likewise for the card's `updatedAt`, which a reuse of a sourced card moves without a new revision. */\n expectedUpdatedAt?: Date;\n }): Promise<Card | null> {\n const where = {\n org_id: orgId,\n id,\n ...(expectedRevision === undefined ? {} : { revision: expectedRevision }),\n ...(expectedUpdatedAt === undefined ? {} : { updated_at: expectedUpdatedAt }),\n };\n const candidate = await this.#cards(this.#db, { transaction: false }).findOne(where);\n if (!candidate) return null;\n\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const existing = await this.#cards(ops, { transaction: true }).findOne(where);\n if (!existing) return null;\n const deleted = await this.#cards(ops, { transaction: true }).deleteMany(where);\n if (deleted === 0) return null;\n await ops.deleteMany(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, { org_id: orgId, work_item_id: id });\n if (purgeRuleState && existing.external_source?.externalId) {\n await this.#purgeRuleState(ops, {\n orgId,\n factoryProjectId: existing.factory_project_id,\n sourceKeys: [existing.external_source.externalId],\n });\n }\n await this.#cards(ops, { transaction: true }).updateMany(\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 }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAS,WAAc,OAAa;CAClC,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,GAAG;EACjE,OAAO,OAAO,KAAK;EACnB,KAAK,MAAM,SAAS,OAAO,OAAO,KAAK,GAAG,WAAW,KAAK;CAC5D;CACA,OAAO;AACT;AAEA,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;AAEA,SAAS,iBAAiB,OAAyC;CACjE,OACE,UAAU,kBACV,UAAU,eACV,UAAU,kBACV,UAAU,gBACV,UAAU,0BACV,UAAU,6BACV,UAAU,yBACV,UAAU,oBACV,UAAU;AAEd;;AAgBA,MAAa,mCAAmC;AAChD,MAAa,0CAA0C;;;;;;;;;;;AAwBvD,SAAgB,aAAa,IAAiC;CAC5D,IAAI,OAAO,KAAA,GAAW,OAAO;CAC7B,OAAO,GAAG,WAAW,QAAQ,KAAK,OAAO;AAC3C;AAkDA,MAAM,iCAAiC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,MAAM,KAAK,OAAO,KAAK,EAAE,aAAa,KAAK,CAAC,CAAC,CAAC,WAC5C;IAAE,QAAQ;IAAO,qBAAqB;GAAG,GACzC;IAAE,qBAAqB;IAAM,4BAAY,IAAI,KAAK;GAAE,CACtD;GACA,OAAO,WAAW,QAAQ;EAC5B,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"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 { factoryDispatchFailureMetadata } from '../../../rules/dispatch-errors.js';\nimport { externalSourceForWorkItem, FACTORY_TRIAGE_TYPES } from '../../../rules/types.js';\nimport type { FactoryTriageType, WorkItemSource } from '../../../rules/types.js';\nimport { splitCardMetadata, workItemProviderAdapter } from '../../../work-items/providers/index.js';\nimport {\n copyLegacyRows,\n migrateWorkItemSplit,\n readLegacyWatermark,\n readWorkItemSplitMarker,\n recordWorkItemSplitComplete,\n} from '../../../work-items/split-migration.js';\nimport type { LegacyWatermark, WorkItemSplitReport } from '../../../work-items/split-migration.js';\nimport { ensureLegacyCollections } from '../../legacy-collections.js';\nimport { ProbedList, probeNewest } from '../../probed-list.js';\nimport {\n BoardScopes,\n bumpBoardVersions,\n CARD_TABLES,\n DECISION_TABLES,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n readBoardVersion,\n trackBoardWrites,\n} from './board-version.js';\nimport type { BoardScope } from './board-version.js';\nimport { Cards, splitCardRows } from './cards.js';\nimport { LEASE_TABLES, trackClaimableWrites } from './claimable-work.js';\nimport type { FactoryClaimableWorkScope } from './claimable-work.js';\nimport {\n LEGACY_REST_PHASE,\n LEGACY_REVIEW_BOARD,\n LEGACY_TRIAGE_PHASE,\n LEGACY_WORK_BOARD,\n readReviewBoardInUse,\n releaseLegacyReviewCards,\n} from './legacy-review.js';\nimport type { ReviewBoardInUse, ReviewBoardScope } from './legacy-review.js';\nimport type {\n WorkItemRow as ProviderWorkItemRow,\n WorkItemDbRecord,\n WorkItemSourceDbRecord,\n WorkItemSourceRow,\n} from './work-item-schema.js';\nimport {\n primarySource,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n WORK_ITEMS_SCHEMA,\n} from './work-item-schema.js';\n\nexport type { FactoryClaimableWorkScope } from './claimable-work.js';\n\nexport type WorkItemStage = string;\n\n/** Freeze `value` and everything reachable from it, so shared cache entries cannot be written to. */\nfunction deepFreeze<T>(value: T): T {\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const entry of Object.values(value)) deepFreeze(entry);\n }\n return value;\n}\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\nfunction isWorkItemSource(value: unknown): value is WorkItemSource {\n return (\n value === 'github-issue' ||\n value === 'github-pr' ||\n value === 'linear-issue' ||\n value === 'jira-issue' ||\n value === 'incidentio-follow-up' ||\n value === 'github-dependabot-alert' ||\n value === 'vanta-vulnerability' ||\n value === 'detail-finding' ||\n value === 'manual'\n );\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 CommitFactoryRuleEvaluationInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string | null;\n ingress: { identity: 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 /** Consent-bearing actor behind the evaluation; their id pre-approves the skill runs it queues. */\n consentedBy?: string;\n /**\n * Card metadata written in the same transaction as the decisions, while the card is still at\n * `expectedRevision`: what the evaluation saw of its source, so a change is never queued without\n * being recorded, nor recorded over what a concurrent, newer evaluation saw. Otherwise `stale`.\n */\n cardMetadata?: { userId: string; metadata: Record<string, unknown> };\n}\n\ninterface SyncCardInput {\n orgId: string;\n id: string;\n userId: string;\n patch: { title?: string; metadata?: Record<string, unknown> | null };\n expectedSourceRevision?: number;\n fillOnly?: boolean;\n /** The card's revision the patch was worked out against: a card that moved on is refused. */\n expectedRevision?: number;\n}\n\n/** Thrown inside a transaction to roll it back when the card is no longer at the revision a write expected. */\nclass CardRevisionMoved extends Error {}\n\nexport type CommitFactoryRuleEvaluationResult =\n | { status: 'committed'; result: Record<string, unknown> }\n | { status: 'replayed'; result: Record<string, unknown> }\n | { status: 'missing' }\n /** The work item's revision moved; nothing was persisted, so the caller may re-read and retry. */\n | { status: 'stale' };\n\nexport interface FactoryToolResultCursorRecord {\n bindingId: string;\n orgId: string;\n factoryProjectId: string;\n lastMessageCreatedAt: Date;\n updatedAt: 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 'source_repository_ambiguous',\n 'unsupported_provider_item',\n 'notification_delivery_failed',\n 'run_terminal_event_missing',\n 'run_incomplete',\n 'skill_delivery_ambiguous',\n 'run_overdue',\n 'repository_git_missing',\n 'repository_sandbox_unresponsive',\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 'run_configuration_invalid',\n 'run_credentials_unavailable',\n 'run_user_unauthenticated',\n 'factory_org_key_missing',\n 'run_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 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 = 'automation-failed' | 'automation-proposed' | 'agent-waiting';\nexport type FactoryAttentionReceiptState = 'read' | 'archived';\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\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, unless `keep` exempts them. */\n olderThan: Date;\n now: Date;\n /** Exempts an over-age binding from the age test only; the item-state checks still apply. */\n keep?: (binding: FactoryRunBindingRecord) => Promise<boolean>;\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 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 FactoryDeferredDecisionClaimInput extends FactoryLeaseClaimInput {\n /** Restrict the claim by decision payload and who caused it; rejected rows are never leased. */\n decisionFilter?: (decision: Record<string, unknown>, provenance: FactoryDecisionProvenance) => boolean;\n}\n\n/** Who caused a deferred decision: the rule actor, and the decisions it follows from. */\nexport interface FactoryDecisionProvenance {\n actor: Record<string, unknown> | null;\n causalChain: FactoryDeferredDecisionRecord['causalChain'];\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 /** The board the card moves to with this transition, when a card-move rule sends it to another one. */\n destinationBoard?: string;\n actorId: string;\n ingress: { identity: string; transitionId: 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: Card | null; result: Record<string, unknown> }\n | { status: 'replayed'; item: Card | null; result: Record<string, unknown> }\n | { status: 'missing' };\n\nexport class FactoryRunBindingSupersededError extends Error {\n constructor() {\n super('Factory run binding was superseded before preparation.');\n }\n}\n\nexport interface PrepareFactoryRunStartInput {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n workItem: { id?: string; input: CreateWorkItemInput };\n role: string;\n /** Only recover this binding if it still owns the role when the transaction starts. */\n expectedBindingId?: string;\n session: WorkItemSessionInput;\n resourceId: string;\n kickoffKey: string;\n kickoffMessage: string | null;\n}\n\nexport interface PrepareFactoryRunStartResult {\n item: Card;\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 Card extends BoardItemRow {\n workItem: ProviderWorkItemRow;\n externalSource: ExternalWorkItemSource | null;\n parentWorkItemId: string | null;\n title: string;\n /** What the card is about, in the words of whoever filed it; handed to agent runs at kickoff. */\n description: string | null;\n}\n\nexport interface BoardItemRow {\n workItemId: string;\n parentBoardItemId: string | null;\n id: string;\n orgId: string;\n factoryProjectId: string;\n board: string | null;\n stages: WorkItemStage[];\n stageHistory: WorkItemStageEntry[];\n sessions: WorkItemSessions;\n metadata: Record<string, unknown> | null;\n /** When the card last changed. A reader that keeps the board tells its copy of the card by it. */\n changedAt?: Date | 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. Boards whose phases don't start\n * on their own 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 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 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 description?: string | null;\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 description?: string | null;\n stages?: WorkItemStage[];\n sessions?: Record<string, WorkItemSessionInput>;\n metadata?: Record<string, unknown> | null;\n}\n\nexport interface WorkItemPriorState {\n stages: WorkItemStage[];\n sessionRoles: string[];\n}\n\nexport interface UpsertWorkItemResult {\n item: Card;\n created: boolean;\n previous: WorkItemPriorState;\n}\n\nexport const FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'factory_work_item_subscriptions',\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 session_id: { type: 'text' },\n thread_id: { type: 'text' },\n resource_id: { type: 'text' },\n user_id: { type: 'text' },\n reason: { type: 'text' },\n created_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_work_item_subscriptions_item_session_unique', columns: ['work_item_id', 'session_id'] },\n ],\n indexes: [\n {\n name: 'factory_work_item_subscriptions_session_idx',\n columns: ['org_id', 'factory_project_id', 'session_id'],\n },\n ],\n};\n\n/** Why a session follows a work item: it filed it, moved it, started a role on it, or asked to. */\nexport type WorkItemSubscriptionReason = 'created' | 'moved' | 'started' | 'subscribed';\n\n/** A session following a work item, so it hears what happens to it. */\nexport interface WorkItemSubscription {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n sessionId: string;\n threadId: string;\n resourceId: string;\n userId: string;\n reason: WorkItemSubscriptionReason;\n createdAt: Date;\n}\n\nexport interface SubscribeToWorkItemInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n sessionId: string;\n threadId: string;\n resourceId: string;\n userId: string;\n reason: WorkItemSubscriptionReason;\n}\n\ninterface WorkItemSubscriptionDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n session_id: string;\n thread_id: string;\n resource_id: string;\n user_id: string;\n reason: WorkItemSubscriptionReason;\n created_at: Date;\n}\n\nfunction toWorkItemSubscription(row: WorkItemSubscriptionDbRow): WorkItemSubscription {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: String(row.factory_project_id),\n workItemId: row.work_item_id,\n sessionId: row.session_id,\n threadId: row.thread_id,\n resourceId: row.resource_id,\n userId: row.user_id,\n reason: row.reason,\n createdAt: row.created_at,\n };\n}\n\nexport interface WorkItemDbRow extends Record<string, unknown> {\n work_item?: WorkItemDbRecord;\n work_item_sources?: WorkItemSourceDbRecord[];\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 claim_key: string | null;\n parent_work_item_id: string | null;\n title: string;\n description: string | null;\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 revision: number;\n created_by: string;\n created_at: Date;\n updated_at: Date;\n changed_at?: Date | null;\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 toSource(source: WorkItemSourceDbRecord): WorkItemSourceRow {\n return {\n id: source.id,\n workItemId: source.work_item_id,\n provider: source.provider,\n integrationId: source.integration_id,\n sourceType: source.source_type,\n workspaceId: source.workspace_id,\n externalId: source.external_id,\n sourceKey: source.source_key,\n key: source.key,\n url: source.url,\n state: source.state,\n labels: source.labels,\n author: source.author,\n metadata: source.metadata,\n revision: source.revision,\n syncedAt: source.synced_at,\n createdAt: source.created_at,\n updatedAt: source.updated_at,\n };\n}\n\nfunction toWorkItem(row: WorkItemDbRow): Card {\n const fallback = row.work_item ? null : splitCardRows(row, { workItemId: row.id });\n const work = row.work_item ?? fallback!.workItem;\n const sources = (row.work_item_sources ?? (fallback?.source ? [fallback.source] : [])).map(toSource);\n const source = primarySource({ workItem: { sources } });\n return {\n workItem: {\n sources,\n id: work.id,\n orgId: work.org_id,\n factoryProjectId: work.factory_project_id,\n provider: source?.provider ?? 'factory',\n externalId: source?.externalId ?? row.id,\n key: source?.key ?? null,\n url: source?.url ?? null,\n title: work.title,\n state: source?.state ?? null,\n labels: source?.labels ?? [],\n author: source?.author ?? null,\n parentWorkItemId: work.parent_work_item_id,\n metadata: source?.metadata ?? null,\n revision: work.revision,\n syncedAt: source?.syncedAt ?? null,\n createdAt: work.created_at,\n updatedAt: work.updated_at,\n },\n workItemId: work.id,\n parentBoardItemId: row.parent_work_item_id,\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 description: row.description ?? null,\n stages: row.stages,\n stageHistory: row.stage_history,\n sessions: row.sessions,\n metadata: splitCardMetadata(row.metadata, workItemProviderAdapter(row.external_source).providerMetadataKeys).board,\n triageType: row.triage_type ?? null,\n autonomyArmedAt: row.autonomy_armed_at ?? null,\n acceptedAt: row.accepted_at ?? null,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n changedAt: row.changed_at ?? null,\n };\n}\n\nconst toRow = toWorkItem;\n\nfunction patchColumns(changes: Partial<Card>): 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.description !== undefined ? { description: changes.description } : {}),\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 WorkItemSplitModeError extends Error {}\n\nconst OPEN_PASS_PAGE_SIZE = 500;\n\nfunction logSplit(line: string): void {\n console.info(`[factory] ${line}`);\n}\n\nfunction sameWatermark(a: LegacyWatermark | null, b: LegacyWatermark): boolean {\n return a !== null && a.id === b.id && new Date(a.updatedAt).getTime() === new Date(b.updatedAt).getTime();\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\n/** The source a caller tried to attach already belongs to another work item in the project. */\nexport class WorkItemSourceConflictError extends Error {\n readonly code = 'work_item_source_conflict';\n\n constructor(readonly ownerWorkItemId: string) {\n super(`The source already belongs to work item ${ownerWorkItemId}.`);\n }\n}\n\nexport function validateParentRelation(\n projectItems: Card[],\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: Card | 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 now = new Date(),\n}: {\n current: WorkItemDbRow;\n userId: string;\n input: UpdateWorkItemInput;\n now?: Date;\n}): Partial<WorkItemDbRow> {\n const metadata = input.metadata ? { ...input.metadata } : input.metadata;\n const reconciliation = current.metadata?.[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n // Clearing an absent reconciliation marker must not invalidate pending rules.\n if (\n metadata?.[FACTORY_PULL_REQUEST_RECONCILIATION_KEY] === null &&\n reconciliation !== 'merged' &&\n reconciliation !== 'closed' &&\n reconciliation !== null\n ) {\n delete metadata[FACTORY_PULL_REQUEST_RECONCILIATION_KEY];\n }\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.description !== undefined ? { description: input.description } : {}),\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 ...(metadata !== undefined\n ? { metadata: metadata === null ? null : { ...(current.metadata ?? {}), ...metadata } }\n : {}),\n revision: current.revision + 1,\n updated_at: now,\n };\n}\n/** Stage-history actor for the one-time move of cards held for triage acceptance. */\nexport const HELD_CARD_SWEEP_ACTOR = 'factory-held-card-sweep';\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 decisionRowPayload(decision: unknown): Record<string, unknown> {\n const parsed = typeof decision === 'string' ? safeJsonParse(decision) : decision;\n return typeof parsed === 'object' && parsed !== null ? (parsed as Record<string, unknown>) : {};\n}\n\nfunction jsonRowValue<T>(value: unknown, is: (parsed: unknown) => parsed is T): T | undefined {\n const parsed = typeof value === 'string' ? safeJsonParse(value) : value;\n return is(parsed) ? parsed : undefined;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\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 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 created_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_rule_evaluations_ingress_idx', columns: ['ingress_id'] }],\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 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 name: 'factory_deferred_decisions_tenant_evaluation_idx',\n columns: ['org_id', 'factory_project_id', 'evaluation_id'],\n },\n // One card's decisions: the update fold, overtaken status events and the intake tester.\n {\n name: 'factory_deferred_decisions_tenant_work_item_idx',\n columns: ['org_id', 'factory_project_id', 'work_item_id', 'created_at'],\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 {\n name: 'factory_run_bindings_org_thread_idx',\n columns: ['org_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_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 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 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 (value === 'automation-failed' || value === 'automation-proposed' || value === 'agent-waiting') {\n return value;\n }\n throw new Error(`Unsupported attention receipt kind '${String(value)}'.`);\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 createdAt: row.created_at,\n updatedAt: row.updated_at as Date,\n };\n}\n\n/** The project whose board a committed card or decision write just changed. */\nexport type FactoryBoardScope = Required<BoardScope>;\n\n/** A safety net, not the invalidation path: bounds how long a missed version bump or a stuck read can last. */\nconst LIST_CACHE_TTL_MS = 60_000;\nconst LIST_CACHE_MAX_PROJECTS = 100;\nconst LIST_DELTA_CLOCK_SKEW_MS = 5_000;\n\ntype WorkItemSourceSyncPatch = Partial<\n Pick<WorkItemSourceRow, 'state' | 'labels' | 'author' | 'url' | 'key' | 'metadata'>\n>;\n\nexport class WorkItemsStorage extends FactoryStorageDomain {\n /** Last full card list per project, valid while the project's board version is unchanged. */\n /** `takenAt` is the last full read; `readFrom` when the latest read, full or delta, began. */\n readonly #listCache = new Map<string, { version: string; takenAt: number; readFrom: number; items: Card[] }>();\n // Joined only at the same board version: a poll after a write must not join a read begun before it.\n readonly #listInFlight = new Map<string, { version: string; startedAt: number; items: Promise<Card[]> }>();\n readonly #projectSubscriptions = new ProbedList<WorkItemSubscription>();\n #boardChanged: (scope: FactoryBoardScope) => void = () => {};\n readonly #claimableWorkListeners = new Set<(scope: FactoryClaimableWorkScope) => void>();\n // Storage does not know boards: no card counts as finished until the host wires the predicate.\n #isTerminal: (item: Card) => boolean = () => false;\n\n #legacyMode = false;\n /**\n * Legacy cards this replica may still have to copy. While pending, lookups by id or source\n * copy a missed card on demand; `since` limits the passes to rows written after the last\n * finished pass.\n */\n #split: { pending: boolean; since: LegacyWatermark | null } = { pending: false, since: null };\n\n get legacyMode(): boolean {\n return this.#legacyMode;\n }\n\n get legacyBackfillPending(): boolean {\n return this.#split.pending;\n }\n\n /** Projects found not to use the Review board; once redundant it stays so, with no card left to reopen on it. */\n readonly #reviewRedundant = new Set<string>();\n\n #ownReviewBoard: ReviewBoardInUse | undefined;\n\n /**\n * Tells cards apart from the retired Review board's: where `owned` answers true the project has\n * a board of its own under `review`, and the cards stored on it are that board's.\n */\n useOwnReviewBoard(owned: ReviewBoardInUse): void {\n this.#ownReviewBoard = owned;\n }\n\n /** {@link reviewBoardInUse} through `ops`, so a caller inside a transaction reads within it. */\n readonly #reviewInUse: ReviewBoardInUse = async (ops, scope) => {\n // Asked every time: a project can make or delete a board of its own under `review` at any moment.\n if (await this.#ownReviewBoard?.(ops, scope)) return true;\n const key = `${scope.orgId}\\0${scope.factoryProjectId}`;\n if (this.#reviewRedundant.has(key)) return false;\n const inUse = await readReviewBoardInUse(ops, scope, {\n split: !this.#legacyMode,\n // Legacy cards not copied yet still count.\n legacy: this.#legacyMode || this.#split.pending,\n });\n if (!inUse) this.#reviewRedundant.add(key);\n return inUse;\n };\n\n /**\n * Whether cards stored on `review` stay there: the project has a board of its own under that\n * key, or still uses the retired Review board (it holds a card stored on Review that isn't Done\n * or Canceled) and keeps it. In any other project Review is redundant and its cards read as Work.\n */\n reviewBoardInUse(scope: ReviewBoardScope): Promise<boolean> {\n return this.#reviewInUse(this.#db, scope);\n }\n\n /**\n * Leaves `review` to a board about to take it: stores the Work placement of the cards the\n * retired Review board left there, through `ops`, so it happens in the board write's\n * transaction. See {@link releaseLegacyReviewCards} for `open`.\n */\n async releaseReviewCards(\n ops: FactoryStorageOps,\n scope: ReviewBoardScope,\n { open }: { open: 'refuse' | 'move' },\n ): Promise<void> {\n const rewritten = await releaseLegacyReviewCards(\n ops,\n scope,\n // Legacy cards not copied yet still count.\n { split: !this.#legacyMode, legacy: this.#legacyMode || this.#split.pending },\n open,\n );\n // An open card that moved was listed on Review until now.\n if (rewritten > 0) await bumpBoardVersions(ops, [scope]);\n }\n\n constructor() {\n super('work-items');\n }\n\n /**\n * Wired once at boot. Fires after a committed write changes what a board shows of a card\n * or a deferred decision, so open boards refetch instead of polling.\n */\n onBoardChanged(listener: (scope: FactoryBoardScope) => void): void {\n this.#boardChanged = listener;\n }\n\n /**\n * Fires after any committed write leaves a pending start or deferred decision\n * `pending` or `retry`, so an idle dispatcher can wake instead of polling.\n * Listeners run after the write has committed, so a listener that throws is\n * logged and skipped rather than failing the write or the other listeners.\n * Returns a function that removes the listener.\n */\n onClaimableWork(listener: (scope: FactoryClaimableWorkScope) => void): () => void {\n this.#claimableWorkListeners.add(listener);\n return () => this.#claimableWorkListeners.delete(listener);\n }\n\n #claimableWork(scope: FactoryClaimableWorkScope): void {\n for (const listener of this.#claimableWorkListeners) {\n try {\n listener(scope);\n } catch (error) {\n console.error('[factory] claimable-work listener failed', error instanceof Error ? error.message : error);\n }\n }\n }\n\n /**\n * When the next pending start or deferred decision becomes claimable: the earliest\n * `available_at` of a queued row, or `lease_expires_at` of a leased one (a crashed\n * dispatcher's lease is reclaimed once it lapses). `null` when nothing is queued or leased.\n * May be in the past when work is already due.\n */\n async nextClaimableAt(): Promise<Date | null> {\n const earliest = async (table: string, status: string | { in: string[] }, column: string) => {\n const [row] = await this.#db.findMany<GovernanceDbRow>(\n table,\n { status },\n { orderBy: [[column, 'asc']], limit: 1 },\n );\n const value = row?.[column];\n return value ? new Date(value as Date | string).getTime() : undefined;\n };\n const times = await Promise.all(\n LEASE_TABLES.flatMap(table => [\n earliest(table, { in: ['pending', 'retry'] }, 'available_at'),\n earliest(table, 'leased', 'lease_expires_at'),\n ]),\n );\n const due = times.filter((time): time is number => time !== undefined);\n return due.length ? new Date(Math.min(...due)) : null;\n }\n\n /** Tells the stale-binding sweep which cards sit in a phase their installed board declares terminal. */\n useTerminalPhasePredicate(isTerminal: (item: Card) => boolean): void {\n this.#isTerminal = isTerminal;\n }\n\n async init(): Promise<void> {\n this.#legacyMode = process.env.MASTRA_FACTORY_WORK_ITEM_SPLIT === 'dry-run';\n // Pre-split cards and the split's progress marker exist only on databases an earlier release\n // wrote cards to; dry-run mode serves from the pre-split table, so it always needs it.\n const legacySchemas = [WORK_ITEMS_SCHEMA, FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA];\n let hasLegacyCards = true;\n if (this.#legacyMode) await this.ensureCollections(legacySchemas);\n else hasLegacyCards = await ensureLegacyCollections(this.storage, legacySchemas);\n await this.ensureCollections([\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n ...FACTORY_GOVERNANCE_SCHEMAS,\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA,\n ]);\n if (this.#legacyMode && (await super.ops.findOne(FACTORY_BOARD_ITEMS_SCHEMA.name, {}))) {\n throw new WorkItemSplitModeError(\n 'MASTRA_FACTORY_WORK_ITEM_SPLIT=dry-run cannot serve a database with migrated board items.',\n );\n }\n if (this.#legacyMode) {\n this.#split = { pending: false, since: null };\n await migrateWorkItemSplit(this.storage, { dryRun: true, ops: super.ops, log: logSplit });\n return;\n }\n if (!hasLegacyCards) {\n this.#split = { pending: false, since: null };\n return;\n }\n const [marker, newest] = await Promise.all([readWorkItemSplitMarker(super.ops), readLegacyWatermark(super.ops)]);\n const finished = !newest || (marker !== null && sameWatermark(marker.watermark, newest));\n // The factory copies open cards once boards load, and the rest in the background.\n this.#split = { pending: !finished, since: marker?.watermark ?? null };\n }\n\n /**\n * Copy the legacy cards `isTerminal` rejects, before Factory serves. Terminal cards are left\n * to `backfillLegacyCards`. A no-op once the split finished.\n */\n async migrateOpenLegacyCards(\n isTerminal: (card: Card) => boolean | Promise<boolean>,\n ): Promise<WorkItemSplitReport | null> {\n if (this.#legacyMode || !this.#split.pending) return null;\n return migrateWorkItemSplit(this.storage, {\n ops: super.ops,\n since: this.#split.since,\n // Mostly unchanged rows on a re-boot: larger pages mean fewer round trips.\n pageSize: OPEN_PASS_PAGE_SIZE,\n include: async row => !(await isTerminal(toWorkItem(row))),\n label: 'boot pass',\n log: logSplit,\n });\n }\n\n /**\n * Copy every remaining legacy card, then record the newest legacy row seen before the pass\n * began, so later boots skip rows up to it. Skipped cards are logged and count as done: they\n * conflict with newer split state and a rescan would only skip them again.\n */\n async backfillLegacyCards({ signal }: { signal?: AbortSignal } = {}): Promise<WorkItemSplitReport | null> {\n if (this.#legacyMode || !this.#split.pending) return null;\n // Captured first: a legacy write during the pass sorts after it and is rescanned next boot.\n const watermark = await readLegacyWatermark(super.ops);\n const report = await migrateWorkItemSplit(this.storage, {\n ops: super.ops,\n since: this.#split.since,\n signal,\n label: 'background pass',\n log: logSplit,\n });\n if (!report.aborted) {\n await recordWorkItemSplitComplete(super.ops, watermark);\n this.#split = { pending: false, since: watermark };\n }\n return report;\n }\n\n /**\n * Copy the legacy cards filed for these external records, so a lookup that matches on `list()`\n * finds them. A no-op once the split finished.\n */\n async copyLegacyCards({\n orgId,\n factoryProjectId,\n sources,\n }: {\n orgId: string;\n factoryProjectId: string;\n sources: readonly ExternalWorkItemSource[];\n }): Promise<void> {\n if (this.#legacyMode || !this.#split.pending || !sources.length) return;\n const sourceKeys = new Set(sources.map(source => externalSourceKey(source)!));\n await this.#cards(this.#db, { transaction: false }).findMany({\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: { in: [...sourceKeys] },\n });\n }\n\n /**\n * Card row access. While legacy cards remain uncopied, a lookup that misses copies the card:\n * inside the caller's transaction when `ops` is one (a nested transaction would deadlock\n * LibSQL), else in a transaction of its own.\n */\n #cards(ops: FactoryStorageOps, { transaction }: { transaction: boolean }): Cards {\n if (this.#legacyMode || !this.#split.pending) return new Cards(ops, this.#legacyMode, undefined, this.#reviewInUse);\n return new Cards(\n ops,\n false,\n {\n copy: async rows => {\n if (transaction) {\n await copyLegacyRows(ops, rows);\n return;\n }\n try {\n await this.#withTransaction(tx => copyLegacyRows(tx, rows));\n } catch (error) {\n // A concurrent first copy won (its retry lost again); the re-read finds its rows.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n },\n },\n this.#reviewInUse,\n );\n }\n\n /** Validation reads the split tables only, so a parent still in legacy is copied first. */\n async #copyLegacyParent(ops: FactoryStorageOps, orgId: string, parentId: string | null | undefined) {\n if (parentId && this.#split.pending)\n await this.#cards(ops, { transaction: true }).findOne({ org_id: orgId, id: parentId });\n }\n\n /** Refresh source evidence without changing work identity or board concurrency tokens. */\n async syncWorkItemSource(params: {\n orgId: string;\n factoryProjectId: string;\n provider: string;\n externalId: string;\n patch: WorkItemSourceSyncPatch | ((current: WorkItemSourceDbRecord) => WorkItemSourceSyncPatch | null);\n expectedRevision?: number;\n }): Promise<void> {\n await this.#withTransaction(async ops => {\n await this.#syncWorkItemSource(ops, params);\n });\n }\n\n async #syncWorkItemSource(\n ops: FactoryStorageOps,\n {\n orgId,\n factoryProjectId,\n provider,\n externalId,\n patch,\n expectedRevision,\n }: Parameters<WorkItemsStorage['syncWorkItemSource']>[0],\n ): Promise<Date | undefined> {\n const where = { org_id: orgId, factory_project_id: factoryProjectId, provider, external_id: externalId };\n const source = await ops.findOne<WorkItemSourceDbRecord>(FACTORY_WORK_ITEM_SOURCES_SCHEMA.name, where);\n const card = source && { work_item_id: source.work_item_id };\n // Lock the card's row before its source, the order every card write takes them in.\n if (card) await ops.updateAtomic(FACTORY_BOARD_ITEMS_SCHEMA.name, card, () => null);\n let synced = false;\n await ops.updateAtomic<WorkItemSourceDbRecord>(\n FACTORY_WORK_ITEM_SOURCES_SCHEMA.name,\n { org_id: orgId, factory_project_id: factoryProjectId, provider, external_id: externalId },\n current => {\n if (expectedRevision !== undefined && current.revision !== expectedRevision) {\n throw new WorkItemUpdateConflictError('revision');\n }\n const next = typeof patch === 'function' ? patch(current) : patch;\n if (!next) return null;\n synced = true;\n const { metadata, ...facts } = next;\n // Raw provider state can be 'closed' while normalized state is 'merged'.\n const nextMetadata =\n metadata === null\n ? null\n : {\n ...current.metadata,\n ...metadata,\n ...(next.labels !== undefined && !Object.hasOwn(metadata ?? {}, 'labels')\n ? { labels: next.labels }\n : {}),\n ...(next.state !== undefined && !Object.hasOwn(metadata ?? {}, 'state') ? { state: next.state } : {}),\n ...(next.author !== undefined && !Object.hasOwn(metadata ?? {}, 'author')\n ? { author: next.author }\n : {}),\n ...(next.key !== undefined && !Object.hasOwn(metadata ?? {}, 'identifier')\n ? { identifier: next.key }\n : {}),\n };\n return {\n ...facts,\n metadata: nextMetadata,\n revision: current.revision + 1,\n synced_at: new Date(),\n updated_at: new Date(),\n };\n },\n );\n // The card shows these facts but its own row did not move: stamp it so a board reload rereads it.\n if (!card || !synced) return undefined;\n const changed_at = new Date();\n await ops.updateMany(FACTORY_BOARD_ITEMS_SCHEMA.name, card, { changed_at });\n return changed_at;\n }\n\n /**\n * File one more external record on an existing card: a pull request on the\n * issue card it fixes. The card's primary source stays first, so the card keeps\n * reading as the issue. Attaching a source the card already holds is a no-op\n * (`attached: false`); one another card holds throws\n * {@link WorkItemSourceConflictError}. Later state for the attached record goes\n * through {@link syncWorkItemSource}, never {@link syncCard}, which writes the\n * primary source.\n */\n async attachSource({\n orgId,\n id,\n source,\n metadata,\n expectedRevision,\n cardMetadata,\n }: {\n orgId: string;\n id: string;\n source: ExternalWorkItemSource;\n metadata: Record<string, unknown> | null;\n expectedRevision?: number;\n /** Rewrites the card's own metadata in the same write that attaches the source. */\n cardMetadata?: (metadata: Record<string, unknown>) => Record<string, unknown>;\n }): Promise<{ item: Card; attached: boolean } | null> {\n let result: Awaited<ReturnType<Cards['attachSource']>>;\n try {\n result = await this.#withTransaction(async ops => {\n const cards = new Cards(ops, this.#legacyMode, undefined, this.#reviewInUse);\n const attached = await cards.attachSource(\n { org_id: orgId, id },\n { external_source: source, metadata, now: new Date() },\n expectedRevision,\n cardMetadata,\n );\n if (attached?.ownerWorkItemId) throw new WorkItemSourceConflictError(attached.ownerWorkItemId);\n if (attached?.revisionConflict) throw new WorkItemUpdateConflictError('revision');\n return attached;\n });\n } catch (error) {\n // A concurrent attach or upsert of the same record won the unique index.\n if (error instanceof UniqueViolationError && error.collection === FACTORY_WORK_ITEM_SOURCES_SCHEMA.name) {\n // Sources are unique per project, so another project's copy of the record is no owner here.\n const card = await new Cards(this.#db, this.#legacyMode, undefined, this.#reviewInUse).findOne({\n org_id: orgId,\n id,\n });\n const owner = card\n ? await this.#db.findOne<WorkItemSourceDbRecord>(FACTORY_WORK_ITEM_SOURCES_SCHEMA.name, {\n org_id: orgId,\n factory_project_id: card.factory_project_id,\n source_key: externalSourceKey(source),\n })\n : null;\n if (owner && card && owner.work_item_id === card.work_item?.id)\n return { item: toWorkItem(card), attached: false };\n throw new WorkItemSourceConflictError(owner?.work_item_id ?? 'unknown');\n }\n throw error;\n }\n return result ? { item: toWorkItem(result.row), attached: result.attached } : null;\n }\n\n /** Apply source facts and their process stamps in one transaction. */\n async syncCard(input: SyncCardInput): Promise<{ item: Card; previous: WorkItemPriorState } | null> {\n try {\n return await this.#withTransaction(ops => this.#syncCardIn(ops, input));\n } catch (error) {\n if (error instanceof CardRevisionMoved) throw new WorkItemUpdateConflictError('revision');\n throw error;\n }\n }\n\n /** `syncCard` inside a transaction; `expectedRevision` makes it throw `CardRevisionMoved` if the card moved on. */\n async #syncCardIn(\n ops: FactoryStorageOps,\n { orgId, id, userId, patch, expectedSourceRevision, fillOnly = false, expectedRevision }: SyncCardInput,\n ): Promise<{ item: Card; previous: WorkItemPriorState } | null> {\n let previous = emptyPrior();\n let stamped: Date | undefined;\n const row = await this.#cards(ops, { transaction: true }).updateAtomic({ org_id: orgId, id }, async current => {\n if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new CardRevisionMoved();\n previous = priorState(current);\n const item = toWorkItem(current);\n const source = primarySource(item);\n if (this.#legacyMode || !source) {\n const metadata = fillOnly\n ? Object.fromEntries(\n Object.entries(patch.metadata ?? {}).filter(([key]) => current.metadata?.[key] === undefined),\n )\n : patch.metadata;\n if (fillOnly && patch.title === undefined && Object.keys(metadata ?? {}).length === 0) return null;\n return applyUpdate({ current, userId, input: { ...patch, metadata } });\n }\n const adapter = workItemProviderAdapter(item.externalSource);\n const split = splitCardMetadata(patch.metadata, adapter.providerMetadataKeys);\n if (Object.keys(split.provider ?? {}).length > 0) {\n stamped = await this.#syncWorkItemSource(ops, {\n orgId,\n factoryProjectId: item.factoryProjectId,\n provider: source.provider,\n externalId: source.externalId,\n expectedRevision: expectedSourceRevision,\n patch: currentSource => {\n const providerPatch = fillOnly\n ? Object.fromEntries(\n Object.entries(split.provider ?? {}).filter(([key]) => currentSource.metadata?.[key] === undefined),\n )\n : split.provider;\n if (fillOnly && Object.keys(providerPatch ?? {}).length === 0) return null;\n const facts = adapter.toSource(item.externalSource, { ...currentSource.metadata, ...providerPatch });\n if (!facts) throw new Error('An external source must produce provider facts.');\n return {\n key: facts.key,\n url: facts.url,\n state: facts.state,\n labels: facts.labels,\n author: facts.author,\n metadata: facts.metadata,\n };\n },\n });\n }\n const boardPatch = Object.fromEntries(\n Object.entries(split.board ?? {}).filter(([key, value]) =>\n fillOnly\n ? item.metadata?.[key] === undefined\n : JSON.stringify(item.metadata?.[key]) !== JSON.stringify(value),\n ),\n );\n if (patch.title === undefined && Object.keys(boardPatch).length === 0) return null;\n return applyUpdate({\n current,\n userId,\n input: { ...(patch.title !== undefined ? { title: patch.title } : {}), metadata: boardPatch },\n });\n });\n if (!row) return null;\n const item = toWorkItem(row);\n // `row` was read before the source's sync stamped it; a write of the card itself stamps later.\n const changedAt = stamped && !(item.changedAt && item.changedAt > stamped) ? stamped : item.changedAt;\n return { item: { ...item, changedAt }, previous };\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.#withTransaction(ops => this.#cards(ops, { transaction: true }).deleteMany({}));\n await super.ops.deleteMany(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, {});\n // A project with no version row is never served from cache, so this invalidates every replica.\n await super.ops.deleteMany(FACTORY_BOARD_VERSIONS_SCHEMA.name, {});\n this.#listCache.clear();\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n protected override get ops(): FactoryStorageOps {\n const ops = super.ops;\n // Outside a transaction a resolved write has committed, so its wake can go out at once.\n const cards = trackBoardWrites(ops, CARD_TABLES, async scope => {\n await bumpBoardVersions(ops, [scope]);\n this.#announceBoard(scope);\n });\n return trackClaimableWrites(\n trackBoardWrites(cards, DECISION_TABLES, scope => this.#announceBoard(scope)),\n scope => this.#claimableWork(scope),\n );\n }\n\n /** Only legacy dry-run writes name no project, and no feed is keyed by org alone. */\n #announceBoard(scope: BoardScope): void {\n if (scope.factoryProjectId) this.#boardChanged({ orgId: scope.orgId, factoryProjectId: scope.factoryProjectId });\n }\n\n /** `storage.withTransaction`, bumping and announcing the board of every project it wrote once it commits. */\n async #withTransaction<T>(\n fn: (ops: FactoryStorageOps) => Promise<T>,\n options?: { isolationLevel?: 'serializable' },\n ): Promise<T> {\n const changed = new BoardScopes();\n const touched = new BoardScopes();\n const cardWritten = (scope: BoardScope) => {\n changed.add(scope);\n touched.add(scope);\n };\n let queued = new Map<string, FactoryClaimableWorkScope>();\n const run = () => {\n // A retried transaction starts over: wakes queued by the rolled-back attempt never committed.\n queued = new Map();\n return this.storage.withTransaction(\n ops =>\n fn(\n trackClaimableWrites(\n trackBoardWrites(trackBoardWrites(ops, CARD_TABLES, cardWritten), DECISION_TABLES, touched.add),\n scope => queued.set(`${scope.orgId}\\u0000${scope.factoryProjectId}`, scope),\n ),\n ),\n options,\n );\n };\n let result: T;\n try {\n result = await run();\n } catch (error) {\n // A first guard insert can race. Retry only after the failed transaction\n // rolls back; PostgreSQL cannot recover from a unique violation inside it.\n if (!(error instanceof UniqueViolationError) || error.collection !== FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name)\n throw error;\n result = await run();\n }\n try {\n await bumpBoardVersions(super.ops, changed.values());\n } finally {\n // Only after commit: a dispatcher woken earlier could miss the uncommitted row and go idle.\n for (const scope of queued.values()) this.#claimableWork(scope);\n }\n for (const scope of touched.values()) this.#announceBoard(scope);\n return result;\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 #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.#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 accept?: (row: GovernanceDbRow) => boolean,\n ): Promise<T[]> {\n const claim = () =>\n this.#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 where = { status: { in: ['pending', 'retry', 'leased'] } };\n const claimed: T[] = [];\n // A filtered claim widens its window past rows it rejects so matching\n // rows queued behind any size of filtered-out backlog stay reachable.\n // Unfiltered claims read one window: the first claimable rows are the\n // oldest. Ties on created_at keep the store's insertion order.\n let window = Math.max(input.limit * 5, 50);\n let scanned = 0;\n let exhausted = false;\n do {\n const page = await ops.findMany<GovernanceDbRow>(table, where, {\n orderBy: [['created_at', 'asc']],\n limit: window,\n });\n exhausted = !accept || page.length < window;\n const candidates = page.slice(scanned);\n scanned = page.length;\n window *= 4;\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 if (accept && !accept(candidate)) 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 // A new attempt starts clean: the previous attempt's cause no longer describes this one.\n ...(table === 'factory_deferred_decisions' ? { last_error: null, failure_code: null } : {}),\n updated_at: input.now,\n };\n });\n if (didClaim && row) claimed.push(map(row));\n }\n } while (!exhausted && claimed.length < input.limit);\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 status?: 'superseded',\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: status ?? (table === 'factory_pending_starts' ? 'sent' : 'succeeded'),\n lease_owner: null,\n lease_expires_at: null,\n ...(table === 'factory_deferred_decisions' ? { 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 ...(table === 'factory_deferred_decisions'\n ? {\n last_error: input.lastError,\n failure_code: input.failureCode,\n completed_at: input.terminal ? input.now : null,\n ...(input.terminal ? { failure_occurrence: Number(current.failure_occurrence ?? 0) + 1 } : {}),\n }\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<Card[]> {\n const rows = await this.#cards(ops, { transaction: true }).findMany(\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 /** The ids deleted after `from`. */\n #removedSince(scope: CollectionWhere, from: Date) {\n return super.ops.findMany<{ id: string }>(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, scope, {\n orderBy: [['deleted_at', 'asc']],\n cursor: { values: [from] },\n });\n }\n\n /**\n * `previous` updated with the cards changed or deleted since `since`. Reads from a few seconds\n * earlier so a writer whose clock runs behind this one is still caught.\n */\n async #listDelta(orgId: string, factoryProjectId: string, previous: readonly Card[], since: number): Promise<Card[]> {\n const from = new Date(since - LIST_DELTA_CLOCK_SKEW_MS);\n const scope = { org_id: orgId, factory_project_id: factoryProjectId };\n const [rows, tombstones] = await Promise.all([\n this.#cards(super.ops, { transaction: true }).findMany(scope, {\n orderBy: [['changed_at', 'asc']],\n cursor: { values: [from] },\n }),\n this.#removedSince(scope, from),\n ]);\n if (rows.length === 0 && tombstones.length === 0) return [...previous];\n const changed = new Map(rows.map(row => [row.id, toWorkItem(row)]));\n const deleted = new Set(tombstones.map(row => row.id));\n const items = previous.filter(item => !changed.has(item.id) && !deleted.has(item.id));\n for (const item of changed.values()) if (!deleted.has(item.id)) items.push(item);\n return items.sort(\n (a, b) =>\n new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime() || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0),\n );\n }\n\n /** The project's cards as {@link list} reads them, uncached, through `ops`: a transaction's, to read them in it. */\n async listWith(ops: FactoryStorageOps, { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }) {\n return this.#listWithOps(ops, orgId, factoryProjectId);\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<Card[]> {\n const { items, cached } = await this.#listCached(orgId, factoryProjectId);\n return cached ? structuredClone(items) : items;\n }\n\n /**\n * Same rows as {@link list}, but shared with the list cache instead of cloned: the board poll\n * reads every card of the project every few seconds, and cloning thousands of rows per poll\n * costs more than the query the cache saves. The cached cards are frozen, so a caller that\n * writes to one throws instead of changing the board every other caller sees.\n */\n async listShared({ orgId, factoryProjectId }: { orgId: string; factoryProjectId: string }): Promise<readonly Card[]> {\n return (await this.#listCached(orgId, factoryProjectId)).items;\n }\n\n /**\n * {@link listShared} for a reader that keeps the board between reads. `cursor` names this read.\n * Sent back as `since`, it adds what moved since that read: `changed`, the listed cards written\n * since, and `removed`, the ids no longer listed. Without them only the whole list answers: no\n * cursor or one this didn't issue, or a board showing Review cards, which move without a write.\n */\n async listSharedSince(scope: { orgId: string; factoryProjectId: string; since?: string }): Promise<{\n items: readonly Card[];\n cursor?: string;\n changed?: Card[];\n removed?: string[];\n }> {\n const { items, readFrom } = await this.#listCached(scope.orgId, scope.factoryProjectId);\n if (readFrom === undefined || items.some(card => card.board === LEGACY_REVIEW_BOARD)) return { items };\n const cursor = String(readFrom);\n if (scope.since === undefined) return { items, cursor };\n // The reader holds this very list.\n if (scope.since === cursor) return { items, cursor, changed: [], removed: [] };\n // Answered from `items`, the list `cursor` names, so the two agree: a write that list doesn't\n // hold yet is left for the read that sends `cursor` back.\n const from = new Date(Number(scope.since) - LIST_DELTA_CLOCK_SKEW_MS);\n const gone = await this.#removedSince({ org_id: scope.orgId, factory_project_id: scope.factoryProjectId }, from);\n const removed = new Set(gone.map(row => row.id));\n const changed = items.filter(card => {\n removed.delete(card.id);\n return card.changedAt && new Date(card.changedAt) > from;\n });\n return { items, cursor, changed, removed: [...removed] };\n }\n\n /**\n * `cached` is true when `items` is shared with other callers, which callers that mutate must clone.\n * `readFrom` is when the read that produced a cached `items` began.\n */\n async #listCached(\n orgId: string,\n factoryProjectId: string,\n ): Promise<{ items: Card[]; cached: boolean; readFrom?: number }> {\n const key = `${orgId}\\u0000${factoryProjectId}`;\n // Read the version before the rows: a write that lands in between bumps it again afterwards,\n // so the next call refetches instead of trusting a snapshot taken before that write.\n const version = await readBoardVersion(super.ops, orgId, factoryProjectId);\n const hit = this.#listCache.get(key);\n if (version && hit?.version === version && Date.now() - hit.takenAt < LIST_CACHE_TTL_MS) {\n return { items: hit.items, cached: true, readFrom: hit.readFrom };\n }\n if (!version) {\n const items = await this.#listWithOps(super.ops, orgId, factoryProjectId);\n this.#listCache.delete(key);\n return { items, cached: false };\n }\n const inFlight = this.#listInFlight.get(key);\n if (inFlight?.version === version && Date.now() - inFlight.startedAt < LIST_CACHE_TTL_MS) {\n return { items: await inFlight.items, cached: true, readFrom: inFlight.startedAt };\n }\n const startedAt = Date.now();\n // Within the TTL a version change only needs the cards changed since the last read; the TTL\n // still forces a full read as a backstop for anything a delta could miss. A board showing\n // Review cards is read whole: closing its last open one moves the others without writing them.\n const delta =\n hit && startedAt - hit.takenAt < LIST_CACHE_TTL_MS && !hit.items.some(card => card.board === LEGACY_REVIEW_BOARD);\n const read = (\n delta\n ? this.#listDelta(orgId, factoryProjectId, hit.items, hit.readFrom)\n : this.#listWithOps(super.ops, orgId, factoryProjectId)\n ).then(deepFreeze);\n this.#listInFlight.set(key, { version, startedAt, items: read });\n try {\n const items = await read;\n if (this.#listInFlight.get(key)?.items === read) {\n this.#listCache.delete(key);\n this.#listCache.set(key, {\n version,\n takenAt: delta ? hit.takenAt : Date.now(),\n readFrom: startedAt,\n items,\n });\n if (this.#listCache.size > LIST_CACHE_MAX_PROJECTS) {\n this.#listCache.delete(this.#listCache.keys().next().value!);\n }\n }\n return { items, cached: true, readFrom: startedAt };\n } finally {\n if (this.#listInFlight.get(key)?.items === read) this.#listInFlight.delete(key);\n }\n }\n\n /**\n * The cards linked to `item` in its project, its parent and its children, newest first as\n * {@link list} orders them. Read by id and by the parent index, so the cost does not grow with\n * the board.\n */\n async listLinked({ item, limit }: { item: Card; limit: number }): Promise<Card[]> {\n const cards = this.#cards(this.#db, { transaction: false });\n const scope = { org_id: item.orgId, factory_project_id: item.factoryProjectId };\n const [parent, children] = await Promise.all([\n item.parentWorkItemId ? cards.findOne({ ...scope, id: item.parentWorkItemId }) : null,\n cards.findMany(\n { ...scope, parent_work_item_id: item.id },\n {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n ),\n ]);\n return (parent ? [parent, ...children] : children)\n .map(toWorkItem)\n .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || (a.id < b.id ? 1 : -1))\n .slice(0, limit);\n }\n\n async listByIds({\n orgId,\n factoryProjectId,\n ids,\n }: {\n orgId: string;\n factoryProjectId: string;\n ids: string[];\n }): Promise<Card[]> {\n if (ids.length === 0) return [];\n const rows = await this.#cards(this.#db, { transaction: false }).findMany({\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<Pick<WorkItemDbRow, 'id' | 'sessions'> & Record<string, unknown>>(\n this.#legacyMode ? WORK_ITEMS_SCHEMA.name : FACTORY_BOARD_ITEMS_SCHEMA.name,\n { org_id: orgId },\n );\n if (this.#split.pending) {\n // An uncopied card holding the session would bring the reference back when copied; the\n // update below copies it first.\n const split = new Set(rows.map(row => row.id));\n const legacy = await this.#db.findMany<Pick<WorkItemDbRow, 'id' | 'sessions'> & Record<string, unknown>>(\n WORK_ITEMS_SCHEMA.name,\n { org_id: orgId },\n );\n rows.push(...legacy.filter(row => !split.has(row.id)));\n }\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.#withTransaction(ops =>\n this.#cards(ops, { transaction: true }).updateAtomic({ 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 );\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<Card | null> {\n const row = await this.#cards(this.#db, { transaction: false }).findOne({\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<Card | null> {\n const row = await this.#cards(this.#db, { transaction: false }).findOne({ 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<Card | null> {\n const rows = await this.#cards(this.#db, { transaction: false }).findMany({\n source_key: externalSourceKey(source),\n });\n return rows.length === 1 ? toWorkItem(rows[0]!) : null;\n }\n\n /**\n * Every card in the org that was linked from one external source, across\n * Factory projects. Source keys are unique per project, not per org, so an\n * issue whose routing moved between projects can own one card in each; intake\n * consults this before creating another.\n */\n async listBySource({ orgId, source }: { orgId: string; source: ExternalWorkItemSource }): Promise<Card[]> {\n const rows = await this.#cards(this.#db, { transaction: false }).findMany({\n org_id: orgId,\n source_key: externalSourceKey(source),\n });\n return rows.map(toWorkItem);\n }\n\n async getForProject(orgId: string, factoryProjectId: string, id: string): Promise<Card | null> {\n const row = await this.#cards(this.#db, { transaction: false }).findOne({\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 listRecordedIngress(\n orgId: string,\n factoryProjectId: string,\n identities: readonly string[],\n ): Promise<Set<string>> {\n if (identities.length === 0) return new Set();\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_rule_ingress', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n identity: { in: [...new Set(identities)] },\n });\n return new Set(rows.map(row => String(row.identity)));\n }\n\n async commitTransition(input: CommitFactoryTransitionInput): Promise<CommitFactoryTransitionResult> {\n const commit = (): Promise<CommitFactoryTransitionResult> =>\n this.#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 // Read through the transaction: on a single-connection database the\n // root client waits for this transaction, which would never finish.\n const row = await this.#cards(ops, { transaction: true }).findOne({\n id: input.workItemId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n return { status: 'replayed', item: row ? toRow(row) : null, result: prior.result as Record<string, unknown> };\n }\n\n const now = new Date();\n let item: Card | null = null;\n let code: string | null = null;\n let reason: string | null = null;\n let result: Record<string, unknown>;\n const updated = await this.#cards(ops, { transaction: true }).updateAtomic(\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 const changesBoard = input.destinationBoard !== undefined && input.destinationBoard !== existing.board;\n if (!changesBoard && 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 ...(changesBoard ? { board: input.destinationBoard } : {}),\n stages: [input.destinationStage],\n // On another board, a phase of the same name is a new one: leave every phase, then enter it.\n stageHistory: changesBoard\n ? applyStageTransition(\n applyStageTransition(existing.stageHistory, existing.stages, [], input.actorId, now),\n [],\n [input.destinationStage],\n input.actorId,\n now,\n )\n : 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 // A stale revision only lost a race with another write; recording it\n // under this identity would replay the loss to every retry, so a\n // re-read at the current revision could never commit the transition.\n if (code === 'stale') return { status: 'committed', item, result };\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 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 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 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.#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 !isWorkItemSource((decision as Record<string, unknown>).source) ||\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> & {\n source: WorkItemSource;\n sourceKey: string;\n idempotencyKey: string;\n };\n const item = await this.#cards(ops, { transaction: true }).findOne({\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: externalSourceKey(\n externalSourceForWorkItem(materialization.source, materialization.sourceKey),\n ),\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 this.#cards(ops, { transaction: true }).findOne({\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 // A lost revision race is not a verdict on the event: persisting it would\n // make every redelivery replay an empty result, so record nothing.\n if (item !== null && item.revision !== input.expectedRevision) return { status: 'stale' as const };\n if (item !== null && input.cardMetadata && input.expectedRevision !== null) {\n await this.#syncCardIn(ops, {\n orgId: input.orgId,\n id: item.id,\n userId: input.cardMetadata.userId,\n patch: { metadata: input.cardMetadata.metadata },\n expectedRevision: input.expectedRevision,\n });\n }\n const outcome = input.outcome.status;\n const code = input.outcome.code ?? null;\n const reason = 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 result,\n created_at: input.now,\n });\n const evaluation = await ops.insertOne<GovernanceDbRow>('factory_rule_evaluations', {\n ingress_id: ingress.id,\n created_at: input.now,\n });\n for (const [effectOrdinal, decision] of decisions.entries()) {\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 ?? null,\n source_key: decisionSourceKey(decision),\n idempotency_key: String(decision.idempotencyKey),\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 approved_at: approvedBy ? input.now : null,\n approved_by: approvedBy,\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 const attempt = async (): Promise<CommitFactoryRuleEvaluationResult> => {\n try {\n return await commit();\n } catch (error) {\n // Another write moved the card between the revision check and the locked card write.\n if (error instanceof CardRevisionMoved) return { status: 'stale' };\n throw error;\n }\n };\n try {\n return await attempt();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n return attempt();\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 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_created_at: cursor.lastMessageCreatedAt,\n updated_at: cursor.updatedAt,\n });\n }\n\n async listDeferredDecisions(\n orgId: string,\n factoryProjectId: string,\n /** `newest`: only that many of the most recent, still oldest first. */\n filter: { statuses?: readonly string[]; workItemId?: string; newest?: number } = {},\n ): Promise<FactoryDeferredDecisionRecord[]> {\n const rows = await this.#db.findMany<GovernanceDbRow>(\n 'factory_deferred_decisions',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n ...(filter.statuses ? { status: { in: [...filter.statuses] } } : {}),\n ...(filter.workItemId ? { work_item_id: filter.workItemId } : {}),\n },\n filter.newest === undefined\n ? { orderBy: [['created_at', 'asc']] }\n : {\n orderBy: [\n ['created_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: filter.newest,\n },\n );\n return (filter.newest === undefined ? rows : rows.toReversed()).map(toDeferredDecision);\n }\n\n async listDecisionsForEvaluations(\n orgId: string,\n factoryProjectId: string,\n evaluationIds: string[],\n ): Promise<FactoryDeferredDecisionRecord[]> {\n if (evaluationIds.length === 0) return [];\n return (\n await this.#db.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n evaluation_id: { in: [...new Set(evaluationIds)] },\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.#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 return true;\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.#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: FactoryDeferredDecisionClaimInput): Promise<FactoryDeferredDecisionRecord[]> {\n const filter = input.decisionFilter;\n const accept = filter\n ? (row: GovernanceDbRow) =>\n filter(decisionRowPayload(row.decision), {\n actor:\n jsonRowValue(\n row.actor,\n (value): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n ) ?? null,\n causalChain:\n jsonRowValue(row.causal_chain, (value): value is FactoryDecisionProvenance['causalChain'] =>\n Array.isArray(value),\n ) ?? [],\n })\n : undefined;\n return this.#claimLeases('factory_deferred_decisions', input, toDeferredDecision, accept);\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 /** Settle a leased decision whose card moved on before it could act: nothing ran, and nothing needs a person. */\n async supersedeLeasedDecision(\n identity: FactoryLeaseIdentity,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n const row = await this.#completeLease('factory_deferred_decisions', identity, now, 'superseded');\n return row ? toDeferredDecision(row) : null;\n }\n\n /**\n * Hand a leased decision back untouched until `availableAt`: it could not act yet and did\n * nothing, so the claim is not an attempt and leaves no error behind.\n */\n async postponeDeferredDecision(\n identity: FactoryLeaseIdentity,\n availableAt: Date,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n let postponed = 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 postponed = true;\n return {\n status: 'pending',\n attempts: Math.max(0, Number(current.attempts) - 1),\n available_at: availableAt,\n lease_owner: null,\n lease_expires_at: null,\n updated_at: now,\n };\n },\n );\n return postponed && 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 return row ? toDeferredDecision(row) : null;\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 return proposed && row ? toDeferredDecision(row) : null;\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 return this.#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 this.#cards(ops, { transaction: true }).updateAtomic({ org_id: orgId, id: record.workItemId }, current =>\n current.autonomy_armed_at ? null : { autonomy_armed_at: now },\n );\n }\n return record;\n });\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 /** Idempotency keys of decisions to keep: what a move just queued for the card. */\n except?: readonly 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 if (input.except?.includes(decision.idempotencyKey)) 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.#supersedeFailedDecision({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n decisionId: decision.id,\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 return this.#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 }\n\n async #supersedeFailedDecision({\n orgId,\n factoryProjectId,\n decisionId,\n now,\n }: {\n orgId: string;\n factoryProjectId: string;\n decisionId: string;\n now: Date;\n }): Promise<FactoryDeferredDecisionRecord | null> {\n return this.#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: 'superseded', 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 }\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 /**\n * Factory used to hold a triaged non-bug in Triage until a person accepted it.\n * Triage now sends those cards back to Intake instead, so move the ones still\n * held there, once. A card with a live run, or one that changed under us, is\n * left alone. Returns the cards moved; a second run finds none.\n */\n async returnHeldTriageCards(): Promise<Card[]> {\n // A one-time migration of rows written when Work was the only board, so it reads Work's phase\n // keys (`triage`, `intake`) by name. Cards filed before boards were recorded carry no board;\n // outside pull requests they are Work cards.\n const held = (\n await this.#cards(this.#db, { transaction: false }).findMany({\n board: { in: [LEGACY_WORK_BOARD, null] },\n triage_type: { in: FACTORY_TRIAGE_TYPES.filter(type => type !== 'bug') },\n accepted_at: null,\n })\n )\n .map(toWorkItem)\n .filter(\n item =>\n item.stages.length === 1 &&\n item.stages[0] === LEGACY_TRIAGE_PHASE &&\n (item.board === LEGACY_WORK_BOARD || item.externalSource?.type !== 'pull-request'),\n );\n if (held.length === 0) return [];\n // A binding stays active after its run ends until the stale-binding sweep, so the triage\n // run that classified the card is still bound. Only a run started since the card last\n // changed can still be working on it.\n const startedAt = new Map<string, number>();\n for (const row of await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', {\n status: 'active',\n work_item_id: { in: held.map(item => item.id) },\n })) {\n const key = `${row.org_id}:${row.work_item_id}`;\n startedAt.set(key, Math.max(startedAt.get(key) ?? 0, new Date(row.created_at as string | Date).getTime()));\n }\n const moved: Card[] = [];\n for (const item of held) {\n if ((startedAt.get(`${item.orgId}:${item.id}`) ?? 0) >= item.updatedAt.getTime()) continue;\n // A governed transition leaves an audit row and disarms autonomy so the card\n // waits for a person; the identity makes a second replica's move a replay.\n const identity = `${HELD_CARD_SWEEP_ACTOR}:${item.id}:${item.revision}`;\n const committed = await this.commitTransition({\n orgId: item.orgId,\n factoryProjectId: item.factoryProjectId,\n workItemId: item.id,\n expectedRevision: item.revision,\n destinationStage: LEGACY_REST_PHASE,\n actorId: HELD_CARD_SWEEP_ACTOR,\n ingress: { identity, transitionId: identity },\n causalChain: [],\n evaluation: { outcome: 'accepted', decisions: [] },\n autonomy: 'disarm',\n });\n if (committed.status === 'committed' && committed.result.status === 'accepted' && committed.item) {\n moved.push(committed.item);\n }\n }\n return moved;\n }\n\n /** Requeue the same idempotent terminal effect; non-failed or non-retryable decisions are never rerun. */\n async retryDeferredDecision(\n orgId: string,\n factoryProjectId: string,\n decisionId: string,\n now: Date,\n ): Promise<FactoryDeferredDecisionRecord | null> {\n return this.#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 const failureCode = isStoredFactoryDispatchFailureCode(current.failure_code) ? current.failure_code : null;\n if (!factoryDispatchFailureMetadata(failureCode).canRetry) 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 }\n\n /** The binding an `agent:<bindingId>` actor names, active or revoked. Identifies; never authorizes. */\n async findRunBindingById(input: {\n orgId: string;\n factoryProjectId: string;\n id: string;\n }): Promise<FactoryRunBindingRecord | null> {\n // Actor ids are free text and the id column is a uuid on Postgres.\n if (!/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(input.id)) return null;\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: input.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n return row ? toBinding(row) : null;\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 rejectAmbiguous?: boolean;\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 const projectCount = new Set(rows.map(row => row.factory_project_id)).size;\n if (projectCount > 1 && input.rejectAmbiguous)\n throw new Error('Factory session has ambiguous active run bindings.');\n if (projectCount !== 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 /** Historical thread membership for model/billing policy only; never grants active agent authority. */\n async findRunBindingByThread(input: {\n orgId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n rejectAmbiguous?: boolean;\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 });\n const projectCount = new Set(rows.map(row => row.factory_project_id)).size;\n if (projectCount > 1 && input.rejectAmbiguous) throw new Error('Factory session has ambiguous run bindings.');\n if (projectCount !== 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 /**\n * The active binding a Factory session is serving, keyed by the session\n * alone so it resolves before the session has a live thread (e.g. when the\n * dispatcher builds the workspace for a kickoff). Ambiguous matches never\n * authorize.\n */\n async findActiveRunBindingForSession(input: {\n orgId: string;\n factoryProjectId: 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 factory_project_id: input.factoryProjectId,\n session_id: input.sessionId,\n status: 'active',\n });\n if (rows.length !== 1) return null;\n return toBinding(rows[0]!);\n }\n\n /** Whether this session was ever bound to a run, on any thread and whether or not the binding was revoked. */\n async hasRunBindingForSession(input: {\n orgId: string;\n factoryProjectId: string;\n sessionId: string;\n }): Promise<boolean> {\n const row = await this.#db.findOne<GovernanceDbRow>('factory_run_bindings', {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n session_id: input.sessionId,\n });\n return 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` (unless\n * `keep` vouches for them), or whose work item is gone, malformed, or\n * already terminal. Terminal-stage cleanup handles bindings go-forward; this\n * sweep drains anything that slipped past 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, Card | null>();\n let revoked = 0;\n for (const binding of bindings) {\n let stale = binding.createdAt.getTime() < input.olderThan.getTime() && !(await input.keep?.(binding));\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 /**\n * The work items a session was ever bound to run, revoked bindings included.\n * `null` stands for a bound item that no longer loads. Empty when the session\n * never ran a work item.\n */\n async listRunBoundItems(sessionId: string): Promise<(Card | null)[]> {\n const rows = await this.#db.findMany<GovernanceDbRow>('factory_run_bindings', { session_id: sessionId });\n const keys = new Map(rows.map(row => [`${row.org_id}:${row.work_item_id}`, row]));\n return Promise.all(\n [...keys.values()].map(row => this.get({ orgId: String(row.org_id), id: String(row.work_item_id) })),\n );\n }\n\n /**\n * Move a session's bindings from the legacy `resourceId = sessionId` onto\n * `resourceId`. Only rows still on the session id change, so a rerun is a no-op.\n */\n async moveRunBindingsToResource(input: { sessionId: string; resourceId: string }): Promise<number> {\n return this.#db.updateMany(\n 'factory_run_bindings',\n { session_id: input.sessionId, resource_id: input.sessionId },\n { resource_id: input.resourceId },\n );\n }\n\n /** List binding history, optionally narrowed to one or some work items. */\n async listRunBindings(\n orgId: string,\n factoryProjectId: string,\n workItemId?: string | string[],\n ): Promise<FactoryRunBindingRecord[]> {\n if (Array.isArray(workItemId) && workItemId.length === 0) return [];\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: Array.isArray(workItemId) ? { in: workItemId } : 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.#withTransaction(async ops => {\n if (input.expectedBindingId) {\n const workItemId = input.workItem.id;\n if (!workItemId) throw new FactoryRunBindingSupersededError();\n const expected = await ops.findOne<GovernanceDbRow>('factory_run_bindings', {\n id: input.expectedBindingId,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: workItemId,\n role: input.role,\n status: 'active',\n });\n if (!expected) throw new FactoryRunBindingSupersededError();\n }\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 this.#cards(ops, { transaction: true }).findOne({\n id: String(bindingRow.work_item_id),\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n }));\n // Replay only a still-live binding. A prior pending row whose binding\n // was revoked (abort → stage re-entry) or whose state is gone is a\n // dead-run artifact: discard it and mint a fresh binding below. The\n // unique kickoff_key index requires removing the stale row before\n // re-inserting.\n if (bindingRow && itemRow && bindingRow.status === 'active') {\n return {\n item: toRow(itemRow),\n binding: toBinding(bindingRow),\n pendingStart: toPendingStart(prior),\n replayed: true,\n };\n }\n await ops.deleteMany('factory_pending_starts', {\n id: prior.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n });\n }\n const now = new Date();\n const create = input.workItem.input;\n let row = input.workItem.id\n ? await this.#cards(ops, { transaction: true }).findOne({\n id: input.workItem.id,\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n : externalSourceKey(create.externalSource)\n ? await this.#cards(ops, { transaction: true }).findOne({\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: externalSourceKey(create.externalSource),\n })\n : null;\n let item: Card;\n if (row) {\n row = await this.#cards(ops, { transaction: true }).updateAtomic({ 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 // The binding below shares this clock, so a run started on an existing card\n // is never older than the card's last change.\n return applyUpdate({\n current,\n userId: input.userId,\n input: { sessions: { [input.role]: input.session } },\n now,\n });\n });\n item = toRow(row!);\n } else {\n if (create.parentWorkItemId) await this.#copyLegacyParent(ops, input.orgId, create.parentWorkItemId);\n if (create.parentWorkItemId)\n validateParentRelation(\n (\n await this.#cards(ops, { transaction: true }).findMany({\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n })\n ).map(toRow),\n undefined,\n create.parentWorkItemId,\n );\n row = await this.#cards(ops, { transaction: true }).insertOne({\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 description: create.description ?? null,\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 // A role continuing in an earlier role's session (e.g. build after plan)\n // may open a new thread; the earlier role's agent must stop acting.\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 session_id: input.session.sessionId,\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 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(bindingId: string, status: 'sent' | 'failed'): Promise<FactoryPendingStartRecord | null> {\n const row = await this.#db.updateAtomic<GovernanceDbRow>(\n 'factory_pending_starts',\n { binding_id: bindingId },\n () => ({ status, 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 : this.#withTransaction(run);\n try {\n return await execute();\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n // Another writer filed the same source key first; the retry reuses its card.\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 this.#cards(ops, { transaction: true }).findOne({\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: key,\n });\n if (!existing) return null;\n if (reuseMode === 'preserve') {\n return { created: false, item: toWorkItem(existing), previous: priorState(existing) };\n }\n\n let previous = emptyPrior();\n const updated = await this.#cards(ops, { transaction: true }).updateAtomic(\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 description: input.description,\n parentWorkItemId: input.parentWorkItemId ?? undefined,\n metadata: input.metadata,\n }\n : fullPatch;\n if (patch.parentWorkItemId !== undefined) {\n await this.#copyLegacyParent(ops, orgId, patch.parentWorkItemId);\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 // The card is handed to this second caller, so a concurrent creator's guarded rollback\n // must see the reuse; pending rules keep their revision.\n { touch: reuseMode === 'non-stage' },\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 // Legacy writers omit stages; they only ever filed onto the default board's resting phase.\n const stages = input.stages ?? [LEGACY_REST_PHASE];\n if (input.parentWorkItemId != null) {\n await this.#copyLegacyParent(ops, orgId, input.parentWorkItemId);\n validateParentRelation(await this.#listWithOps(ops, orgId, factoryProjectId), undefined, input.parentWorkItemId);\n }\n const row = await this.#cards(ops, { transaction: true }).insertOne({\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 description: input.description ?? null,\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<Card | null> {\n const candidate = await this.#cards(this.#db, { transaction: false }).findOne({ 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 this.#cards(ops, { transaction: true }).updateAtomic({ org_id: orgId, id }, async current => {\n if (current.parent_work_item_id !== null) return current;\n await this.#copyLegacyParent(ops, orgId, parentWorkItemId);\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 check,\n }: {\n orgId: string;\n id: string;\n userId: string;\n patch: UpdateWorkItemInput;\n expectedRevision?: number;\n expectedBoard?: string | null;\n /**\n * Runs on the card as locked for the write, sources included; throw to refuse it. Source syncs\n * lock the card first, so what it reads can't change before the write lands.\n */\n check?: (item: Card) => void;\n }): Promise<{ item: Card; previous: WorkItemPriorState } | null> {\n const run = async (ops: FactoryStorageOps) => {\n let previous = emptyPrior();\n const row = await this.#cards(ops, { transaction: true }).updateAtomic({ 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 check?.(toWorkItem(current));\n if (patch.parentWorkItemId !== undefined) {\n await this.#copyLegacyParent(ops, orgId, patch.parentWorkItemId);\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 this.#withTransaction(run);\n const candidate = await this.#cards(this.#db, { transaction: false }).findOne({ 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, sourceKeys }: { orgId: string; factoryProjectId: string; sourceKeys: string[] },\n ): Promise<void> {\n const keys = [...new Set(sourceKeys)];\n const decisions = await ops.findMany<GovernanceDbRow>('factory_deferred_decisions', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n source_key: { in: keys },\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: { in: keys },\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 * Make a session follow a work item. Idempotent: following again keeps the\n * first subscription, including its reason (filing beats a later subscribe).\n */\n async subscribeToWorkItem(input: SubscribeToWorkItemInput): Promise<WorkItemSubscription> {\n // Subscriptions never change the board, so they skip the board-version bump.\n const ops = super.ops;\n const where = { work_item_id: input.workItemId, session_id: input.sessionId };\n const existing = await ops.findOne<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, where);\n if (existing) return toWorkItemSubscription(existing);\n try {\n const row = await ops.insertOne<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n session_id: input.sessionId,\n thread_id: input.threadId,\n resource_id: input.resourceId,\n user_id: input.userId,\n reason: input.reason,\n created_at: new Date(),\n });\n return toWorkItemSubscription(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const raced = await ops.findOne<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, where);\n if (!raced) throw error;\n return toWorkItemSubscription(raced);\n }\n }\n\n /** Stop a session following a work item. Returns whether it was following. */\n async unsubscribeFromWorkItem({\n orgId,\n workItemId,\n sessionId,\n }: {\n orgId: string;\n workItemId: string;\n sessionId: string;\n }): Promise<boolean> {\n const deleted = await super.ops.deleteMany(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, {\n org_id: orgId,\n work_item_id: workItemId,\n session_id: sessionId,\n });\n return deleted > 0;\n }\n\n /** The sessions following a work item, earliest first. */\n async listWorkItemSubscribers({\n orgId,\n workItemId,\n }: {\n orgId: string;\n workItemId: string;\n }): Promise<WorkItemSubscription[]> {\n const rows = await super.ops.findMany<WorkItemSubscriptionDbRow>(\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name,\n { org_id: orgId, work_item_id: workItemId },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n },\n );\n return rows.map(toWorkItemSubscription);\n }\n\n /** Every follow link in a Factory, earliest first: which session follows which work item. */\n async listProjectSubscriptions({\n orgId,\n factoryProjectId,\n }: {\n orgId: string;\n factoryProjectId: string;\n }): Promise<readonly WorkItemSubscription[]> {\n const ops = super.ops;\n const where = { org_id: orgId, factory_project_id: factoryProjectId };\n return this.#projectSubscriptions.read(\n `${orgId}\\u0000${factoryProjectId}`,\n () => probeNewest(ops, FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, where, 'created_at'),\n async () =>\n (\n await ops.findMany<WorkItemSubscriptionDbRow>(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, where, {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n })\n ).map(toWorkItemSubscription),\n );\n }\n\n /** The work items one session follows in a Factory, earliest first. */\n async listSessionSubscriptions({\n orgId,\n factoryProjectId,\n sessionId,\n }: {\n orgId: string;\n factoryProjectId: string;\n sessionId: string;\n }): Promise<WorkItemSubscription[]> {\n const rows = await super.ops.findMany<WorkItemSubscriptionDbRow>(\n FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name,\n { org_id: orgId, factory_project_id: factoryProjectId, session_id: sessionId },\n {\n orderBy: [\n ['created_at', 'asc'],\n ['id', 'asc'],\n ],\n },\n );\n return rows.map(toWorkItemSubscription);\n }\n\n async delete({\n orgId,\n id,\n purgeRuleState = true,\n expectedRevision,\n expectedUpdatedAt,\n }: {\n orgId: string;\n id: string;\n purgeRuleState?: boolean;\n /** Deletes only while the card is still at this revision; returns `null` and keeps it otherwise. */\n expectedRevision?: number;\n /** Likewise for the card's `updatedAt`, which a reuse of a sourced card moves without a new revision. */\n expectedUpdatedAt?: Date;\n }): Promise<Card | null> {\n const where = {\n org_id: orgId,\n id,\n ...(expectedRevision === undefined ? {} : { revision: expectedRevision }),\n ...(expectedUpdatedAt === undefined ? {} : { updated_at: expectedUpdatedAt }),\n };\n const candidate = await this.#cards(this.#db, { transaction: false }).findOne(where);\n if (!candidate) return null;\n\n return this.#withProjectRelationTransaction(orgId, candidate.factory_project_id, async ops => {\n const existing = await this.#cards(ops, { transaction: true }).findOne(where);\n if (!existing) return null;\n const deleted = await this.#cards(ops, { transaction: true }).deleteMany(where);\n if (deleted === 0) return null;\n await ops.deleteMany(FACTORY_WORK_ITEM_SUBSCRIPTIONS_SCHEMA.name, { org_id: orgId, work_item_id: id });\n if (purgeRuleState && existing.external_source?.externalId) {\n await this.#purgeRuleState(ops, {\n orgId,\n factoryProjectId: existing.factory_project_id,\n sourceKeys: [existing.external_source.externalId],\n });\n }\n await this.#cards(ops, { transaction: true }).updateMany(\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 }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,SAAS,WAAc,OAAa;CAClC,IAAI,SAAS,OAAO,UAAU,YAAY,CAAC,OAAO,SAA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