@temmo/cli 0.0.0-stage → 0.19.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 (445) hide show
  1. package/.claude-plugin/marketplace.json +14 -0
  2. package/.claude-plugin/plugin.json +16 -0
  3. package/.codex-plugin/plugin.json +30 -0
  4. package/.cursor-plugin/plugin.json +22 -0
  5. package/.mcp.json +18 -0
  6. package/LICENSE +202 -0
  7. package/README.md +82 -2
  8. package/THIRD_PARTY_NOTICES +32 -0
  9. package/commands/afk.md +17 -0
  10. package/deploy/build-ui.mjs +65 -0
  11. package/deploy/claude/README.md +16 -0
  12. package/deploy/claude/auto-mode.json +31 -0
  13. package/deploy/postgres/compose.yaml +26 -0
  14. package/deploy/temmo-runner.service +24 -0
  15. package/deploy/verify-ui.mjs +15 -0
  16. package/harness-core/README.md +27 -0
  17. package/harness-core/bin/harness.mjs +17 -0
  18. package/harness-core/package.json +10 -0
  19. package/harness-core/stage.mjs +108 -0
  20. package/harness-core/stages/commit.md +7 -0
  21. package/harness-core/stages/pr.md +7 -0
  22. package/harness-core/stages/push.md +7 -0
  23. package/hooks/codex-hooks.json +14 -0
  24. package/hooks/cursor-hooks.json +17 -0
  25. package/hooks/hooks.json +27 -0
  26. package/lib/acp/permission.js +72 -0
  27. package/lib/acp/sessionConfig.js +109 -0
  28. package/lib/activity.js +244 -0
  29. package/lib/agent-guard.js +72 -0
  30. package/lib/agents-route.js +55 -0
  31. package/lib/agents.js +213 -0
  32. package/lib/agui.js +255 -0
  33. package/lib/alerts.js +36 -0
  34. package/lib/analyze-otlp.js +46 -0
  35. package/lib/analyze-run-code.js +397 -0
  36. package/lib/analyze-sources.js +372 -0
  37. package/lib/approval-card.js +54 -0
  38. package/lib/approval-cli.js +53 -0
  39. package/lib/approval-request.js +81 -0
  40. package/lib/approval-signer.js +48 -0
  41. package/lib/approvals.js +295 -0
  42. package/lib/attachment-cache.js +236 -0
  43. package/lib/attachment.js +63 -0
  44. package/lib/blocked.js +20 -0
  45. package/lib/build-review.js +90 -0
  46. package/lib/builder/cli.js +90 -0
  47. package/lib/builder/policy.js +176 -0
  48. package/lib/builder/recover.js +189 -0
  49. package/lib/builder/run.js +240 -0
  50. package/lib/builder/settle.js +198 -0
  51. package/lib/builder/stage.js +240 -0
  52. package/lib/builder/state.js +73 -0
  53. package/lib/builder/supervisor.js +289 -0
  54. package/lib/builder-clean.js +223 -0
  55. package/lib/builder-code.cjs +67 -0
  56. package/lib/builder.js +9 -0
  57. package/lib/bus-postgres.js +281 -0
  58. package/lib/bus.js +349 -0
  59. package/lib/catalog/author.js +278 -0
  60. package/lib/catalog/dot.js +426 -0
  61. package/lib/catalog/pattern-model.js +193 -0
  62. package/lib/catalog/patterns.js +324 -0
  63. package/lib/catalog/projects.js +83 -0
  64. package/lib/catalog/records.js +2 -0
  65. package/lib/catalog/roster.js +70 -0
  66. package/lib/catalog/team-files.js +49 -0
  67. package/lib/catalog/teams.js +109 -0
  68. package/lib/claude-socket.js +333 -0
  69. package/lib/cli.js +741 -0
  70. package/lib/code-mode.js +45 -0
  71. package/lib/code-read-policy.yaml +9 -0
  72. package/lib/code-run.js +461 -0
  73. package/lib/codex-compact.js +141 -0
  74. package/lib/compaction.js +21 -0
  75. package/lib/config.js +424 -0
  76. package/lib/cursor-trace.js +248 -0
  77. package/lib/deep-link.js +20 -0
  78. package/lib/deliver-push.js +120 -0
  79. package/lib/delivery.js +28 -0
  80. package/lib/deploy-tree.js +227 -0
  81. package/lib/durable.js +404 -0
  82. package/lib/factory-tick.js +32 -0
  83. package/lib/family.js +63 -0
  84. package/lib/fetch-origin.js +53 -0
  85. package/lib/format.js +133 -0
  86. package/lib/harness-surface-cli.js +153 -0
  87. package/lib/harness-surface.js +486 -0
  88. package/lib/harness.js +271 -0
  89. package/lib/hook.mjs +291 -0
  90. package/lib/idle.js +40 -0
  91. package/lib/install-cursor.js +115 -0
  92. package/lib/install-opencode.js +105 -0
  93. package/lib/job.js +82 -0
  94. package/lib/land-cli.js +319 -0
  95. package/lib/land-member.js +64 -0
  96. package/lib/land.js +320 -0
  97. package/lib/lessons.js +223 -0
  98. package/lib/limit-alert.js +423 -0
  99. package/lib/limits.js +284 -0
  100. package/lib/machine-prompt.js +19 -0
  101. package/lib/merge-sweep.js +149 -0
  102. package/lib/messaging.js +1002 -0
  103. package/lib/mission-cli.js +103 -0
  104. package/lib/mission.js +241 -0
  105. package/lib/mode.js +215 -0
  106. package/lib/models.js +114 -0
  107. package/lib/names.js +86 -0
  108. package/lib/opencode-api.js +57 -0
  109. package/lib/opencode-plugin.mjs +313 -0
  110. package/lib/operator-token.js +78 -0
  111. package/lib/operator.js +187 -0
  112. package/lib/pad-activity.js +143 -0
  113. package/lib/pad-fresh.js +44 -0
  114. package/lib/pad.js +198 -0
  115. package/lib/pattern-cli.js +120 -0
  116. package/lib/pattern-compiler.js +68 -0
  117. package/lib/pattern-runs.js +795 -0
  118. package/lib/pattern-stall.js +58 -0
  119. package/lib/pattern-tick.js +45 -0
  120. package/lib/pattern-workflow.js +69 -0
  121. package/lib/pi-extension.mjs +98 -0
  122. package/lib/pi.js +57 -0
  123. package/lib/plugin-copy.js +76 -0
  124. package/lib/pm-review.js +32 -0
  125. package/lib/pm-workspace.js +87 -0
  126. package/lib/postgres.js +115 -0
  127. package/lib/pr-card.js +34 -0
  128. package/lib/probe.js +295 -0
  129. package/lib/process.js +67 -0
  130. package/lib/project-pause.js +23 -0
  131. package/lib/prune.js +793 -0
  132. package/lib/questions.js +250 -0
  133. package/lib/receipts.js +63 -0
  134. package/lib/reflect.js +962 -0
  135. package/lib/rename-migration.js +118 -0
  136. package/lib/run-terminal.js +437 -0
  137. package/lib/runner-request.js +33 -0
  138. package/lib/sandbox-app.js +120 -0
  139. package/lib/sandbox-claims.js +258 -0
  140. package/lib/sandbox-cli.js +188 -0
  141. package/lib/sandbox-hosts-cli.js +68 -0
  142. package/lib/sandbox-hosts.js +94 -0
  143. package/lib/sandbox-pr.js +102 -0
  144. package/lib/sandbox-proposal.js +367 -0
  145. package/lib/sandbox-tools.js +143 -0
  146. package/lib/sandbox.js +501 -0
  147. package/lib/schedule-session.js +68 -0
  148. package/lib/session-activity.js +67 -0
  149. package/lib/session-events.js +94 -0
  150. package/lib/sessions/control.js +244 -0
  151. package/lib/sessions/git-refs.js +265 -0
  152. package/lib/sessions/launch.js +359 -0
  153. package/lib/sessions/registry.js +450 -0
  154. package/lib/sessions/scope.js +111 -0
  155. package/lib/setup.js +377 -0
  156. package/lib/signed-approval.js +225 -0
  157. package/lib/slash.js +167 -0
  158. package/lib/spawn-cli.js +45 -0
  159. package/lib/spawn.js +107 -0
  160. package/lib/start-limit.js +58 -0
  161. package/lib/state.js +24 -0
  162. package/lib/stop.js +308 -0
  163. package/lib/store-read.js +62 -0
  164. package/lib/store.js +252 -0
  165. package/lib/subagent-guard.js +240 -0
  166. package/lib/surfaces/channel-post.js +43 -0
  167. package/lib/surfaces/instructions.js +15 -0
  168. package/lib/surfaces/mcp-reload.js +144 -0
  169. package/lib/surfaces/ops.js +629 -0
  170. package/lib/surfaces/render-mcp.js +33 -0
  171. package/lib/surfaces/run-terminal-ops.js +40 -0
  172. package/lib/surfaces/sandbox-ops.js +36 -0
  173. package/lib/surfaces/schema.js +7 -0
  174. package/lib/surfaces/task-view.js +90 -0
  175. package/lib/surfaces/types.js +4 -0
  176. package/lib/task-cli.js +274 -0
  177. package/lib/task-order.js +34 -0
  178. package/lib/task-order.mjs +2 -0
  179. package/lib/task-route.js +125 -0
  180. package/lib/tasks.js +631 -0
  181. package/lib/team-permission.js +34 -0
  182. package/lib/team-templates/blitz/team.dot +9 -0
  183. package/lib/team-templates/factory/team.dot +26 -0
  184. package/lib/team-templates/feature/team.dot +14 -0
  185. package/lib/team-templates/fix-and-review/team.dot +12 -0
  186. package/lib/team-templates/product/team.dot +16 -0
  187. package/lib/team-templates/release/team.dot +7 -0
  188. package/lib/team-templates/review/team.dot +6 -0
  189. package/lib/terminal-draft.js +42 -0
  190. package/lib/thread-branch.js +82 -0
  191. package/lib/thread-channel-store.js +181 -0
  192. package/lib/thread-channels.js +116 -0
  193. package/lib/thread-listening.js +20 -0
  194. package/lib/thread-routes.js +91 -0
  195. package/lib/threads.js +441 -0
  196. package/lib/tool-api.js +33 -0
  197. package/lib/transcript.js +98 -0
  198. package/lib/ui-build-output.js +19 -0
  199. package/lib/ui-capabilities.js +90 -0
  200. package/lib/usage.js +182 -0
  201. package/lib/vendor/mcp-sdk.d.mts +4 -0
  202. package/lib/vendor/mcp-sdk.mjs +17046 -0
  203. package/lib/waiter.js +127 -0
  204. package/lib/workflows.js +546 -0
  205. package/lib/worktree-setup.js +86 -0
  206. package/package.json +110 -4
  207. package/runner/adapters/claude.js +465 -0
  208. package/runner/adapters/cli-sandbox.js +277 -0
  209. package/runner/adapters/codex.js +675 -0
  210. package/runner/adapters/cursor.mjs +937 -0
  211. package/runner/adapters/fake.js +119 -0
  212. package/runner/adapters/opencode-sandbox.js +370 -0
  213. package/runner/adapters/opencode.js +486 -0
  214. package/runner/adapters/pi-sandbox.js +134 -0
  215. package/runner/adapters/pi.js +364 -0
  216. package/runner/client.js +40 -0
  217. package/runner/contract.js +129 -0
  218. package/runner/control.js +178 -0
  219. package/runner/delivery.js +184 -0
  220. package/runner/factory-tick.mjs +10 -0
  221. package/runner/lock.js +41 -0
  222. package/runner/main.mjs +118 -0
  223. package/runner/pattern-tick.mjs +16 -0
  224. package/runner/publish.js +113 -0
  225. package/runner/runner.js +2612 -0
  226. package/runner/sandbox-run.mjs +239 -0
  227. package/runner/schedules.js +294 -0
  228. package/runner/task-wake.js +59 -0
  229. package/scripts/ai-collab +3 -0
  230. package/scripts/ai-collab-bus.mjs +4 -0
  231. package/scripts/ai-collab-code-mcp.mjs +3 -0
  232. package/scripts/ai-collab-hook +3 -0
  233. package/scripts/ai-collab-hook.mjs +3 -0
  234. package/scripts/ai-collab-mcp-tools.mjs +2 -0
  235. package/scripts/ai-collab-mcp.mjs +3 -0
  236. package/scripts/ai-collab.mjs +3 -0
  237. package/scripts/install-cursor.mjs +11 -0
  238. package/scripts/install-opencode.mjs +10 -0
  239. package/scripts/temmo +3 -0
  240. package/scripts/temmo-bus.mjs +151 -0
  241. package/scripts/temmo-code-mcp.mjs +63 -0
  242. package/scripts/temmo-hook +3 -0
  243. package/scripts/temmo-hook.mjs +201 -0
  244. package/scripts/temmo-mcp-tools.mjs +22 -0
  245. package/scripts/temmo-mcp.mjs +27 -0
  246. package/scripts/temmo.mjs +4 -0
  247. package/skills/antislop/SKILL.md +701 -0
  248. package/skills/antislop/VERSION +1 -0
  249. package/skills/antislop-code/SKILL.md +128 -0
  250. package/skills/antislop-human/LICENSE-web-quality-skills +21 -0
  251. package/skills/antislop-human/SKILL.md +204 -0
  252. package/skills/antislop-human/contrast-check.py +168 -0
  253. package/skills/antislop-human/contrast-mcp.py +125 -0
  254. package/skills/antislop-human/references/A11Y-PATTERNS.md +249 -0
  255. package/skills/antislop-human/references/WCAG.md +127 -0
  256. package/skills/antislop-layoutmobile/SKILL.md +170 -0
  257. package/skills/antislop-ui/LICENSE-web-quality-skills +21 -0
  258. package/skills/antislop-ui/SKILL.md +351 -0
  259. package/skills/antislop-ui/references/CORE-WEB-VITALS.md +181 -0
  260. package/skills/antislop-ui/references/WEB-BASELINE.md +28 -0
  261. package/skills/harness-surface/SKILL.md +42 -0
  262. package/skills/land/SKILL.md +32 -0
  263. package/skills/memory-file/SKILL.md +39 -0
  264. package/skills/temmo/SKILL.md +101 -0
  265. package/skills/temmo/references/role-programs.md +47 -0
  266. package/skills/ui-sdk/SKILL.md +56 -0
  267. package/skills/ui-sdk/references/agent-ready.md +136 -0
  268. package/skills/ui-sdk/references/build-interface.md +187 -0
  269. package/skills/ui-sdk/references/create-component.md +88 -0
  270. package/skills/ui-sdk/references/patterns.md +246 -0
  271. package/skills/ui-sdk/references/styles.md +66 -0
  272. package/skills/ui-sdk/references/testing.md +172 -0
  273. package/skills/ui-sdk/references/web-components.md +78 -0
  274. package/tools/screen-state.mjs +119 -0
  275. package/tools/smoke-ui.mjs +540 -0
  276. package/web/app/activity.jsx +251 -0
  277. package/web/app/agent-mark.tsx +43 -0
  278. package/web/app/alert-level.jsx +16 -0
  279. package/web/app/api/[action]/route.js +8 -0
  280. package/web/app/api/auth/[step]/route.js +12 -0
  281. package/web/app/api/events/route.js +8 -0
  282. package/web/app/api/file/[name]/route.js +8 -0
  283. package/web/app/api/land/route.js +12 -0
  284. package/web/app/api/lessons/route.js +8 -0
  285. package/web/app/api/push/key/route.js +8 -0
  286. package/web/app/api/push/subscribe/route.js +12 -0
  287. package/web/app/api/push/test/route.js +8 -0
  288. package/web/app/api/refs/route.js +8 -0
  289. package/web/app/api/review-diff/route.js +8 -0
  290. package/web/app/api/schedules/route.js +8 -0
  291. package/web/app/api/thread-diff/route.js +8 -0
  292. package/web/app/api/version/route.js +6 -0
  293. package/web/app/cards.jsx +189 -0
  294. package/web/app/chat-api.js +82 -0
  295. package/web/app/chat-composer.jsx +313 -0
  296. package/web/app/chat-console.jsx +691 -0
  297. package/web/app/chat-image.tsx +61 -0
  298. package/web/app/chat-message.jsx +122 -0
  299. package/web/app/chat-shared.jsx +59 -0
  300. package/web/app/chat-sidebar.jsx +25 -0
  301. package/web/app/chat-stream.js +127 -0
  302. package/web/app/chat.jsx +31 -0
  303. package/web/app/compactions.jsx +57 -0
  304. package/web/app/composer-actions.tsx +87 -0
  305. package/web/app/decisions.jsx +53 -0
  306. package/web/app/fonts/OFL-hanken-grotesk.txt +93 -0
  307. package/web/app/fonts/OFL-ibm-plex-mono.txt +93 -0
  308. package/web/app/fonts/hanken-grotesk-latin-wght-normal.woff2 +0 -0
  309. package/web/app/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
  310. package/web/app/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
  311. package/web/app/globals.css +199 -0
  312. package/web/app/home.jsx +246 -0
  313. package/web/app/icon.svg +1 -0
  314. package/web/app/land-panel.jsx +63 -0
  315. package/web/app/land-reviews.jsx +20 -0
  316. package/web/app/layout.jsx +17 -0
  317. package/web/app/lessons.tsx +76 -0
  318. package/web/app/logo.tsx +13 -0
  319. package/web/app/logos.jsx +16 -0
  320. package/web/app/manifest.js +8 -0
  321. package/web/app/mode-menu.tsx +46 -0
  322. package/web/app/new-session.jsx +275 -0
  323. package/web/app/notify.jsx +180 -0
  324. package/web/app/outcomes.tsx +94 -0
  325. package/web/app/page.jsx +9 -0
  326. package/web/app/pattern-graph.jsx +75 -0
  327. package/web/app/patterns-page.jsx +293 -0
  328. package/web/app/phone-nav.tsx +36 -0
  329. package/web/app/progress-feed.tsx +33 -0
  330. package/web/app/providers.tsx +27 -0
  331. package/web/app/quote.jsx +15 -0
  332. package/web/app/run-card.tsx +200 -0
  333. package/web/app/run-requests.tsx +148 -0
  334. package/web/app/scheduled.jsx +105 -0
  335. package/web/app/session-panel.tsx +174 -0
  336. package/web/app/session-toolbar.tsx +180 -0
  337. package/web/app/shadcn.css +638 -0
  338. package/web/app/shipped.jsx +49 -0
  339. package/web/app/subagent-runs.jsx +31 -0
  340. package/web/app/task-graph.jsx +67 -0
  341. package/web/app/tasks-strip.tsx +36 -0
  342. package/web/app/tasks.jsx +375 -0
  343. package/web/app/team-author.jsx +145 -0
  344. package/web/app/team-editor.jsx +88 -0
  345. package/web/app/thread-agents.tsx +32 -0
  346. package/web/app/thread-place.tsx +9 -0
  347. package/web/app/thread-sessions.tsx +149 -0
  348. package/web/app/thread-sidebar.tsx +418 -0
  349. package/web/app/thread-switcher.tsx +27 -0
  350. package/web/app/tool-diff.jsx +94 -0
  351. package/web/components/a2ui/controls.jsx +36 -0
  352. package/web/components/a2ui/option-picker.jsx +23 -0
  353. package/web/components/a2ui/script.tsx +121 -0
  354. package/web/components/a2ui/surface.jsx +81 -0
  355. package/web/components/chat/thread.jsx +50 -0
  356. package/web/components/script-text.tsx +42 -0
  357. package/web/components/ui/avatar.jsx +115 -0
  358. package/web/components/ui/badge.jsx +47 -0
  359. package/web/components/ui/button.jsx +63 -0
  360. package/web/components/ui/chat-container.jsx +52 -0
  361. package/web/components/ui/choice-list.tsx +72 -0
  362. package/web/components/ui/code-block.jsx +60 -0
  363. package/web/components/ui/copy-button.tsx +41 -0
  364. package/web/components/ui/dropdown-menu.jsx +257 -0
  365. package/web/components/ui/markdown.jsx +84 -0
  366. package/web/components/ui/message.jsx +28 -0
  367. package/web/components/ui/popover.jsx +33 -0
  368. package/web/components/ui/scroll-button.jsx +34 -0
  369. package/web/components/ui/select.jsx +189 -0
  370. package/web/components/ui/sheet.jsx +152 -0
  371. package/web/components/ui/sonner.jsx +10 -0
  372. package/web/components/ui/tabs.jsx +88 -0
  373. package/web/components/ui/textarea.jsx +20 -0
  374. package/web/components/ui/tooltip.jsx +56 -0
  375. package/web/components.json +24 -0
  376. package/web/instrumentation.js +8 -0
  377. package/web/lib/a2ui-catalog.js +34 -0
  378. package/web/lib/a2ui-pr.js +76 -0
  379. package/web/lib/a2ui-run-catalog.js +18 -0
  380. package/web/lib/a2ui-run.js +93 -0
  381. package/web/lib/a2ui.js +262 -0
  382. package/web/lib/activity-rows.js +275 -0
  383. package/web/lib/agent-detail.js +5 -0
  384. package/web/lib/alert-level.js +44 -0
  385. package/web/lib/approval-mode.js +22 -0
  386. package/web/lib/chat-turns.js +174 -0
  387. package/web/lib/child-subagents.js +16 -0
  388. package/web/lib/compaction-view.js +48 -0
  389. package/web/lib/composer-actions.js +40 -0
  390. package/web/lib/context-view.js +57 -0
  391. package/web/lib/fuzzy.js +26 -0
  392. package/web/lib/highlight.js +44 -0
  393. package/web/lib/lessons-view.js +23 -0
  394. package/web/lib/mentions.js +16 -0
  395. package/web/lib/message-routing.js +105 -0
  396. package/web/lib/new-session.js +85 -0
  397. package/web/lib/operator-messages.js +28 -0
  398. package/web/lib/pattern-graph.js +165 -0
  399. package/web/lib/pattern-view.js +33 -0
  400. package/web/lib/pending-summary.js +18 -0
  401. package/web/lib/permission-modes.js +30 -0
  402. package/web/lib/project-feed.js +107 -0
  403. package/web/lib/quote.js +7 -0
  404. package/web/lib/reply-quote.js +31 -0
  405. package/web/lib/scheduled.js +79 -0
  406. package/web/lib/selection.js +110 -0
  407. package/web/lib/send-confirmation.js +22 -0
  408. package/web/lib/session-dead.js +10 -0
  409. package/web/lib/session-state.js +132 -0
  410. package/web/lib/sidebar.js +15 -0
  411. package/web/lib/slash-commands.js +164 -0
  412. package/web/lib/start-default.js +35 -0
  413. package/web/lib/start-mode.js +35 -0
  414. package/web/lib/stream-views.js +49 -0
  415. package/web/lib/subagent-state.js +20 -0
  416. package/web/lib/task-board.js +54 -0
  417. package/web/lib/task-graph.js +183 -0
  418. package/web/lib/task-tags.js +41 -0
  419. package/web/lib/team-editor.js +10 -0
  420. package/web/lib/thread-groups.js +86 -0
  421. package/web/lib/threads.js +28 -0
  422. package/web/lib/tool-diff.js +273 -0
  423. package/web/lib/ui-events.js +58 -0
  424. package/web/lib/utils.js +5 -0
  425. package/web/lib/view-memory.js +25 -0
  426. package/web/next.config.mjs +37 -0
  427. package/web/postcss.config.mjs +1 -0
  428. package/web/proxy.js +25 -0
  429. package/web/public/sw.js +39 -0
  430. package/web/server/auth.js +178 -0
  431. package/web/server/dispatch.js +293 -0
  432. package/web/server/history.js +56 -0
  433. package/web/server/hosted.js +58 -0
  434. package/web/server/hub.js +126 -0
  435. package/web/server/instance.js +5 -0
  436. package/web/server/land-reviews.js +64 -0
  437. package/web/server/push.js +148 -0
  438. package/web/server/run-terminal.js +79 -0
  439. package/web/server/schedules.js +38 -0
  440. package/web/server/shipped.js +51 -0
  441. package/web/server/task-board.js +71 -0
  442. package/web/server/threads.js +209 -0
  443. package/web/server/ui.js +2937 -0
  444. package/web/tsconfig.base.json +16 -0
  445. package/web/tsconfig.json +9 -0
@@ -0,0 +1,546 @@
1
+ /**
2
+ * Workflow engine switch: `workflowEngine: "sqlite"` (default) keeps the hand-rolled durable log;
3
+ * `"dbos"` runs the same interface on DBOS Transact TS over Postgres. Callers (runner, schedules,
4
+ * delivery, pattern runs) use one interface; methods that were sync become async, which the
5
+ * call sites await. DBOS equivalents verified against the 5.7.0 d.ts and docs.dbos.dev:
6
+ * startWorkflow→startWorkflow(workflowID), step→runStep, send/recv→send(idempotencyKey)/recv,
7
+ * status/result→listWorkflows/retrieveWorkflow, cancel→cancelWorkflow, recovery→launch().
8
+ * Not public API: pendingCount, drain and the send dedupe probe read dbos.notifications, readPriorSteps reads
9
+ * dbos.operation_outputs, the version guard reads and drains dbos.workflow_status, and runWithTopContext comes
10
+ * from internal/context. The exact 5.7.0 pin in package.json holds that schema; an SDK upgrade must recheck them.
11
+ */
12
+ import { DBOS } from "@dbos-inc/dbos-sdk";
13
+ import { runWithTopContext } from "@dbos-inc/dbos-sdk/internal/context";
14
+ import pg from "pg";
15
+ import { openDurable } from "./durable.js";
16
+ import { PG_CONNECT_TIMEOUT_MS } from "./postgres.js";
17
+ /** The DBOS applicationVersion: bump it whenever a workflow's recorded op sequence changes (test/dbos-step-sequences.test.mjs). */
18
+ export const DBOS_APP_VERSION = "temmo-1";
19
+ /** Opens the engine named by `engine`: "sqlite" (default) or "dbos". */
20
+ export async function openWorkflows(opts) {
21
+ if ((opts.engine || "sqlite") === "sqlite") {
22
+ if (!opts.file)
23
+ throw new Error("openWorkflows: the sqlite engine needs a file");
24
+ return adaptSqlite(openDurable(opts.file, { now: opts.now }));
25
+ }
26
+ return await openDbosEngine(opts);
27
+ }
28
+ /** Wraps the sync sqlite durable log so both engines expose one async interface; awaiting a sync value is a no-op. */
29
+ export function adaptSqlite(raw) {
30
+ const d = raw;
31
+ return {
32
+ isAsync: true,
33
+ register: (name, fn) => d.register(name, fn),
34
+ scheduled: (name, opts, fn) => d.scheduled(name, opts, fn),
35
+ hasSchedule: (name) => d.hasSchedule(name),
36
+ async startSchedules() { d.startSchedules(); },
37
+ async runScheduled(name) { return d.runScheduled(name); },
38
+ async schedules() { return d.schedules(); },
39
+ async scheduleRuns(name, limit) { return d.scheduleRuns(name, limit); },
40
+ async startWorkflow(name, id, input) { return d.startWorkflow(name, id, input); },
41
+ async startWorkflowOnce(name, id, input) {
42
+ const run = d.startWorkflowOnce(name, id, input);
43
+ if (run === null)
44
+ return false;
45
+ run.catch(() => { }); // the caller learns "started" from the boolean; the result promise is the runner's business
46
+ return true;
47
+ },
48
+ async listNamed(name, limit) { return d.listNamed(name, limit); },
49
+ async pending() { return d.pending(); },
50
+ async recover() { return d.recover(); },
51
+ async send(workflowId, topic, value, o) { return d.send(workflowId, topic, value, o); },
52
+ async status(id) { return d.status(id); },
53
+ async result(id) { return d.result(id); },
54
+ async cancel(id) { d.cancel(id); },
55
+ async steps(id) { return d.steps(id); },
56
+ async getKv(key) { return d.getKv(key); },
57
+ async setKv(key, value) { d.setKv(key, value); },
58
+ async prune(names, before) { return d.prune(names, before); },
59
+ async drain(workflowId, topic) { return d.drain(workflowId, topic); },
60
+ async pendingCount(workflowId, topic) { return d.pendingCount(workflowId, topic); },
61
+ async close() { await d.close(); },
62
+ };
63
+ }
64
+ const MAX_TIMER_MS = 2 ** 31 - 1;
65
+ const GRACE_MS = 60_000;
66
+ const tickName = (name) => `scheduled:${name}`;
67
+ const tickId = (name, at) => `${name}@${new Date(at).toISOString()}`;
68
+ const dueAt = (everyMs, at) => Math.floor(at / everyMs) * everyMs;
69
+ const asJson = (value) => (value && typeof value === "object" ? value : {});
70
+ /** DBOS stores workflow arguments as an array; the engine passes one object argument. */
71
+ const wfInput = (r) => (Array.isArray(r.input) ? asJson(r.input[0]) : asJson(r.input));
72
+ /**
73
+ * A run's recorded op names, read straight from DBOS's operation table: a DBOS.listWorkflowSteps call inside a
74
+ * workflow would itself be recorded and replay stale. Retries a failing query with backoff, then throws: an
75
+ * empty answer would read as "no prior record" and re-run a cut step.
76
+ */
77
+ export async function readPriorSteps(query, id, { attempts = 5, delayMs = 200, log = () => { } } = {}) {
78
+ for (let attempt = 1;; attempt += 1) {
79
+ try {
80
+ const { rows } = await query("SELECT function_name FROM dbos.operation_outputs WHERE workflow_uuid = $1", [id]);
81
+ return rows.map((r) => r.function_name);
82
+ }
83
+ catch (error) {
84
+ const why = error instanceof Error ? error.message : String(error);
85
+ if (attempt >= attempts)
86
+ throw new Error(`prior steps of ${id} unreadable after ${attempts} attempts: ${why}`, { cause: error });
87
+ log(`workflows: prior step lookup for ${id} failed (attempt ${attempt} of ${attempts}), retrying: ${why}`);
88
+ await new Promise((r) => setTimeout(r, delayMs * 2 ** (attempt - 1)));
89
+ }
90
+ }
91
+ }
92
+ /** The DBOS-backed engine. Same surface as openDurable; every query is async (Postgres). */
93
+ async function openDbosEngine({ pgUrl = "", now = Date.now, log = () => { }, applicationVersion = DBOS_APP_VERSION, priorStepsQuery, priorStepsRetry = {} }) {
94
+ const pool = new pg.Pool({ connectionString: pgUrl, max: 5, connectionTimeoutMillis: PG_CONNECT_TIMEOUT_MS });
95
+ const stepQuery = priorStepsQuery ?? ((sql, params) => pool.query(sql, params));
96
+ await pool.query(`CREATE SCHEMA IF NOT EXISTS ai_collab;
97
+ CREATE TABLE IF NOT EXISTS ai_collab.kv (key TEXT PRIMARY KEY, value TEXT NOT NULL);
98
+ CREATE TABLE IF NOT EXISTS ai_collab.skipped (id TEXT PRIMARY KEY, name TEXT NOT NULL, input TEXT NOT NULL, reason TEXT NOT NULL, created_at BIGINT NOT NULL, app_version TEXT);
99
+ ALTER TABLE ai_collab.skipped ADD COLUMN IF NOT EXISTS app_version TEXT;
100
+ DROP TABLE IF EXISTS ai_collab.started;
101
+ DROP TABLE IF EXISTS ai_collab.dedupe;`);
102
+ const registry = new Map();
103
+ const dbosFns = new Map();
104
+ const schedules = new Map();
105
+ const closing = new AbortController();
106
+ const ctrls = new Map(); // one per live run, so cancel() can abort that workflow's signal
107
+ let launched = null;
108
+ // close() aborts every context signal, like the sqlite engine. DBOS records whatever a step or workflow throws
109
+ // as a terminal error, so a run unwinding on that abort parks instead: shutdown leaves it PENDING with its
110
+ // step cut, and the next boot recovers it.
111
+ async function unlessClosing(fn) {
112
+ try {
113
+ return await fn();
114
+ }
115
+ catch (error) {
116
+ if (closing.signal.aborted)
117
+ return await new Promise(() => { });
118
+ throw error;
119
+ }
120
+ }
121
+ // Registration must finish before launch; the runner registers at boot, so launch on first async use.
122
+ function ready() {
123
+ if (!launched) {
124
+ launched = (async () => {
125
+ for (const name of registry.keys())
126
+ if (!dbosFns.has(name))
127
+ registerDbos(name);
128
+ await versionGuard();
129
+ // DBOS hashes registered functions into the app version by default; our registrations are one wrapper whose
130
+ // count changes with the code, which would orphan PENDING workflows on every deploy. Pin it instead.
131
+ // The DBOS app name stays ai-collab across the product rename, so workflows recorded before it still recover.
132
+ DBOS.setConfig({ name: "ai-collab", systemDatabaseUrl: pgUrl, applicationVersion });
133
+ await DBOS.launch();
134
+ })();
135
+ }
136
+ return launched;
137
+ }
138
+ // Upgrade rule: DBOS only recovers PENDING runs recorded under the CURRENT applicationVersion, so a
139
+ // bump orphans the old ones (dropped records and reservations). TEMMO_DBOS_VERSION_GUARD: refuse
140
+ // (default: boot fails listing every foreign-version run of our own workflows), drain (cancel them,
141
+ // then boot) or off (the test suite, whose shared database holds stale rows). Bump only after the old fleet drains.
142
+ async function versionGuard() {
143
+ const mode = process.env.TEMMO_DBOS_VERSION_GUARD || "refuse";
144
+ if (mode !== "refuse" && mode !== "drain")
145
+ return;
146
+ const names = [...registry.keys()];
147
+ if (!names.length)
148
+ return;
149
+ let ids;
150
+ try {
151
+ const { rows } = await pool.query("SELECT workflow_uuid FROM dbos.workflow_status WHERE application_version <> $1 AND status IN ('PENDING', 'ENQUEUED') AND name = ANY($2) ORDER BY created_at", [applicationVersion, names]);
152
+ ids = rows.map((r) => r.workflow_uuid);
153
+ }
154
+ catch (error) {
155
+ // A fresh database has no dbos schema until launch() migrates it, so it holds no foreign runs either.
156
+ const code = error?.code;
157
+ if (code === "42P01" || code === "3F000")
158
+ return;
159
+ throw new Error(`workflows: version guard query failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
160
+ }
161
+ if (!ids.length)
162
+ return;
163
+ if (mode === "refuse")
164
+ throw new Error(`workflows: ${ids.length} PENDING run(s) recorded under another application version (${ids.join(", ")}); drain the old fleet first, or boot with TEMMO_DBOS_VERSION_GUARD=drain to cancel them`);
165
+ await pool.query("UPDATE dbos.workflow_status SET status = 'CANCELLED', updated_at = $2 WHERE workflow_uuid = ANY($1) AND status IN ('PENDING', 'ENQUEUED')", [ids, now()]);
166
+ log(`workflows: drained ${ids.length} PENDING run(s) recorded under another application version: ${ids.join(", ")}`);
167
+ }
168
+ function registerDbos(name) {
169
+ const wf = registry.get(name);
170
+ if (!wf)
171
+ throw new Error(`no workflow named ${name}`);
172
+ const fn = DBOS.registerWorkflow(async (input) => {
173
+ const id = String(asJson(input).__id ?? "");
174
+ const ctrl = new AbortController();
175
+ ctrls.set(id, ctrl);
176
+ try {
177
+ // Steps recorded by an earlier life of this run: they mark cuts (started, never finished)
178
+ // and tell the workflow it is replaying. Without them a cut step would re-run (a second harness
179
+ // turn), and a thrown error would record a terminal ERROR: park the run PENDING for the next boot.
180
+ let prior;
181
+ try {
182
+ prior = await readPriorSteps(stepQuery, id, { ...priorStepsRetry, log });
183
+ }
184
+ catch (error) {
185
+ log(`workflows: ${id} parked PENDING until the next boot: ${error instanceof Error ? error.message : String(error)}`);
186
+ return await new Promise(() => { });
187
+ }
188
+ return await unlessClosing(() => wf(makeContext(id, input, ctrl, prior), input));
189
+ }
190
+ finally {
191
+ ctrls.delete(id);
192
+ }
193
+ }, { name });
194
+ dbosFns.set(name, fn);
195
+ return fn;
196
+ }
197
+ function makeContext(id, input, ctrl, prior) {
198
+ const signal = AbortSignal.any([closing.signal, ctrl.signal]);
199
+ const priorOps = prior.length;
200
+ let consumed = 0; // recorded rows this run issued or replayed: a step 2 (marker + result), a recv 1 or 2, a sleep 0 or 1
201
+ // Cut detection keys on the occurrence, not the name: the runner repeats step names in loops
202
+ // (wake.reserve, wake.send, wake.wait), so a name anywhere in the record says nothing about *this*
203
+ // occurrence. Occurrence k of a name is cut when the record holds >= k markers but < k results.
204
+ const priorMarkers = new Map();
205
+ const priorResults = new Map();
206
+ for (const n of prior) {
207
+ if (n.endsWith("!started"))
208
+ priorMarkers.set(n, (priorMarkers.get(n) ?? 0) + 1);
209
+ else
210
+ priorResults.set(n, (priorResults.get(n) ?? 0) + 1);
211
+ }
212
+ const issued = new Map();
213
+ const recvOp = async (topic, opts) => {
214
+ // DBOS records each recv as a DBOS.recv row; a timeout above 0 first records its deadline as a DBOS.sleep row.
215
+ consumed += opts.timeoutSeconds > 0 ? 2 : 1;
216
+ return await DBOS.recv(topic, opts);
217
+ };
218
+ return {
219
+ id, input, signal,
220
+ get replaying() { return consumed < priorOps; },
221
+ step: async (name, fn, { onCut } = {}) => {
222
+ // A marker step records that fn started; a marker without a result at context build time is a cut
223
+ // (killed mid-step): onCut answers it once, mirroring the sqlite engine, and fn never re-runs.
224
+ const marker = `${name}!started`;
225
+ const k = (issued.get(name) ?? 0) + 1;
226
+ issued.set(name, k);
227
+ consumed += 1;
228
+ await DBOS.runStep(async () => true, { name: marker });
229
+ consumed += 1;
230
+ if (onCut && k > (priorResults.get(name) ?? 0) && k <= (priorMarkers.get(marker) ?? 0)) {
231
+ return await DBOS.runStep(() => unlessClosing(async () => await onCut()), { name });
232
+ }
233
+ return await DBOS.runStep(() => unlessClosing(fn), { name });
234
+ },
235
+ recv: async (topic, { all = false, timeoutSeconds = null } = {}) => {
236
+ if (!all) {
237
+ const first = await recvOp(topic, { timeoutSeconds: 0 });
238
+ if (first !== null)
239
+ return first;
240
+ for (;;) {
241
+ const next = await recvOp(topic, { timeoutSeconds: 60 });
242
+ if (next !== null)
243
+ return next;
244
+ }
245
+ }
246
+ // Like the sqlite engine: recv-all waits for the first message, then takes the whole backlog.
247
+ // timeoutSeconds 0 never waits: it returns the backlog, empty included (the wake loop polls).
248
+ const values = [];
249
+ if (timeoutSeconds !== 0) {
250
+ for (;;) {
251
+ const first = await recvOp(topic, { timeoutSeconds: 60 });
252
+ if (first !== null) {
253
+ values.push(first);
254
+ break;
255
+ }
256
+ }
257
+ }
258
+ for (;;) {
259
+ const next = await recvOp(topic, { timeoutSeconds: 0 });
260
+ if (next === null)
261
+ break;
262
+ values.push(next);
263
+ }
264
+ return values;
265
+ },
266
+ pending: async (topic) => await pendingCount(id, topic),
267
+ pause: (ms) => new Promise((resolve, reject) => {
268
+ if (signal.aborted)
269
+ return reject(signal.reason);
270
+ const t = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, Math.max(0, ms));
271
+ function onAbort() { clearTimeout(t); reject(signal.reason); }
272
+ signal.addEventListener("abort", onAbort, { once: true });
273
+ }),
274
+ sleep: async (ms) => { consumed += ms > 0 ? 1 : 0; await DBOS.sleep(ms); }, // DBOS records no row for ms <= 0
275
+ };
276
+ }
277
+ function dbosFn(name) {
278
+ const fn = dbosFns.get(name);
279
+ if (fn)
280
+ return fn;
281
+ if (launched)
282
+ throw new Error(`workflow ${name} registered after launch; register before the first async call`);
283
+ return registerDbos(name);
284
+ }
285
+ async function pendingCount(workflowId, topic) {
286
+ const { rows } = await pool.query("SELECT COUNT(*)::int AS n FROM dbos.notifications WHERE destination_uuid = $1 AND topic = $2 AND consumed = false", [workflowId, topic]);
287
+ return rows[0].n;
288
+ }
289
+ function mapStatus(r) {
290
+ return {
291
+ id: r.workflowID, name: r.workflowName, status: r.status,
292
+ output: r.output,
293
+ error: r.error instanceof Error ? r.error.message : (typeof r.error === "string" ? r.error : null),
294
+ input: Array.isArray(r.input) ? r.input[0] : undefined,
295
+ createdAt: r.createdAt, updatedAt: r.updatedAt ?? r.createdAt,
296
+ };
297
+ }
298
+ async function statusRow(id) {
299
+ await ready();
300
+ const rows = await DBOS.listWorkflows({ workflowIDs: [id], loadOutput: true });
301
+ return rows[0] ? mapStatus(rows[0]) : null;
302
+ }
303
+ // A start from inside a workflow is an independent workflow, like on the sqlite engine. DBOS forbids it
304
+ // inside a step (the pattern flow's steps start role sessions), and from a workflow body it records a
305
+ // child start, a DBOS.listWorkflows and a late DBOS.getResult row in the caller (the wake's late handoff),
306
+ // rows `replaying` cannot count. A cleared context makes it a top-level start that records nothing in the
307
+ // caller; the deterministic workflow id keeps a replayed start idempotent.
308
+ function outsideWorkflow(fn) {
309
+ return DBOS.isWithinWorkflow() ? runWithTopContext({}, fn) : fn();
310
+ }
311
+ function startOnce(name, id, input) {
312
+ return outsideWorkflow(() => startOnceTop(name, id, input));
313
+ }
314
+ async function startOnceTop(name, id, input) {
315
+ await ready();
316
+ // Start first: DBOS dedupes by workflowID (a repeat start returns the first run's handle), so no guard row
317
+ // can strand a message when a crash lands between the guard and the start. The pre-check only informs the
318
+ // boolean; two racing callers both reporting "started" is harmless because the workflow itself runs once.
319
+ const existed = Boolean(await statusRow(id));
320
+ const h = await DBOS.startWorkflow(dbosFn(name), { workflowID: id })({ ...input, __id: id });
321
+ h.getResult().catch(() => { });
322
+ return !existed;
323
+ }
324
+ async function pendingIds() {
325
+ await ready();
326
+ const rows = await DBOS.listWorkflows({ status: "PENDING", applicationVersion });
327
+ return rows.filter((r) => registry.has(r.workflowName)).map((r) => r.workflowID);
328
+ }
329
+ // Why a scheduled tick at scheduledTime is skipped for an edited interval, or null.
330
+ async function intervalReason(s, scheduledTime) {
331
+ // No limit before the find: a manual run is the newest row and must not hide the last real tick.
332
+ // Scoped to this application version: PENDING ticks left by an older deploy are orphans for
333
+ // recovery to settle, not runs still going — unscoped they would skip every future tick.
334
+ const rows = await DBOS.listWorkflows({ workflowName: tickName(s.name), applicationVersion, limit: 50, sortDesc: true, loadInput: true });
335
+ const last = rows.find((r) => r.status !== "SKIPPED" && !r.workflowID.includes("@manual@"));
336
+ if (!last)
337
+ return null;
338
+ const previous = Number(wfInput(last).scheduledTime);
339
+ if (scheduledTime - previous >= s.everyMs)
340
+ return null;
341
+ return `interval changed: previous tick ${new Date(previous).toISOString()} is under ${s.everyMs} ms earlier`;
342
+ }
343
+ async function fire(s, scheduledTime, actualTime, { manual = false } = {}) {
344
+ if (closing.signal.aborted)
345
+ return { id: null, status: "closed" };
346
+ await ready();
347
+ const name = tickName(s.name);
348
+ const id = manual ? `${s.name}@manual@${crypto.randomUUID()}` : tickId(s.name, scheduledTime);
349
+ // A boot inside a tick's period fires that tick again; one that already ran is not re-judged against itself.
350
+ if (!manual && (await statusRow(id)))
351
+ return { id, status: "recorded" };
352
+ const input = { scheduledTime, actualTime, ...(manual ? { manual: true } : {}) };
353
+ // Mirror the sqlite engine: a tick that finds the previous run still going is skipped, and every
354
+ // skip is recorded. DBOS has no public SKIPPED status, so the mirror table carries the visibility.
355
+ const inflight = await DBOS.listWorkflows({ workflowName: name, status: ["PENDING", "ENQUEUED"], applicationVersion });
356
+ const reason = (!manual && (await intervalReason(s, scheduledTime))) || (inflight.length > 0 && "previous run still going") || null;
357
+ if (reason) {
358
+ await pool.query("INSERT INTO ai_collab.skipped(id, name, input, reason, created_at, app_version) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING", [id, name, JSON.stringify(input), reason, now(), applicationVersion]);
359
+ return { id, status: "skipped" };
360
+ }
361
+ const started = await startOnce(name, id, input);
362
+ return { id, status: started ? "started" : "recorded" };
363
+ }
364
+ function arm(s) {
365
+ if (closing.signal.aborted)
366
+ return;
367
+ if (s.timer)
368
+ clearTimeout(s.timer);
369
+ const at = now();
370
+ const wait = dueAt(s.everyMs, at) + s.everyMs - at;
371
+ s.timer = setTimeout(() => {
372
+ s.timer = null;
373
+ void fire(s, dueAt(s.everyMs, now()), now()).catch(() => { });
374
+ arm(s);
375
+ }, Math.min(wait, MAX_TIMER_MS));
376
+ s.timer.unref();
377
+ }
378
+ return {
379
+ isAsync: true,
380
+ register(name, fn) {
381
+ if (launched)
382
+ throw new Error(`workflow ${name} registered after launch; register before the first async call`);
383
+ registry.set(name, fn);
384
+ },
385
+ scheduled(name, { everyMs, firstStep = null }, fn) {
386
+ if (!Number.isSafeInteger(everyMs) || everyMs < 1)
387
+ throw new Error(`schedule ${name}: everyMs must be a positive integer`);
388
+ if (typeof fn !== "function")
389
+ throw new Error(`schedule ${name}: fn must be a function`);
390
+ if (schedules.has(name))
391
+ throw new Error(`schedule ${name} is already registered`);
392
+ registry.set(tickName(name), (wf, input) => fn(new Date(Number(input.scheduledTime)), new Date(Number(input.actualTime)), wf));
393
+ schedules.set(name, { name, everyMs, firstStep, timer: null });
394
+ },
395
+ async startSchedules() {
396
+ for (const s of schedules.values()) {
397
+ const at = now();
398
+ const due = dueAt(s.everyMs, at);
399
+ if (due + s.everyMs - at >= Math.min(GRACE_MS, Math.floor(s.everyMs / 2)))
400
+ await fire(s, due, at);
401
+ arm(s);
402
+ }
403
+ },
404
+ hasSchedule: (name) => schedules.has(name),
405
+ async runScheduled(name) {
406
+ const s = schedules.get(name);
407
+ if (!s)
408
+ throw new Error(`no schedule named ${name}`);
409
+ const at = now();
410
+ return await fire(s, at, at, { manual: true });
411
+ },
412
+ async schedules() {
413
+ const at = now();
414
+ const out = [];
415
+ for (const s of schedules.values()) {
416
+ const rows = await DBOS.listWorkflows({ workflowName: tickName(s.name), applicationVersion, limit: 50, sortDesc: true, loadInput: true, loadOutput: true });
417
+ const last = rows.find((r) => r.status !== "SKIPPED");
418
+ out.push({
419
+ name: s.name, everyMs: s.everyMs, nextRun: new Date(dueAt(s.everyMs, at) + s.everyMs).toISOString(),
420
+ last: last ? { id: last.workflowID, status: last.status, scheduledTime: new Date(Number(wfInput(last).scheduledTime)).toISOString(), output: last.output, error: last.error ?? null } : null,
421
+ });
422
+ }
423
+ return out;
424
+ },
425
+ async scheduleRuns(name, limit = 20) {
426
+ if (!schedules.has(name))
427
+ throw Object.assign(new Error(`no schedule named ${name}`), { status: 404 });
428
+ const rows = await DBOS.listWorkflows({ workflowName: tickName(name), applicationVersion, limit, sortDesc: true, loadInput: true, loadOutput: true });
429
+ const real = rows.map((r) => ({
430
+ id: r.workflowID, status: r.status, scheduledTime: new Date(Number(wfInput(r).scheduledTime)).toISOString(),
431
+ startedAt: r.createdAt, finishedAt: r.status === "PENDING" ? null : (r.updatedAt ?? null),
432
+ updatedAt: r.updatedAt ?? r.createdAt, output: r.output, error: r.error ?? null,
433
+ }));
434
+ // DBOS has no public SKIPPED status: skipped ticks live in the mirror table and merge into the list.
435
+ const { rows: skips } = await pool.query("SELECT id, input, reason, created_at FROM ai_collab.skipped WHERE name = $1 AND app_version = $2 ORDER BY created_at DESC LIMIT $3", [tickName(name), applicationVersion, limit]);
436
+ const skipped = skips.map((k) => ({
437
+ id: k.id, status: "SKIPPED",
438
+ scheduledTime: new Date(Number(JSON.parse(k.input).scheduledTime)).toISOString(),
439
+ startedAt: null, finishedAt: null, updatedAt: new Date(Number(k.created_at)).toISOString(),
440
+ output: { skipped: k.reason }, error: null,
441
+ }));
442
+ // Newest scheduledTime first; a skip sorts above the run it skipped, like the sqlite engine.
443
+ return [...skipped, ...real].sort((a, b) => Date.parse(String(b.scheduledTime)) - Date.parse(String(a.scheduledTime))).slice(0, limit);
444
+ },
445
+ startWorkflow: (name, id, input) => outsideWorkflow(async () => {
446
+ await ready();
447
+ const h = await DBOS.startWorkflow(dbosFn(name), { workflowID: id })({ ...input, __id: id });
448
+ return await h.getResult();
449
+ }),
450
+ startWorkflowOnce: startOnce,
451
+ async listNamed(name, limit = 100) {
452
+ const rows = await DBOS.listWorkflows({ workflowName: name, limit, sortDesc: true, loadInput: true, loadOutput: true });
453
+ return rows.map((r) => mapStatus(r));
454
+ },
455
+ pending: pendingIds,
456
+ async recover() {
457
+ await ready(); // launch() already recovered PENDING workflows
458
+ return await pendingIds();
459
+ },
460
+ async send(workflowId, topic, value, { dedupe = null } = {}) {
461
+ await ready();
462
+ // DBOS dedupes a repeat send by idempotencyKey itself, so a failed send never spends the key and a crash
463
+ // after the send cannot lose the message. The boolean is a presence probe on the notification the key
464
+ // names; DBOS scopes its own key per destination, so the probe matches the sqlite engine's global
465
+ // dedupe by looking for the key toward ANY destination. DBOS stores the key as "<key>::<destination>":
466
+ // match that exactly, since a prefix match makes "k" collide with "k:" or "k::x" (an empty session
467
+ // label). If the internal schema ever moves, the probe degrades to "fresh" and delivery stays exactly-once.
468
+ if (dedupe) {
469
+ try {
470
+ const { rows } = await pool.query("SELECT 1 FROM dbos.notifications WHERE message_uuid = $1 || '::' || destination_uuid LIMIT 1", [dedupe]);
471
+ if (rows.length)
472
+ return false;
473
+ }
474
+ catch { /* unknown schema: let idempotencyKey enforce dedupe and report fresh */ }
475
+ }
476
+ // A send racing its own workflow start: DBOS rejects unknown destinations, so retry briefly.
477
+ for (let attempt = 0;; attempt++) {
478
+ try {
479
+ await DBOS.send(workflowId, value, topic, dedupe ?? undefined);
480
+ break;
481
+ }
482
+ catch (error) {
483
+ const code = error?.dbosErrorCode;
484
+ if (code !== 16 || attempt >= 20)
485
+ throw error;
486
+ await new Promise((r) => setTimeout(r, 50));
487
+ }
488
+ }
489
+ return true;
490
+ },
491
+ status: statusRow,
492
+ async result(id) {
493
+ await ready();
494
+ // DBOS refuses retrieveWorkflow inside a step, where the pattern steps wait on a run they started (a call
495
+ // node's child run). The step's own checkpoint records the outcome, so the wait runs as a top-level call
496
+ // that records nothing; a workflow body keeps its recorded DBOS.getResult row (op sequences stay put).
497
+ const wait = async () => await DBOS.retrieveWorkflow(id).getResult();
498
+ return DBOS.isWithinWorkflow() && !DBOS.isInWorkflow() ? await runWithTopContext({}, wait) : await wait();
499
+ },
500
+ async cancel(id) {
501
+ await ready();
502
+ // Mark CANCELLED first (deterministic status), then wake the run so it unwinds on its signal.
503
+ await DBOS.cancelWorkflow(id);
504
+ ctrls.get(id)?.abort("cancel");
505
+ },
506
+ async steps(id) {
507
+ await ready();
508
+ const rows = (await DBOS.listWorkflowSteps(id)) ?? [];
509
+ return rows.map((s) => ({ seq: s.functionID, name: s.name, status: s.error ? "error" : "done", output: s.output, error: s.error ?? null }));
510
+ },
511
+ async getKv(key) {
512
+ const { rows } = await pool.query("SELECT value FROM ai_collab.kv WHERE key = $1", [key]);
513
+ return rows.length ? JSON.parse(String(rows[0].value)) : undefined;
514
+ },
515
+ async setKv(key, value) {
516
+ await pool.query("INSERT INTO ai_collab.kv(key, value) VALUES ($1, $2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", [key, JSON.stringify(value ?? null)]);
517
+ },
518
+ async prune(names, before) {
519
+ await ready();
520
+ const rows = await DBOS.listWorkflows({ workflowName: names, status: ["SUCCESS", "ERROR", "CANCELLED"], completedBefore: new Date(before).toISOString() });
521
+ if (rows.length)
522
+ await DBOS.deleteWorkflows(rows.map((r) => r.workflowID));
523
+ // Skipped-tick mirror rows outlive their visibility window; drop the old ones so the table stays small.
524
+ await pool.query("DELETE FROM ai_collab.skipped WHERE created_at < $1", [before]);
525
+ return rows.length;
526
+ },
527
+ async drain(workflowId, topic) {
528
+ const { rows } = await pool.query("SELECT message FROM dbos.notifications WHERE destination_uuid = $1 AND topic = $2 AND consumed = false ORDER BY created_at_epoch_ms", [workflowId, topic]);
529
+ // Peek only: consuming is DBOS's job (recv inside the workflow); the caller hands the values to a new run.
530
+ return rows.map((r) => {
531
+ const raw = JSON.parse(String(r.message));
532
+ return raw && typeof raw === "object" && raw.__dbos_serializer ? raw.json : raw;
533
+ });
534
+ },
535
+ pendingCount,
536
+ async close() {
537
+ for (const s of schedules.values())
538
+ if (s.timer)
539
+ clearTimeout(s.timer);
540
+ closing.abort(new Error("workflows closed"));
541
+ if (launched)
542
+ await DBOS.shutdown({ workflowCompletionTimeoutMS: 5000 });
543
+ await pool.end();
544
+ },
545
+ };
546
+ }
@@ -0,0 +1,86 @@
1
+ // Worktree setup in Cursor's .cursor/worktrees.json format (https://cursor.com/docs/configuration/worktrees): a fresh
2
+ // worktree has no dependencies, so an agent started in one otherwise spends its first turns rebuilding them.
3
+ import { spawn } from "node:child_process";
4
+ import { existsSync, readFileSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
6
+ export const SETUP_FILE = join(".cursor", "worktrees.json");
7
+ // The runner's start answers within the UI's 70 s client timeout, and the harness open shares that budget.
8
+ export const WORKTREE_SETUP_TIMEOUT_MS = 45_000;
9
+ const TAIL_CHARS = 600;
10
+ /** The setup a worktree gets: setup-worktree-unix over setup-worktree, from the worktree's file first, then the root's. */
11
+ export function setupSteps(worktree, root) {
12
+ for (const base of [worktree, root]) {
13
+ const file = join(base, SETUP_FILE);
14
+ if (!existsSync(file))
15
+ continue;
16
+ let config;
17
+ try {
18
+ config = JSON.parse(readFileSync(file, "utf8"));
19
+ }
20
+ catch {
21
+ return { file, steps: [] };
22
+ }
23
+ const entry = config["setup-worktree-unix"] ?? config["setup-worktree"];
24
+ // A string names a script relative to worktrees.json.
25
+ if (typeof entry === "string" && entry)
26
+ return { file, steps: [[resolve(dirname(file), entry)]] };
27
+ if (Array.isArray(entry))
28
+ return { file, steps: entry.filter((c) => typeof c === "string" && c.trim() !== "").map((c) => ["sh", "-c", c]) };
29
+ return null;
30
+ }
31
+ return null;
32
+ }
33
+ /** Runs a fresh worktree's setup steps in order inside it, stopping at the first failure; never throws. */
34
+ export async function setupWorktree(worktree, root, { env = process.env, timeoutMs = WORKTREE_SETUP_TIMEOUT_MS } = {}) {
35
+ const found = setupSteps(worktree, root);
36
+ if (!found)
37
+ return { ran: false };
38
+ const { file, steps } = found;
39
+ if (!steps.length)
40
+ return { ran: true, ok: false, file, detail: `${SETUP_FILE} names no setup commands it can run` };
41
+ const deadline = Date.now() + timeoutMs;
42
+ for (const argv of steps) {
43
+ const left = deadline - Date.now();
44
+ const what = argv[0] === "sh" ? argv[2] : argv[0];
45
+ if (left <= 0)
46
+ return { ran: true, ok: false, file, detail: `timed out after ${timeoutMs} ms before: ${what}` };
47
+ const out = await runStep(argv, { cwd: worktree, env: { ...env, ROOT_WORKTREE_PATH: root }, timeoutMs: left });
48
+ if (out.code !== 0) {
49
+ const why = out.timedOut ? `timed out after ${timeoutMs} ms` : `exited ${out.code ?? "on a signal"}`;
50
+ return { ran: true, ok: false, file, detail: `${what} ${why}${out.tail ? `:\n${out.tail}` : ""}` };
51
+ }
52
+ }
53
+ return { ran: true, ok: true, file, detail: `${steps.length} step(s) ran` };
54
+ }
55
+ /** The note a session's first prompt carries about its worktree's setup, or "" when the project has none. */
56
+ export function setupNote(setup) {
57
+ if (!setup.ran)
58
+ return "";
59
+ return setup.ok
60
+ ? `\n\n(temmo ran this worktree's setup from ${SETUP_FILE}: ${setup.detail}.)`
61
+ : `\n\n(temmo could not finish this worktree's setup from ${SETUP_FILE}; dependencies may be missing until you run it: ${setup.detail})`;
62
+ }
63
+ // One step in its own process group, so a timeout also stops the tools it started.
64
+ function runStep(argv, { cwd, env, timeoutMs }) {
65
+ return new Promise((done) => {
66
+ let output = "";
67
+ let timedOut = false;
68
+ const keep = (chunk) => { output = (output + chunk.toString("utf8")).slice(-TAIL_CHARS * 4); };
69
+ const child = spawn(argv[0], argv.slice(1), { cwd, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
70
+ child.stdout.on("data", keep);
71
+ child.stderr.on("data", keep);
72
+ const timer = setTimeout(() => {
73
+ timedOut = true;
74
+ try {
75
+ process.kill(-child.pid, "SIGKILL");
76
+ }
77
+ catch { /* already gone */ }
78
+ }, timeoutMs);
79
+ const finish = (code, extra = "") => {
80
+ clearTimeout(timer);
81
+ done({ code, timedOut, tail: (output + extra).trim().slice(-TAIL_CHARS) });
82
+ };
83
+ child.on("error", (error) => finish(null, error.message));
84
+ child.on("close", (code) => finish(code));
85
+ });
86
+ }