corporateai 0.0.1

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 (704) hide show
  1. package/.dockerignore +10 -0
  2. package/.env.example +3 -0
  3. package/.github/workflows/publish-cli.yml +49 -0
  4. package/.mailmap +1 -0
  5. package/AGENTS.md +148 -0
  6. package/CONTRIBUTING.md +75 -0
  7. package/Dockerfile +59 -0
  8. package/Dockerfile.onboard-smoke +42 -0
  9. package/LICENSE +21 -0
  10. package/README.md +93 -0
  11. package/cli/esbuild.config.mjs +11 -0
  12. package/cli/package.json +24 -0
  13. package/cli/scripts/build-cli.mjs +5 -0
  14. package/cli/src/index.ts +27 -0
  15. package/docker-compose.quickstart.yml +18 -0
  16. package/docker-compose.untrusted-review.yml +33 -0
  17. package/docker-compose.yml +38 -0
  18. package/package.json +56 -0
  19. package/patches/embedded-postgres@18.1.0-beta.16.patch +0 -0
  20. package/pnpm-workspace.yaml +4 -0
  21. package/releases/.gitkeep +0 -0
  22. package/releases/v0.0.1.md +36 -0
  23. package/releases/v0.2.7.md +15 -0
  24. package/releases/v0.3.0.md +54 -0
  25. package/releases/v0.3.1.md +55 -0
  26. package/releases/v2026.318.0.md +66 -0
  27. package/releases/v2026.325.0.md +78 -0
  28. package/report/2026-03-13-08-46-token-optimization-implementation.md +48 -0
  29. package/scripts/backup-db.sh +17 -0
  30. package/scripts/build-npm.sh +80 -0
  31. package/scripts/check-forbidden-tokens.mjs +115 -0
  32. package/scripts/clean-onboard-git.sh +14 -0
  33. package/scripts/clean-onboard-npm.sh +13 -0
  34. package/scripts/clean-onboard-ref.sh +86 -0
  35. package/scripts/create-github-release.sh +99 -0
  36. package/scripts/dev-runner-paths.mjs +38 -0
  37. package/scripts/dev-runner.mjs +606 -0
  38. package/scripts/docker-onboard-smoke.sh +306 -0
  39. package/scripts/ensure-plugin-build-deps.mjs +47 -0
  40. package/scripts/generate-company-assets.ts +365 -0
  41. package/scripts/generate-npm-package-json.mjs +113 -0
  42. package/scripts/generate-org-chart-images.ts +694 -0
  43. package/scripts/generate-org-chart-satori-comparison.ts +225 -0
  44. package/scripts/generate-ui-package-json.mjs +31 -0
  45. package/scripts/kill-dev.sh +71 -0
  46. package/scripts/migrate-inline-env-secrets.ts +126 -0
  47. package/scripts/prepare-server-ui-dist.sh +22 -0
  48. package/scripts/provision-worktree.sh +333 -0
  49. package/scripts/release-lib.sh +306 -0
  50. package/scripts/release-package-map.mjs +169 -0
  51. package/scripts/release.sh +312 -0
  52. package/scripts/rollback-latest.sh +111 -0
  53. package/scripts/smoke/openclaw-docker-ui.sh +329 -0
  54. package/scripts/smoke/openclaw-gateway-e2e.sh +954 -0
  55. package/scripts/smoke/openclaw-join.sh +295 -0
  56. package/scripts/smoke/openclaw-sse-standalone.sh +146 -0
  57. package/scripts/workspace-compat.mjs +60 -0
  58. package/server/CHANGELOG.md +130 -0
  59. package/server/package.json +96 -0
  60. package/server/scripts/copy-onboarding-assets.mjs +10 -0
  61. package/server/scripts/dev-watch.ts +33 -0
  62. package/server/src/__tests__/activity-routes.test.ts +70 -0
  63. package/server/src/__tests__/adapter-models.test.ts +105 -0
  64. package/server/src/__tests__/adapter-session-codecs.test.ts +194 -0
  65. package/server/src/__tests__/agent-auth-jwt.test.ts +79 -0
  66. package/server/src/__tests__/agent-instructions-routes.test.ts +318 -0
  67. package/server/src/__tests__/agent-instructions-service.test.ts +361 -0
  68. package/server/src/__tests__/agent-permissions-routes.test.ts +275 -0
  69. package/server/src/__tests__/agent-shortname-collision.test.ts +69 -0
  70. package/server/src/__tests__/agent-skill-contract.test.ts +50 -0
  71. package/server/src/__tests__/agent-skills-routes.test.ts +462 -0
  72. package/server/src/__tests__/app-hmr-port.test.ts +19 -0
  73. package/server/src/__tests__/approval-routes-idempotency.test.ts +110 -0
  74. package/server/src/__tests__/approvals-service.test.ts +107 -0
  75. package/server/src/__tests__/assets.test.ts +250 -0
  76. package/server/src/__tests__/attachment-types.test.ts +97 -0
  77. package/server/src/__tests__/board-mutation-guard.test.ts +105 -0
  78. package/server/src/__tests__/budgets-service.test.ts +311 -0
  79. package/server/src/__tests__/claude-local-adapter-environment.test.ts +92 -0
  80. package/server/src/__tests__/claude-local-adapter.test.ts +31 -0
  81. package/server/src/__tests__/claude-local-skill-sync.test.ts +111 -0
  82. package/server/src/__tests__/cli-auth-routes.test.ts +230 -0
  83. package/server/src/__tests__/codex-local-adapter-environment.test.ts +143 -0
  84. package/server/src/__tests__/codex-local-adapter.test.ts +253 -0
  85. package/server/src/__tests__/codex-local-execute.test.ts +391 -0
  86. package/server/src/__tests__/codex-local-skill-injection.test.ts +175 -0
  87. package/server/src/__tests__/codex-local-skill-sync.test.ts +123 -0
  88. package/server/src/__tests__/companies-route-path-guard.test.ts +56 -0
  89. package/server/src/__tests__/company-branding-route.test.ts +196 -0
  90. package/server/src/__tests__/company-portability-routes.test.ts +175 -0
  91. package/server/src/__tests__/company-portability.test.ts +2186 -0
  92. package/server/src/__tests__/company-skills-routes.test.ts +113 -0
  93. package/server/src/__tests__/company-skills.test.ts +229 -0
  94. package/server/src/__tests__/costs-service.test.ts +226 -0
  95. package/server/src/__tests__/cursor-local-adapter-environment.test.ts +196 -0
  96. package/server/src/__tests__/cursor-local-adapter.test.ts +406 -0
  97. package/server/src/__tests__/cursor-local-execute.test.ts +263 -0
  98. package/server/src/__tests__/cursor-local-skill-injection.test.ts +104 -0
  99. package/server/src/__tests__/cursor-local-skill-sync.test.ts +145 -0
  100. package/server/src/__tests__/dev-runner-paths.test.ts +25 -0
  101. package/server/src/__tests__/dev-server-status.test.ts +66 -0
  102. package/server/src/__tests__/dev-watch-ignore.test.ts +42 -0
  103. package/server/src/__tests__/documents.test.ts +29 -0
  104. package/server/src/__tests__/error-handler.test.ts +53 -0
  105. package/server/src/__tests__/execution-workspace-policy.test.ts +170 -0
  106. package/server/src/__tests__/forbidden-tokens.test.ts +77 -0
  107. package/server/src/__tests__/gemini-local-adapter-environment.test.ts +135 -0
  108. package/server/src/__tests__/gemini-local-adapter.test.ts +190 -0
  109. package/server/src/__tests__/gemini-local-execute.test.ts +172 -0
  110. package/server/src/__tests__/gemini-local-skill-sync.test.ts +90 -0
  111. package/server/src/__tests__/health.test.ts +16 -0
  112. package/server/src/__tests__/heartbeat-process-recovery.test.ts +256 -0
  113. package/server/src/__tests__/heartbeat-run-summary.test.ts +33 -0
  114. package/server/src/__tests__/heartbeat-workspace-session.test.ts +334 -0
  115. package/server/src/__tests__/helpers/embedded-postgres.ts +7 -0
  116. package/server/src/__tests__/hire-hook.test.ts +181 -0
  117. package/server/src/__tests__/instance-settings-routes.test.ts +156 -0
  118. package/server/src/__tests__/invite-accept-gateway-defaults.test.ts +119 -0
  119. package/server/src/__tests__/invite-accept-replay.test.ts +92 -0
  120. package/server/src/__tests__/invite-expiry.test.ts +10 -0
  121. package/server/src/__tests__/invite-join-grants.test.ts +57 -0
  122. package/server/src/__tests__/invite-join-manager.test.ts +33 -0
  123. package/server/src/__tests__/invite-onboarding-text.test.ts +116 -0
  124. package/server/src/__tests__/issue-comment-reopen-routes.test.ts +146 -0
  125. package/server/src/__tests__/issue-goal-fallback.test.ts +99 -0
  126. package/server/src/__tests__/issues-checkout-wakeup.test.ts +48 -0
  127. package/server/src/__tests__/issues-goal-context-routes.test.ts +187 -0
  128. package/server/src/__tests__/issues-service.test.ts +317 -0
  129. package/server/src/__tests__/issues-user-context.test.ts +113 -0
  130. package/server/src/__tests__/log-redaction.test.ts +74 -0
  131. package/server/src/__tests__/monthly-spend-service.test.ts +90 -0
  132. package/server/src/__tests__/normalize-agent-mention-token.test.ts +41 -0
  133. package/server/src/__tests__/openclaw-gateway-adapter.test.ts +626 -0
  134. package/server/src/__tests__/openclaw-invite-prompt-route.test.ts +192 -0
  135. package/server/src/__tests__/opencode-local-adapter-environment.test.ts +97 -0
  136. package/server/src/__tests__/opencode-local-adapter.test.ts +226 -0
  137. package/server/src/__tests__/opencode-local-skill-sync.test.ts +91 -0
  138. package/server/src/__tests__/paperclip-env.test.ts +58 -0
  139. package/server/src/__tests__/paperclip-skill-utils.test.ts +63 -0
  140. package/server/src/__tests__/pi-local-adapter-environment.test.ts +102 -0
  141. package/server/src/__tests__/pi-local-skill-sync.test.ts +95 -0
  142. package/server/src/__tests__/plugin-dev-watcher.test.ts +68 -0
  143. package/server/src/__tests__/plugin-worker-manager.test.ts +43 -0
  144. package/server/src/__tests__/private-hostname-guard.test.ts +56 -0
  145. package/server/src/__tests__/project-shortname-resolution.test.ts +45 -0
  146. package/server/src/__tests__/quota-windows-service.test.ts +56 -0
  147. package/server/src/__tests__/quota-windows.test.ts +1109 -0
  148. package/server/src/__tests__/redaction.test.ts +66 -0
  149. package/server/src/__tests__/routines-e2e.test.ts +276 -0
  150. package/server/src/__tests__/routines-routes.test.ts +271 -0
  151. package/server/src/__tests__/routines-service.test.ts +424 -0
  152. package/server/src/__tests__/storage-local-provider.test.ts +78 -0
  153. package/server/src/__tests__/ui-branding.test.ts +82 -0
  154. package/server/src/__tests__/work-products.test.ts +95 -0
  155. package/server/src/__tests__/workspace-runtime.test.ts +1131 -0
  156. package/server/src/__tests__/worktree-config.test.ts +426 -0
  157. package/server/src/adapters/codex-models.ts +105 -0
  158. package/server/src/adapters/cursor-models.ts +171 -0
  159. package/server/src/adapters/http/execute.ts +42 -0
  160. package/server/src/adapters/http/index.ts +21 -0
  161. package/server/src/adapters/http/test.ts +116 -0
  162. package/server/src/adapters/index.ts +18 -0
  163. package/server/src/adapters/process/execute.ts +77 -0
  164. package/server/src/adapters/process/index.ts +24 -0
  165. package/server/src/adapters/process/test.ts +89 -0
  166. package/server/src/adapters/registry.ts +225 -0
  167. package/server/src/adapters/server-utils-compat.ts +57 -0
  168. package/server/src/adapters/types.ts +30 -0
  169. package/server/src/adapters/utils.ts +48 -0
  170. package/server/src/agent-auth-jwt.ts +141 -0
  171. package/server/src/app.ts +321 -0
  172. package/server/src/attachment-types.ts +74 -0
  173. package/server/src/auth/better-auth.ts +148 -0
  174. package/server/src/board-claim.ts +150 -0
  175. package/server/src/config-file.ts +17 -0
  176. package/server/src/config.ts +260 -0
  177. package/server/src/dev-server-status.ts +103 -0
  178. package/server/src/dev-watch-ignore.ts +36 -0
  179. package/server/src/errors.ts +34 -0
  180. package/server/src/home-paths.ts +95 -0
  181. package/server/src/index.ts +799 -0
  182. package/server/src/log-redaction.ts +146 -0
  183. package/server/src/middleware/auth.ts +178 -0
  184. package/server/src/middleware/board-mutation-guard.ts +66 -0
  185. package/server/src/middleware/error-handler.ts +71 -0
  186. package/server/src/middleware/index.ts +3 -0
  187. package/server/src/middleware/logger.ts +90 -0
  188. package/server/src/middleware/private-hostname-guard.ts +92 -0
  189. package/server/src/middleware/validate.ts +9 -0
  190. package/server/src/onboarding-assets/ceo/AGENTS.md +54 -0
  191. package/server/src/onboarding-assets/ceo/HEARTBEAT.md +72 -0
  192. package/server/src/onboarding-assets/ceo/SOUL.md +33 -0
  193. package/server/src/onboarding-assets/ceo/TOOLS.md +3 -0
  194. package/server/src/onboarding-assets/default/AGENTS.md +3 -0
  195. package/server/src/paths.ts +34 -0
  196. package/server/src/realtime/live-events-ws.ts +274 -0
  197. package/server/src/redaction.ts +59 -0
  198. package/server/src/routes/access.ts +2888 -0
  199. package/server/src/routes/activity.ts +89 -0
  200. package/server/src/routes/agents.ts +2313 -0
  201. package/server/src/routes/approvals.ts +346 -0
  202. package/server/src/routes/assets.ts +341 -0
  203. package/server/src/routes/authz.ts +52 -0
  204. package/server/src/routes/companies.ts +343 -0
  205. package/server/src/routes/company-skills.ts +300 -0
  206. package/server/src/routes/costs.ts +335 -0
  207. package/server/src/routes/dashboard.ts +19 -0
  208. package/server/src/routes/execution-workspaces.ts +182 -0
  209. package/server/src/routes/goals.ts +107 -0
  210. package/server/src/routes/health.ts +94 -0
  211. package/server/src/routes/index.ts +17 -0
  212. package/server/src/routes/instance-settings.ts +95 -0
  213. package/server/src/routes/issues-checkout-wakeup.ts +14 -0
  214. package/server/src/routes/issues.ts +1680 -0
  215. package/server/src/routes/llms.ts +86 -0
  216. package/server/src/routes/org-chart-svg.ts +777 -0
  217. package/server/src/routes/plugin-ui-static.ts +497 -0
  218. package/server/src/routes/plugins.ts +2220 -0
  219. package/server/src/routes/projects.ts +295 -0
  220. package/server/src/routes/routines.ts +300 -0
  221. package/server/src/routes/secrets.ts +166 -0
  222. package/server/src/routes/sidebar-badges.ts +52 -0
  223. package/server/src/secrets/external-stub-providers.ts +32 -0
  224. package/server/src/secrets/local-encrypted-provider.ts +135 -0
  225. package/server/src/secrets/provider-registry.ts +31 -0
  226. package/server/src/secrets/types.ts +23 -0
  227. package/server/src/services/access.ts +381 -0
  228. package/server/src/services/activity-log.ts +95 -0
  229. package/server/src/services/activity.ts +164 -0
  230. package/server/src/services/agent-instructions.ts +735 -0
  231. package/server/src/services/agent-permissions.ts +27 -0
  232. package/server/src/services/agents.ts +694 -0
  233. package/server/src/services/approvals.ts +273 -0
  234. package/server/src/services/assets.ts +23 -0
  235. package/server/src/services/board-auth.ts +355 -0
  236. package/server/src/services/budgets.ts +959 -0
  237. package/server/src/services/companies.ts +313 -0
  238. package/server/src/services/company-export-readme.ts +173 -0
  239. package/server/src/services/company-portability.ts +4263 -0
  240. package/server/src/services/company-skills.ts +2356 -0
  241. package/server/src/services/costs.ts +365 -0
  242. package/server/src/services/cron.ts +373 -0
  243. package/server/src/services/dashboard.ts +110 -0
  244. package/server/src/services/default-agent-instructions.ts +27 -0
  245. package/server/src/services/documents.ts +434 -0
  246. package/server/src/services/execution-workspace-policy.ts +210 -0
  247. package/server/src/services/execution-workspaces.ts +100 -0
  248. package/server/src/services/finance.ts +135 -0
  249. package/server/src/services/goals.ts +81 -0
  250. package/server/src/services/heartbeat-run-summary.ts +35 -0
  251. package/server/src/services/heartbeat.ts +3863 -0
  252. package/server/src/services/hire-hook.ts +114 -0
  253. package/server/src/services/index.ts +32 -0
  254. package/server/src/services/instance-settings.ts +138 -0
  255. package/server/src/services/issue-approvals.ts +175 -0
  256. package/server/src/services/issue-assignment-wakeup.ts +48 -0
  257. package/server/src/services/issue-goal-fallback.ts +56 -0
  258. package/server/src/services/issues.ts +1828 -0
  259. package/server/src/services/live-events.ts +55 -0
  260. package/server/src/services/plugin-capability-validator.ts +450 -0
  261. package/server/src/services/plugin-config-validator.ts +55 -0
  262. package/server/src/services/plugin-dev-watcher.ts +339 -0
  263. package/server/src/services/plugin-event-bus.ts +413 -0
  264. package/server/src/services/plugin-host-service-cleanup.ts +59 -0
  265. package/server/src/services/plugin-host-services.ts +1132 -0
  266. package/server/src/services/plugin-job-coordinator.ts +261 -0
  267. package/server/src/services/plugin-job-scheduler.ts +753 -0
  268. package/server/src/services/plugin-job-store.ts +466 -0
  269. package/server/src/services/plugin-lifecycle.ts +822 -0
  270. package/server/src/services/plugin-loader.ts +1955 -0
  271. package/server/src/services/plugin-log-retention.ts +87 -0
  272. package/server/src/services/plugin-manifest-validator.ts +164 -0
  273. package/server/src/services/plugin-registry.ts +683 -0
  274. package/server/src/services/plugin-runtime-sandbox.ts +222 -0
  275. package/server/src/services/plugin-secrets-handler.ts +355 -0
  276. package/server/src/services/plugin-state-store.ts +238 -0
  277. package/server/src/services/plugin-stream-bus.ts +81 -0
  278. package/server/src/services/plugin-tool-dispatcher.ts +449 -0
  279. package/server/src/services/plugin-tool-registry.ts +450 -0
  280. package/server/src/services/plugin-worker-manager.ts +1343 -0
  281. package/server/src/services/projects.ts +860 -0
  282. package/server/src/services/quota-windows.ts +65 -0
  283. package/server/src/services/routines.ts +1269 -0
  284. package/server/src/services/run-log-store.ts +156 -0
  285. package/server/src/services/secrets.ts +370 -0
  286. package/server/src/services/sidebar-badges.ts +56 -0
  287. package/server/src/services/work-products.ts +124 -0
  288. package/server/src/services/workspace-operation-log-store.ts +156 -0
  289. package/server/src/services/workspace-operations.ts +262 -0
  290. package/server/src/services/workspace-runtime.ts +1565 -0
  291. package/server/src/startup-banner.ts +176 -0
  292. package/server/src/storage/index.ts +35 -0
  293. package/server/src/storage/local-disk-provider.ts +89 -0
  294. package/server/src/storage/provider-registry.ts +18 -0
  295. package/server/src/storage/s3-provider.ts +153 -0
  296. package/server/src/storage/service.ts +131 -0
  297. package/server/src/storage/types.ts +63 -0
  298. package/server/src/ui-branding.ts +217 -0
  299. package/server/src/version.ts +10 -0
  300. package/server/src/worktree-config.ts +468 -0
  301. package/server/tsconfig.json +9 -0
  302. package/server/vitest.config.ts +7 -0
  303. package/skills/paperclip/SKILL.md +365 -0
  304. package/skills/paperclip/references/api-reference.md +647 -0
  305. package/skills/paperclip/references/company-skills.md +193 -0
  306. package/skills/paperclip-create-agent/SKILL.md +142 -0
  307. package/skills/paperclip-create-agent/references/api-reference.md +105 -0
  308. package/skills/paperclip-create-plugin/SKILL.md +102 -0
  309. package/skills/para-memory-files/SKILL.md +104 -0
  310. package/skills/para-memory-files/references/schemas.md +35 -0
  311. package/tests/e2e/onboarding.spec.ts +142 -0
  312. package/tests/e2e/playwright.config.ts +35 -0
  313. package/tests/release-smoke/docker-auth-onboarding.spec.ts +141 -0
  314. package/tests/release-smoke/playwright.config.ts +28 -0
  315. package/tsconfig.base.json +18 -0
  316. package/tsconfig.json +18 -0
  317. package/ui/README.md +12 -0
  318. package/ui/components.json +21 -0
  319. package/ui/index.html +47 -0
  320. package/ui/package.json +73 -0
  321. package/ui/public/android-chrome-192x192.png +0 -0
  322. package/ui/public/android-chrome-512x512.png +0 -0
  323. package/ui/public/apple-touch-icon.png +0 -0
  324. package/ui/public/brands/opencode-logo-dark-square.svg +18 -0
  325. package/ui/public/brands/opencode-logo-light-square.svg +18 -0
  326. package/ui/public/favicon-16x16.png +0 -0
  327. package/ui/public/favicon-32x32.png +0 -0
  328. package/ui/public/favicon.ico +0 -0
  329. package/ui/public/favicon.svg +9 -0
  330. package/ui/public/site.webmanifest +30 -0
  331. package/ui/public/sprites/1-D-1.png +0 -0
  332. package/ui/public/sprites/1-D-2.png +0 -0
  333. package/ui/public/sprites/1-D-3.png +0 -0
  334. package/ui/public/sprites/1-L-1.png +0 -0
  335. package/ui/public/sprites/1-R-1.png +0 -0
  336. package/ui/public/sprites/10-D-1.png +0 -0
  337. package/ui/public/sprites/10-D-2.png +0 -0
  338. package/ui/public/sprites/10-D-3.png +0 -0
  339. package/ui/public/sprites/10-L-1.png +0 -0
  340. package/ui/public/sprites/10-R-1.png +0 -0
  341. package/ui/public/sprites/11-D-1.png +0 -0
  342. package/ui/public/sprites/11-D-2.png +0 -0
  343. package/ui/public/sprites/11-D-3.png +0 -0
  344. package/ui/public/sprites/11-L-1.png +0 -0
  345. package/ui/public/sprites/11-R-1.png +0 -0
  346. package/ui/public/sprites/12-D-1.png +0 -0
  347. package/ui/public/sprites/12-D-2.png +0 -0
  348. package/ui/public/sprites/12-D-3.png +0 -0
  349. package/ui/public/sprites/12-L-1.png +0 -0
  350. package/ui/public/sprites/12-R-1.png +0 -0
  351. package/ui/public/sprites/13-D-1.png +0 -0
  352. package/ui/public/sprites/13-D-2.png +0 -0
  353. package/ui/public/sprites/13-D-3.png +0 -0
  354. package/ui/public/sprites/13-L-1.png +0 -0
  355. package/ui/public/sprites/13-R-1.png +0 -0
  356. package/ui/public/sprites/14-D-1.png +0 -0
  357. package/ui/public/sprites/14-D-2.png +0 -0
  358. package/ui/public/sprites/14-D-3.png +0 -0
  359. package/ui/public/sprites/14-L-1.png +0 -0
  360. package/ui/public/sprites/14-R-1.png +0 -0
  361. package/ui/public/sprites/2-D-1.png +0 -0
  362. package/ui/public/sprites/2-D-2.png +0 -0
  363. package/ui/public/sprites/2-D-3.png +0 -0
  364. package/ui/public/sprites/2-L-1.png +0 -0
  365. package/ui/public/sprites/2-R-1.png +0 -0
  366. package/ui/public/sprites/3-D-1.png +0 -0
  367. package/ui/public/sprites/3-D-2.png +0 -0
  368. package/ui/public/sprites/3-D-3.png +0 -0
  369. package/ui/public/sprites/3-L-1.png +0 -0
  370. package/ui/public/sprites/3-R-1.png +0 -0
  371. package/ui/public/sprites/4-D-1.png +0 -0
  372. package/ui/public/sprites/4-D-2.png +0 -0
  373. package/ui/public/sprites/4-D-3.png +0 -0
  374. package/ui/public/sprites/4-L-1.png +0 -0
  375. package/ui/public/sprites/4-R-1.png +0 -0
  376. package/ui/public/sprites/5-D-1.png +0 -0
  377. package/ui/public/sprites/5-D-2.png +0 -0
  378. package/ui/public/sprites/5-D-3.png +0 -0
  379. package/ui/public/sprites/5-L-1.png +0 -0
  380. package/ui/public/sprites/5-R-1.png +0 -0
  381. package/ui/public/sprites/6-D-1.png +0 -0
  382. package/ui/public/sprites/6-D-2.png +0 -0
  383. package/ui/public/sprites/6-D-3.png +0 -0
  384. package/ui/public/sprites/6-L-1.png +0 -0
  385. package/ui/public/sprites/6-R-1.png +0 -0
  386. package/ui/public/sprites/7-D-1.png +0 -0
  387. package/ui/public/sprites/7-D-2.png +0 -0
  388. package/ui/public/sprites/7-D-3.png +0 -0
  389. package/ui/public/sprites/7-L-1.png +0 -0
  390. package/ui/public/sprites/7-R-1.png +0 -0
  391. package/ui/public/sprites/8-D-1.png +0 -0
  392. package/ui/public/sprites/8-D-2.png +0 -0
  393. package/ui/public/sprites/8-D-3.png +0 -0
  394. package/ui/public/sprites/8-L-1.png +0 -0
  395. package/ui/public/sprites/8-R-1.png +0 -0
  396. package/ui/public/sprites/9-D-1.png +0 -0
  397. package/ui/public/sprites/9-D-2.png +0 -0
  398. package/ui/public/sprites/9-D-3.png +0 -0
  399. package/ui/public/sprites/9-L-1.png +0 -0
  400. package/ui/public/sprites/9-R-1.png +0 -0
  401. package/ui/public/sprites/ceo-lobster.png +0 -0
  402. package/ui/public/sw.js +42 -0
  403. package/ui/public/worktree-favicon-16x16.png +0 -0
  404. package/ui/public/worktree-favicon-32x32.png +0 -0
  405. package/ui/public/worktree-favicon.ico +0 -0
  406. package/ui/public/worktree-favicon.svg +9 -0
  407. package/ui/src/App.tsx +354 -0
  408. package/ui/src/adapters/claude-local/config-fields.tsx +138 -0
  409. package/ui/src/adapters/claude-local/index.ts +13 -0
  410. package/ui/src/adapters/codex-local/config-fields.tsx +104 -0
  411. package/ui/src/adapters/codex-local/index.ts +13 -0
  412. package/ui/src/adapters/cursor/config-fields.tsx +49 -0
  413. package/ui/src/adapters/cursor/index.ts +13 -0
  414. package/ui/src/adapters/gemini-local/config-fields.tsx +51 -0
  415. package/ui/src/adapters/gemini-local/index.ts +13 -0
  416. package/ui/src/adapters/http/build-config.ts +9 -0
  417. package/ui/src/adapters/http/config-fields.tsx +38 -0
  418. package/ui/src/adapters/http/index.ts +12 -0
  419. package/ui/src/adapters/http/parse-stdout.ts +5 -0
  420. package/ui/src/adapters/index.ts +9 -0
  421. package/ui/src/adapters/local-workspace-runtime-fields.tsx +5 -0
  422. package/ui/src/adapters/openclaw-gateway/config-fields.tsx +237 -0
  423. package/ui/src/adapters/openclaw-gateway/index.ts +13 -0
  424. package/ui/src/adapters/opencode-local/config-fields.tsx +72 -0
  425. package/ui/src/adapters/opencode-local/index.ts +13 -0
  426. package/ui/src/adapters/pi-local/config-fields.tsx +49 -0
  427. package/ui/src/adapters/pi-local/index.ts +13 -0
  428. package/ui/src/adapters/process/build-config.ts +18 -0
  429. package/ui/src/adapters/process/config-fields.tsx +77 -0
  430. package/ui/src/adapters/process/index.ts +12 -0
  431. package/ui/src/adapters/process/parse-stdout.ts +5 -0
  432. package/ui/src/adapters/registry.ts +34 -0
  433. package/ui/src/adapters/runtime-json-fields.tsx +122 -0
  434. package/ui/src/adapters/transcript.test.ts +30 -0
  435. package/ui/src/adapters/transcript.ts +62 -0
  436. package/ui/src/adapters/types.ts +34 -0
  437. package/ui/src/api/access.ts +160 -0
  438. package/ui/src/api/activity.ts +37 -0
  439. package/ui/src/api/agents.ts +194 -0
  440. package/ui/src/api/approvals.ts +25 -0
  441. package/ui/src/api/assets.ts +30 -0
  442. package/ui/src/api/auth.ts +74 -0
  443. package/ui/src/api/budgets.ts +21 -0
  444. package/ui/src/api/client.ts +50 -0
  445. package/ui/src/api/companies.ts +59 -0
  446. package/ui/src/api/companySkills.ts +55 -0
  447. package/ui/src/api/costs.ts +60 -0
  448. package/ui/src/api/dashboard.ts +7 -0
  449. package/ui/src/api/execution-workspaces.ts +27 -0
  450. package/ui/src/api/goals.ts +12 -0
  451. package/ui/src/api/health.ts +41 -0
  452. package/ui/src/api/heartbeats.ts +62 -0
  453. package/ui/src/api/index.ts +18 -0
  454. package/ui/src/api/instanceSettings.ts +19 -0
  455. package/ui/src/api/issues.ts +115 -0
  456. package/ui/src/api/plugins.ts +424 -0
  457. package/ui/src/api/projects.ts +34 -0
  458. package/ui/src/api/routines.ts +59 -0
  459. package/ui/src/api/secrets.ts +26 -0
  460. package/ui/src/api/sidebarBadges.ts +7 -0
  461. package/ui/src/components/AccountingModelCard.tsx +69 -0
  462. package/ui/src/components/ActiveAgentsPanel.tsx +157 -0
  463. package/ui/src/components/ActivityCharts.tsx +264 -0
  464. package/ui/src/components/ActivityRow.tsx +147 -0
  465. package/ui/src/components/AgentActionButtons.tsx +51 -0
  466. package/ui/src/components/AgentConfigForm.tsx +1468 -0
  467. package/ui/src/components/AgentIconPicker.tsx +81 -0
  468. package/ui/src/components/AgentProperties.tsx +107 -0
  469. package/ui/src/components/ApprovalCard.tsx +107 -0
  470. package/ui/src/components/ApprovalPayload.tsx +134 -0
  471. package/ui/src/components/AsciiArtAnimation.tsx +355 -0
  472. package/ui/src/components/BillerSpendCard.tsx +146 -0
  473. package/ui/src/components/BreadcrumbBar.tsx +113 -0
  474. package/ui/src/components/BudgetIncidentCard.tsx +101 -0
  475. package/ui/src/components/BudgetPolicyCard.tsx +220 -0
  476. package/ui/src/components/BudgetSidebarMarker.tsx +13 -0
  477. package/ui/src/components/ClaudeSubscriptionPanel.tsx +141 -0
  478. package/ui/src/components/CodexSubscriptionPanel.tsx +158 -0
  479. package/ui/src/components/CommandPalette.tsx +239 -0
  480. package/ui/src/components/CommentThread.tsx +503 -0
  481. package/ui/src/components/CompanyPatternIcon.tsx +212 -0
  482. package/ui/src/components/CompanyRail.tsx +329 -0
  483. package/ui/src/components/CompanySwitcher.tsx +81 -0
  484. package/ui/src/components/CopyText.tsx +56 -0
  485. package/ui/src/components/DevRestartBanner.tsx +89 -0
  486. package/ui/src/components/EmptyState.tsx +27 -0
  487. package/ui/src/components/EntityRow.tsx +69 -0
  488. package/ui/src/components/FilterBar.tsx +39 -0
  489. package/ui/src/components/FinanceBillerCard.tsx +45 -0
  490. package/ui/src/components/FinanceKindCard.tsx +44 -0
  491. package/ui/src/components/FinanceTimelineCard.tsx +72 -0
  492. package/ui/src/components/GoalProperties.tsx +165 -0
  493. package/ui/src/components/GoalTree.tsx +118 -0
  494. package/ui/src/components/Identity.tsx +39 -0
  495. package/ui/src/components/InlineEditor.tsx +248 -0
  496. package/ui/src/components/InlineEntitySelector.tsx +206 -0
  497. package/ui/src/components/InstanceSidebar.tsx +53 -0
  498. package/ui/src/components/IssueDocumentsSection.tsx +892 -0
  499. package/ui/src/components/IssueProperties.tsx +621 -0
  500. package/ui/src/components/IssueRow.tsx +149 -0
  501. package/ui/src/components/IssueWorkspaceCard.tsx +404 -0
  502. package/ui/src/components/IssuesList.tsx +889 -0
  503. package/ui/src/components/JsonSchemaForm.tsx +1048 -0
  504. package/ui/src/components/KanbanBoard.tsx +275 -0
  505. package/ui/src/components/Layout.tsx +441 -0
  506. package/ui/src/components/LiveRunWidget.tsx +160 -0
  507. package/ui/src/components/MarkdownBody.test.tsx +50 -0
  508. package/ui/src/components/MarkdownBody.tsx +152 -0
  509. package/ui/src/components/MarkdownEditor.tsx +622 -0
  510. package/ui/src/components/MetricCard.tsx +53 -0
  511. package/ui/src/components/MobileBottomNav.tsx +123 -0
  512. package/ui/src/components/NewAgentDialog.tsx +223 -0
  513. package/ui/src/components/NewGoalDialog.tsx +283 -0
  514. package/ui/src/components/NewIssueDialog.tsx +1473 -0
  515. package/ui/src/components/NewProjectDialog.tsx +451 -0
  516. package/ui/src/components/OnboardingWizard.tsx +1392 -0
  517. package/ui/src/components/OpenCodeLogoIcon.tsx +22 -0
  518. package/ui/src/components/PackageFileTree.tsx +318 -0
  519. package/ui/src/components/PageSkeleton.tsx +180 -0
  520. package/ui/src/components/PageTabBar.tsx +45 -0
  521. package/ui/src/components/PathInstructionsModal.tsx +143 -0
  522. package/ui/src/components/PriorityIcon.tsx +77 -0
  523. package/ui/src/components/ProjectProperties.tsx +1127 -0
  524. package/ui/src/components/PropertiesPanel.tsx +29 -0
  525. package/ui/src/components/ProviderQuotaCard.tsx +417 -0
  526. package/ui/src/components/QuotaBar.tsx +65 -0
  527. package/ui/src/components/ReportsToPicker.tsx +127 -0
  528. package/ui/src/components/ScheduleEditor.tsx +344 -0
  529. package/ui/src/components/ScrollToBottom.tsx +79 -0
  530. package/ui/src/components/Sidebar.tsx +130 -0
  531. package/ui/src/components/SidebarAgents.tsx +146 -0
  532. package/ui/src/components/SidebarNavItem.tsx +92 -0
  533. package/ui/src/components/SidebarProjects.tsx +234 -0
  534. package/ui/src/components/SidebarSection.tsx +17 -0
  535. package/ui/src/components/StatusBadge.tsx +15 -0
  536. package/ui/src/components/StatusIcon.tsx +71 -0
  537. package/ui/src/components/SwipeToArchive.tsx +152 -0
  538. package/ui/src/components/ToastViewport.tsx +99 -0
  539. package/ui/src/components/WorktreeBanner.tsx +25 -0
  540. package/ui/src/components/agent-config-defaults.ts +31 -0
  541. package/ui/src/components/agent-config-primitives.tsx +476 -0
  542. package/ui/src/components/transcript/RunTranscriptView.test.tsx +84 -0
  543. package/ui/src/components/transcript/RunTranscriptView.tsx +1015 -0
  544. package/ui/src/components/transcript/useLiveRunTranscripts.ts +297 -0
  545. package/ui/src/components/ui/avatar.tsx +107 -0
  546. package/ui/src/components/ui/badge.tsx +48 -0
  547. package/ui/src/components/ui/breadcrumb.tsx +109 -0
  548. package/ui/src/components/ui/button.tsx +64 -0
  549. package/ui/src/components/ui/card.tsx +92 -0
  550. package/ui/src/components/ui/checkbox.tsx +32 -0
  551. package/ui/src/components/ui/collapsible.tsx +33 -0
  552. package/ui/src/components/ui/command.tsx +194 -0
  553. package/ui/src/components/ui/dialog.tsx +156 -0
  554. package/ui/src/components/ui/dropdown-menu.tsx +257 -0
  555. package/ui/src/components/ui/input.tsx +21 -0
  556. package/ui/src/components/ui/label.tsx +22 -0
  557. package/ui/src/components/ui/popover.tsx +88 -0
  558. package/ui/src/components/ui/scroll-area.tsx +56 -0
  559. package/ui/src/components/ui/select.tsx +188 -0
  560. package/ui/src/components/ui/separator.tsx +28 -0
  561. package/ui/src/components/ui/sheet.tsx +143 -0
  562. package/ui/src/components/ui/skeleton.tsx +13 -0
  563. package/ui/src/components/ui/tabs.tsx +89 -0
  564. package/ui/src/components/ui/textarea.tsx +18 -0
  565. package/ui/src/components/ui/tooltip.tsx +57 -0
  566. package/ui/src/components/visual-office/AgentAvatar.tsx +99 -0
  567. package/ui/src/components/visual-office/OfficeViewExact.tsx +417 -0
  568. package/ui/src/components/visual-office/i18n.ts +52 -0
  569. package/ui/src/components/visual-office/office-view/CliUsagePanel.tsx +240 -0
  570. package/ui/src/components/visual-office/office-view/VirtualPadOverlay.tsx +104 -0
  571. package/ui/src/components/visual-office/office-view/buildScene-break-room.ts +248 -0
  572. package/ui/src/components/visual-office/office-view/buildScene-ceo-hallway.ts +345 -0
  573. package/ui/src/components/visual-office/office-view/buildScene-department-agent.ts +242 -0
  574. package/ui/src/components/visual-office/office-view/buildScene-departments.ts +360 -0
  575. package/ui/src/components/visual-office/office-view/buildScene-final-layers.ts +113 -0
  576. package/ui/src/components/visual-office/office-view/buildScene-types.ts +91 -0
  577. package/ui/src/components/visual-office/office-view/buildScene.ts +232 -0
  578. package/ui/src/components/visual-office/office-view/drawing-core.ts +374 -0
  579. package/ui/src/components/visual-office/office-view/drawing-furniture-a.ts +338 -0
  580. package/ui/src/components/visual-office/office-view/drawing-furniture-b.ts +241 -0
  581. package/ui/src/components/visual-office/office-view/model.ts +301 -0
  582. package/ui/src/components/visual-office/office-view/officeTicker.ts +455 -0
  583. package/ui/src/components/visual-office/office-view/officeTickerRoomAndDelivery.ts +133 -0
  584. package/ui/src/components/visual-office/office-view/themes-locale.ts +460 -0
  585. package/ui/src/components/visual-office/office-view/useCliUsage.ts +37 -0
  586. package/ui/src/components/visual-office/office-view/useOfficeDeliveryEffects.ts +465 -0
  587. package/ui/src/components/visual-office/office-view/useOfficePixiRuntime.ts +282 -0
  588. package/ui/src/components/visual-office/types.ts +123 -0
  589. package/ui/src/context/BreadcrumbContext.tsx +44 -0
  590. package/ui/src/context/CompanyContext.tsx +151 -0
  591. package/ui/src/context/DialogContext.tsx +135 -0
  592. package/ui/src/context/LiveUpdatesProvider.test.ts +119 -0
  593. package/ui/src/context/LiveUpdatesProvider.tsx +760 -0
  594. package/ui/src/context/PanelContext.tsx +73 -0
  595. package/ui/src/context/SidebarContext.tsx +43 -0
  596. package/ui/src/context/ThemeContext.tsx +83 -0
  597. package/ui/src/context/ToastContext.tsx +172 -0
  598. package/ui/src/fixtures/runTranscriptFixtures.ts +226 -0
  599. package/ui/src/hooks/useAgentOrder.ts +105 -0
  600. package/ui/src/hooks/useAutosaveIndicator.ts +72 -0
  601. package/ui/src/hooks/useCompanyPageMemory.test.ts +90 -0
  602. package/ui/src/hooks/useCompanyPageMemory.ts +79 -0
  603. package/ui/src/hooks/useDateRange.ts +120 -0
  604. package/ui/src/hooks/useInboxBadge.ts +132 -0
  605. package/ui/src/hooks/useKeyboardShortcuts.ts +40 -0
  606. package/ui/src/hooks/useProjectOrder.ts +106 -0
  607. package/ui/src/index.css +770 -0
  608. package/ui/src/lib/agent-icons.ts +99 -0
  609. package/ui/src/lib/agent-order.ts +107 -0
  610. package/ui/src/lib/agent-skills-state.test.ts +90 -0
  611. package/ui/src/lib/agent-skills-state.ts +41 -0
  612. package/ui/src/lib/assignees.test.ts +92 -0
  613. package/ui/src/lib/assignees.ts +82 -0
  614. package/ui/src/lib/color-contrast.ts +107 -0
  615. package/ui/src/lib/company-export-selection.test.ts +41 -0
  616. package/ui/src/lib/company-export-selection.ts +57 -0
  617. package/ui/src/lib/company-page-memory.ts +65 -0
  618. package/ui/src/lib/company-portability-sidebar.test.ts +101 -0
  619. package/ui/src/lib/company-portability-sidebar.ts +62 -0
  620. package/ui/src/lib/company-routes.ts +88 -0
  621. package/ui/src/lib/company-selection.test.ts +34 -0
  622. package/ui/src/lib/company-selection.ts +18 -0
  623. package/ui/src/lib/groupBy.ts +11 -0
  624. package/ui/src/lib/inbox.test.ts +404 -0
  625. package/ui/src/lib/inbox.ts +292 -0
  626. package/ui/src/lib/instance-settings.test.ts +26 -0
  627. package/ui/src/lib/instance-settings.ts +25 -0
  628. package/ui/src/lib/issueDetailBreadcrumb.ts +24 -0
  629. package/ui/src/lib/legacy-agent-config.test.ts +40 -0
  630. package/ui/src/lib/legacy-agent-config.ts +17 -0
  631. package/ui/src/lib/mention-aware-link-node.test.ts +50 -0
  632. package/ui/src/lib/mention-aware-link-node.ts +67 -0
  633. package/ui/src/lib/mention-chips.ts +168 -0
  634. package/ui/src/lib/mention-deletion.test.ts +87 -0
  635. package/ui/src/lib/mention-deletion.ts +143 -0
  636. package/ui/src/lib/model-utils.ts +16 -0
  637. package/ui/src/lib/onboarding-goal.test.ts +22 -0
  638. package/ui/src/lib/onboarding-goal.ts +18 -0
  639. package/ui/src/lib/onboarding-launch.test.ts +131 -0
  640. package/ui/src/lib/onboarding-launch.ts +54 -0
  641. package/ui/src/lib/onboarding-route.test.ts +80 -0
  642. package/ui/src/lib/onboarding-route.ts +51 -0
  643. package/ui/src/lib/portable-files.ts +42 -0
  644. package/ui/src/lib/project-order.ts +71 -0
  645. package/ui/src/lib/queryKeys.ts +140 -0
  646. package/ui/src/lib/recent-assignees.ts +36 -0
  647. package/ui/src/lib/router.tsx +76 -0
  648. package/ui/src/lib/routine-trigger-patch.test.ts +72 -0
  649. package/ui/src/lib/routine-trigger-patch.ts +31 -0
  650. package/ui/src/lib/status-colors.ts +108 -0
  651. package/ui/src/lib/timeAgo.ts +31 -0
  652. package/ui/src/lib/utils.ts +168 -0
  653. package/ui/src/lib/worktree-branding.ts +65 -0
  654. package/ui/src/lib/zip.test.ts +289 -0
  655. package/ui/src/lib/zip.ts +284 -0
  656. package/ui/src/main.tsx +67 -0
  657. package/ui/src/pages/Activity.tsx +141 -0
  658. package/ui/src/pages/AgentDetail.tsx +4053 -0
  659. package/ui/src/pages/Agents.tsx +415 -0
  660. package/ui/src/pages/ApprovalDetail.tsx +369 -0
  661. package/ui/src/pages/Approvals.tsx +132 -0
  662. package/ui/src/pages/Auth.tsx +180 -0
  663. package/ui/src/pages/BoardClaim.tsx +125 -0
  664. package/ui/src/pages/CliAuth.tsx +184 -0
  665. package/ui/src/pages/Companies.tsx +297 -0
  666. package/ui/src/pages/CompanyExport.tsx +1019 -0
  667. package/ui/src/pages/CompanyImport.tsx +1355 -0
  668. package/ui/src/pages/CompanySettings.tsx +661 -0
  669. package/ui/src/pages/CompanySkills.tsx +1171 -0
  670. package/ui/src/pages/Costs.tsx +1103 -0
  671. package/ui/src/pages/Dashboard.tsx +388 -0
  672. package/ui/src/pages/DesignGuide.tsx +1330 -0
  673. package/ui/src/pages/ExecutionWorkspaceDetail.tsx +82 -0
  674. package/ui/src/pages/GoalDetail.tsx +197 -0
  675. package/ui/src/pages/Goals.tsx +63 -0
  676. package/ui/src/pages/Inbox.tsx +1291 -0
  677. package/ui/src/pages/InstanceExperimentalSettings.tsx +139 -0
  678. package/ui/src/pages/InstanceGeneralSettings.tsx +104 -0
  679. package/ui/src/pages/InstanceSettings.tsx +284 -0
  680. package/ui/src/pages/InviteLanding.tsx +320 -0
  681. package/ui/src/pages/IssueDetail.tsx +1201 -0
  682. package/ui/src/pages/Issues.tsx +116 -0
  683. package/ui/src/pages/MyIssues.tsx +72 -0
  684. package/ui/src/pages/NewAgent.tsx +353 -0
  685. package/ui/src/pages/NotFound.tsx +66 -0
  686. package/ui/src/pages/Org.tsx +132 -0
  687. package/ui/src/pages/OrgChart.tsx +447 -0
  688. package/ui/src/pages/PluginManager.tsx +510 -0
  689. package/ui/src/pages/PluginPage.tsx +156 -0
  690. package/ui/src/pages/PluginSettings.tsx +836 -0
  691. package/ui/src/pages/ProjectDetail.tsx +633 -0
  692. package/ui/src/pages/Projects.tsx +87 -0
  693. package/ui/src/pages/RoutineDetail.tsx +1022 -0
  694. package/ui/src/pages/Routines.tsx +661 -0
  695. package/ui/src/pages/RunTranscriptUxLab.tsx +334 -0
  696. package/ui/src/pages/VisualOffice.tsx +243 -0
  697. package/ui/src/plugins/bridge-init.ts +69 -0
  698. package/ui/src/plugins/bridge.ts +476 -0
  699. package/ui/src/plugins/launchers.tsx +834 -0
  700. package/ui/src/plugins/slots.tsx +855 -0
  701. package/ui/tsconfig.json +21 -0
  702. package/ui/vite.config.ts +23 -0
  703. package/ui/vitest.config.ts +14 -0
  704. package/vitest.config.ts +11 -0
@@ -0,0 +1,1269 @@
1
+ import crypto from "node:crypto";
2
+ import { and, asc, desc, eq, inArray, isNotNull, isNull, lte, ne, or, sql } from "drizzle-orm";
3
+ import type { Db } from "@corporateai/db";
4
+ import {
5
+ agents,
6
+ companySecrets,
7
+ goals,
8
+ heartbeatRuns,
9
+ issues,
10
+ projects,
11
+ routineRuns,
12
+ routines,
13
+ routineTriggers,
14
+ } from "@corporateai/db";
15
+ import type {
16
+ CreateRoutine,
17
+ CreateRoutineTrigger,
18
+ Routine,
19
+ RoutineDetail,
20
+ RoutineListItem,
21
+ RoutineRunSummary,
22
+ RoutineTrigger,
23
+ RoutineTriggerSecretMaterial,
24
+ RunRoutine,
25
+ UpdateRoutine,
26
+ UpdateRoutineTrigger,
27
+ } from "@corporateai/shared";
28
+ import { conflict, forbidden, notFound, unauthorized, unprocessable } from "../errors.js";
29
+ import { logger } from "../middleware/logger.js";
30
+ import { issueService } from "./issues.js";
31
+ import { secretService } from "./secrets.js";
32
+ import { parseCron, validateCron } from "./cron.js";
33
+ import { heartbeatService } from "./heartbeat.js";
34
+ import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "./issue-assignment-wakeup.js";
35
+ import { logActivity } from "./activity-log.js";
36
+
37
+ const OPEN_ISSUE_STATUSES = ["backlog", "todo", "in_progress", "in_review", "blocked"];
38
+ const LIVE_HEARTBEAT_RUN_STATUSES = ["queued", "running"];
39
+ const TERMINAL_ISSUE_STATUSES = new Set(["done", "cancelled"]);
40
+ const MAX_CATCH_UP_RUNS = 25;
41
+ const WEEKDAY_INDEX: Record<string, number> = {
42
+ Sun: 0,
43
+ Mon: 1,
44
+ Tue: 2,
45
+ Wed: 3,
46
+ Thu: 4,
47
+ Fri: 5,
48
+ Sat: 6,
49
+ };
50
+
51
+ type Actor = { agentId?: string | null; userId?: string | null };
52
+
53
+ function assertTimeZone(timeZone: string) {
54
+ try {
55
+ new Intl.DateTimeFormat("en-US", { timeZone }).format(new Date());
56
+ } catch {
57
+ throw unprocessable(`Invalid timezone: ${timeZone}`);
58
+ }
59
+ }
60
+
61
+ function floorToMinute(date: Date) {
62
+ const copy = new Date(date.getTime());
63
+ copy.setUTCSeconds(0, 0);
64
+ return copy;
65
+ }
66
+
67
+ function getZonedMinuteParts(date: Date, timeZone: string) {
68
+ const formatter = new Intl.DateTimeFormat("en-US", {
69
+ timeZone,
70
+ hour12: false,
71
+ year: "numeric",
72
+ month: "numeric",
73
+ day: "numeric",
74
+ hour: "numeric",
75
+ minute: "numeric",
76
+ weekday: "short",
77
+ });
78
+ const parts = formatter.formatToParts(date);
79
+ const map = Object.fromEntries(parts.map((part) => [part.type, part.value]));
80
+ const weekday = WEEKDAY_INDEX[map.weekday ?? ""];
81
+ if (weekday == null) {
82
+ throw new Error(`Unable to resolve weekday for timezone ${timeZone}`);
83
+ }
84
+ return {
85
+ year: Number(map.year),
86
+ month: Number(map.month),
87
+ day: Number(map.day),
88
+ hour: Number(map.hour),
89
+ minute: Number(map.minute),
90
+ weekday,
91
+ };
92
+ }
93
+
94
+ function matchesCronMinute(expression: string, timeZone: string, date: Date) {
95
+ const cron = parseCron(expression);
96
+ const parts = getZonedMinuteParts(date, timeZone);
97
+ return (
98
+ cron.minutes.includes(parts.minute) &&
99
+ cron.hours.includes(parts.hour) &&
100
+ cron.daysOfMonth.includes(parts.day) &&
101
+ cron.months.includes(parts.month) &&
102
+ cron.daysOfWeek.includes(parts.weekday)
103
+ );
104
+ }
105
+
106
+ function nextCronTickInTimeZone(expression: string, timeZone: string, after: Date) {
107
+ const trimmed = expression.trim();
108
+ assertTimeZone(timeZone);
109
+ const error = validateCron(trimmed);
110
+ if (error) {
111
+ throw unprocessable(error);
112
+ }
113
+
114
+ const cursor = floorToMinute(after);
115
+ cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
116
+ const limit = 366 * 24 * 60 * 5;
117
+ for (let i = 0; i < limit; i += 1) {
118
+ if (matchesCronMinute(trimmed, timeZone, cursor)) {
119
+ return new Date(cursor.getTime());
120
+ }
121
+ cursor.setUTCMinutes(cursor.getUTCMinutes() + 1);
122
+ }
123
+ return null;
124
+ }
125
+
126
+ function nextResultText(status: string, issueId?: string | null) {
127
+ if (status === "issue_created" && issueId) return `Created execution issue ${issueId}`;
128
+ if (status === "coalesced") return "Coalesced into an existing live execution issue";
129
+ if (status === "skipped") return "Skipped because a live execution issue already exists";
130
+ if (status === "completed") return "Execution issue completed";
131
+ if (status === "failed") return "Execution failed";
132
+ return status;
133
+ }
134
+
135
+ function normalizeWebhookTimestampMs(rawTimestamp: string) {
136
+ const parsed = Number(rawTimestamp);
137
+ if (!Number.isFinite(parsed)) return null;
138
+ return parsed > 1e12 ? parsed : parsed * 1000;
139
+ }
140
+
141
+ export function routineService(db: Db, deps: { heartbeat?: IssueAssignmentWakeupDeps } = {}) {
142
+ const issueSvc = issueService(db);
143
+ const secretsSvc = secretService(db);
144
+ const heartbeat = deps.heartbeat ?? heartbeatService(db);
145
+
146
+ async function getRoutineById(id: string) {
147
+ return db
148
+ .select()
149
+ .from(routines)
150
+ .where(eq(routines.id, id))
151
+ .then((rows) => rows[0] ?? null);
152
+ }
153
+
154
+ async function getTriggerById(id: string) {
155
+ return db
156
+ .select()
157
+ .from(routineTriggers)
158
+ .where(eq(routineTriggers.id, id))
159
+ .then((rows) => rows[0] ?? null);
160
+ }
161
+
162
+ async function assertRoutineAccess(companyId: string, routineId: string) {
163
+ const routine = await getRoutineById(routineId);
164
+ if (!routine) throw notFound("Routine not found");
165
+ if (routine.companyId !== companyId) throw forbidden("Routine must belong to same company");
166
+ return routine;
167
+ }
168
+
169
+ async function assertAssignableAgent(companyId: string, agentId: string) {
170
+ const agent = await db
171
+ .select({ id: agents.id, companyId: agents.companyId, status: agents.status })
172
+ .from(agents)
173
+ .where(eq(agents.id, agentId))
174
+ .then((rows) => rows[0] ?? null);
175
+ if (!agent) throw notFound("Assignee agent not found");
176
+ if (agent.companyId !== companyId) throw unprocessable("Assignee must belong to same company");
177
+ if (agent.status === "pending_approval") throw conflict("Cannot assign routines to pending approval agents");
178
+ if (agent.status === "terminated") throw conflict("Cannot assign routines to terminated agents");
179
+ }
180
+
181
+ async function assertProject(companyId: string, projectId: string) {
182
+ const project = await db
183
+ .select({ id: projects.id, companyId: projects.companyId })
184
+ .from(projects)
185
+ .where(eq(projects.id, projectId))
186
+ .then((rows) => rows[0] ?? null);
187
+ if (!project) throw notFound("Project not found");
188
+ if (project.companyId !== companyId) throw unprocessable("Project must belong to same company");
189
+ }
190
+
191
+ async function assertGoal(companyId: string, goalId: string) {
192
+ const goal = await db
193
+ .select({ id: goals.id, companyId: goals.companyId })
194
+ .from(goals)
195
+ .where(eq(goals.id, goalId))
196
+ .then((rows) => rows[0] ?? null);
197
+ if (!goal) throw notFound("Goal not found");
198
+ if (goal.companyId !== companyId) throw unprocessable("Goal must belong to same company");
199
+ }
200
+
201
+ async function assertParentIssue(companyId: string, issueId: string) {
202
+ const parentIssue = await db
203
+ .select({ id: issues.id, companyId: issues.companyId })
204
+ .from(issues)
205
+ .where(eq(issues.id, issueId))
206
+ .then((rows) => rows[0] ?? null);
207
+ if (!parentIssue) throw notFound("Parent issue not found");
208
+ if (parentIssue.companyId !== companyId) throw unprocessable("Parent issue must belong to same company");
209
+ }
210
+
211
+ async function listTriggersForRoutineIds(companyId: string, routineIds: string[]) {
212
+ if (routineIds.length === 0) return new Map<string, RoutineTrigger[]>();
213
+ const rows = await db
214
+ .select()
215
+ .from(routineTriggers)
216
+ .where(and(eq(routineTriggers.companyId, companyId), inArray(routineTriggers.routineId, routineIds)))
217
+ .orderBy(asc(routineTriggers.createdAt), asc(routineTriggers.id));
218
+ const map = new Map<string, RoutineTrigger[]>();
219
+ for (const row of rows) {
220
+ const list = map.get(row.routineId) ?? [];
221
+ list.push(row);
222
+ map.set(row.routineId, list);
223
+ }
224
+ return map;
225
+ }
226
+
227
+ async function listLatestRunByRoutineIds(companyId: string, routineIds: string[]) {
228
+ if (routineIds.length === 0) return new Map<string, RoutineRunSummary>();
229
+ const rows = await db
230
+ .selectDistinctOn([routineRuns.routineId], {
231
+ id: routineRuns.id,
232
+ companyId: routineRuns.companyId,
233
+ routineId: routineRuns.routineId,
234
+ triggerId: routineRuns.triggerId,
235
+ source: routineRuns.source,
236
+ status: routineRuns.status,
237
+ triggeredAt: routineRuns.triggeredAt,
238
+ idempotencyKey: routineRuns.idempotencyKey,
239
+ triggerPayload: routineRuns.triggerPayload,
240
+ linkedIssueId: routineRuns.linkedIssueId,
241
+ coalescedIntoRunId: routineRuns.coalescedIntoRunId,
242
+ failureReason: routineRuns.failureReason,
243
+ completedAt: routineRuns.completedAt,
244
+ createdAt: routineRuns.createdAt,
245
+ updatedAt: routineRuns.updatedAt,
246
+ triggerKind: routineTriggers.kind,
247
+ triggerLabel: routineTriggers.label,
248
+ issueIdentifier: issues.identifier,
249
+ issueTitle: issues.title,
250
+ issueStatus: issues.status,
251
+ issuePriority: issues.priority,
252
+ issueUpdatedAt: issues.updatedAt,
253
+ })
254
+ .from(routineRuns)
255
+ .leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id))
256
+ .leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id))
257
+ .where(and(eq(routineRuns.companyId, companyId), inArray(routineRuns.routineId, routineIds)))
258
+ .orderBy(routineRuns.routineId, desc(routineRuns.createdAt), desc(routineRuns.id));
259
+
260
+ const map = new Map<string, RoutineRunSummary>();
261
+ for (const row of rows) {
262
+ map.set(row.routineId, {
263
+ id: row.id,
264
+ companyId: row.companyId,
265
+ routineId: row.routineId,
266
+ triggerId: row.triggerId,
267
+ source: row.source as RoutineRunSummary["source"],
268
+ status: row.status as RoutineRunSummary["status"],
269
+ triggeredAt: row.triggeredAt,
270
+ idempotencyKey: row.idempotencyKey,
271
+ triggerPayload: row.triggerPayload as Record<string, unknown> | null,
272
+ linkedIssueId: row.linkedIssueId,
273
+ coalescedIntoRunId: row.coalescedIntoRunId,
274
+ failureReason: row.failureReason,
275
+ completedAt: row.completedAt,
276
+ createdAt: row.createdAt,
277
+ updatedAt: row.updatedAt,
278
+ linkedIssue: row.linkedIssueId
279
+ ? {
280
+ id: row.linkedIssueId,
281
+ identifier: row.issueIdentifier,
282
+ title: row.issueTitle ?? "Routine execution",
283
+ status: row.issueStatus ?? "todo",
284
+ priority: row.issuePriority ?? "medium",
285
+ updatedAt: row.issueUpdatedAt ?? row.updatedAt,
286
+ }
287
+ : null,
288
+ trigger: row.triggerId
289
+ ? {
290
+ id: row.triggerId,
291
+ kind: row.triggerKind as NonNullable<RoutineRunSummary["trigger"]>["kind"],
292
+ label: row.triggerLabel,
293
+ }
294
+ : null,
295
+ });
296
+ }
297
+ return map;
298
+ }
299
+
300
+ async function listLiveIssueByRoutineIds(companyId: string, routineIds: string[]) {
301
+ if (routineIds.length === 0) return new Map<string, RoutineListItem["activeIssue"]>();
302
+ const executionBoundRows = await db
303
+ .selectDistinctOn([issues.originId], {
304
+ originId: issues.originId,
305
+ id: issues.id,
306
+ identifier: issues.identifier,
307
+ title: issues.title,
308
+ status: issues.status,
309
+ priority: issues.priority,
310
+ updatedAt: issues.updatedAt,
311
+ })
312
+ .from(issues)
313
+ .innerJoin(
314
+ heartbeatRuns,
315
+ and(
316
+ eq(heartbeatRuns.id, issues.executionRunId),
317
+ inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES),
318
+ ),
319
+ )
320
+ .where(
321
+ and(
322
+ eq(issues.companyId, companyId),
323
+ eq(issues.originKind, "routine_execution"),
324
+ inArray(issues.originId, routineIds),
325
+ inArray(issues.status, OPEN_ISSUE_STATUSES),
326
+ isNull(issues.hiddenAt),
327
+ ),
328
+ )
329
+ .orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt));
330
+
331
+ const rowsByOriginId = new Map<string, (typeof executionBoundRows)[number]>();
332
+ for (const row of executionBoundRows) {
333
+ if (!row.originId) continue;
334
+ rowsByOriginId.set(row.originId, row);
335
+ }
336
+
337
+ const missingRoutineIds = routineIds.filter((routineId) => !rowsByOriginId.has(routineId));
338
+ if (missingRoutineIds.length > 0) {
339
+ const legacyRows = await db
340
+ .selectDistinctOn([issues.originId], {
341
+ originId: issues.originId,
342
+ id: issues.id,
343
+ identifier: issues.identifier,
344
+ title: issues.title,
345
+ status: issues.status,
346
+ priority: issues.priority,
347
+ updatedAt: issues.updatedAt,
348
+ })
349
+ .from(issues)
350
+ .innerJoin(
351
+ heartbeatRuns,
352
+ and(
353
+ eq(heartbeatRuns.companyId, issues.companyId),
354
+ inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES),
355
+ sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = cast(${issues.id} as text)`,
356
+ ),
357
+ )
358
+ .where(
359
+ and(
360
+ eq(issues.companyId, companyId),
361
+ eq(issues.originKind, "routine_execution"),
362
+ inArray(issues.originId, missingRoutineIds),
363
+ inArray(issues.status, OPEN_ISSUE_STATUSES),
364
+ isNull(issues.hiddenAt),
365
+ ),
366
+ )
367
+ .orderBy(issues.originId, desc(issues.updatedAt), desc(issues.createdAt));
368
+
369
+ for (const row of legacyRows) {
370
+ if (!row.originId) continue;
371
+ rowsByOriginId.set(row.originId, row);
372
+ }
373
+ }
374
+
375
+ const map = new Map<string, RoutineListItem["activeIssue"]>();
376
+ for (const row of rowsByOriginId.values()) {
377
+ if (!row.originId) continue;
378
+ map.set(row.originId, {
379
+ id: row.id,
380
+ identifier: row.identifier,
381
+ title: row.title,
382
+ status: row.status,
383
+ priority: row.priority,
384
+ updatedAt: row.updatedAt,
385
+ });
386
+ }
387
+ return map;
388
+ }
389
+
390
+ async function updateRoutineTouchedState(input: {
391
+ routineId: string;
392
+ triggerId?: string | null;
393
+ triggeredAt: Date;
394
+ status: string;
395
+ issueId?: string | null;
396
+ nextRunAt?: Date | null;
397
+ }, executor: Db = db) {
398
+ await executor
399
+ .update(routines)
400
+ .set({
401
+ lastTriggeredAt: input.triggeredAt,
402
+ lastEnqueuedAt: input.issueId ? input.triggeredAt : undefined,
403
+ updatedAt: new Date(),
404
+ })
405
+ .where(eq(routines.id, input.routineId));
406
+
407
+ if (input.triggerId) {
408
+ await executor
409
+ .update(routineTriggers)
410
+ .set({
411
+ lastFiredAt: input.triggeredAt,
412
+ lastResult: nextResultText(input.status, input.issueId),
413
+ nextRunAt: input.nextRunAt === undefined ? undefined : input.nextRunAt,
414
+ updatedAt: new Date(),
415
+ })
416
+ .where(eq(routineTriggers.id, input.triggerId));
417
+ }
418
+ }
419
+
420
+ async function findLiveExecutionIssue(routine: typeof routines.$inferSelect, executor: Db = db) {
421
+ const executionBoundIssue = await executor
422
+ .select()
423
+ .from(issues)
424
+ .innerJoin(
425
+ heartbeatRuns,
426
+ and(
427
+ eq(heartbeatRuns.id, issues.executionRunId),
428
+ inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES),
429
+ ),
430
+ )
431
+ .where(
432
+ and(
433
+ eq(issues.companyId, routine.companyId),
434
+ eq(issues.originKind, "routine_execution"),
435
+ eq(issues.originId, routine.id),
436
+ inArray(issues.status, OPEN_ISSUE_STATUSES),
437
+ isNull(issues.hiddenAt),
438
+ ),
439
+ )
440
+ .orderBy(desc(issues.updatedAt), desc(issues.createdAt))
441
+ .limit(1)
442
+ .then((rows) => rows[0]?.issues ?? null);
443
+ if (executionBoundIssue) return executionBoundIssue;
444
+
445
+ return executor
446
+ .select()
447
+ .from(issues)
448
+ .innerJoin(
449
+ heartbeatRuns,
450
+ and(
451
+ eq(heartbeatRuns.companyId, issues.companyId),
452
+ inArray(heartbeatRuns.status, LIVE_HEARTBEAT_RUN_STATUSES),
453
+ sql`${heartbeatRuns.contextSnapshot} ->> 'issueId' = cast(${issues.id} as text)`,
454
+ ),
455
+ )
456
+ .where(
457
+ and(
458
+ eq(issues.companyId, routine.companyId),
459
+ eq(issues.originKind, "routine_execution"),
460
+ eq(issues.originId, routine.id),
461
+ inArray(issues.status, OPEN_ISSUE_STATUSES),
462
+ isNull(issues.hiddenAt),
463
+ ),
464
+ )
465
+ .orderBy(desc(issues.updatedAt), desc(issues.createdAt))
466
+ .limit(1)
467
+ .then((rows) => rows[0]?.issues ?? null);
468
+ }
469
+
470
+ async function finalizeRun(runId: string, patch: Partial<typeof routineRuns.$inferInsert>, executor: Db = db) {
471
+ return executor
472
+ .update(routineRuns)
473
+ .set({
474
+ ...patch,
475
+ updatedAt: new Date(),
476
+ })
477
+ .where(eq(routineRuns.id, runId))
478
+ .returning()
479
+ .then((rows) => rows[0] ?? null);
480
+ }
481
+
482
+ async function createWebhookSecret(
483
+ companyId: string,
484
+ routineId: string,
485
+ actor: Actor,
486
+ ) {
487
+ const secretValue = crypto.randomBytes(24).toString("hex");
488
+ const secret = await secretsSvc.create(
489
+ companyId,
490
+ {
491
+ name: `routine-${routineId}-${crypto.randomBytes(6).toString("hex")}`,
492
+ provider: "local_encrypted",
493
+ value: secretValue,
494
+ description: `Webhook auth for routine ${routineId}`,
495
+ },
496
+ actor,
497
+ );
498
+ return { secret, secretValue };
499
+ }
500
+
501
+ async function resolveTriggerSecret(trigger: typeof routineTriggers.$inferSelect, companyId: string) {
502
+ if (!trigger.secretId) throw notFound("Routine trigger secret not found");
503
+ const secret = await db
504
+ .select()
505
+ .from(companySecrets)
506
+ .where(eq(companySecrets.id, trigger.secretId))
507
+ .then((rows) => rows[0] ?? null);
508
+ if (!secret || secret.companyId !== companyId) throw notFound("Routine trigger secret not found");
509
+ const value = await secretsSvc.resolveSecretValue(companyId, trigger.secretId, "latest");
510
+ return value;
511
+ }
512
+
513
+ async function dispatchRoutineRun(input: {
514
+ routine: typeof routines.$inferSelect;
515
+ trigger: typeof routineTriggers.$inferSelect | null;
516
+ source: "schedule" | "manual" | "api" | "webhook";
517
+ payload?: Record<string, unknown> | null;
518
+ idempotencyKey?: string | null;
519
+ }) {
520
+ const run = await db.transaction(async (tx) => {
521
+ const txDb = tx as unknown as Db;
522
+ await tx.execute(
523
+ sql`select id from ${routines} where ${routines.id} = ${input.routine.id} and ${routines.companyId} = ${input.routine.companyId} for update`,
524
+ );
525
+
526
+ if (input.idempotencyKey) {
527
+ const existing = await txDb
528
+ .select()
529
+ .from(routineRuns)
530
+ .where(
531
+ and(
532
+ eq(routineRuns.companyId, input.routine.companyId),
533
+ eq(routineRuns.routineId, input.routine.id),
534
+ eq(routineRuns.source, input.source),
535
+ eq(routineRuns.idempotencyKey, input.idempotencyKey),
536
+ input.trigger ? eq(routineRuns.triggerId, input.trigger.id) : isNull(routineRuns.triggerId),
537
+ ),
538
+ )
539
+ .orderBy(desc(routineRuns.createdAt))
540
+ .limit(1)
541
+ .then((rows) => rows[0] ?? null);
542
+ if (existing) return existing;
543
+ }
544
+
545
+ const triggeredAt = new Date();
546
+ const [createdRun] = await txDb
547
+ .insert(routineRuns)
548
+ .values({
549
+ companyId: input.routine.companyId,
550
+ routineId: input.routine.id,
551
+ triggerId: input.trigger?.id ?? null,
552
+ source: input.source,
553
+ status: "received",
554
+ triggeredAt,
555
+ idempotencyKey: input.idempotencyKey ?? null,
556
+ triggerPayload: input.payload ?? null,
557
+ })
558
+ .returning();
559
+
560
+ const nextRunAt = input.trigger?.kind === "schedule" && input.trigger.cronExpression && input.trigger.timezone
561
+ ? nextCronTickInTimeZone(input.trigger.cronExpression, input.trigger.timezone, triggeredAt)
562
+ : undefined;
563
+
564
+ let createdIssue: Awaited<ReturnType<typeof issueSvc.create>> | null = null;
565
+ try {
566
+ const activeIssue = await findLiveExecutionIssue(input.routine, txDb);
567
+ if (activeIssue && input.routine.concurrencyPolicy !== "always_enqueue") {
568
+ const status = input.routine.concurrencyPolicy === "skip_if_active" ? "skipped" : "coalesced";
569
+ const updated = await finalizeRun(createdRun.id, {
570
+ status,
571
+ linkedIssueId: activeIssue.id,
572
+ coalescedIntoRunId: activeIssue.originRunId,
573
+ completedAt: triggeredAt,
574
+ }, txDb);
575
+ await updateRoutineTouchedState({
576
+ routineId: input.routine.id,
577
+ triggerId: input.trigger?.id ?? null,
578
+ triggeredAt,
579
+ status,
580
+ issueId: activeIssue.id,
581
+ nextRunAt,
582
+ }, txDb);
583
+ return updated ?? createdRun;
584
+ }
585
+
586
+ try {
587
+ createdIssue = await issueSvc.create(input.routine.companyId, {
588
+ projectId: input.routine.projectId,
589
+ goalId: input.routine.goalId,
590
+ parentId: input.routine.parentIssueId,
591
+ title: input.routine.title,
592
+ description: input.routine.description,
593
+ status: "todo",
594
+ priority: input.routine.priority,
595
+ assigneeAgentId: input.routine.assigneeAgentId,
596
+ originKind: "routine_execution",
597
+ originId: input.routine.id,
598
+ originRunId: createdRun.id,
599
+ });
600
+ } catch (error) {
601
+ const isOpenExecutionConflict =
602
+ !!error &&
603
+ typeof error === "object" &&
604
+ "code" in error &&
605
+ (error as { code?: string }).code === "23505" &&
606
+ "constraint" in error &&
607
+ (error as { constraint?: string }).constraint === "issues_open_routine_execution_uq";
608
+ if (!isOpenExecutionConflict || input.routine.concurrencyPolicy === "always_enqueue") {
609
+ throw error;
610
+ }
611
+
612
+ const existingIssue = await findLiveExecutionIssue(input.routine, txDb);
613
+ if (!existingIssue) throw error;
614
+ const status = input.routine.concurrencyPolicy === "skip_if_active" ? "skipped" : "coalesced";
615
+ const updated = await finalizeRun(createdRun.id, {
616
+ status,
617
+ linkedIssueId: existingIssue.id,
618
+ coalescedIntoRunId: existingIssue.originRunId,
619
+ completedAt: triggeredAt,
620
+ }, txDb);
621
+ await updateRoutineTouchedState({
622
+ routineId: input.routine.id,
623
+ triggerId: input.trigger?.id ?? null,
624
+ triggeredAt,
625
+ status,
626
+ issueId: existingIssue.id,
627
+ nextRunAt,
628
+ }, txDb);
629
+ return updated ?? createdRun;
630
+ }
631
+
632
+ // Keep the dispatch lock until the issue is linked to a queued heartbeat run.
633
+ await queueIssueAssignmentWakeup({
634
+ heartbeat,
635
+ issue: createdIssue,
636
+ reason: "issue_assigned",
637
+ mutation: "create",
638
+ contextSource: "routine.dispatch",
639
+ requestedByActorType: input.source === "schedule" ? "system" : undefined,
640
+ rethrowOnError: true,
641
+ });
642
+ const updated = await finalizeRun(createdRun.id, {
643
+ status: "issue_created",
644
+ linkedIssueId: createdIssue.id,
645
+ }, txDb);
646
+ await updateRoutineTouchedState({
647
+ routineId: input.routine.id,
648
+ triggerId: input.trigger?.id ?? null,
649
+ triggeredAt,
650
+ status: "issue_created",
651
+ issueId: createdIssue.id,
652
+ nextRunAt,
653
+ }, txDb);
654
+ return updated ?? createdRun;
655
+ } catch (error) {
656
+ if (createdIssue) {
657
+ await txDb.delete(issues).where(eq(issues.id, createdIssue.id));
658
+ }
659
+ const failureReason = error instanceof Error ? error.message : String(error);
660
+ const failed = await finalizeRun(createdRun.id, {
661
+ status: "failed",
662
+ failureReason,
663
+ completedAt: new Date(),
664
+ }, txDb);
665
+ await updateRoutineTouchedState({
666
+ routineId: input.routine.id,
667
+ triggerId: input.trigger?.id ?? null,
668
+ triggeredAt,
669
+ status: "failed",
670
+ nextRunAt,
671
+ }, txDb);
672
+ return failed ?? createdRun;
673
+ }
674
+ });
675
+
676
+ if (input.source === "schedule" || input.source === "webhook") {
677
+ const actorId = input.source === "schedule" ? "routine-scheduler" : "routine-webhook";
678
+ try {
679
+ await logActivity(db, {
680
+ companyId: input.routine.companyId,
681
+ actorType: "system",
682
+ actorId,
683
+ action: "routine.run_triggered",
684
+ entityType: "routine_run",
685
+ entityId: run.id,
686
+ details: {
687
+ routineId: input.routine.id,
688
+ triggerId: input.trigger?.id ?? null,
689
+ source: run.source,
690
+ status: run.status,
691
+ },
692
+ });
693
+ } catch (err) {
694
+ logger.warn({ err, routineId: input.routine.id, runId: run.id }, "failed to log automated routine run");
695
+ }
696
+ }
697
+
698
+ return run;
699
+ }
700
+
701
+ return {
702
+ get: getRoutineById,
703
+ getTrigger: getTriggerById,
704
+
705
+ list: async (companyId: string): Promise<RoutineListItem[]> => {
706
+ const rows = await db
707
+ .select()
708
+ .from(routines)
709
+ .where(eq(routines.companyId, companyId))
710
+ .orderBy(desc(routines.updatedAt), asc(routines.title));
711
+ const routineIds = rows.map((row) => row.id);
712
+ const [triggersByRoutine, latestRunByRoutine, activeIssueByRoutine] = await Promise.all([
713
+ listTriggersForRoutineIds(companyId, routineIds),
714
+ listLatestRunByRoutineIds(companyId, routineIds),
715
+ listLiveIssueByRoutineIds(companyId, routineIds),
716
+ ]);
717
+ return rows.map((row) => ({
718
+ ...row,
719
+ triggers: (triggersByRoutine.get(row.id) ?? []).map((trigger) => ({
720
+ id: trigger.id,
721
+ kind: trigger.kind as RoutineListItem["triggers"][number]["kind"],
722
+ label: trigger.label,
723
+ enabled: trigger.enabled,
724
+ nextRunAt: trigger.nextRunAt,
725
+ lastFiredAt: trigger.lastFiredAt,
726
+ lastResult: trigger.lastResult,
727
+ })),
728
+ lastRun: latestRunByRoutine.get(row.id) ?? null,
729
+ activeIssue: activeIssueByRoutine.get(row.id) ?? null,
730
+ }));
731
+ },
732
+
733
+ getDetail: async (id: string): Promise<RoutineDetail | null> => {
734
+ const row = await getRoutineById(id);
735
+ if (!row) return null;
736
+ const [project, assignee, parentIssue, triggers, recentRuns, activeIssue] = await Promise.all([
737
+ db.select().from(projects).where(eq(projects.id, row.projectId)).then((rows) => rows[0] ?? null),
738
+ db.select().from(agents).where(eq(agents.id, row.assigneeAgentId)).then((rows) => rows[0] ?? null),
739
+ row.parentIssueId ? issueSvc.getById(row.parentIssueId) : null,
740
+ db.select().from(routineTriggers).where(eq(routineTriggers.routineId, row.id)).orderBy(asc(routineTriggers.createdAt)),
741
+ db
742
+ .select({
743
+ id: routineRuns.id,
744
+ companyId: routineRuns.companyId,
745
+ routineId: routineRuns.routineId,
746
+ triggerId: routineRuns.triggerId,
747
+ source: routineRuns.source,
748
+ status: routineRuns.status,
749
+ triggeredAt: routineRuns.triggeredAt,
750
+ idempotencyKey: routineRuns.idempotencyKey,
751
+ triggerPayload: routineRuns.triggerPayload,
752
+ linkedIssueId: routineRuns.linkedIssueId,
753
+ coalescedIntoRunId: routineRuns.coalescedIntoRunId,
754
+ failureReason: routineRuns.failureReason,
755
+ completedAt: routineRuns.completedAt,
756
+ createdAt: routineRuns.createdAt,
757
+ updatedAt: routineRuns.updatedAt,
758
+ triggerKind: routineTriggers.kind,
759
+ triggerLabel: routineTriggers.label,
760
+ issueIdentifier: issues.identifier,
761
+ issueTitle: issues.title,
762
+ issueStatus: issues.status,
763
+ issuePriority: issues.priority,
764
+ issueUpdatedAt: issues.updatedAt,
765
+ })
766
+ .from(routineRuns)
767
+ .leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id))
768
+ .leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id))
769
+ .where(eq(routineRuns.routineId, row.id))
770
+ .orderBy(desc(routineRuns.createdAt))
771
+ .limit(25)
772
+ .then((runs) =>
773
+ runs.map((run) => ({
774
+ id: run.id,
775
+ companyId: run.companyId,
776
+ routineId: run.routineId,
777
+ triggerId: run.triggerId,
778
+ source: run.source as RoutineRunSummary["source"],
779
+ status: run.status as RoutineRunSummary["status"],
780
+ triggeredAt: run.triggeredAt,
781
+ idempotencyKey: run.idempotencyKey,
782
+ triggerPayload: run.triggerPayload as Record<string, unknown> | null,
783
+ linkedIssueId: run.linkedIssueId,
784
+ coalescedIntoRunId: run.coalescedIntoRunId,
785
+ failureReason: run.failureReason,
786
+ completedAt: run.completedAt,
787
+ createdAt: run.createdAt,
788
+ updatedAt: run.updatedAt,
789
+ linkedIssue: run.linkedIssueId
790
+ ? {
791
+ id: run.linkedIssueId,
792
+ identifier: run.issueIdentifier,
793
+ title: run.issueTitle ?? "Routine execution",
794
+ status: run.issueStatus ?? "todo",
795
+ priority: run.issuePriority ?? "medium",
796
+ updatedAt: run.issueUpdatedAt ?? run.updatedAt,
797
+ }
798
+ : null,
799
+ trigger: run.triggerId
800
+ ? {
801
+ id: run.triggerId,
802
+ kind: run.triggerKind as NonNullable<RoutineRunSummary["trigger"]>["kind"],
803
+ label: run.triggerLabel,
804
+ }
805
+ : null,
806
+ })),
807
+ ),
808
+ findLiveExecutionIssue(row),
809
+ ]);
810
+
811
+ return {
812
+ ...row,
813
+ project,
814
+ assignee,
815
+ parentIssue,
816
+ triggers: triggers as RoutineTrigger[],
817
+ recentRuns,
818
+ activeIssue,
819
+ };
820
+ },
821
+
822
+ create: async (companyId: string, input: CreateRoutine, actor: Actor): Promise<Routine> => {
823
+ await assertProject(companyId, input.projectId);
824
+ await assertAssignableAgent(companyId, input.assigneeAgentId);
825
+ if (input.goalId) await assertGoal(companyId, input.goalId);
826
+ if (input.parentIssueId) await assertParentIssue(companyId, input.parentIssueId);
827
+ const [created] = await db
828
+ .insert(routines)
829
+ .values({
830
+ companyId,
831
+ projectId: input.projectId,
832
+ goalId: input.goalId ?? null,
833
+ parentIssueId: input.parentIssueId ?? null,
834
+ title: input.title,
835
+ description: input.description ?? null,
836
+ assigneeAgentId: input.assigneeAgentId,
837
+ priority: input.priority,
838
+ status: input.status,
839
+ concurrencyPolicy: input.concurrencyPolicy,
840
+ catchUpPolicy: input.catchUpPolicy,
841
+ createdByAgentId: actor.agentId ?? null,
842
+ createdByUserId: actor.userId ?? null,
843
+ updatedByAgentId: actor.agentId ?? null,
844
+ updatedByUserId: actor.userId ?? null,
845
+ })
846
+ .returning();
847
+ return created;
848
+ },
849
+
850
+ update: async (id: string, patch: UpdateRoutine, actor: Actor): Promise<Routine | null> => {
851
+ const existing = await getRoutineById(id);
852
+ if (!existing) return null;
853
+ const nextProjectId = patch.projectId ?? existing.projectId;
854
+ const nextAssigneeAgentId = patch.assigneeAgentId ?? existing.assigneeAgentId;
855
+ if (patch.projectId) await assertProject(existing.companyId, nextProjectId);
856
+ if (patch.assigneeAgentId) await assertAssignableAgent(existing.companyId, nextAssigneeAgentId);
857
+ if (patch.goalId) await assertGoal(existing.companyId, patch.goalId);
858
+ if (patch.parentIssueId) await assertParentIssue(existing.companyId, patch.parentIssueId);
859
+ const [updated] = await db
860
+ .update(routines)
861
+ .set({
862
+ projectId: nextProjectId,
863
+ goalId: patch.goalId === undefined ? existing.goalId : patch.goalId,
864
+ parentIssueId: patch.parentIssueId === undefined ? existing.parentIssueId : patch.parentIssueId,
865
+ title: patch.title ?? existing.title,
866
+ description: patch.description === undefined ? existing.description : patch.description,
867
+ assigneeAgentId: nextAssigneeAgentId,
868
+ priority: patch.priority ?? existing.priority,
869
+ status: patch.status ?? existing.status,
870
+ concurrencyPolicy: patch.concurrencyPolicy ?? existing.concurrencyPolicy,
871
+ catchUpPolicy: patch.catchUpPolicy ?? existing.catchUpPolicy,
872
+ updatedByAgentId: actor.agentId ?? null,
873
+ updatedByUserId: actor.userId ?? null,
874
+ updatedAt: new Date(),
875
+ })
876
+ .where(eq(routines.id, id))
877
+ .returning();
878
+ return updated ?? null;
879
+ },
880
+
881
+ createTrigger: async (
882
+ routineId: string,
883
+ input: CreateRoutineTrigger,
884
+ actor: Actor,
885
+ ): Promise<{ trigger: RoutineTrigger; secretMaterial: RoutineTriggerSecretMaterial | null }> => {
886
+ const routine = await getRoutineById(routineId);
887
+ if (!routine) throw notFound("Routine not found");
888
+
889
+ let secretMaterial: RoutineTriggerSecretMaterial | null = null;
890
+ let secretId: string | null = null;
891
+ let publicId: string | null = null;
892
+ let nextRunAt: Date | null = null;
893
+
894
+ if (input.kind === "schedule") {
895
+ const timeZone = input.timezone || "UTC";
896
+ assertTimeZone(timeZone);
897
+ const error = validateCron(input.cronExpression);
898
+ if (error) throw unprocessable(error);
899
+ nextRunAt = nextCronTickInTimeZone(input.cronExpression, timeZone, new Date());
900
+ }
901
+
902
+ if (input.kind === "webhook") {
903
+ publicId = crypto.randomBytes(12).toString("hex");
904
+ const created = await createWebhookSecret(routine.companyId, routine.id, actor);
905
+ secretId = created.secret.id;
906
+ secretMaterial = {
907
+ webhookUrl: `${process.env.PAPERCLIP_API_URL}/api/routine-triggers/public/${publicId}/fire`,
908
+ webhookSecret: created.secretValue,
909
+ };
910
+ }
911
+
912
+ const [trigger] = await db
913
+ .insert(routineTriggers)
914
+ .values({
915
+ companyId: routine.companyId,
916
+ routineId: routine.id,
917
+ kind: input.kind,
918
+ label: input.label ?? null,
919
+ enabled: input.enabled ?? true,
920
+ cronExpression: input.kind === "schedule" ? input.cronExpression : null,
921
+ timezone: input.kind === "schedule" ? (input.timezone || "UTC") : null,
922
+ nextRunAt,
923
+ publicId,
924
+ secretId,
925
+ signingMode: input.kind === "webhook" ? input.signingMode : null,
926
+ replayWindowSec: input.kind === "webhook" ? input.replayWindowSec : null,
927
+ lastRotatedAt: input.kind === "webhook" ? new Date() : null,
928
+ createdByAgentId: actor.agentId ?? null,
929
+ createdByUserId: actor.userId ?? null,
930
+ updatedByAgentId: actor.agentId ?? null,
931
+ updatedByUserId: actor.userId ?? null,
932
+ })
933
+ .returning();
934
+
935
+ return {
936
+ trigger: trigger as RoutineTrigger,
937
+ secretMaterial,
938
+ };
939
+ },
940
+
941
+ updateTrigger: async (id: string, patch: UpdateRoutineTrigger, actor: Actor): Promise<RoutineTrigger | null> => {
942
+ const existing = await getTriggerById(id);
943
+ if (!existing) return null;
944
+
945
+ let nextRunAt = existing.nextRunAt;
946
+ let cronExpression = existing.cronExpression;
947
+ let timezone = existing.timezone;
948
+
949
+ if (existing.kind === "schedule") {
950
+ if (patch.cronExpression !== undefined) {
951
+ if (patch.cronExpression == null) throw unprocessable("Scheduled triggers require cronExpression");
952
+ const error = validateCron(patch.cronExpression);
953
+ if (error) throw unprocessable(error);
954
+ cronExpression = patch.cronExpression;
955
+ }
956
+ if (patch.timezone !== undefined) {
957
+ if (patch.timezone == null) throw unprocessable("Scheduled triggers require timezone");
958
+ assertTimeZone(patch.timezone);
959
+ timezone = patch.timezone;
960
+ }
961
+ if (cronExpression && timezone) {
962
+ nextRunAt = nextCronTickInTimeZone(cronExpression, timezone, new Date());
963
+ }
964
+ }
965
+
966
+ const [updated] = await db
967
+ .update(routineTriggers)
968
+ .set({
969
+ label: patch.label === undefined ? existing.label : patch.label,
970
+ enabled: patch.enabled ?? existing.enabled,
971
+ cronExpression,
972
+ timezone,
973
+ nextRunAt,
974
+ signingMode: patch.signingMode === undefined ? existing.signingMode : patch.signingMode,
975
+ replayWindowSec: patch.replayWindowSec === undefined ? existing.replayWindowSec : patch.replayWindowSec,
976
+ updatedByAgentId: actor.agentId ?? null,
977
+ updatedByUserId: actor.userId ?? null,
978
+ updatedAt: new Date(),
979
+ })
980
+ .where(eq(routineTriggers.id, id))
981
+ .returning();
982
+
983
+ return (updated as RoutineTrigger | undefined) ?? null;
984
+ },
985
+
986
+ deleteTrigger: async (id: string): Promise<boolean> => {
987
+ const existing = await getTriggerById(id);
988
+ if (!existing) return false;
989
+ await db.delete(routineTriggers).where(eq(routineTriggers.id, id));
990
+ return true;
991
+ },
992
+
993
+ rotateTriggerSecret: async (
994
+ id: string,
995
+ actor: Actor,
996
+ ): Promise<{ trigger: RoutineTrigger; secretMaterial: RoutineTriggerSecretMaterial }> => {
997
+ const existing = await getTriggerById(id);
998
+ if (!existing) throw notFound("Routine trigger not found");
999
+ if (existing.kind !== "webhook" || !existing.publicId || !existing.secretId) {
1000
+ throw unprocessable("Only webhook triggers can rotate secrets");
1001
+ }
1002
+
1003
+ const secretValue = crypto.randomBytes(24).toString("hex");
1004
+ await secretsSvc.rotate(existing.secretId, { value: secretValue }, actor);
1005
+ const [updated] = await db
1006
+ .update(routineTriggers)
1007
+ .set({
1008
+ lastRotatedAt: new Date(),
1009
+ updatedByAgentId: actor.agentId ?? null,
1010
+ updatedByUserId: actor.userId ?? null,
1011
+ updatedAt: new Date(),
1012
+ })
1013
+ .where(eq(routineTriggers.id, id))
1014
+ .returning();
1015
+
1016
+ return {
1017
+ trigger: updated as RoutineTrigger,
1018
+ secretMaterial: {
1019
+ webhookUrl: `${process.env.PAPERCLIP_API_URL}/api/routine-triggers/public/${existing.publicId}/fire`,
1020
+ webhookSecret: secretValue,
1021
+ },
1022
+ };
1023
+ },
1024
+
1025
+ runRoutine: async (id: string, input: RunRoutine) => {
1026
+ const routine = await getRoutineById(id);
1027
+ if (!routine) throw notFound("Routine not found");
1028
+ if (routine.status === "archived") throw conflict("Routine is archived");
1029
+ const trigger = input.triggerId ? await getTriggerById(input.triggerId) : null;
1030
+ if (trigger && trigger.routineId !== routine.id) throw forbidden("Trigger does not belong to routine");
1031
+ if (trigger && !trigger.enabled) throw conflict("Routine trigger is not active");
1032
+ return dispatchRoutineRun({
1033
+ routine,
1034
+ trigger,
1035
+ source: input.source,
1036
+ payload: input.payload as Record<string, unknown> | null | undefined,
1037
+ idempotencyKey: input.idempotencyKey,
1038
+ });
1039
+ },
1040
+
1041
+ firePublicTrigger: async (publicId: string, input: {
1042
+ authorizationHeader?: string | null;
1043
+ signatureHeader?: string | null;
1044
+ timestampHeader?: string | null;
1045
+ idempotencyKey?: string | null;
1046
+ rawBody?: Buffer | null;
1047
+ payload?: Record<string, unknown> | null;
1048
+ }) => {
1049
+ const trigger = await db
1050
+ .select()
1051
+ .from(routineTriggers)
1052
+ .where(and(eq(routineTriggers.publicId, publicId), eq(routineTriggers.kind, "webhook")))
1053
+ .then((rows) => rows[0] ?? null);
1054
+ if (!trigger) throw notFound("Routine trigger not found");
1055
+ const routine = await getRoutineById(trigger.routineId);
1056
+ if (!routine) throw notFound("Routine not found");
1057
+ if (!trigger.enabled || routine.status !== "active") throw conflict("Routine trigger is not active");
1058
+
1059
+ const secretValue = await resolveTriggerSecret(trigger, routine.companyId);
1060
+ if (trigger.signingMode === "bearer") {
1061
+ const expected = `Bearer ${secretValue}`;
1062
+ const provided = input.authorizationHeader?.trim() ?? "";
1063
+ const expectedBuf = Buffer.from(expected);
1064
+ const providedBuf = Buffer.alloc(expectedBuf.length);
1065
+ providedBuf.write(provided.slice(0, expectedBuf.length));
1066
+ const valid =
1067
+ provided.length === expected.length &&
1068
+ crypto.timingSafeEqual(providedBuf, expectedBuf);
1069
+ if (!valid) {
1070
+ throw unauthorized();
1071
+ }
1072
+ } else {
1073
+ const rawBody = input.rawBody ?? Buffer.from(JSON.stringify(input.payload ?? {}));
1074
+ const providedSignature = input.signatureHeader?.trim() ?? "";
1075
+ const providedTimestamp = input.timestampHeader?.trim() ?? "";
1076
+ if (!providedSignature || !providedTimestamp) throw unauthorized();
1077
+ const tsMillis = normalizeWebhookTimestampMs(providedTimestamp);
1078
+ if (tsMillis == null) throw unauthorized();
1079
+ const replayWindowSec = trigger.replayWindowSec ?? 300;
1080
+ if (Math.abs(Date.now() - tsMillis) > replayWindowSec * 1000) {
1081
+ throw unauthorized();
1082
+ }
1083
+ const expectedHmac = crypto
1084
+ .createHmac("sha256", secretValue)
1085
+ .update(`${providedTimestamp}.`)
1086
+ .update(rawBody)
1087
+ .digest("hex");
1088
+ const normalizedSignature = providedSignature.replace(/^sha256=/, "");
1089
+ const valid =
1090
+ normalizedSignature.length === expectedHmac.length &&
1091
+ crypto.timingSafeEqual(Buffer.from(normalizedSignature), Buffer.from(expectedHmac));
1092
+ if (!valid) throw unauthorized();
1093
+ }
1094
+
1095
+ return dispatchRoutineRun({
1096
+ routine,
1097
+ trigger,
1098
+ source: "webhook",
1099
+ payload: input.payload,
1100
+ idempotencyKey: input.idempotencyKey,
1101
+ });
1102
+ },
1103
+
1104
+ listRuns: async (routineId: string, limit = 50): Promise<RoutineRunSummary[]> => {
1105
+ const cappedLimit = Math.max(1, Math.min(limit, 200));
1106
+ const rows = await db
1107
+ .select({
1108
+ id: routineRuns.id,
1109
+ companyId: routineRuns.companyId,
1110
+ routineId: routineRuns.routineId,
1111
+ triggerId: routineRuns.triggerId,
1112
+ source: routineRuns.source,
1113
+ status: routineRuns.status,
1114
+ triggeredAt: routineRuns.triggeredAt,
1115
+ idempotencyKey: routineRuns.idempotencyKey,
1116
+ triggerPayload: routineRuns.triggerPayload,
1117
+ linkedIssueId: routineRuns.linkedIssueId,
1118
+ coalescedIntoRunId: routineRuns.coalescedIntoRunId,
1119
+ failureReason: routineRuns.failureReason,
1120
+ completedAt: routineRuns.completedAt,
1121
+ createdAt: routineRuns.createdAt,
1122
+ updatedAt: routineRuns.updatedAt,
1123
+ triggerKind: routineTriggers.kind,
1124
+ triggerLabel: routineTriggers.label,
1125
+ issueIdentifier: issues.identifier,
1126
+ issueTitle: issues.title,
1127
+ issueStatus: issues.status,
1128
+ issuePriority: issues.priority,
1129
+ issueUpdatedAt: issues.updatedAt,
1130
+ })
1131
+ .from(routineRuns)
1132
+ .leftJoin(routineTriggers, eq(routineRuns.triggerId, routineTriggers.id))
1133
+ .leftJoin(issues, eq(routineRuns.linkedIssueId, issues.id))
1134
+ .where(eq(routineRuns.routineId, routineId))
1135
+ .orderBy(desc(routineRuns.createdAt))
1136
+ .limit(cappedLimit);
1137
+
1138
+ return rows.map((row) => ({
1139
+ id: row.id,
1140
+ companyId: row.companyId,
1141
+ routineId: row.routineId,
1142
+ triggerId: row.triggerId,
1143
+ source: row.source as RoutineRunSummary["source"],
1144
+ status: row.status as RoutineRunSummary["status"],
1145
+ triggeredAt: row.triggeredAt,
1146
+ idempotencyKey: row.idempotencyKey,
1147
+ triggerPayload: row.triggerPayload as Record<string, unknown> | null,
1148
+ linkedIssueId: row.linkedIssueId,
1149
+ coalescedIntoRunId: row.coalescedIntoRunId,
1150
+ failureReason: row.failureReason,
1151
+ completedAt: row.completedAt,
1152
+ createdAt: row.createdAt,
1153
+ updatedAt: row.updatedAt,
1154
+ linkedIssue: row.linkedIssueId
1155
+ ? {
1156
+ id: row.linkedIssueId,
1157
+ identifier: row.issueIdentifier,
1158
+ title: row.issueTitle ?? "Routine execution",
1159
+ status: row.issueStatus ?? "todo",
1160
+ priority: row.issuePriority ?? "medium",
1161
+ updatedAt: row.issueUpdatedAt ?? row.updatedAt,
1162
+ }
1163
+ : null,
1164
+ trigger: row.triggerId
1165
+ ? {
1166
+ id: row.triggerId,
1167
+ kind: row.triggerKind as NonNullable<RoutineRunSummary["trigger"]>["kind"],
1168
+ label: row.triggerLabel,
1169
+ }
1170
+ : null,
1171
+ }));
1172
+ },
1173
+
1174
+ tickScheduledTriggers: async (now: Date = new Date()) => {
1175
+ const due = await db
1176
+ .select({
1177
+ trigger: routineTriggers,
1178
+ routine: routines,
1179
+ })
1180
+ .from(routineTriggers)
1181
+ .innerJoin(routines, eq(routineTriggers.routineId, routines.id))
1182
+ .where(
1183
+ and(
1184
+ eq(routineTriggers.kind, "schedule"),
1185
+ eq(routineTriggers.enabled, true),
1186
+ eq(routines.status, "active"),
1187
+ isNotNull(routineTriggers.nextRunAt),
1188
+ lte(routineTriggers.nextRunAt, now),
1189
+ ),
1190
+ )
1191
+ .orderBy(asc(routineTriggers.nextRunAt), asc(routineTriggers.createdAt));
1192
+
1193
+ let triggered = 0;
1194
+ for (const row of due) {
1195
+ if (!row.trigger.nextRunAt || !row.trigger.cronExpression || !row.trigger.timezone) continue;
1196
+
1197
+ let runCount = 1;
1198
+ let claimedNextRunAt = nextCronTickInTimeZone(row.trigger.cronExpression, row.trigger.timezone, now);
1199
+
1200
+ if (row.routine.catchUpPolicy === "enqueue_missed_with_cap") {
1201
+ let cursor: Date | null = row.trigger.nextRunAt;
1202
+ runCount = 0;
1203
+ while (cursor && cursor <= now && runCount < MAX_CATCH_UP_RUNS) {
1204
+ runCount += 1;
1205
+ claimedNextRunAt = nextCronTickInTimeZone(row.trigger.cronExpression, row.trigger.timezone, cursor);
1206
+ cursor = claimedNextRunAt;
1207
+ }
1208
+ }
1209
+
1210
+ const claimed = await db
1211
+ .update(routineTriggers)
1212
+ .set({
1213
+ nextRunAt: claimedNextRunAt,
1214
+ updatedAt: new Date(),
1215
+ })
1216
+ .where(
1217
+ and(
1218
+ eq(routineTriggers.id, row.trigger.id),
1219
+ eq(routineTriggers.enabled, true),
1220
+ eq(routineTriggers.nextRunAt, row.trigger.nextRunAt),
1221
+ ),
1222
+ )
1223
+ .returning({ id: routineTriggers.id })
1224
+ .then((rows) => rows[0] ?? null);
1225
+ if (!claimed) continue;
1226
+
1227
+ for (let i = 0; i < runCount; i += 1) {
1228
+ await dispatchRoutineRun({
1229
+ routine: row.routine,
1230
+ trigger: row.trigger,
1231
+ source: "schedule",
1232
+ });
1233
+ triggered += 1;
1234
+ }
1235
+ }
1236
+
1237
+ return { triggered };
1238
+ },
1239
+
1240
+ syncRunStatusForIssue: async (issueId: string) => {
1241
+ const issue = await db
1242
+ .select({
1243
+ id: issues.id,
1244
+ status: issues.status,
1245
+ originKind: issues.originKind,
1246
+ originRunId: issues.originRunId,
1247
+ })
1248
+ .from(issues)
1249
+ .where(eq(issues.id, issueId))
1250
+ .then((rows) => rows[0] ?? null);
1251
+ if (!issue || issue.originKind !== "routine_execution" || !issue.originRunId) return null;
1252
+ if (issue.status === "done") {
1253
+ return finalizeRun(issue.originRunId, {
1254
+ status: "completed",
1255
+ completedAt: new Date(),
1256
+ });
1257
+ }
1258
+ if (issue.status === "blocked" || issue.status === "cancelled") {
1259
+ return finalizeRun(issue.originRunId, {
1260
+ status: "failed",
1261
+ failureReason: `Execution issue moved to ${issue.status}`,
1262
+ completedAt: new Date(),
1263
+ });
1264
+ }
1265
+ return null;
1266
+ },
1267
+ };
1268
+ }
1269
+