@mastra/factory 0.28.0-alpha.9 → 0.29.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/README.md +67 -46
  2. package/dist/boards/board-writes.d.ts +3 -3
  3. package/dist/boards/board-writes.d.ts.map +1 -1
  4. package/dist/boards/board-writes.js +24 -20
  5. package/dist/boards/board-writes.js.map +1 -1
  6. package/dist/boards/project-boards.d.ts +20 -0
  7. package/dist/boards/project-boards.d.ts.map +1 -1
  8. package/dist/boards/project-boards.js +35 -11
  9. package/dist/boards/project-boards.js.map +1 -1
  10. package/dist/boards/registry.d.ts.map +1 -1
  11. package/dist/boards/registry.js +0 -3
  12. package/dist/boards/registry.js.map +1 -1
  13. package/dist/boards/reroute.d.ts +31 -0
  14. package/dist/boards/reroute.d.ts.map +1 -0
  15. package/dist/boards/reroute.js +71 -0
  16. package/dist/boards/reroute.js.map +1 -0
  17. package/dist/capabilities/version-control.d.ts +6 -1
  18. package/dist/capabilities/version-control.d.ts.map +1 -1
  19. package/dist/environment/build-runner.d.ts +13 -2
  20. package/dist/environment/build-runner.d.ts.map +1 -1
  21. package/dist/environment/build-runner.js +42 -0
  22. package/dist/environment/build-runner.js.map +1 -1
  23. package/dist/environment/build-schedule.js +1 -1
  24. package/dist/environment/build-schedule.js.map +1 -1
  25. package/dist/environment/build-workflow.d.ts +6 -4
  26. package/dist/environment/build-workflow.d.ts.map +1 -1
  27. package/dist/environment/build-workflow.js +70 -66
  28. package/dist/environment/build-workflow.js.map +1 -1
  29. package/dist/environment/build.d.ts +22 -7
  30. package/dist/environment/build.d.ts.map +1 -1
  31. package/dist/environment/build.js +73 -15
  32. package/dist/environment/build.js.map +1 -1
  33. package/dist/environment/heads.d.ts +1 -1
  34. package/dist/environment/heads.d.ts.map +1 -1
  35. package/dist/environment/heads.js +4 -1
  36. package/dist/environment/heads.js.map +1 -1
  37. package/dist/environment/repository-access.d.ts +15 -0
  38. package/dist/environment/repository-access.d.ts.map +1 -0
  39. package/dist/environment/repository-access.js +60 -0
  40. package/dist/environment/repository-access.js.map +1 -0
  41. package/dist/factory.d.ts +5 -2
  42. package/dist/factory.d.ts.map +1 -1
  43. package/dist/factory.js +40 -30
  44. package/dist/factory.js.map +1 -1
  45. package/dist/integrations/base.d.ts +8 -0
  46. package/dist/integrations/base.d.ts.map +1 -1
  47. package/dist/integrations/dependabot/default-rules.d.ts +38 -0
  48. package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
  49. package/dist/integrations/dependabot/default-rules.js +63 -0
  50. package/dist/integrations/dependabot/default-rules.js.map +1 -0
  51. package/dist/integrations/dependabot/rules.d.ts +42 -0
  52. package/dist/integrations/dependabot/rules.d.ts.map +1 -0
  53. package/dist/integrations/dependabot/rules.js +187 -0
  54. package/dist/integrations/dependabot/rules.js.map +1 -0
  55. package/dist/integrations/dependabot/sync.d.ts +76 -0
  56. package/dist/integrations/dependabot/sync.d.ts.map +1 -0
  57. package/dist/integrations/dependabot/sync.js +111 -0
  58. package/dist/integrations/dependabot/sync.js.map +1 -0
  59. package/dist/integrations/github/routes.d.ts.map +1 -1
  60. package/dist/integrations/github/routes.js +7 -2
  61. package/dist/integrations/github/routes.js.map +1 -1
  62. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  63. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  64. package/dist/integrations/github/sandbox-release.js +16 -1
  65. package/dist/integrations/github/sandbox-release.js.map +1 -1
  66. package/dist/integrations/github/sandbox.d.ts +12 -0
  67. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  68. package/dist/integrations/github/sandbox.js +22 -1
  69. package/dist/integrations/github/sandbox.js.map +1 -1
  70. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  71. package/dist/integrations/platform/connect/routes.js +4 -0
  72. package/dist/integrations/platform/connect/routes.js.map +1 -1
  73. package/dist/integrations/platform/github/event-worker.d.ts +5 -0
  74. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  75. package/dist/integrations/platform/github/event-worker.js +33 -2
  76. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  77. package/dist/integrations/platform/github/integration.d.ts +19 -1
  78. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  79. package/dist/integrations/platform/github/integration.js +183 -105
  80. package/dist/integrations/platform/github/integration.js.map +1 -1
  81. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  82. package/dist/integrations/platform/jira/integration.js +5 -1
  83. package/dist/integrations/platform/jira/integration.js.map +1 -1
  84. package/dist/integrations/platform/vanta/integration.d.ts +33 -0
  85. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
  86. package/dist/integrations/platform/vanta/integration.js +133 -0
  87. package/dist/integrations/platform/vanta/integration.js.map +1 -0
  88. package/dist/integrations/slack/integration.d.ts.map +1 -1
  89. package/dist/integrations/slack/integration.js +7 -4
  90. package/dist/integrations/slack/integration.js.map +1 -1
  91. package/dist/integrations/vanta/default-rules.d.ts +34 -0
  92. package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
  93. package/dist/integrations/vanta/default-rules.js +61 -0
  94. package/dist/integrations/vanta/default-rules.js.map +1 -0
  95. package/dist/integrations/vanta/rules.d.ts +40 -0
  96. package/dist/integrations/vanta/rules.d.ts.map +1 -0
  97. package/dist/integrations/vanta/rules.js +208 -0
  98. package/dist/integrations/vanta/rules.js.map +1 -0
  99. package/dist/integrations/vanta/sync.d.ts +36 -0
  100. package/dist/integrations/vanta/sync.d.ts.map +1 -0
  101. package/dist/integrations/vanta/sync.js +73 -0
  102. package/dist/integrations/vanta/sync.js.map +1 -0
  103. package/dist/mcp/routes.d.ts.map +1 -1
  104. package/dist/mcp/routes.js +3 -5
  105. package/dist/mcp/routes.js.map +1 -1
  106. package/dist/routes/board-snapshot.d.ts +24 -1
  107. package/dist/routes/board-snapshot.d.ts.map +1 -1
  108. package/dist/routes/board-snapshot.js +75 -7
  109. package/dist/routes/board-snapshot.js.map +1 -1
  110. package/dist/routes/boards.d.ts +2 -3
  111. package/dist/routes/boards.d.ts.map +1 -1
  112. package/dist/routes/boards.js.map +1 -1
  113. package/dist/routes/contracts.d.ts +307 -0
  114. package/dist/routes/contracts.d.ts.map +1 -1
  115. package/dist/routes/contracts.js +253 -9
  116. package/dist/routes/contracts.js.map +1 -1
  117. package/dist/routes/intake-routes.d.ts +3 -0
  118. package/dist/routes/intake-routes.d.ts.map +1 -1
  119. package/dist/routes/intake-routes.js +44 -0
  120. package/dist/routes/intake-routes.js.map +1 -1
  121. package/dist/routes/knowledge.d.ts.map +1 -1
  122. package/dist/routes/knowledge.js +3 -2
  123. package/dist/routes/knowledge.js.map +1 -1
  124. package/dist/routes/projects.d.ts.map +1 -1
  125. package/dist/routes/projects.js +5 -0
  126. package/dist/routes/projects.js.map +1 -1
  127. package/dist/routes/sandbox-envs.d.ts +2 -0
  128. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  129. package/dist/routes/sandbox-envs.js +3 -0
  130. package/dist/routes/sandbox-envs.js.map +1 -1
  131. package/dist/routes/source-control-sessions.d.ts +1 -1
  132. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  133. package/dist/routes/source-control-sessions.js +109 -3
  134. package/dist/routes/source-control-sessions.js.map +1 -1
  135. package/dist/routes/source-control-settings.d.ts +2 -0
  136. package/dist/routes/source-control-settings.d.ts.map +1 -1
  137. package/dist/routes/source-control-settings.js +5 -0
  138. package/dist/routes/source-control-settings.js.map +1 -1
  139. package/dist/routes/surface.d.ts +8 -1
  140. package/dist/routes/surface.d.ts.map +1 -1
  141. package/dist/routes/surface.js +74 -10
  142. package/dist/routes/surface.js.map +1 -1
  143. package/dist/routes/work-item-activity.d.ts +11 -0
  144. package/dist/routes/work-item-activity.d.ts.map +1 -0
  145. package/dist/routes/work-item-activity.js +25 -0
  146. package/dist/routes/work-item-activity.js.map +1 -0
  147. package/dist/routes/work-item-selection.d.ts +14 -0
  148. package/dist/routes/work-item-selection.d.ts.map +1 -0
  149. package/dist/routes/work-item-selection.js +44 -0
  150. package/dist/routes/work-item-selection.js.map +1 -0
  151. package/dist/routes/work-item-starters.d.ts +29 -0
  152. package/dist/routes/work-item-starters.d.ts.map +1 -0
  153. package/dist/routes/work-item-starters.js +152 -0
  154. package/dist/routes/work-item-starters.js.map +1 -0
  155. package/dist/routes/work-items.d.ts.map +1 -1
  156. package/dist/routes/work-items.js +239 -16
  157. package/dist/routes/work-items.js.map +1 -1
  158. package/dist/rules/dispatch-errors.d.ts +3 -0
  159. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  160. package/dist/rules/dispatch-errors.js +9 -0
  161. package/dist/rules/dispatch-errors.js.map +1 -1
  162. package/dist/rules/dispatcher.d.ts +4 -1
  163. package/dist/rules/dispatcher.d.ts.map +1 -1
  164. package/dist/rules/dispatcher.js +122 -33
  165. package/dist/rules/dispatcher.js.map +1 -1
  166. package/dist/rules/index.d.ts +2 -2
  167. package/dist/rules/index.d.ts.map +1 -1
  168. package/dist/rules/index.js +2 -2
  169. package/dist/rules/processor.d.ts +2 -0
  170. package/dist/rules/processor.d.ts.map +1 -1
  171. package/dist/rules/processor.js +18 -4
  172. package/dist/rules/processor.js.map +1 -1
  173. package/dist/rules/start-coordinator.d.ts +6 -1
  174. package/dist/rules/start-coordinator.d.ts.map +1 -1
  175. package/dist/rules/start-coordinator.js +6 -2
  176. package/dist/rules/start-coordinator.js.map +1 -1
  177. package/dist/rules/transition-service.d.ts +20 -2
  178. package/dist/rules/transition-service.d.ts.map +1 -1
  179. package/dist/rules/transition-service.js +43 -20
  180. package/dist/rules/transition-service.js.map +1 -1
  181. package/dist/rules/types.d.ts +71 -3
  182. package/dist/rules/types.d.ts.map +1 -1
  183. package/dist/rules/types.js +10 -2
  184. package/dist/rules/types.js.map +1 -1
  185. package/dist/rules/validation.d.ts.map +1 -1
  186. package/dist/rules/validation.js +5 -0
  187. package/dist/rules/validation.js.map +1 -1
  188. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  189. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  190. package/dist/sandbox/context-sandboxes.js +120 -0
  191. package/dist/sandbox/context-sandboxes.js.map +1 -0
  192. package/dist/sandbox/session-retirement.d.ts +11 -4
  193. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  194. package/dist/sandbox/session-retirement.js +39 -13
  195. package/dist/sandbox/session-retirement.js.map +1 -1
  196. package/dist/session/factory-session.d.ts +20 -5
  197. package/dist/session/factory-session.d.ts.map +1 -1
  198. package/dist/session/factory-session.js +20 -6
  199. package/dist/session/factory-session.js.map +1 -1
  200. package/dist/session/live-sessions.d.ts +1 -1
  201. package/dist/session/live-sessions.d.ts.map +1 -1
  202. package/dist/session/live-sessions.js +12 -2
  203. package/dist/session/live-sessions.js.map +1 -1
  204. package/dist/storage/domains/audit/actions.d.ts +1 -1
  205. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  206. package/dist/storage/domains/audit/actions.js +2 -1
  207. package/dist/storage/domains/audit/actions.js.map +1 -1
  208. package/dist/storage/domains/audit/actors.d.ts.map +1 -1
  209. package/dist/storage/domains/audit/actors.js +1 -1
  210. package/dist/storage/domains/audit/actors.js.map +1 -1
  211. package/dist/storage/domains/boards/base.d.ts +25 -5
  212. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  213. package/dist/storage/domains/boards/base.js +57 -20
  214. package/dist/storage/domains/boards/base.js.map +1 -1
  215. package/dist/storage/domains/intake/base.d.ts +1 -1
  216. package/dist/storage/domains/intake/base.js +2 -2
  217. package/dist/storage/domains/intake/base.js.map +1 -1
  218. package/dist/storage/domains/projects/base.d.ts +16 -2
  219. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  220. package/dist/storage/domains/projects/base.js +32 -5
  221. package/dist/storage/domains/projects/base.js.map +1 -1
  222. package/dist/storage/domains/work-items/base.d.ts +60 -8
  223. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  224. package/dist/storage/domains/work-items/base.js +180 -18
  225. package/dist/storage/domains/work-items/base.js.map +1 -1
  226. package/dist/storage/domains/work-items/cards.d.ts +1 -0
  227. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  228. package/dist/storage/domains/work-items/cards.js +32 -8
  229. package/dist/storage/domains/work-items/cards.js.map +1 -1
  230. package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
  231. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
  232. package/dist/storage/domains/work-items/legacy-review.js +62 -3
  233. package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
  234. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -0
  235. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  236. package/dist/storage/domains/work-items/work-item-schema.js +46 -18
  237. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  238. package/dist/tools/annotations.d.ts.map +1 -1
  239. package/dist/tools/annotations.js +4 -0
  240. package/dist/tools/annotations.js.map +1 -1
  241. package/dist/tools/approval-tools.d.ts +20 -0
  242. package/dist/tools/approval-tools.d.ts.map +1 -1
  243. package/dist/tools/approval-tools.js +79 -30
  244. package/dist/tools/approval-tools.js.map +1 -1
  245. package/dist/tools/audit-events-tool.d.ts +29 -0
  246. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  247. package/dist/tools/audit-events-tool.js +180 -0
  248. package/dist/tools/audit-events-tool.js.map +1 -0
  249. package/dist/tools/index.d.ts +2 -1
  250. package/dist/tools/index.d.ts.map +1 -1
  251. package/dist/tools/index.js +2 -0
  252. package/dist/tools/index.js.map +1 -1
  253. package/dist/tools/messaging-tools.d.ts.map +1 -1
  254. package/dist/tools/messaging-tools.js +1 -1
  255. package/dist/tools/messaging-tools.js.map +1 -1
  256. package/dist/tools/permissions.d.ts.map +1 -1
  257. package/dist/tools/permissions.js +1 -0
  258. package/dist/tools/permissions.js.map +1 -1
  259. package/dist/tools/read-tools.d.ts +0 -2
  260. package/dist/tools/read-tools.d.ts.map +1 -1
  261. package/dist/tools/read-tools.js +2 -7
  262. package/dist/tools/read-tools.js.map +1 -1
  263. package/dist/tools/reports.d.ts +3 -0
  264. package/dist/tools/reports.d.ts.map +1 -1
  265. package/dist/tools/reports.js +3 -3
  266. package/dist/tools/reports.js.map +1 -1
  267. package/dist/tools/run-watch.d.ts +14 -2
  268. package/dist/tools/run-watch.d.ts.map +1 -1
  269. package/dist/tools/run-watch.js +24 -4
  270. package/dist/tools/run-watch.js.map +1 -1
  271. package/dist/tools/session-tools.d.ts.map +1 -1
  272. package/dist/tools/session-tools.js +17 -6
  273. package/dist/tools/session-tools.js.map +1 -1
  274. package/dist/tools/sessions-state-processor.js +1 -1
  275. package/dist/tools/sessions-state-processor.js.map +1 -1
  276. package/dist/tools/side-sessions.d.ts.map +1 -1
  277. package/dist/tools/side-sessions.js +1 -1
  278. package/dist/tools/side-sessions.js.map +1 -1
  279. package/dist/tools/work-item-tools.d.ts.map +1 -1
  280. package/dist/tools/work-item-tools.js +12 -2
  281. package/dist/tools/work-item-tools.js.map +1 -1
  282. package/dist/work-item-branch.d.ts +1 -1
  283. package/dist/work-item-branch.d.ts.map +1 -1
  284. package/dist/work-item-branch.js +2 -0
  285. package/dist/work-item-branch.js.map +1 -1
  286. package/dist/work-items/board-check.d.ts +11 -0
  287. package/dist/work-items/board-check.d.ts.map +1 -0
  288. package/dist/work-items/board-check.js +20 -0
  289. package/dist/work-items/board-check.js.map +1 -0
  290. package/dist/work-items/board-filter-options.d.ts +5 -0
  291. package/dist/work-items/board-filter-options.d.ts.map +1 -0
  292. package/dist/work-items/board-filter-options.js +27 -0
  293. package/dist/work-items/board-filter-options.js.map +1 -0
  294. package/dist/work-items/board-phases.d.ts +28 -0
  295. package/dist/work-items/board-phases.d.ts.map +1 -0
  296. package/dist/work-items/board-phases.js +165 -0
  297. package/dist/work-items/board-phases.js.map +1 -0
  298. package/dist/work-items/card-facts.d.ts +24 -0
  299. package/dist/work-items/card-facts.d.ts.map +1 -0
  300. package/dist/work-items/card-facts.js +75 -0
  301. package/dist/work-items/card-facts.js.map +1 -0
  302. package/dist/work-items/card-labels.d.ts +5 -0
  303. package/dist/work-items/card-labels.d.ts.map +1 -0
  304. package/dist/work-items/card-labels.js +13 -0
  305. package/dist/work-items/card-labels.js.map +1 -0
  306. package/dist/work-items/card-number.d.ts +10 -0
  307. package/dist/work-items/card-number.d.ts.map +1 -0
  308. package/dist/work-items/card-number.js +15 -0
  309. package/dist/work-items/card-number.js.map +1 -0
  310. package/dist/work-items/card-people.d.ts +25 -0
  311. package/dist/work-items/card-people.d.ts.map +1 -0
  312. package/dist/work-items/card-people.js +100 -0
  313. package/dist/work-items/card-people.js.map +1 -0
  314. package/dist/work-items/card-search-text.d.ts +4 -0
  315. package/dist/work-items/card-search-text.d.ts.map +1 -0
  316. package/dist/work-items/card-search-text.js +15 -0
  317. package/dist/work-items/card-search-text.js.map +1 -0
  318. package/dist/work-items/card-source-filters.d.ts +23 -0
  319. package/dist/work-items/card-source-filters.d.ts.map +1 -0
  320. package/dist/work-items/card-source-filters.js +25 -0
  321. package/dist/work-items/card-source-filters.js.map +1 -0
  322. package/dist/work-items/create-work-item.d.ts +0 -6
  323. package/dist/work-items/create-work-item.d.ts.map +1 -1
  324. package/dist/work-items/create-work-item.js +2 -7
  325. package/dist/work-items/create-work-item.js.map +1 -1
  326. package/dist/work-items/list-related-cards.d.ts +4 -0
  327. package/dist/work-items/list-related-cards.d.ts.map +1 -0
  328. package/dist/work-items/list-related-cards.js +24 -0
  329. package/dist/work-items/list-related-cards.js.map +1 -0
  330. package/dist/work-items/related-cards.d.ts +21 -0
  331. package/dist/work-items/related-cards.d.ts.map +1 -0
  332. package/dist/work-items/related-cards.js +45 -0
  333. package/dist/work-items/related-cards.js.map +1 -0
  334. package/dist/work-items/search-words.d.ts +5 -0
  335. package/dist/work-items/search-words.d.ts.map +1 -0
  336. package/dist/work-items/search-words.js +12 -0
  337. package/dist/work-items/search-words.js.map +1 -0
  338. package/dist/work-items/split-migration.d.ts.map +1 -1
  339. package/dist/work-items/split-migration.js +6 -2
  340. package/dist/work-items/split-migration.js.map +1 -1
  341. package/dist/workspace.d.ts +0 -1
  342. package/dist/workspace.d.ts.map +1 -1
  343. package/dist/workspace.js +140 -78
  344. package/dist/workspace.js.map +1 -1
  345. package/factory-skills/factory-build/SKILL.md +1 -1
  346. package/factory-skills/factory-self-review/SKILL.md +1 -1
  347. package/factory-skills/factory-triage/SKILL.md +4 -4
  348. package/package.json +17 -16
@@ -0,0 +1 @@
1
+ {"version":3,"file":"default-rules.js","names":[],"sources":["../../../src/integrations/vanta/default-rules.ts"],"sourcesContent":["import { closedByRoutes } from '../../rules/event-rules.js';\nimport type { FactoryRuleHandler, FactoryVantaEventName, FactoryVantaRuleContext } from '../../rules/types.js';\n\nexport type VantaEventRules = Readonly<\n Record<FactoryVantaEventName, FactoryRuleHandler<FactoryVantaRuleContext> | null>\n>;\n\nconst MAX_DESCRIPTION_LENGTH = 8000;\n\nfunction vantaDescription(vulnerability: FactoryVantaRuleContext['vulnerability']): string {\n const facts = [\n `**Vulnerability:** ${vulnerability.name}`,\n vulnerability.packageIdentifier && `**Package:** \\`${vulnerability.packageIdentifier}\\``,\n vulnerability.severity && `**Severity:** ${vulnerability.severity}`,\n vulnerability.fixable !== null && `**Fixable:** ${vulnerability.fixable ? 'yes' : 'no'}`,\n vulnerability.remediateBy && `**Remediate by:** ${vulnerability.remediateBy.slice(0, 10)}`,\n vulnerability.url && `**Details:** ${vulnerability.url}`,\n ].filter((fact): fact is string => typeof fact === 'string');\n const parts = [facts.map(fact => `- ${fact}`).join('\\n'), vulnerability.description?.trim()].filter(Boolean);\n const text = parts.join('\\n\\n');\n return text.length <= MAX_DESCRIPTION_LENGTH ? text : `${text.slice(0, MAX_DESCRIPTION_LENGTH - 1)}…`;\n}\n\nfunction vantaVulnerabilityObserved(context: FactoryVantaRuleContext) {\n if (context.item || !context.intake) return;\n const { vulnerability } = context;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:vulnerability-intake`,\n // Filed on the default board's first phase; the project's intake routes place it from there.\n board: context.intake.board,\n source: 'vanta-vulnerability',\n sourceKey: vulnerability.id,\n title: vulnerability.title,\n description: vantaDescription(vulnerability),\n url: vulnerability.url,\n stage: context.intake.initialPhase,\n metadata: {\n identifier: vulnerability.name,\n ...(vulnerability.description ? { body: vulnerability.description } : {}),\n state: vulnerability.state,\n severity: vulnerability.severity,\n packageIdentifier: vulnerability.packageIdentifier,\n fixable: vulnerability.fixable,\n remediateBy: vulnerability.remediateBy,\n author: 'vanta',\n labels: [...vulnerability.labels] as string[],\n sourceCreatedAt: vulnerability.createdAt,\n createdAt: vulnerability.createdAt,\n updatedAt: vulnerability.createdAt,\n },\n } as const;\n}\n\nfunction vantaVulnerabilityClosed(context: FactoryVantaRuleContext) {\n if (!context.item || context.item.source !== 'vanta-vulnerability') return;\n const closure = context.boardClosure;\n if (!context.board || !closure || closure.itemTerminal) return;\n return closedByRoutes(false, {\n idempotencyKey: `${context.ingress.id}:vulnerability-closed`,\n board: context.board,\n stage: closure.completed.phase,\n message: {\n text: `Vanta no longer lists ${context.vulnerability.name} as active; this ${closure.boardTitle} card was moved to ${closure.completed.title}.`,\n },\n });\n}\n\nexport const defaultVantaRules = Object.freeze({\n vulnerabilityObserved: vantaVulnerabilityObserved,\n vulnerabilityClosed: vantaVulnerabilityClosed,\n} satisfies VantaEventRules);\n"],"mappings":";;AAOA,MAAM,yBAAyB;AAE/B,SAAS,iBAAiB,eAAiE;CAUzF,MAAM,OADQ,CARA;EACZ,sBAAsB,cAAc;EACpC,cAAc,qBAAqB,kBAAkB,cAAc,kBAAkB;EACrF,cAAc,YAAY,iBAAiB,cAAc;EACzD,cAAc,YAAY,QAAQ,gBAAgB,cAAc,UAAU,QAAQ;EAClF,cAAc,eAAe,qBAAqB,cAAc,YAAY,MAAM,GAAG,EAAE;EACvF,cAAc,OAAO,gBAAgB,cAAc;CACrD,CAAC,CAAC,QAAQ,SAAyB,OAAO,SAAS,QAChC,CAAC,CA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H;AAEA,MAAa,oBAAoB,OAAO,OAAO;CAC7C,uBAAuB;CACvB,qBAAqB;AACvB,CAA2B"}
@@ -0,0 +1,40 @@
1
+ import type { BoardEventFacts } from '../../boards/board-events.js';
2
+ import type { BoardRegistry } from '../../boards/index.js';
3
+ import type { ProjectBoardSource } from '../../boards/project-boards.js';
4
+ import type { FactoryVantaRuleContext } from '../../rules/types.js';
5
+ import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
6
+ import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
7
+ import type { IntegrationContext } from '../base.js';
8
+ import type { VantaEventRules } from './default-rules.js';
9
+ /** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */
10
+ export declare function vantaLabels(severity: string | null): string[];
11
+ export type VantaVulnerabilityIngress = FactoryVantaRuleContext['vulnerability'];
12
+ export interface VantaRulesOptions {
13
+ projects: Pick<FactoryProjectsStorage, 'get'>;
14
+ storage: WorkItemsStorage;
15
+ configVersion: string;
16
+ boards: BoardRegistry | ProjectBoardSource;
17
+ rules?: VantaEventRules;
18
+ }
19
+ export interface VantaRulesIngress {
20
+ orgId: string;
21
+ userId: string;
22
+ factoryProjectId: string;
23
+ /** Every vulnerability Vanta currently lists as active. Open cards missing from it are closed. */
24
+ vulnerabilities: VantaVulnerabilityIngress[];
25
+ }
26
+ type IngressStatus = 'committed' | 'replayed' | 'missing';
27
+ /** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */
28
+ export declare function boardEventFor(context: Pick<FactoryVantaRuleContext, 'event' | 'item'>): BoardEventFacts | undefined;
29
+ export declare class VantaRules {
30
+ #private;
31
+ private readonly options;
32
+ constructor(options: VantaRulesOptions);
33
+ ingest(input: VantaRulesIngress): Promise<{
34
+ status: IngressStatus;
35
+ ingested: number;
36
+ }>;
37
+ }
38
+ export declare function attachVantaRules(context: IntegrationContext): ((input: VantaRulesIngress) => Promise<unknown>) | undefined;
39
+ export {};
40
+ //# sourceMappingURL=rules.d.ts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BAAgB,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,uBAAuB,EAAE,OAAO,GAAG,MAAM,CAAC,GAAG,eAAe,GAAG,SAAS,CAKnH;AAsBD,qBAAa,UAAU;;IAGT,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,iBAAiB,EAEtD;IAMK,MAAM,CAAC,KAAK,EAAE,iBAAiB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAwB3F;CAsGF;AAED,wBAAgB,gBAAgB,CAC9B,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,iBAAiB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAS9D"}
@@ -0,0 +1,208 @@
1
+ import { closeReason } from "../../boards/board-events.js";
2
+ import "../../boards/index.js";
3
+ import { boardForWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from "../../boards/semantics.js";
4
+ import { toBoardSource } from "../../boards/project-boards.js";
5
+ import { routeEventDecision } from "../../rules/event-rules.js";
6
+ import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "../../rules/validation.js";
7
+ import { defaultVantaRules } from "./default-rules.js";
8
+ // src/integrations/vanta/rules.ts
9
+ const MAX_STALE_RULE_ATTEMPTS = 3;
10
+ /** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */
11
+ function vantaLabels(severity) {
12
+ return [
13
+ "security",
14
+ "vanta",
15
+ ...severity ? [`severity:${severity.toLowerCase()}`] : []
16
+ ];
17
+ }
18
+ /** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */
19
+ function boardEventFor(context) {
20
+ if (context.event === "vulnerabilityClosed") return {
21
+ type: "work_item.closed",
22
+ reason: closeReason(false)
23
+ };
24
+ return context.item ? void 0 : { type: "work_item.created" };
25
+ }
26
+ /** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */
27
+ function resolvedFromCard(sourceKey, item) {
28
+ const metadata = item.metadata ?? {};
29
+ const text = (key) => typeof metadata[key] === "string" ? metadata[key] : null;
30
+ return {
31
+ id: sourceKey,
32
+ name: text("identifier") ?? sourceKey,
33
+ title: item.title,
34
+ description: null,
35
+ url: item.externalSource?.url ?? null,
36
+ state: "resolved",
37
+ severity: text("severity"),
38
+ packageIdentifier: text("packageIdentifier"),
39
+ fixable: null,
40
+ remediateBy: text("remediateBy"),
41
+ labels: [],
42
+ createdAt: text("sourceCreatedAt") ?? (/* @__PURE__ */ new Date(0)).toISOString()
43
+ };
44
+ }
45
+ var VantaRules = class {
46
+ options;
47
+ #rules;
48
+ constructor(options) {
49
+ this.options = options;
50
+ this.#rules = options.rules ?? defaultVantaRules;
51
+ }
52
+ #boards(scope) {
53
+ return toBoardSource(this.options.boards).forProject(scope);
54
+ }
55
+ async ingest(input) {
56
+ if (!await this.options.projects.get({
57
+ orgId: input.orgId,
58
+ id: input.factoryProjectId
59
+ })) return {
60
+ status: "missing",
61
+ ingested: 0
62
+ };
63
+ await toBoardSource(this.options.boards).load(input);
64
+ const items = await this.options.storage.listShared({
65
+ orgId: input.orgId,
66
+ factoryProjectId: input.factoryProjectId
67
+ });
68
+ const itemsBySourceKey = new Map(items.filter((item) => item.externalSource?.integrationId === "vanta" && item.externalSource.type === "vulnerability").map((item) => [item.externalSource?.externalId, item]));
69
+ const statuses = [];
70
+ const active = new Set(input.vulnerabilities.map((vulnerability) => vulnerability.id));
71
+ for (const vulnerability of input.vulnerabilities) {
72
+ const relatedItem = itemsBySourceKey.get(vulnerability.id);
73
+ statuses.push(await this.#ingestAlert(input, vulnerability, relatedItem && structuredClone(relatedItem)));
74
+ }
75
+ for (const [sourceKey, item] of itemsBySourceKey) {
76
+ if (!sourceKey || active.has(sourceKey) || item.metadata?.state === "resolved") continue;
77
+ statuses.push(await this.#ingestAlert(input, resolvedFromCard(sourceKey, item), structuredClone(item)));
78
+ }
79
+ if (statuses.includes("committed")) return {
80
+ status: "committed",
81
+ ingested: statuses.length
82
+ };
83
+ if (statuses.includes("replayed")) return {
84
+ status: "replayed",
85
+ ingested: statuses.length
86
+ };
87
+ return {
88
+ status: "missing",
89
+ ingested: statuses.length
90
+ };
91
+ }
92
+ async #ingestAlert(input, alert, relatedItem, attempt = 1) {
93
+ const closed = alert.state === "resolved";
94
+ if (closed && !relatedItem) return "missing";
95
+ const ingressId = `vanta:${alert.id}:${alert.state}`;
96
+ const actor = {
97
+ type: "human",
98
+ id: input.userId
99
+ };
100
+ const event = closed ? "vulnerabilityClosed" : "vulnerabilityObserved";
101
+ const boards = this.#boards(input);
102
+ const context = {
103
+ tenant: {
104
+ orgId: input.orgId,
105
+ projectId: input.factoryProjectId
106
+ },
107
+ actor,
108
+ ingress: {
109
+ type: "vanta",
110
+ id: ingressId
111
+ },
112
+ cause: `vanta.${event}`,
113
+ causalChain: [],
114
+ configVersion: this.options.configVersion,
115
+ ...relatedItem ? {
116
+ item: {
117
+ id: relatedItem.id,
118
+ source: "vanta-vulnerability",
119
+ sourceKey: relatedItem.externalSource?.externalId ?? null,
120
+ parentWorkItemId: relatedItem.parentWorkItemId,
121
+ title: relatedItem.title,
122
+ url: relatedItem.externalSource?.url ?? null,
123
+ stages: relatedItem.stages,
124
+ workItem: relatedItem.workItem,
125
+ acceptedAt: relatedItem.acceptedAt,
126
+ metadata: relatedItem.metadata
127
+ },
128
+ board: boardForWorkItem(relatedItem),
129
+ itemRevision: relatedItem.revision,
130
+ ...withBoardClosure(boards, relatedItem),
131
+ ...rulePhaseField(boards, relatedItem)
132
+ } : {},
133
+ ...withIntakeTarget(boards),
134
+ event,
135
+ vulnerability: alert
136
+ };
137
+ const boardEvent = boardEventFor(context);
138
+ if (boardEvent) context.boardEvent = boardEvent;
139
+ const rule = this.#rules[event];
140
+ let decision = void 0;
141
+ let decisions = [];
142
+ let outcome = { status: "accepted" };
143
+ try {
144
+ decision = rule ? await rule(Object.freeze(context)) : void 0;
145
+ if (decision?.type === "reject") outcome = {
146
+ status: "rejected",
147
+ code: decision.code,
148
+ reason: decision.reason
149
+ };
150
+ else if (decision) decisions = validateFactoryRuleDecisions([decision]).map((entry) => {
151
+ assertFactoryDecisionTarget(entry, boards, relatedItem ? boardForWorkItem(relatedItem) : void 0);
152
+ return { ...entry };
153
+ });
154
+ } catch (error) {
155
+ outcome = {
156
+ status: "rejected",
157
+ code: "rule_error",
158
+ reason: error instanceof Error ? error.message.slice(0, 2e3) : "Factory Vanta rule failed."
159
+ };
160
+ }
161
+ if (!decision && outcome.status === "accepted") {
162
+ const routed = await routeEventDecision(context, this.options.storage, {
163
+ orgId: input.orgId,
164
+ factoryProjectId: input.factoryProjectId
165
+ });
166
+ if (routed) decisions = [{ ...routed }];
167
+ }
168
+ const committed = await this.options.storage.commitRuleEvaluation({
169
+ orgId: input.orgId,
170
+ factoryProjectId: input.factoryProjectId,
171
+ workItemId: relatedItem?.id ?? null,
172
+ ingress: {
173
+ identity: ingressId,
174
+ triggerType: `vanta.${event}`
175
+ },
176
+ configVersion: this.options.configVersion,
177
+ expectedRevision: relatedItem?.revision ?? null,
178
+ actor,
179
+ outcome,
180
+ decisions,
181
+ causalChain: [],
182
+ now: /* @__PURE__ */ new Date()
183
+ });
184
+ if (committed.status === "stale") {
185
+ if (attempt >= MAX_STALE_RULE_ATTEMPTS) throw new Error(`Factory Vanta rule evaluation for ${ingressId} kept losing revision races.`);
186
+ const fresh = relatedItem ? await this.options.storage.get({
187
+ orgId: input.orgId,
188
+ id: relatedItem.id
189
+ }) : null;
190
+ if (relatedItem && !fresh) return "missing";
191
+ return this.#ingestAlert(input, alert, fresh ?? void 0, attempt + 1);
192
+ }
193
+ return committed.status;
194
+ }
195
+ };
196
+ function attachVantaRules(context) {
197
+ if (!context.runtime) return void 0;
198
+ const rules = new VantaRules({
199
+ projects: context.storage.projects,
200
+ storage: context.runtime.workItems,
201
+ configVersion: context.runtime.configVersion,
202
+ boards: context.runtime.boards
203
+ });
204
+ return (input) => rules.ingest(input);
205
+ }
206
+ export { VantaRules, attachVantaRules, boardEventFor, vantaLabels };
207
+
208
+ //# sourceMappingURL=rules.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/vanta/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport { boardForWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { routeEventDecision } from '../../rules/event-rules.js';\nimport type { FactoryVantaRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { defaultVantaRules } from './default-rules.js';\nimport type { VantaEventRules } from './default-rules.js';\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\n/** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */\nexport function vantaLabels(severity: string | null): string[] {\n return ['security', 'vanta', ...(severity ? [`severity:${severity.toLowerCase()}`] : [])];\n}\n\nexport type VantaVulnerabilityIngress = FactoryVantaRuleContext['vulnerability'];\n\nexport interface VantaRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry | ProjectBoardSource;\n rules?: VantaEventRules;\n}\n\nexport interface VantaRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /** Every vulnerability Vanta currently lists as active. Open cards missing from it are closed. */\n vulnerabilities: VantaVulnerabilityIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */\nexport function boardEventFor(context: Pick<FactoryVantaRuleContext, 'event' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'vulnerabilityClosed') {\n return { type: 'work_item.closed', reason: closeReason(false) };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\n/** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */\nfunction resolvedFromCard(sourceKey: string, item: Card): VantaVulnerabilityIngress {\n const metadata = item.metadata ?? {};\n const text = (key: string) => (typeof metadata[key] === 'string' ? (metadata[key] as string) : null);\n return {\n id: sourceKey,\n name: text('identifier') ?? sourceKey,\n title: item.title,\n description: null,\n url: item.externalSource?.url ?? null,\n state: 'resolved',\n severity: text('severity'),\n packageIdentifier: text('packageIdentifier'),\n fixable: null,\n remediateBy: text('remediateBy'),\n labels: [],\n createdAt: text('sourceCreatedAt') ?? new Date(0).toISOString(),\n };\n}\n\nexport class VantaRules {\n readonly #rules: VantaEventRules;\n\n constructor(private readonly options: VantaRulesOptions) {\n this.#rules = options.rules ?? defaultVantaRules;\n }\n\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: VantaRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(\n items\n .filter(item => item.externalSource?.integrationId === 'vanta' && item.externalSource.type === 'vulnerability')\n .map(item => [item.externalSource?.externalId, item]),\n );\n const statuses: IngressStatus[] = [];\n const active = new Set(input.vulnerabilities.map(vulnerability => vulnerability.id));\n for (const vulnerability of input.vulnerabilities) {\n const relatedItem = itemsBySourceKey.get(vulnerability.id);\n statuses.push(await this.#ingestAlert(input, vulnerability, relatedItem && structuredClone(relatedItem)));\n }\n for (const [sourceKey, item] of itemsBySourceKey) {\n if (!sourceKey || active.has(sourceKey) || item.metadata?.state === 'resolved') continue;\n statuses.push(await this.#ingestAlert(input, resolvedFromCard(sourceKey, item), structuredClone(item)));\n }\n if (statuses.includes('committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.includes('replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestAlert(\n input: VantaRulesIngress,\n alert: VantaVulnerabilityIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const closed = alert.state === 'resolved';\n // A resolved vulnerability Factory never filed stays off the board.\n if (closed && !relatedItem) return 'missing';\n\n const ingressId = `vanta:${alert.id}:${alert.state}`;\n const actor = { type: 'human' as const, id: input.userId };\n const event = closed ? 'vulnerabilityClosed' : 'vulnerabilityObserved';\n const boards = this.#boards(input);\n const context: FactoryVantaRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'vanta', id: ingressId },\n cause: `vanta.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'vanta-vulnerability',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(boards, relatedItem),\n ...rulePhaseField(boards, relatedItem),\n }\n : {}),\n ...withIntakeTarget(boards),\n event,\n vulnerability: alert,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const rule = this.#rules[event];\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await rule(Object.freeze(context)) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(entry, boards, relatedItem ? boardForWorkItem(relatedItem) : undefined);\n return { ...entry };\n });\n }\n } catch (error) {\n outcome = {\n status: 'rejected',\n code: 'rule_error',\n reason: error instanceof Error ? error.message.slice(0, 2_000) : 'Factory Vanta rule failed.',\n };\n }\n if (!decision && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: `vanta.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Vanta rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestAlert(input, alert, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachVantaRules(\n context: IntegrationContext,\n): ((input: VantaRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new VantaRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return input => rules.ingest(input);\n}\n"],"mapp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reconciler.js';
2
+ import type { VantaRulesIngress, VantaVulnerabilityIngress } from './rules.js';
3
+ export declare const VANTA_VULNERABILITIES_SOURCE_ID = "vanta:vulnerabilities";
4
+ export declare const DEFAULT_VANTA_SYNC_INTERVAL_MS: number;
5
+ /** The subset of Vanta's `GET /v1/vulnerabilities` item Factory reads. */
6
+ export interface VantaVulnerability {
7
+ id: string;
8
+ name: string;
9
+ description?: string | null;
10
+ packageIdentifier?: string | null;
11
+ severity?: string | null;
12
+ isFixable?: boolean | null;
13
+ remediateByDate?: string | null;
14
+ firstDetectedDate?: string | null;
15
+ externalURL?: string | null;
16
+ }
17
+ /** Lists every active Vanta vulnerability. Throws when Vanta can't be read. */
18
+ export type VantaVulnerabilityLister = () => Promise<VantaVulnerability[]>;
19
+ export declare function toVantaIngress(vulnerability: VantaVulnerability): VantaVulnerabilityIngress;
20
+ /**
21
+ * Reads Vanta's active vulnerabilities once and hands them to every Factory project that takes
22
+ * Vanta intake. A project takes it when its org has Vanta intake enabled and either binds the
23
+ * vulnerabilities source to it or binds it to no project at all.
24
+ */
25
+ export declare function createVantaSync(options: {
26
+ listVulnerabilities: VantaVulnerabilityLister;
27
+ listProjects: () => Promise<ReadonlyArray<{
28
+ orgId: string;
29
+ id: string;
30
+ }>>;
31
+ intakeEnabled: (orgId: string) => Promise<boolean>;
32
+ boundProjectIds: (orgId: string) => Promise<string[]>;
33
+ ingest: (input: VantaRulesIngress) => Promise<unknown>;
34
+ userId: string;
35
+ }): () => Promise<IssueReconcileSummary>;
36
+ //# sourceMappingURL=sync.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../../../src/integrations/vanta/sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAE/E,eAAO,MAAM,+BAA+B,0BAA0B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
+ import { vantaLabels } from "./rules.js";
2
+ // src/integrations/vanta/sync.ts
3
+ const VANTA_VULNERABILITIES_SOURCE_ID = "vanta:vulnerabilities";
4
+ const DEFAULT_VANTA_SYNC_INTERVAL_MS = 9e5;
5
+ function toVantaIngress(vulnerability) {
6
+ const severity = vulnerability.severity?.toLowerCase() ?? null;
7
+ const packageIdentifier = vulnerability.packageIdentifier ?? null;
8
+ return {
9
+ id: vulnerability.id,
10
+ name: vulnerability.name,
11
+ title: packageIdentifier ? `${packageIdentifier}: ${vulnerability.name}` : vulnerability.name,
12
+ description: vulnerability.description && vulnerability.description !== vulnerability.name ? vulnerability.description : null,
13
+ url: vulnerability.externalURL ?? null,
14
+ state: "open",
15
+ severity,
16
+ packageIdentifier,
17
+ fixable: vulnerability.isFixable ?? null,
18
+ remediateBy: vulnerability.remediateByDate ?? null,
19
+ labels: vantaLabels(severity),
20
+ createdAt: vulnerability.firstDetectedDate ?? (/* @__PURE__ */ new Date(0)).toISOString()
21
+ };
22
+ }
23
+ /**
24
+ * Reads Vanta's active vulnerabilities once and hands them to every Factory project that takes
25
+ * Vanta intake. A project takes it when its org has Vanta intake enabled and either binds the
26
+ * vulnerabilities source to it or binds it to no project at all.
27
+ */
28
+ function createVantaSync(options) {
29
+ return async () => {
30
+ const summary = {
31
+ projects: 0,
32
+ checked: 0,
33
+ updated: 0,
34
+ closed: 0,
35
+ missing: 0,
36
+ failed: 0,
37
+ errors: []
38
+ };
39
+ const projects = await options.listProjects();
40
+ if (projects.length === 0) return summary;
41
+ const vulnerabilities = (await options.listVulnerabilities()).map(toVantaIngress);
42
+ const orgTargets = /* @__PURE__ */ new Map();
43
+ for (const project of projects) try {
44
+ let target = orgTargets.get(project.orgId);
45
+ if (!target) {
46
+ target = {
47
+ enabled: await options.intakeEnabled(project.orgId),
48
+ bound: await options.boundProjectIds(project.orgId)
49
+ };
50
+ orgTargets.set(project.orgId, target);
51
+ }
52
+ if (!target.enabled || target.bound.length > 0 && !target.bound.includes(project.id)) continue;
53
+ await options.ingest({
54
+ orgId: project.orgId,
55
+ userId: options.userId,
56
+ factoryProjectId: project.id,
57
+ vulnerabilities
58
+ });
59
+ summary.projects += 1;
60
+ summary.checked += vulnerabilities.length;
61
+ } catch (error) {
62
+ summary.failed += 1;
63
+ summary.errors.push({
64
+ projectId: project.id,
65
+ error: error instanceof Error ? error.message : String(error)
66
+ });
67
+ }
68
+ return summary;
69
+ };
70
+ }
71
+ export { DEFAULT_VANTA_SYNC_INTERVAL_MS, VANTA_VULNERABILITIES_SOURCE_ID, createVantaSync, toVantaIngress };
72
+
73
+ //# sourceMappingURL=sync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sync.js","names":[],"sources":["../../../src/integrations/vanta/sync.ts"],"sourcesContent":["import type { IssueReconcileSummary } from '../issue-reconciler.js';\nimport { vantaLabels } from './rules.js';\nimport type { VantaRulesIngress, VantaVulnerabilityIngress } from './rules.js';\n\nexport const VANTA_VULNERABILITIES_SOURCE_ID = 'vanta:vulnerabilities';\nexport const DEFAULT_VANTA_SYNC_INTERVAL_MS = 15 * 60_000;\n\n/** The subset of Vanta's `GET /v1/vulnerabilities` item Factory reads. */\nexport interface VantaVulnerability {\n id: string;\n name: string;\n description?: string | null;\n packageIdentifier?: string | null;\n severity?: string | null;\n isFixable?: boolean | null;\n remediateByDate?: string | null;\n firstDetectedDate?: string | null;\n externalURL?: string | null;\n}\n\n/** Lists every active Vanta vulnerability. Throws when Vanta can't be read. */\nexport type VantaVulnerabilityLister = () => Promise<VantaVulnerability[]>;\n\nexport function toVantaIngress(vulnerability: VantaVulnerability): VantaVulnerabilityIngress {\n const severity = vulnerability.severity?.toLowerCase() ?? null;\n const packageIdentifier = vulnerability.packageIdentifier ?? null;\n return {\n id: vulnerability.id,\n name: vulnerability.name,\n title: packageIdentifier ? `${packageIdentifier}: ${vulnerability.name}` : vulnerability.name,\n description: vulnerability.description && vulnerability.description !== vulnerability.name ? vulnerability.description : null,\n url: vulnerability.externalURL ?? null,\n state: 'open',\n severity,\n packageIdentifier,\n fixable: vulnerability.isFixable ?? null,\n remediateBy: vulnerability.remediateByDate ?? null,\n labels: vantaLabels(severity),\n createdAt: vulnerability.firstDetectedDate ?? new Date(0).toISOString(),\n };\n}\n\n/**\n * Reads Vanta's active vulnerabilities once and hands them to every Factory project that takes\n * Vanta intake. A project takes it when its org has Vanta intake enabled and either binds the\n * vulnerabilities source to it or binds it to no project at all.\n */\nexport function createVantaSync(options: {\n listVulnerabilities: VantaVulnerabilityLister;\n listProjects: () => Promise<ReadonlyArray<{ orgId: string; id: string }>>;\n intakeEnabled: (orgId: string) => Promise<boolean>;\n boundProjectIds: (orgId: string) => Promise<string[]>;\n ingest: (input: VantaRulesIngress) => Promise<unknown>;\n userId: string;\n}): () => Promise<IssueReconcileSummary> {\n return async () => {\n const summary: IssueReconcileSummary = { projects: 0, checked: 0, updated: 0, closed: 0, missing: 0, failed: 0, errors: [] };\n const projects = await options.listProjects();\n if (projects.length === 0) return summary;\n const vulnerabilities = (await options.listVulnerabilities()).map(toVantaIngress);\n const orgTargets = new Map<string, { enabled: boolean; bound: string[] }>();\n for (const project of projects) {\n try {\n let target = orgTargets.get(project.orgId);\n if (!target) {\n target = {\n enabled: await options.intakeEnabled(project.orgId),\n bound: await options.boundProjectIds(project.orgId),\n };\n orgTargets.set(project.orgId, target);\n }\n if (!target.enabled || (target.bound.length > 0 && !target.bound.includes(project.id))) continue;\n await options.ingest({\n orgId: project.orgId,\n userId: options.userId,\n factoryProjectId: project.id,\n vulnerabilities,\n });\n summary.projects += 1;\n summary.checked += vulnerabilities.length;\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({ projectId: project.id, error: error instanceof Error ? error.message : String(error) });\n }\n }\n return summary;\n };\n}\n"],"mappings":";;AAIA,MAAa,kCAAkC;AAC/C,MAAa,iCAAiC;AAkB9C,SAAgB,eAAe,eAA8D;CAC3F,MAAM,WAAW,cAAc,UAAU,YAAY,KAAK;CAC1D,MAAM,oBAAoB,c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AAgBD,+FAA+F;AAC/F,eAAO,MAAM,iCAAiC,+BAA+B,CAAC;AAE9E,wBAAgB,8BAA8B,CAC5C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,MAAM,EAAE,gBAAgB,GAAG,SAAS,EACpC,GAAG,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAe,GACpD,MAAM,EAAE,CAMV;AAED,MAAM,WAAW,oBAAoB;IACnC,IAAI,EAAE,SAAS,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,oBAAoB,EAAE,MAAM,EAAE,CAAC;IAC/B,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;IAC9C,qFAAqF;IACrF,cAAc,EAAE,SAAS,0BAA0B,EAAE,CAAC;IACtD,KAAK,EAAE,uBAAuB,CAAC;CAChC;AAED,6GAA6G;AAC7G,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAGlG;AAsFD,sEAAsE;AACtE,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,gBAAgB,EACvB,IAAI,EAAE,oBAAoB,EAC1B,OAAO,GAAE;IAAE,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC3C,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAe1C;AAuFD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAoB5E"}
@@ -4,6 +4,7 @@ import { FactorySourceSessionResolutionError, ensureFactorySourceSession } from
4
4
  import { auditActorProfile } from "../storage/domains/audit/base.js";
5
5
  import { FACTORY_TOOL_ANNOTATIONS } from "../tools/annotations.js";
6
6
  import { createFactoryTools } from "../tools/index.js";
7
+ import { hasEveryWord, searchWords } from "../work-items/search-words.js";
7
8
  import { propagateClientDisconnect } from "./disconnect.js";
8
9
  import { factoryActivityEvent } from "./events.js";
9
10
  import { registerApiRoute } from "@mastra/core/server";
@@ -98,11 +99,8 @@ function createSearchFetchTools(scope, deps, inspect) {
98
99
  description: "Search this Factory’s work items by title or id. Returns matching items with ids to pass to `fetch`.",
99
100
  inputSchema: z.object({ query: z.string().describe("Words to look for in work item titles.") }),
100
101
  execute: async ({ query }) => {
101
- const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
102
- return { results: (await deps.tools.workItems.listShared(project)).filter((item) => {
103
- const haystack = `${item.id} ${item.title}`.toLowerCase();
104
- return terms.every((term) => haystack.includes(term));
105
- }).slice(0, 20).map((item) => ({
102
+ const words = searchWords(query);
103
+ return { results: (await deps.tools.workItems.listShared(project)).filter((item) => hasEveryWord(`${item.id} ${item.title}`.toLowerCase(), words)).slice(0, 20).map((item) => ({
106
104
  id: item.id,
107
105
  title: item.title,
108
106
  url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, item.id)
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../src/mcp/routes.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport { createTool } from '@mastra/core/tools';\nimport type { Tool } from '@mastra/core/tools';\nimport { MCPServer } from '@mastra/mcp';\nimport { toFetchResponse, toReqRes } from 'fetch-to-node';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport { getFactoryAuthUser } from '../auth.js';\nimport { PLATFORM_AUTH_PROVIDER } from '../platform-auth-host.js';\nimport type { RouteAuth } from '../routes/route.js';\nimport { ensureFactorySourceSession, FactorySourceSessionResolutionError } from '../session/factory-session.js';\nimport { auditActorProfile } from '../storage/domains/audit/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { FACTORY_TOOL_ANNOTATIONS } from '../tools/annotations.js';\nimport { createFactoryTools } from '../tools/index.js';\nimport type { FactoryToolDependencies, FactoryToolScope } from '../tools/index.js';\nimport { propagateClientDisconnect } from './disconnect.js';\nimport { factoryActivityEvent } from './events.js';\n\nexport const FACTORY_MCP_PATH = '/web/factory/projects/:projectId/mcp';\nconst PROTECTED_RESOURCE_PREFIX = '/.well-known/oauth-protected-resource';\n\n/**\n * Tools an MCP client never gets. `factory_message_origin` answers the session\n * that started this one; a connector session is started by a person, not a session.\n */\nconst EXCLUDED_TOOLS = new Set(['factory_message_origin']);\n\nexport interface FactoryMcpConfig {\n /** Serve the MCP endpoint. Default `true`; it is never served without an auth provider. */\n enabled?: boolean;\n /**\n * OAuth authorization servers advertised in the protected-resource metadata\n * (RFC 9728) so clients like ChatGPT know where to sign in. Defaults to the\n * `MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER` env var, then to Mastra Platform's\n * AuthKit when the Factory uses Platform auth. The endpoint isn't served\n * without one, since clients would have nowhere to sign in.\n */\n authorizationServers?: string[];\n}\n\n/**\n * MCP requires a server version. The Factory doesn't expose its package\n * version at runtime, so this versions the endpoint's interface instead.\n */\nconst FACTORY_MCP_SERVER_VERSION = '1.0.0';\n\n/** What a connected client is told the server is for and where to start. */\nconst FACTORY_MCP_INSTRUCTIONS = [\n 'A Mastra Factory tracks software work as work items on a board; agent sessions plan and build them.',\n 'Start with `factory_list_attention` for what needs a person, or `search` and `fetch` to find a work item.',\n 'Work item tools file, update, move and follow items; session tools start, message and follow the agent sessions working on them.',\n 'Every call runs as the signed-in user. When the Factory has a repository, session tools act from a private connector session of theirs.',\n].join(' ');\n\n/** Mastra Platform's WorkOS AuthKit, which issues tokens Platform's `/auth/verify` accepts. */\nexport const PLATFORM_MCP_AUTHORIZATION_SERVER = 'https://auth-kit.mastra.ai';\n\nexport function resolveMcpAuthorizationServers(\n providerName: string | undefined,\n config: FactoryMcpConfig | undefined,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n if (config?.authorizationServers?.length) return config.authorizationServers;\n const fromEnv = env.MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER?.trim();\n if (fromEnv) return [fromEnv];\n if (providerName === PLATFORM_AUTH_PROVIDER) return [PLATFORM_MCP_AUTHORIZATION_SERVER];\n return [];\n}\n\nexport interface FactoryMcpRoutesDeps {\n auth: RouteAuth;\n publicOrigin: string;\n authorizationServers: string[];\n projects: Pick<FactoryProjectsStorage, 'get'>;\n /** Source-control handles a connector session can be filed under, tried in order. */\n sourceControls: readonly SourceControlStorageHandle[];\n tools: FactoryToolDependencies;\n}\n\n/** The connector session a user's MCP client acts from: one per user and Factory, stable across requests. */\nexport function connectorSessionId(orgId: string, userId: string, factoryProjectId: string): string {\n const hex = createHash('sha256').update(`mcp\\0${orgId}\\0${userId}\\0${factoryProjectId}`).digest('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Get or create the private user session behind a person's MCP client, so\n * session-scoped tools (start/signal sessions, follow work items) have a real\n * session to act from. A Factory without a connected repository has nowhere to\n * file one; its tools still run against the stable id.\n */\nasync function ensureConnectorSession(\n deps: FactoryMcpRoutesDeps,\n args: { orgId: string; userId: string; factoryProjectId: string },\n): Promise<{ sessionId: string; persisted: boolean }> {\n const sessionId = connectorSessionId(args.orgId, args.userId, args.factoryProjectId);\n if (await deps.tools.sessions.getBySessionId(sessionId)) return { sessionId, persisted: true };\n for (const sourceControl of deps.sourceControls) {\n try {\n await ensureFactorySourceSession({\n sourceControl,\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n branch: `factory/mcp-${sessionId.slice(0, 8)}`,\n attributeToUserId: args.userId,\n sessionId,\n visibility: 'private',\n });\n return { sessionId, persisted: true };\n } catch (error) {\n if (!(error instanceof FactorySourceSessionResolutionError)) throw error;\n }\n }\n return { sessionId, persisted: false };\n}\n\nfunction workItemUrl(publicOrigin: string, factoryProjectId: string, workItemId: string): string {\n return `${publicOrigin}/factory/${encodeURIComponent(factoryProjectId)}/work-items/${encodeURIComponent(workItemId)}`;\n}\n\n/**\n * `search` and `fetch`, the two tools ChatGPT's connectors and deep research\n * look for, answered from the Factory's work items.\n */\nfunction createSearchFetchTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n inspect: Tool<any, any, any, any> | undefined,\n): Record<string, Tool<any, any, any, any>> {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n return {\n search: createTool({\n id: 'search',\n description:\n 'Search this Factory’s work items by title or id. Returns matching items with ids to pass to `fetch`.',\n inputSchema: z.object({ query: z.string().describe('Words to look for in work item titles.') }),\n execute: async ({ query }) => {\n const terms = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const items = await deps.tools.workItems.listShared(project);\n const results = items\n .filter(item => {\n const haystack = `${item.id} ${item.title}`.toLowerCase();\n return terms.every(term => haystack.includes(term));\n })\n .slice(0, 20)\n .map(item => ({\n id: item.id,\n title: item.title,\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, item.id),\n }));\n return { results };\n },\n }),\n fetch: createTool({\n id: 'fetch',\n description: 'Fetch everything the Factory knows about one work item, by the id `search` returned.',\n inputSchema: z.object({ id: z.string().describe('Work item id.') }),\n execute: async ({ id }, context) => {\n if (!inspect?.execute) throw new Error('Work item details are unavailable.');\n const details = (await inspect.execute({ workItem: id }, context)) as { item?: { title?: string } };\n return {\n id,\n title: details.item?.title ?? id,\n text: JSON.stringify(details, null, 2),\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, id),\n metadata: { factoryProjectId: scope.factoryProjectId },\n };\n },\n }),\n };\n}\n\n/** The tools a signed-in person's MCP client sees for one Factory. */\nexport function createFactoryMcpTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n options: { persistedSession?: boolean } = {},\n): Record<string, Tool<any, any, any, any>> {\n const factoryTools = createFactoryTools({ scope, deps: deps.tools }) as Record<string, Tool<any, any, any, any>>;\n const tools: Record<string, Tool<any, any, any, any>> = {};\n for (const [name, tool] of Object.entries(factoryTools)) {\n if (EXCLUDED_TOOLS.has(name)) continue;\n // Starting a sub-session needs a real parent session row to file it under.\n if (name === 'factory_start_session' && options.persistedSession === false) continue;\n tools[name] = tool;\n }\n Object.assign(tools, createSearchFetchTools(scope, deps, factoryTools.factory_inspect_work_item));\n for (const [name, tool] of Object.entries(tools)) {\n const annotations = FACTORY_TOOL_ANNOTATIONS[name];\n if (annotations) tool.mcp = { ...tool.mcp, annotations };\n }\n return tools;\n}\n\nfunction resourceMetadataUrl(deps: FactoryMcpRoutesDeps, mcpPath: string): string {\n return `${deps.publicOrigin}${PROTECTED_RESOURCE_PREFIX}${mcpPath}`;\n}\n\nfunction unauthorized(deps: FactoryMcpRoutesDeps, mcpPath: string, error = 'unauthorized'): Response {\n return new Response(JSON.stringify({ error }), {\n status: 401,\n headers: {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': `Bearer resource_metadata=\"${resourceMetadataUrl(deps, mcpPath)}\"`,\n },\n });\n}\n\nasync function handleMcp(deps: FactoryMcpRoutesDeps, c: Context): Promise<Response> {\n const factoryProjectId = c.req.param('projectId') ?? '';\n const mcpPath = new URL(c.req.url).pathname;\n\n await deps.auth.ensureUser(c);\n const tenant = deps.auth.tenant(c);\n if (!tenant) return unauthorized(deps, mcpPath);\n if (!tenant.orgId) return c.json({ error: 'organization_required' }, 403);\n\n const project = await deps.projects.get({ orgId: tenant.orgId, id: factoryProjectId });\n if (!project) return c.json({ error: 'not_found' }, 404);\n\n const { sessionId, persisted } = await ensureConnectorSession(deps, {\n orgId: tenant.orgId,\n userId: tenant.userId,\n factoryProjectId,\n });\n const actorProfile = auditActorProfile(getFactoryAuthUser(c));\n const scope: FactoryToolScope = {\n orgId: tenant.orgId,\n factoryProjectId,\n userId: tenant.userId,\n sessionId,\n // A user session's memory lives under its owner.\n resourceId: tenant.userId,\n threadId: sessionId,\n kind: 'user',\n // A signed-in person is driving the client: the same reach as a web UI turn.\n interactive: true,\n ...(actorProfile ? { actorProfile } : {}),\n };\n\n const server = new MCPServer({\n id: `factory-${factoryProjectId}`,\n name: `${project.name ?? 'Mastra'} Factory`,\n version: FACTORY_MCP_SERVER_VERSION,\n description: 'Manage work items, sessions and decisions in a Mastra Factory.',\n instructions: FACTORY_MCP_INSTRUCTIONS,\n // VS Code and Cursor still open with 2025-era `initialize`; serve them statelessly.\n legacy: 'stateless',\n tools: createFactoryMcpTools(scope, deps, { persistedSession: persisted }),\n events: {\n 'factory.activity': factoryActivityEvent({\n orgId: tenant.orgId,\n factoryProjectId,\n audit: deps.tools.audit,\n workItems: deps.tools.workItems,\n sessions: deps.tools.sessions,\n viewer: { orgId: tenant.orgId, userId: tenant.userId },\n }),\n },\n });\n\n const { req, res } = toReqRes(c.req.raw);\n const done = server\n .startHTTP({ url: new URL(c.req.url), httpPath: mcpPath, req, res })\n .catch(error => {\n console.warn('[factory] MCP request failed:', error);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null }),\n );\n }\n })\n .finally(() => void server.close());\n const response = propagateClientDisconnect(await toFetchResponse(res), res);\n if (res.writableEnded) await done;\n return response;\n}\n\n/**\n * The Factory's MCP endpoint: Streamable HTTP at\n * `/web/factory/projects/:projectId/mcp`, plus its RFC 9728 protected-resource\n * metadata. Callers sign in with OAuth through the Factory's auth provider and\n * get the tools a web UI session would, under the same permissions.\n */\nexport function buildFactoryMcpRoutes(deps: FactoryMcpRoutesDeps): ApiRoute[] {\n const handler = (c: unknown) => handleMcp(deps, c as Context);\n return [\n ...(['POST', 'GET', 'DELETE'] as const).map(method =>\n registerApiRoute(FACTORY_MCP_PATH, { method, requiresAuth: false, handler }),\n ),\n registerApiRoute(`${PROTECTED_RESOURCE_PREFIX}${FACTORY_MCP_PATH}`, {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const mcpPath = new URL(c.req.url).pathname.slice(PROTECTED_RESOURCE_PREFIX.length);\n return c.json({\n resource: `${deps.publicOrigin}${mcpPath}`,\n authorization_servers: deps.authorizationServers,\n bearer_methods_supported: ['header'],\n resource_name: 'Mastra Factory',\n });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,MAAa,mBAAmB;AAChC,MAAM,4BAA4B;;;;;AAMlC,MAAM,iCAAiB,IAAI,IAAI,CAAC,wBAAwB,CAAC;;;;;AAmBzD,MAAM,6BAA6B;;AAGnC,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;AAGV,MAAa,oCAAoC;AAEjD,SAAgB,+BACd,cACA,QACA,MAA0C,QAAQ,KACxC;CACV,IAAI,QAAQ,sBAAsB,QAAQ,OAAO,OAAO;CACxD,MAAM,UAAU,IAAI,yCAAyC,KAAK;CAClE,IAAI,SAAS,OAAO,CAAC,OAAO;CAC5B,IAAI,iBAAA,iBAAyC,OAAO,CAAC,iCAAiC;CACtF,OAAO,CAAC;AACV;;AAaA,SAAgB,mBAAmB,OAAe,QAAgB,kBAAkC;CAClG,MAAM,MAAM,WAAW,QAAQ,CAAC,CAAC,OAAO,QAAQ,MAAM,IAAI,OAAO,IAAI,kBAAkB,CAAC,CAAC,OAAO,KAAK;CACrG,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,EAAE,EAAE,IAAI,IAAI,MAAM,IAAI,EAAE,EAAE,IAAI,IAAI,MAAM,IAAI,EAAE,EAAE,GAAG,IAAI,MAAM,IAAI,EAAE;AAC/G;;;;;;;AAQA,eAAe,uBACb,MACA,MACoD;CACpD,MAAM,YAAY,mBAAmB,KAAK,OAAO,KAAK,QAAQ,KAAK,gBAAgB;CACnF,IAAI,MAAM,KAAK,MAAM,SAAS,eAAe,SAAS,GAAG,OAAO;EAAE;EAAW,WAAW;CAAK;CAC7F,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../../src/mcp/routes.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport { createTool } from '@mastra/core/tools';\nimport type { Tool } from '@mastra/core/tools';\nimport { MCPServer } from '@mastra/mcp';\nimport { toFetchResponse, toReqRes } from 'fetch-to-node';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport { getFactoryAuthUser } from '../auth.js';\nimport { PLATFORM_AUTH_PROVIDER } from '../platform-auth-host.js';\nimport type { RouteAuth } from '../routes/route.js';\nimport { ensureFactorySourceSession, FactorySourceSessionResolutionError } from '../session/factory-session.js';\nimport { auditActorProfile } from '../storage/domains/audit/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { FACTORY_TOOL_ANNOTATIONS } from '../tools/annotations.js';\nimport { createFactoryTools } from '../tools/index.js';\nimport type { FactoryToolDependencies, FactoryToolScope } from '../tools/index.js';\nimport { hasEveryWord, searchWords } from '../work-items/search-words.js';\nimport { propagateClientDisconnect } from './disconnect.js';\nimport { factoryActivityEvent } from './events.js';\n\nexport const FACTORY_MCP_PATH = '/web/factory/projects/:projectId/mcp';\nconst PROTECTED_RESOURCE_PREFIX = '/.well-known/oauth-protected-resource';\n\n/**\n * Tools an MCP client never gets. `factory_message_origin` answers the session\n * that started this one; a connector session is started by a person, not a session.\n */\nconst EXCLUDED_TOOLS = new Set(['factory_message_origin']);\n\nexport interface FactoryMcpConfig {\n /** Serve the MCP endpoint. Default `true`; it is never served without an auth provider. */\n enabled?: boolean;\n /**\n * OAuth authorization servers advertised in the protected-resource metadata\n * (RFC 9728) so clients like ChatGPT know where to sign in. Defaults to the\n * `MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER` env var, then to Mastra Platform's\n * AuthKit when the Factory uses Platform auth. The endpoint isn't served\n * without one, since clients would have nowhere to sign in.\n */\n authorizationServers?: string[];\n}\n\n/**\n * MCP requires a server version. The Factory doesn't expose its package\n * version at runtime, so this versions the endpoint's interface instead.\n */\nconst FACTORY_MCP_SERVER_VERSION = '1.0.0';\n\n/** What a connected client is told the server is for and where to start. */\nconst FACTORY_MCP_INSTRUCTIONS = [\n 'A Mastra Factory tracks software work as work items on a board; agent sessions plan and build them.',\n 'Start with `factory_list_attention` for what needs a person, or `search` and `fetch` to find a work item.',\n 'Work item tools file, update, move and follow items; session tools start, message and follow the agent sessions working on them.',\n 'Every call runs as the signed-in user. When the Factory has a repository, session tools act from a private connector session of theirs.',\n].join(' ');\n\n/** Mastra Platform's WorkOS AuthKit, which issues tokens Platform's `/auth/verify` accepts. */\nexport const PLATFORM_MCP_AUTHORIZATION_SERVER = 'https://auth-kit.mastra.ai';\n\nexport function resolveMcpAuthorizationServers(\n providerName: string | undefined,\n config: FactoryMcpConfig | undefined,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n if (config?.authorizationServers?.length) return config.authorizationServers;\n const fromEnv = env.MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER?.trim();\n if (fromEnv) return [fromEnv];\n if (providerName === PLATFORM_AUTH_PROVIDER) return [PLATFORM_MCP_AUTHORIZATION_SERVER];\n return [];\n}\n\nexport interface FactoryMcpRoutesDeps {\n auth: RouteAuth;\n publicOrigin: string;\n authorizationServers: string[];\n projects: Pick<FactoryProjectsStorage, 'get'>;\n /** Source-control handles a connector session can be filed under, tried in order. */\n sourceControls: readonly SourceControlStorageHandle[];\n tools: FactoryToolDependencies;\n}\n\n/** The connector session a user's MCP client acts from: one per user and Factory, stable across requests. */\nexport function connectorSessionId(orgId: string, userId: string, factoryProjectId: string): string {\n const hex = createHash('sha256').update(`mcp\\0${orgId}\\0${userId}\\0${factoryProjectId}`).digest('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Get or create the private user session behind a person's MCP client, so\n * session-scoped tools (start/signal sessions, follow work items) have a real\n * session to act from. A Factory without a connected repository has nowhere to\n * file one; its tools still run against the stable id.\n */\nasync function ensureConnectorSession(\n deps: FactoryMcpRoutesDeps,\n args: { orgId: string; userId: string; factoryProjectId: string },\n): Promise<{ sessionId: string; persisted: boolean }> {\n const sessionId = connectorSessionId(args.orgId, args.userId, args.factoryProjectId);\n if (await deps.tools.sessions.getBySessionId(sessionId)) return { sessionId, persisted: true };\n for (const sourceControl of deps.sourceControls) {\n try {\n await ensureFactorySourceSession({\n sourceControl,\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n branch: `factory/mcp-${sessionId.slice(0, 8)}`,\n attributeToUserId: args.userId,\n sessionId,\n visibility: 'private',\n });\n return { sessionId, persisted: true };\n } catch (error) {\n if (!(error instanceof FactorySourceSessionResolutionError)) throw error;\n }\n }\n return { sessionId, persisted: false };\n}\n\nfunction workItemUrl(publicOrigin: string, factoryProjectId: string, workItemId: string): string {\n return `${publicOrigin}/factory/${encodeURIComponent(factoryProjectId)}/work-items/${encodeURIComponent(workItemId)}`;\n}\n\n/**\n * `search` and `fetch`, the two tools ChatGPT's connectors and deep research\n * look for, answered from the Factory's work items.\n */\nfunction createSearchFetchTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n inspect: Tool<any, any, any, any> | undefined,\n): Record<string, Tool<any, any, any, any>> {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n return {\n search: createTool({\n id: 'search',\n description:\n 'Search this Factory’s work items by title or id. Returns matching items with ids to pass to `fetch`.',\n inputSchema: z.object({ query: z.string().describe('Words to look for in work item titles.') }),\n execute: async ({ query }) => {\n const words = searchWords(query);\n const items = await deps.tools.workItems.listShared(project);\n const results = items\n .filter(item => hasEveryWord(`${item.id} ${item.title}`.toLowerCase(), words))\n .slice(0, 20)\n .map(item => ({\n id: item.id,\n title: item.title,\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, item.id),\n }));\n return { results };\n },\n }),\n fetch: createTool({\n id: 'fetch',\n description: 'Fetch everything the Factory knows about one work item, by the id `search` returned.',\n inputSchema: z.object({ id: z.string().describe('Work item id.') }),\n execute: async ({ id }, context) => {\n if (!inspect?.execute) throw new Error('Work item details are unavailable.');\n const details = (await inspect.execute({ workItem: id }, context)) as { item?: { title?: string } };\n return {\n id,\n title: details.item?.title ?? id,\n text: JSON.stringify(details, null, 2),\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, id),\n metadata: { factoryProjectId: scope.factoryProjectId },\n };\n },\n }),\n };\n}\n\n/** The tools a signed-in person's MCP client sees for one Factory. */\nexport function createFactoryMcpTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n options: { persistedSession?: boolean } = {},\n): Record<string, Tool<any, any, any, any>> {\n const factoryTools = createFactoryTools({ scope, deps: deps.tools }) as Record<string, Tool<any, any, any, any>>;\n const tools: Record<string, Tool<any, any, any, any>> = {};\n for (const [name, tool] of Object.entries(factoryTools)) {\n if (EXCLUDED_TOOLS.has(name)) continue;\n // Starting a sub-session needs a real parent session row to file it under.\n if (name === 'factory_start_session' && options.persistedSession === false) continue;\n tools[name] = tool;\n }\n Object.assign(tools, createSearchFetchTools(scope, deps, factoryTools.factory_inspect_work_item));\n for (const [name, tool] of Object.entries(tools)) {\n const annotations = FACTORY_TOOL_ANNOTATIONS[name];\n if (annotations) tool.mcp = { ...tool.mcp, annotations };\n }\n return tools;\n}\n\nfunction resourceMetadataUrl(deps: FactoryMcpRoutesDeps, mcpPath: string): string {\n return `${deps.publicOrigin}${PROTECTED_RESOURCE_PREFIX}${mcpPath}`;\n}\n\nfunction unauthorized(deps: FactoryMcpRoutesDeps, mcpPath: string, error = 'unauthorized'): Response {\n return new Response(JSON.stringify({ error }), {\n status: 401,\n headers: {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': `Bearer resource_metadata=\"${resourceMetadataUrl(deps, mcpPath)}\"`,\n },\n });\n}\n\nasync function handleMcp(deps: FactoryMcpRoutesDeps, c: Context): Promise<Response> {\n const factoryProjectId = c.req.param('projectId') ?? '';\n const mcpPath = new URL(c.req.url).pathname;\n\n await deps.auth.ensureUser(c);\n const tenant = deps.auth.tenant(c);\n if (!tenant) return unauthorized(deps, mcpPath);\n if (!tenant.orgId) return c.json({ error: 'organization_required' }, 403);\n\n const project = await deps.projects.get({ orgId: tenant.orgId, id: factoryProjectId });\n if (!project) return c.json({ error: 'not_found' }, 404);\n\n const { sessionId, persisted } = await ensureConnectorSession(deps, {\n orgId: tenant.orgId,\n userId: tenant.userId,\n factoryProjectId,\n });\n const actorProfile = auditActorProfile(getFactoryAuthUser(c));\n const scope: FactoryToolScope = {\n orgId: tenant.orgId,\n factoryProjectId,\n userId: tenant.userId,\n sessionId,\n // A user session's memory lives under its owner.\n resourceId: tenant.userId,\n threadId: sessionId,\n kind: 'user',\n // A signed-in person is driving the client: the same reach as a web UI turn.\n interactive: true,\n ...(actorProfile ? { actorProfile } : {}),\n };\n\n const server = new MCPServer({\n id: `factory-${factoryProjectId}`,\n name: `${project.name ?? 'Mastra'} Factory`,\n version: FACTORY_MCP_SERVER_VERSION,\n description: 'Manage work items, sessions and decisions in a Mastra Factory.',\n instructions: FACTORY_MCP_INSTRUCTIONS,\n // VS Code and Cursor still open with 2025-era `initialize`; serve them statelessly.\n legacy: 'stateless',\n tools: createFactoryMcpTools(scope, deps, { persistedSession: persisted }),\n events: {\n 'factory.activity': factoryActivityEvent({\n orgId: tenant.orgId,\n factoryProjectId,\n audit: deps.tools.audit,\n workItems: deps.tools.workItems,\n sessions: deps.tools.sessions,\n viewer: { orgId: tenant.orgId, userId: tenant.userId },\n }),\n },\n });\n\n const { req, res } = toReqRes(c.req.raw);\n const done = server\n .startHTTP({ url: new URL(c.req.url), httpPath: mcpPath, req, res })\n .catch(error => {\n console.warn('[factory] MCP request failed:', error);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null }),\n );\n }\n })\n .finally(() => void server.close());\n const response = propagateClientDisconnect(await toFetchResponse(res), res);\n if (res.writableEnded) await done;\n return response;\n}\n\n/**\n * The Factory's MCP endpoint: Streamable HTTP at\n * `/web/factory/projects/:projectId/mcp`, plus its RFC 9728 protected-resource\n * metadata. Callers sign in with OAuth through the Factory's auth provider and\n * get the tools a web UI session would, under the same permissions.\n */\nexport function buildFactoryMcpRoutes(deps: FactoryMcpRoutesDeps): ApiRoute[] {\n const handler = (c: unknown) => handleMcp(deps, c as Context);\n return [\n ...(['POST', 'GET', 'DELETE'] as const).map(method =>\n registerApiRoute(FACTORY_MCP_PATH, { method, requiresAuth: false, handler }),\n ),\n registerApiRoute(`${PROTECTED_RESOURCE_PREFIX}${FACTORY_MCP_PATH}`, {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const mcpPath = new URL(c.req.url).pathname.slice(PROTECTED_RESOURCE_PREFIX.length);\n return c.json({\n resource: `${deps.publicOrigin}${mcpPath}`,\n authorization_servers: deps.authorizationServers,\n bearer_methods_supported: ['header'],\n resource_name: 'Mastra Factory',\n });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAa,mBAAmB;AAChC,MAAM,4BAA4B;;;;;AAMlC,MAAM,iCAAiB,IAAI,IAAI,CAAC,wBAAwB,CAAC;;;;;AAmBzD,MAAM,6BAA6B;;AAGnC,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;AAGV,MAAa,oCAAoC;AAEjD,SAAgB,+BACd,cACA,QACA,MAA0C,QAAQ,KACxC;CACV,IAAI,QAAQ,sBAAsB,QAAQ,OAAO,OAAO;CACxD,MAAM,UAAU,IAAI,yCAAyC,KAAK;CAClE,IAAI,SAAS,OAAO,CAAC,OAAO;CAC5B,IAAI,iBAAA,iBAAyC,OAAO,CAAC,iCAAiC;CACtF,OAAO,CAAC;AACV;;AA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,CAAC,CAAW,KAAI,WAC1C,iBAAiB,kBAAkB;EAAE;EAAQ,cAAc;EAAO;CAAQ,CAAC,CAC7E,GACA,iBAAiB,GAAG,4BAA4B,oBAAoB;EAClE,QAAQ;EACR,cAAc;EACd,UAAS,MAAK;GACZ,MAAM,UAAU,IAAI,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,EAAgC;GAClF,OAAO,EAAE,KAAK;IACZ,UAAU,GAAG,KAAK,eAAe;IACjC,uBAAuB,KAAK;IAC5B,0BAA0B,CAAC,QAAQ;IACnC,eAAe;GACjB,CAAC;EACH;CACF,CAAC,CACH;AACF"}
@@ -9,7 +9,30 @@ export interface BoardSnapshot {
9
9
  * polling an unchanged board shares one serialization and one gzip, and its
10
10
  * ETag lets the browser revalidate instead of downloading the board again.
11
11
  */
12
- export declare function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, runningSessionIds: readonly string[], parkedSessionIds: readonly string[]): BoardSnapshot;
12
+ export declare function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, runningSessionIds: readonly string[], parkedSessionIds: readonly string[], cursor?: string): BoardSnapshot;
13
+ /**
14
+ * The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of
15
+ * their body, not by the board version: a write to a card outside the scope leaves it unchanged,
16
+ * so the tab gets a 304. A caller that passes the same list again shares its serialization.
17
+ * `total` is how many cards matched when `items` is only the first of them.
18
+ */
19
+ export declare function scopedSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, runningSessionIds: readonly string[], parkedSessionIds: readonly string[], total?: number): BoardSnapshot;
20
+ /** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */
21
+ export declare function movedBody(body: unknown): Pick<BoardSnapshot, 'json' | 'gzipped'>;
22
+ /**
23
+ * A computed answer's wire body, named by a hash of itself: a reader that kept it revalidates
24
+ * instead of downloading it again.
25
+ */
26
+ export declare function hashedBody(body: unknown): BoardSnapshot;
27
+ /**
28
+ * An answer whose `names` hold the version of every card body `bodies` adds: its ETag is a hash of
29
+ * `names`, and the bodies are serialized only for a reader that does not hold the answer.
30
+ */
31
+ export declare function namedBody(names: object, bodies?: () => object): BoardSnapshot;
32
+ /** {@link boardCheck} of a cached list, computed once for every reader that sends its cursor. */
33
+ export declare function listCheck(items: readonly Card[]): string;
34
+ /** Names a text: a reader holding another text holds another name. */
35
+ export declare function sha1(text: string): string;
13
36
  /** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */
14
37
  export declare function matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean;
15
38
  //# sourceMappingURL=board-snapshot.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"board-snapshot.d.ts","sourceRoot":"","sources":["../../src/routes/board-snapshot.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAWlE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC5B;AAMD;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC/B,iBAAiB,EAAE,SAAS,MAAM,EAAE,EACpC,gBAAgB,EAAE,SAAS,MAAM,EAAE,GAClC,aAAa,CAef;AAED,uFAAuF;AACvF,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAIlF"}
1
+ {"version":3,"file":"board-snapshot.d.ts","sourceRoot":"","sources":["../../src/routes/board-snapshot.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAYlE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;I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