@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,26 @@
1
+ // factory: the software factory. The CEO sets direction, the PM grooms the backlog (the temmo task store),
2
+ // three lanes each run one feature at a time as a child "feature" run, a "blitz" child run cleans up every 5 merged
3
+ // features while no new feature starts, and a "release" child run checks the release the merges produced.
4
+ digraph "factory" {
5
+ graph [description="CEO direction, PM backlog, three feature lanes, a cleanup blitz every 5 merges, a release check per round.", fallbacks="claude:claude-opus-5-5,claude:claude-haiku-5-5"];
6
+ pm [agent="claude:claude-opus-5-5", prompt="You are the PM. The backlog is the temmo task store: search it with task_list (status, query, limit; ids for full tasks) instead of reading it whole. Read the mission file's goals and the CEO's latest course-set note. Split work into small tasks with blockers; write acceptance criteria into the detail before decided. When a task failed or its PR was held, reopen or close its dependents. Answer task questions the direction settles. On round over: 5+ tasks done since the newest done blitz-* task: blitz due; else a feature merged since the last release check: release due; else 3 rounds since the CEO set course: direction due; else backlog ready. Send stop only when the operator asked. Do not implement."];
7
+ lane [agent="claude:claude-haiku-5-5", count=3, prompt="You are one of three feature lanes. Pick the first decided task, in priority order, that no other lane owns and whose blockers are done or have an open PR. Claim it: task_update owner=you, status=building. If a blocker is not merged, note its branch so the feature stacks on it. Send claimed with the task id, title, detail and the base branch. When the feature returns, record the PR or the failure on the task. If 5 or more tasks reached done since the newest done blitz-* task, or no task is ready, send round over; else claim the next task."];
8
+ feature [pattern="feature", count=3, prompt="Build one task from the store, have it reviewed, and leave an approved PR for the merge sweep."];
9
+ blitz [pattern="blitz", prompt="Cleanup blitz: review oncebitten rule suggestions, fix violations, and choose whether an architecture review is due."];
10
+ release [pattern="release", prompt="Check the release the merged features produced."];
11
+ ceo [agent="claude:claude-opus-5-5", prompt="You are the CEO and keep the product on the vision in the mission file the task names. Read the PM's notes, the done tasks since your last direction and the release notes. Write the next direction as a short note: what to build next and what to stop. Do not implement."];
12
+ pm -> lane [on="backlog ready", kind="broadcast", required=true];
13
+ lane -> feature [on="claimed", kind="pair", required=false];
14
+ feature -> lane [on="done", kind="pair", required=false];
15
+ feature -> lane [on="failed", kind="pair", required=false];
16
+ lane -> pm [on="round over", kind="fan-in", required=true];
17
+ pm -> blitz [on="blitz due", kind="pair", required=false];
18
+ blitz -> pm [on="done", kind="pair", required=false];
19
+ blitz -> pm [on="failed", kind="pair", required=false];
20
+ pm -> release [on="release due", kind="pair", required=false];
21
+ release -> pm [on="done", kind="pair", required=false];
22
+ release -> pm [on="failed", kind="pair", required=false];
23
+ pm -> ceo [on="direction due", kind="pair", required=false];
24
+ ceo -> pm [on="course set", kind="pair", required=false];
25
+ pm -> done [on="stop", kind="pair", required=true];
26
+ }
@@ -0,0 +1,14 @@
1
+ // feature: one task, test first. Haiku builds; Opus reviews. One round of changes, then a second rejection or a
2
+ // stuck build (two CI or test failures) goes to the Opus senior engineer, who takes over the same branch.
3
+ digraph "feature" {
4
+ graph [description="Haiku engineer builds one task, Opus reviews, Opus senior takes over after repeated failures.", landing="pr", fallbacks="claude:claude-opus-5-5,claude:claude-haiku-5-5"];
5
+ engineer [agent="claude:claude-haiku-5-5", prompt="Build the task named in your brief on this run's branch to the acceptance criteria in its task detail. If it names an unmerged base branch, fetch it (fetch_origin) and rebase onto it so the work stacks. Write the failing test first, then the code; run the relevant tests. Commit with a Conventional Commit and an Assisted-by trailer, land with LAND_FINISH and its proof, and send built with the task id and the head SHA. Fix review findings; do not mark them resolved. After two failed attempts at the tests or checks, send stuck with what failed."];
6
+ reviewer [agent="claude:claude-opus-5-5", prompt="Review the change on this run's branch against the acceptance criteria in its task detail, not only the engineer's tests: each criterion met and proven by a test, correctness, scope. Approve by recording task progress 'approved <head sha>' and sending approved with the task id and SHA; the merge sweep merges it once checks pass. Record each problem as task progress 'finding <low|medium|high|critical> <id>: <text>' and, once fixed, 'resolved <id>'; only you can resolve your findings, and an open medium or worse finding blocks the merge. Then send changes with concrete fixes; a second changes goes to the senior."];
7
+ senior [agent="claude:claude-opus-5-5", prompt="You are the senior engineer taking over this task from the Haiku engineer. Read the branch, the git log and the review notes first, and continue the work rather than restart it. Record the escalation on the task. Fix it test first, land with LAND_FINISH and its proof, and send built with the task id and head SHA."];
8
+ engineer -> reviewer [on="built", kind="pair", required=false];
9
+ engineer -> senior [on="stuck", kind="pair", required=false];
10
+ reviewer -> engineer [on="changes", kind="pair", required=false, cap=1, overflow="escalate"];
11
+ reviewer -> senior [on="escalate", kind="pair", required=false];
12
+ senior -> reviewer [on="built", kind="pair", required=false];
13
+ reviewer -> done [on="approved", kind="pair", required=true];
14
+ }
@@ -0,0 +1,12 @@
1
+ // fix-and-review: scope, implement and review one change; the reviewer sends it back up to three times.
2
+ digraph "fix-and-review" {
3
+ graph [description="Scope, implement, and review one change; the reviewer sends it back up to three times."];
4
+ lead [agent="cursor:deepseek-v41-flash-1017-high", prompt="Scope the task into one change with acceptance criteria. Hand off to the implementer."];
5
+ implementer [agent="claude:claude-haiku-5-5", prompt="Edit the code and add or run tests. Hand off the diff and test results to the reviewer."];
6
+ reviewer [agent="cursor:deepseek-v41-flash-1017-high", prompt="Review the diff against the scope. Run node tools/screen-state.mjs --write /tmp/screen-base.json in the base checkout and node tools/screen-state.mjs --against /tmp/screen-base.json in the change. Include which screens changed, and judge whether those screens are the ones the task named. A review without that result is not done. Approve, or request changes with specific points."];
7
+ lead -> implementer [on="scope", kind="pair", required=false];
8
+ implementer -> reviewer [on="diff and test results", kind="pair", required=true];
9
+ reviewer -> implementer [on="changes requested", kind="pair", required=false, cap=3];
10
+ reviewer -> lead [on="approved", kind="pair", required=true];
11
+ lead -> done [on="finished", kind="pair", required=false];
12
+ }
@@ -0,0 +1,16 @@
1
+ // product: the PM checks the vision, engineering does the work, review reports back to the PM.
2
+ // The CEO is not on every task. Every few finished tasks the PM hands over notes.
3
+ digraph "product" {
4
+ graph [description="PM checks the vision, engineering builds, review reports to the PM. The CEO sees every few tasks."];
5
+ pm [agent="cursor:grok-4.7-high", prompt="Check this task against the product vision in MISSION.md. Hand it to engineering when it fits. When review reports back, close the task or send it for another pass. Every few finished tasks, not every task, hand the PM notes and the engineer's notes to the CEO. Each tick, clean the backlog: remove done tasks and blocked ids ending in -wt and a number, then render the board. Leave open, ready, building, and review. Each tick, answer operator and agent questions the vision already decides, then clear them. Ask the operator only what the vision does not decide. Do not implement.", fallback="cursor:deepseek-v41-flash-1017-high"];
6
+ engineer [agent="cursor:grok-4.7-high", prompt="Do the engineering work for the task the PM handed you. Record what you learned about engineering direction for the PM. Hand the change to review. Do not set product direction.", fallback="cursor:deepseek-v41-flash-1017-high"];
7
+ review [agent="cursor:grok-4.7-high", prompt="Review the change against the task, including whether a test proves the behavior. Run node tools/screen-state.mjs --write /tmp/screen-base.json in the base checkout and node tools/screen-state.mjs --against /tmp/screen-base.json in the change. Include which screens changed, and judge whether those screens are the ones the task named. A review without that result is not done. Report that result back to the PM. Do not invent the next feature.", fallback="cursor:deepseek-v41-flash-1017-high"];
8
+ ceo [agent="cursor:grok-4.7-high", prompt="You do not see every task. When the PM hands you several finished tasks, read the PM's notes and the engineer's notes, do market research, and keep the company on the vision in MISSION.md. Write the direction. Do not implement.", fallback="cursor:deepseek-v41-flash-1017-high"];
9
+ pm -> engineer [on="in vision", kind="pair", required=true];
10
+ engineer -> review [on="built", kind="pair", required=true];
11
+ review -> engineer [on="changes", kind="pair", required=false, cap=3];
12
+ review -> pm [on="reported", kind="pair", required=true];
13
+ pm -> ceo [on="several tasks", kind="pair", required=false];
14
+ ceo -> done [on="course set", kind="pair", required=false];
15
+ pm -> done [on="task closed", kind="pair", required=true];
16
+ }
@@ -0,0 +1,7 @@
1
+ // release: each merge to main cuts a release in CI (prepare-release.yml on push); this checks what it cut.
2
+ digraph "release" {
3
+ graph [description="Check the releases CI cut since the last check: version bump and notes against the merged commits.", fallbacks="claude:claude-opus-5-5,claude:claude-haiku-5-5"];
4
+ release [agent="claude:claude-haiku-5-5", prompt="Fetch origin/main (fetch_origin). For each chore(release) commit since the last release check, check that its version bump matches the Conventional Commits it released (feat: minor, fix: patch, ! or BREAKING CHANGE: minor below 1.0.0, else major) and that CHANGELOG.md lists each merged feature. Record the result as task progress on a release-<version> task you add as done. Send checked when every release matches; otherwise add a decided task describing the mismatch and send wrong."];
5
+ release -> done [on="checked", kind="pair", required=false];
6
+ release -> done [on="wrong", kind="pair", required=false];
7
+ }
@@ -0,0 +1,6 @@
1
+ // review: review one Ready task's diff. Each role continues as the first model of the limit chain when its own model is limited.
2
+ digraph "review" {
3
+ graph [description="Review one Ready task's diff; the reviewer approves or requests changes."];
4
+ reviewer [agent="cursor:grok-4.7-high", prompt="Review the Ready task's diff against its acceptance criteria. Run node tools/screen-state.mjs --write /tmp/screen-base.json in the base checkout and node tools/screen-state.mjs --against /tmp/screen-base.json in the change. Include which screens changed, and judge whether those screens are the ones the task named. A review without that result is not done. Approve, or request changes with specific points. Do not edit the code.", fallback="cursor:deepseek-v41-flash-1017-high"];
5
+ reviewer -> done [on="reviewed", kind="pair", required=true];
6
+ }
@@ -0,0 +1,42 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFileSync, readlinkSync } from "node:fs";
3
+ import { promisify } from "node:util";
4
+ import { isRunning } from "./process.js";
5
+ const exec = promisify(execFile);
6
+ // oxlint-disable-next-line quality/no-known-value-widening -- looked up by a runtime harness name
7
+ const PROMPT = { claude: /^( *❯ +)/u, codex: /^( *› +)/u };
8
+ export function paneHasDraft(harness, tty, output) {
9
+ const [metadata, ...rows] = output.split("\n");
10
+ const [paneTty, mode, x, y] = metadata.split(" ");
11
+ if (paneTty !== tty || mode !== "0" || !/^\d+$/.test(x) || !/^\d+$/.test(y))
12
+ return false;
13
+ const line = rows[Number(y)] ?? "";
14
+ const prefix = PROMPT[harness]?.exec(line)?.[0];
15
+ // An empty composer can display placeholder text, with its cursor at the start of the input.
16
+ return Boolean(prefix && Number(x) > prefix.length && line.slice(prefix.length).trim());
17
+ }
18
+ /** Best-effort local signal. Pane contents stay in memory and only the boolean leaves this function. */
19
+ export async function terminalHasDraft(session, { env = process.env } = {}) {
20
+ if (!session?.online || !Object.hasOwn(PROMPT, session.harness))
21
+ return false;
22
+ const { pid, pidStart: start, harness } = session;
23
+ if (!isRunning({ pid, start }))
24
+ return false;
25
+ try {
26
+ const tty = readlinkSync(`/proc/${pid}/fd/0`);
27
+ if (!/^\/dev\/pts\/\d+$/.test(tty))
28
+ return false;
29
+ const vars = readFileSync(`/proc/${pid}/environ`, "utf8").split("\0");
30
+ const pane = vars.find(value => /^TMUX_PANE=%\d+$/.test(value))?.slice(10);
31
+ const socket = vars.find(value => value.startsWith("TMUX="))?.slice(5).replace(/,\d+,\d+$/, "");
32
+ if (!pane || !socket?.startsWith("/"))
33
+ return false;
34
+ const { stdout } = await exec("tmux", ["-N", "-S", socket,
35
+ "display-message", "-p", "-t", pane, "#{pane_tty} #{pane_in_mode} #{cursor_x} #{cursor_y}", ";",
36
+ "capture-pane", "-p", "-t", pane], { env, timeout: 750, maxBuffer: 256 * 1024 });
37
+ return isRunning({ pid, start }) && paneHasDraft(harness, tty, stdout);
38
+ }
39
+ catch {
40
+ return false;
41
+ }
42
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * One thread, one branch: a spawned child's worktree branch is cut from its parent's branch, and each successful run
3
+ * rebases the child's commits onto that branch and fast-forwards it. docs/threads.md "One branch per thread".
4
+ */
5
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { parseWorktreeList } from "./sessions/git-refs.js";
9
+ // Branches a child never merges into: the operator lands those.
10
+ const PROTECTED = new Set(["main", "master", "HEAD"]);
11
+ const CONFLICTS_SHOWN = 8;
12
+ /** The branch checked out in cwd when a child may merge into it, else null (detached, main, not a repo). */
13
+ export async function parentBranch(run, cwd) {
14
+ const head = await run(["rev-parse", "--abbrev-ref", "HEAD"], cwd);
15
+ const name = head.stdout.trim();
16
+ return head.code === 0 && name && !PROTECTED.has(name) ? name : null;
17
+ }
18
+ /**
19
+ * Rebases the branch checked out in childCwd onto `into` and fast-forwards `into`; returns the line for the parent's report, "" when there is nothing to merge.
20
+ * keepBranch rebases a detached copy instead, so the child's branch keeps the commits its sandbox clone has; the rebase drops ones `into` already has.
21
+ */
22
+ export async function mergeIntoParent(run, childCwd, into, { keepBranch = false } = {}) {
23
+ if (PROTECTED.has(into))
24
+ return `not merged: ${into} is landed by the operator`;
25
+ // A restart can cut an earlier merge mid-rebase; start from the branch as it was.
26
+ for (const dir of ["rebase-merge", "rebase-apply"]) {
27
+ const path = (await run(["rev-parse", "--path-format=absolute", "--git-path", dir], childCwd)).stdout.trim();
28
+ if (path && existsSync(path))
29
+ await run(["rebase", "--abort"], childCwd);
30
+ }
31
+ const branch = (await run(["rev-parse", "--abbrev-ref", "HEAD"], childCwd)).stdout.trim();
32
+ if (!branch || branch === "HEAD" || branch === into)
33
+ return "";
34
+ if ((await run(["rev-parse", "--verify", "--quiet", `refs/heads/${into}`], childCwd)).code !== 0)
35
+ return `not merged: branch ${into} no longer exists`;
36
+ const ahead = Number((await run(["rev-list", "--count", `${into}..HEAD`], childCwd)).stdout.trim()) || 0;
37
+ if (!ahead)
38
+ return "";
39
+ if ((await run(["status", "--porcelain", "--untracked-files=no"], childCwd)).stdout.trim())
40
+ return `not merged into ${into}: ${branch} has uncommitted changes; commit them`;
41
+ if (!keepBranch)
42
+ return rebaseAndAdvance(run, childCwd, childCwd, branch, into, `${branch} is rebased onto it`);
43
+ const scratch = mkdtempSync(join(tmpdir(), "temmo-thread-merge-"));
44
+ const copy = join(scratch, "copy");
45
+ try {
46
+ if ((await run(["worktree", "add", "--quiet", "--detach", copy, "HEAD"], childCwd)).code !== 0)
47
+ return `not merged into ${into}: git worktree add failed`;
48
+ return await rebaseAndAdvance(run, childCwd, copy, branch, into, `${branch} is unchanged`);
49
+ }
50
+ finally {
51
+ await run(["worktree", "remove", "--force", copy], childCwd);
52
+ rmSync(scratch, { recursive: true, force: true });
53
+ }
54
+ }
55
+ // Rebases the checkout in `work` onto `into` and fast-forwards `into` to it; `kept` ends the line when the fast-forward is refused.
56
+ async function rebaseAndAdvance(run, childCwd, work, branch, into, kept) {
57
+ if ((await run(["rebase", "--quiet", into], work)).code !== 0) {
58
+ const files = (await run(["diff", "--name-only", "--diff-filter=U"], work)).stdout.trim().split("\n").filter(Boolean);
59
+ await run(["rebase", "--abort"], work);
60
+ const shown = files.slice(0, CONFLICTS_SHOWN).join(", ") + (files.length > CONFLICTS_SHOWN ? `, +${files.length - CONFLICTS_SHOWN} more` : "");
61
+ return `not merged into ${into}: ${branch} conflicts with it${shown ? ` in ${shown}` : ""}; both branches are unchanged`;
62
+ }
63
+ // Counted after the rebase, which drops commits an earlier merge of a kept branch already put on `into`.
64
+ const ahead = Number((await run(["rev-list", "--count", `${into}..HEAD`], work)).stdout.trim()) || 0;
65
+ if (!ahead)
66
+ return "";
67
+ const head = (await run(["rev-parse", "HEAD"], work)).stdout.trim();
68
+ const holder = await checkoutOf(run, childCwd, into);
69
+ if (holder) {
70
+ // Git refuses a fast-forward that would overwrite the holder's uncommitted edits, so they are never lost.
71
+ if ((await run(["merge", "--ff-only", "--quiet", head], holder)).code !== 0)
72
+ return `not merged into ${into}: its checkout at ${holder} refused the fast-forward (uncommitted edits in the same files?); ${kept}`;
73
+ }
74
+ else if ((await run(["branch", "-f", into, head], childCwd)).code !== 0)
75
+ return `not merged into ${into}: git branch -f failed`;
76
+ return `merged ${ahead} commit${ahead === 1 ? "" : "s"} from ${branch} into ${into}`;
77
+ }
78
+ // The worktree that has `branch` checked out, or null.
79
+ async function checkoutOf(run, cwd, branch) {
80
+ const rows = parseWorktreeList((await run(["worktree", "list", "--porcelain"], cwd)).stdout);
81
+ return rows.find((row) => row.branch === `refs/heads/${branch}`)?.path ?? null;
82
+ }
@@ -0,0 +1,181 @@
1
+ export const MESSAGES_DEFAULT = 30;
2
+ export const MESSAGES_MAX = 100;
3
+ const THREAD_ID = /^th_[a-f0-9]{16}$/;
4
+ const SESSION = /^[a-z0-9-]+#[a-f0-9]{16}$/;
5
+ const EVENT_ID = /^\d{1,15}$/;
6
+ const CHANNEL_PATH = /^\/threads\/(th_[a-f0-9]{16})\/(channel|listening|messages)$/;
7
+ const BODY_MAX_BYTES = 64 * 1024;
8
+ function bad(message, status = 400) {
9
+ return Object.assign(new Error(message), { status });
10
+ }
11
+ /** The since of a thread_messages read: a message id, or an ISO time as unix seconds; null when absent. */
12
+ export function parseChannelSince(since) {
13
+ if (since === undefined || since === null || since === "")
14
+ return null;
15
+ if (typeof since !== "string")
16
+ throw bad("since must be an ISO time or a message id");
17
+ if (EVENT_ID.test(since))
18
+ return { kind: "id", value: Number(since) };
19
+ const ms = /^\d{4}-\d{2}-\d{2}/.test(since) ? Date.parse(since) : Number.NaN;
20
+ if (!Number.isFinite(ms))
21
+ throw bad("since must be an ISO time or a message id");
22
+ return { kind: "time", value: Math.floor(ms / 1000) };
23
+ }
24
+ /** A thread_messages limit: an integer from 1 to MESSAGES_MAX, MESSAGES_DEFAULT when absent. */
25
+ export function channelLimit(limit) {
26
+ if (limit === undefined || limit === null || limit === "")
27
+ return MESSAGES_DEFAULT;
28
+ const n = Number(limit);
29
+ if (!Number.isInteger(n) || n < 1 || n > MESSAGES_MAX)
30
+ throw bad(`limit must be 1-${MESSAGES_MAX}`);
31
+ return n;
32
+ }
33
+ /** Creates thread_listeners inside the caller's open migration transaction, after the threads table. */
34
+ export async function migrateThreadChannels(client, schema) {
35
+ await client.query(`CREATE TABLE IF NOT EXISTS ${schema}.thread_listeners (
36
+ thread_id TEXT NOT NULL REFERENCES ${schema}.threads(id) ON DELETE CASCADE,
37
+ session TEXT NOT NULL,
38
+ listening BOOLEAN NOT NULL,
39
+ updated_at BIGINT NOT NULL,
40
+ PRIMARY KEY (thread_id, session)
41
+ )`);
42
+ }
43
+ /** The channel store over one pool; `schema` is already validated by the caller. */
44
+ export function createThreadChannelStore({ pool, schema, now = Date.now }) {
45
+ async function thread(id) {
46
+ if (typeof id !== "string" || !THREAD_ID.test(id))
47
+ throw bad("Invalid thread");
48
+ const { rows } = await pool.query(`SELECT id, project, title, lead_session FROM ${schema}.threads WHERE id = $1`, [id]);
49
+ if (!rows.length)
50
+ throw bad("Unknown thread", 404);
51
+ return rows[0];
52
+ }
53
+ /** The thread with its members and every stored setting, members first in join order. */
54
+ async function channel(id) {
55
+ const row = await thread(id);
56
+ const members = await pool.query(`SELECT session FROM ${schema}.thread_sessions WHERE thread_id = $1 ORDER BY joined_at, session`, [id]);
57
+ const settings = await pool.query(`SELECT session, listening FROM ${schema}.thread_listeners WHERE thread_id = $1 ORDER BY session`, [id]);
58
+ const setting = new Map(settings.rows.map((r) => [r.session, r.listening]));
59
+ const sessions = members.rows.map((r) => ({ session: r.session, member: true, listening: setting.get(r.session) ?? null }));
60
+ const listed = new Set(sessions.map((s) => s.session));
61
+ for (const r of settings.rows)
62
+ if (!listed.has(r.session))
63
+ sessions.push({ session: r.session, member: false, listening: r.listening });
64
+ return { thread: { id: row.id, project: row.project, title: row.title, leadSession: row.lead_session }, sessions };
65
+ }
66
+ /** Stores a session's setting for the thread; on null deletes it, so the role default applies again. */
67
+ async function setListening(id, { session, on } = {}) {
68
+ if (typeof session !== "string" || !SESSION.test(session))
69
+ throw bad("Invalid session");
70
+ if (on !== null && typeof on !== "boolean")
71
+ throw bad("on must be true, false or null");
72
+ await thread(id);
73
+ if (on === null)
74
+ await pool.query(`DELETE FROM ${schema}.thread_listeners WHERE thread_id = $1 AND session = $2`, [id, session]);
75
+ else {
76
+ await pool.query(`INSERT INTO ${schema}.thread_listeners (thread_id, session, listening, updated_at) VALUES ($1, $2, $3, $4)
77
+ ON CONFLICT (thread_id, session) DO UPDATE SET listening = EXCLUDED.listening, updated_at = EXCLUDED.updated_at`, [id, session, on, now()]);
78
+ }
79
+ return { thread: id, session, listening: on };
80
+ }
81
+ /** Posts of the thread, oldest first: after since (first `limit`), else the newest `limit`; more says whether posts remain. */
82
+ async function messages(id, { since, limit } = {}) {
83
+ await thread(id);
84
+ const n = channelLimit(limit);
85
+ const s = parseChannelSince(since);
86
+ const columns = "id, time, topic, message, attachment";
87
+ const { rows } = s === null
88
+ ? await pool.query(`SELECT ${columns} FROM ${schema}.events WHERE thread_id = $1 ORDER BY id DESC LIMIT $2`, [id, n + 1])
89
+ : await pool.query(`SELECT ${columns} FROM ${schema}.events WHERE thread_id = $1 AND ${s.kind === "id" ? "id > $2" : "time >= $2"} ORDER BY id LIMIT $3`, [id, s.value, n + 1]);
90
+ const more = rows.length > n;
91
+ const page = rows.slice(0, n);
92
+ if (s === null)
93
+ page.reverse();
94
+ return {
95
+ events: page.map((r) => ({ id: String(r.id), time: Number(r.time), topic: r.topic, message: r.message, ...(r.attachment ? { attachment: JSON.parse(r.attachment) } : {}) })),
96
+ more,
97
+ };
98
+ }
99
+ /** Every stored setting of the project's threads, for the UI snapshot. */
100
+ async function listeners(project) {
101
+ if (typeof project !== "string" || !project)
102
+ throw bad("project required");
103
+ const { rows } = await pool.query(`SELECT l.thread_id, l.session, l.listening FROM ${schema}.thread_listeners l JOIN ${schema}.threads t ON t.id = l.thread_id WHERE t.project = $1 ORDER BY l.thread_id, l.session`, [project]);
104
+ return rows.map((r) => ({ thread: r.thread_id, session: r.session, listening: r.listening }));
105
+ }
106
+ return { channel, setListening, messages, listeners };
107
+ }
108
+ async function readJson(req) {
109
+ const chunks = [];
110
+ let total = 0;
111
+ for await (const chunk of req) {
112
+ total += chunk.length;
113
+ if (total > BODY_MAX_BYTES)
114
+ throw bad("body too large", 413);
115
+ chunks.push(chunk);
116
+ }
117
+ try {
118
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
119
+ if (value && typeof value === "object" && !Array.isArray(value))
120
+ return value;
121
+ }
122
+ catch { /* falls through */ }
123
+ throw bad("bad json");
124
+ }
125
+ /** Answers one channel request; false when the path is not a channel route, so the /threads routes take it. */
126
+ export async function threadChannelRoute(store, req, res, url) {
127
+ const match = CHANNEL_PATH.exec(url.pathname);
128
+ if (!match && url.pathname !== "/threads/listeners")
129
+ return false;
130
+ const reply = (status, value) => {
131
+ res.writeHead(status, { "content-type": "application/json" });
132
+ res.end(JSON.stringify(value));
133
+ return true;
134
+ };
135
+ const channels = store.threadChannels;
136
+ if (!channels)
137
+ return reply(404, { error: "threads need the postgres bus store" });
138
+ try {
139
+ const method = req.method || "GET";
140
+ if (!match)
141
+ return method === "GET" ? reply(200, { listeners: await channels.listeners(url.searchParams.get("project")) }) : reply(405, { error: "method not allowed" });
142
+ const [, id, part] = match;
143
+ if (part === "channel" && method === "GET")
144
+ return reply(200, await channels.channel(id));
145
+ if (part === "listening" && method === "PUT")
146
+ return reply(200, await channels.setListening(id, await readJson(req)));
147
+ if (part === "messages" && method === "GET") {
148
+ return reply(200, await channels.messages(id, { since: url.searchParams.get("since") ?? undefined, limit: url.searchParams.get("limit") ?? undefined }));
149
+ }
150
+ return reply(405, { error: "method not allowed" });
151
+ }
152
+ catch (error) {
153
+ const status = error.status || 500;
154
+ return reply(status, { error: status === 500 ? "thread store failed" : error.message });
155
+ }
156
+ }
157
+ /** The bus client for the channel routes ({url, token, timeoutMs}); errors carry the HTTP status. */
158
+ export function channelClient(cfg) {
159
+ const call = async (method, route, body) => {
160
+ const res = await fetch(`${cfg.url}${route}`, {
161
+ method,
162
+ headers: { ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}), ...(body ? { "content-type": "application/json" } : {}) },
163
+ ...(body ? { body: JSON.stringify(body) } : {}),
164
+ signal: AbortSignal.timeout(cfg.timeoutMs || 5000),
165
+ });
166
+ const value = await res.json().catch(() => ({}));
167
+ if (!res.ok)
168
+ throw Object.assign(new Error(value.error || `threads: HTTP ${res.status}`), { status: res.status });
169
+ return value;
170
+ };
171
+ const at = (id) => `/threads/${encodeURIComponent(id)}`;
172
+ return {
173
+ channel: (id) => call("GET", `${at(id)}/channel`),
174
+ setListening: (id, session, on) => call("PUT", `${at(id)}/listening`, { session, on }),
175
+ messages: (id, { since, limit } = {}) => {
176
+ const query = new URLSearchParams({ ...(since ? { since } : {}), ...(limit !== undefined ? { limit: String(limit) } : {}) });
177
+ return call("GET", `${at(id)}/messages${query.size ? `?${query}` : ""}`);
178
+ },
179
+ listeners: async (project) => (await call("GET", `/threads/listeners?project=${encodeURIComponent(project)}`)).listeners,
180
+ };
181
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Thread channels, sender side (docs/threads.md "Thread channels"): resolve who a `thread:<id>` post reaches, publish
3
+ * the post once on its thread topic and one direct copy per recipient, and read or toggle a session's listening.
4
+ */
5
+ import { listProjects } from "./config.js";
6
+ import { listOwned, listSessions, worktreeGone } from "./sessions/registry.js";
7
+ import { mentionsAgent, parseEnvelope, publishThreadPost, sendMessage } from "./messaging.js";
8
+ import { channelClient } from "./thread-channel-store.js";
9
+ import { THREAD_TARGET, delivered, threadRole } from "./thread-listening.js";
10
+ const FULL_MENTION = /(^|[^\w#-])@([a-z0-9-]{1,24}#[a-f0-9]{16})(?:\/[A-Za-z0-9_-]{1,64})?(?![\w-])/g;
11
+ const clientOf = (cfg) => channelClient({ url: cfg.url, token: cfg.token, timeoutMs: cfg.timeoutMs });
12
+ const senderOf = (cfg) => (cfg.session ? `${cfg.peer}#${cfg.session}` : cfg.peer);
13
+ function threadIdOf(target) {
14
+ const id = THREAD_TARGET.exec(String(target))?.[1];
15
+ if (!id)
16
+ throw new Error(`invalid thread "${target}": use thread:th_<16 hex>`);
17
+ return id;
18
+ }
19
+ async function ownChannel(cfg, client, id) {
20
+ const channel = await client.channel(id);
21
+ if (channel.thread.project !== cfg.project)
22
+ throw Object.assign(new Error("Unknown thread"), { status: 404 });
23
+ return channel;
24
+ }
25
+ /** The addresses a post reaches, in channel order then mention order; live or resumable registry sessions only, the sender never. */
26
+ export function channelRecipients(channel, { sessions = [], owned = [], body = "", sender = "", root = "" }) {
27
+ const known = new Set();
28
+ const parents = new Map();
29
+ for (const s of sessions) {
30
+ if (typeof s?.id !== "string")
31
+ continue;
32
+ // An ended session (offline, its worktree deleted) has nothing to resume, so it gets no copy.
33
+ if (typeof s.cwd === "string" && worktreeGone({ cwd: s.cwd, online: Boolean(s.online || s.runningJobs), sandbox: Boolean(s.sandbox) }, root))
34
+ continue;
35
+ known.add(s.id);
36
+ if (typeof s.parent === "string" && s.parent)
37
+ parents.set(s.id, s.parent);
38
+ }
39
+ for (const o of owned) {
40
+ if (typeof o?.address === "string" && typeof o.parent === "string" && o.parent && !parents.has(o.address))
41
+ parents.set(o.address, o.parent);
42
+ }
43
+ const candidates = new Map(channel.sessions.map((s) => [s.session, s]));
44
+ const full = new Set([...String(body).matchAll(FULL_MENTION)].map((m) => m[2]));
45
+ for (const address of full)
46
+ if (!candidates.has(address))
47
+ candidates.set(address, { session: address, member: false, listening: null });
48
+ const out = [];
49
+ for (const [address, c] of candidates) {
50
+ if (address === sender || !known.has(address))
51
+ continue;
52
+ const [peer, session] = address.split("#");
53
+ // A member or a session with a setting answers to @peer too; anyone else only to its full address.
54
+ const mentioned = c.member || c.listening !== null ? mentionsAgent(body, { peer, session }) : full.has(address);
55
+ if (delivered({ role: threadRole(parents.get(address)), member: c.member, listening: c.listening, mentioned }))
56
+ out.push(address);
57
+ }
58
+ return out;
59
+ }
60
+ /** Posts body to thread:<id>: the post once on the thread topic, then a direct copy to each recipient. */
61
+ export async function sendToThread(cfg, target, body, options = {}) {
62
+ const { attachment, urgent, priority, replyTo, by, expectReply, onPublished, onPost, client = clientOf(cfg), sessions, owned, root, ...rest } = options;
63
+ const id = threadIdOf(target);
64
+ const unsupported = Object.keys(rest).filter((key) => rest[key] !== undefined && key !== "threadId" && key !== "operatorThread");
65
+ if (unsupported.length)
66
+ throw new Error(`a thread post takes no ${unsupported.join(", ")}`);
67
+ if (expectReply === true)
68
+ throw new Error("expect_reply needs a direct, non-fyi message");
69
+ if (rest.threadId !== undefined && rest.threadId !== id)
70
+ throw new Error("threadId must match the thread target");
71
+ if (typeof body !== "string" || (!body.trim() && attachment === undefined))
72
+ throw new Error("empty message");
73
+ const channel = await ownChannel(cfg, client, id);
74
+ const recipients = channelRecipients(channel, {
75
+ sessions: sessions ?? listSessions(cfg), owned: owned ?? listOwned(cfg), body, sender: senderOf(cfg),
76
+ root: root ?? listProjects().find(entry => entry.project === cfg.project)?.root ?? "",
77
+ });
78
+ const post = await publishThreadPost(cfg, id, body, { attachment, onPublished: onPost, ...(by ? { by } : {}) });
79
+ if (!post.id)
80
+ throw new Error("the bus returned no id for the thread post");
81
+ const operator = cfg.peer === "operator";
82
+ for (const to of recipients) {
83
+ await sendMessage(cfg, to, body, {
84
+ threadId: id, channelOf: post.id, attachment, urgent, priority, replyTo, onPublished,
85
+ ...(operator ? { operatorThread: true, ...(by ? { by } : {}) } : {}),
86
+ });
87
+ }
88
+ return { topic: post.topic, id: post.id, thread: id, delivered: recipients, members: channel.sessions.filter((s) => s.member).map((s) => s.session) };
89
+ }
90
+ /** The thread's posts as message views, oldest first (docs/threads.md "Listening toggle"). */
91
+ export async function threadMessages(cfg, thread, { since, limit, client = clientOf(cfg) } = {}) {
92
+ const id = threadIdOf(thread.startsWith("thread:") ? thread : `thread:${thread}`);
93
+ const channel = await ownChannel(cfg, client, id);
94
+ const page = await client.messages(id, { since, limit });
95
+ const messages = page.events.flatMap((ev) => {
96
+ const m = parseEnvelope(ev.message);
97
+ if (m?.kind !== "msg" || typeof m.body !== "string")
98
+ return [];
99
+ return [{
100
+ id: ev.id, ts: new Date(ev.time * 1000).toISOString(),
101
+ from: m.session ? `${m.from}#${m.session}` : m.from, to: m.toSession ? `${m.to}#${m.toSession}` : m.to,
102
+ body: m.body, ...(ev.attachment ? { attachment: ev.attachment } : {}),
103
+ }];
104
+ });
105
+ return { thread: id, title: channel.thread.title, messages, more: page.more };
106
+ }
107
+ /** Turns listening on or off for the caller's own session in the thread. */
108
+ export async function threadListen(cfg, thread, on, { client = clientOf(cfg) } = {}) {
109
+ if (!cfg.session)
110
+ throw new Error("thread listen needs a session");
111
+ if (typeof on !== "boolean")
112
+ throw new Error("on must be true or false");
113
+ const id = threadIdOf(thread.startsWith("thread:") ? thread : `thread:${thread}`);
114
+ await ownChannel(cfg, client, id);
115
+ return client.setListening(id, senderOf(cfg), on);
116
+ }
@@ -0,0 +1,20 @@
1
+ /** Who receives a thread-channel post (docs/threads.md "Who receives a post"); no imports, so the browser bundle uses it too. */
2
+ export const THREAD_TARGET = /^thread:(th_[a-f0-9]{16})$/;
3
+ /** A session with a parent is a subagent; one without is cooperative. */
4
+ export function threadRole(parent) {
5
+ return typeof parent === "string" && parent ? "subagent" : "cooperative";
6
+ }
7
+ /** True when the session listens without a mention: its setting, else the role default (cooperative members listen). */
8
+ export function listens({ role, member, listening }) {
9
+ if (listening === true || listening === false)
10
+ return listening;
11
+ return role === "cooperative" && member;
12
+ }
13
+ /** True when a post reaches the session: a mention always does, otherwise only listening. */
14
+ export function delivered(c) {
15
+ return c.mentioned === true || listens(c);
16
+ }
17
+ /** True when the session the operator is reading needs its own copy of a thread post: a session address the channel missed. */
18
+ export function readerCopy(target, delivered) {
19
+ return target.includes("#") && !delivered.has(target);
20
+ }
@@ -0,0 +1,91 @@
1
+ const BODY_MAX_BYTES = 1024 * 1024;
2
+ const THREAD_PATH = /^\/threads\/(th_[a-f0-9]{16})(?:\/(prs|sessions)(?:\/(\d{1,12}))?)?$/;
3
+ async function readJson(req) {
4
+ const chunks = [];
5
+ let total = 0;
6
+ for await (const chunk of req) {
7
+ total += chunk.length;
8
+ if (total > BODY_MAX_BYTES)
9
+ throw Object.assign(new Error("body too large"), { status: 413 });
10
+ chunks.push(chunk);
11
+ }
12
+ try {
13
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
14
+ if (value && typeof value === "object" && !Array.isArray(value))
15
+ return value;
16
+ }
17
+ catch { /* falls through */ }
18
+ throw Object.assign(new Error("bad json"), { status: 400 });
19
+ }
20
+ function send(res, status, value) {
21
+ res.writeHead(status, { "content-type": "application/json" });
22
+ res.end(JSON.stringify(value));
23
+ }
24
+ /** Answers one /threads request; false when the path is not a thread route. */
25
+ export async function threadRoute(store, req, res, url) {
26
+ if (url.pathname !== "/threads" && !url.pathname.startsWith("/threads/"))
27
+ return false;
28
+ const threads = store.threads;
29
+ const reply = (status, value) => {
30
+ send(res, status, value);
31
+ return true;
32
+ };
33
+ if (!threads)
34
+ return reply(404, { error: "threads need the postgres bus store" });
35
+ try {
36
+ const method = req.method;
37
+ if (url.pathname === "/threads" && method === "GET") {
38
+ return reply(200, { threads: await threads.list({ project: url.searchParams.get("project") || "", archived: url.searchParams.get("archived") === "1" }) });
39
+ }
40
+ if (url.pathname === "/threads" && method === "POST")
41
+ return reply(201, await threads.create(await readJson(req)));
42
+ if (url.pathname === "/threads/sync" && method === "POST")
43
+ return reply(200, await threads.sync(await readJson(req)));
44
+ const match = THREAD_PATH.exec(url.pathname);
45
+ if (!match)
46
+ return reply(404, { error: "unknown thread route" });
47
+ const [, id, part, prId] = match;
48
+ if (!part && method === "GET")
49
+ return reply(200, await threads.get(id));
50
+ if (!part && method === "PATCH")
51
+ return reply(200, await threads.update(id, await readJson(req)));
52
+ if (part === "prs" && !prId && method === "POST")
53
+ return reply(201, await threads.attachPr(id, await readJson(req)));
54
+ if (part === "prs" && prId && method === "DELETE")
55
+ return reply(200, await threads.detachPr(id, Number(prId)));
56
+ if (part === "sessions" && !prId && method === "POST")
57
+ return reply(200, await threads.moveSession(id, await readJson(req)));
58
+ return reply(405, { error: "method not allowed" });
59
+ }
60
+ catch (error) {
61
+ // Postgres check and foreign-key violations are the caller's bad input.
62
+ const status = error.status || (/^23/.test(error.code || "") ? 400 : 500);
63
+ return reply(status, { error: status === 500 ? "thread store failed" : error.message });
64
+ }
65
+ }
66
+ /** The bus /threads client for one config ({url, token, timeoutMs}); a 404 from a store without threads reads as unavailable. */
67
+ export function threadClient(cfg) {
68
+ const call = async (method, route, body) => {
69
+ const res = await fetch(`${cfg.url}${route}`, {
70
+ method,
71
+ headers: { ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}), ...(body ? { "content-type": "application/json" } : {}) },
72
+ ...(body ? { body: JSON.stringify(body) } : {}),
73
+ signal: AbortSignal.timeout(cfg.timeoutMs || 5000),
74
+ });
75
+ const value = await res.json().catch(() => ({}));
76
+ if (!res.ok)
77
+ throw Object.assign(new Error(value.error || `threads: HTTP ${res.status}`), { status: res.status });
78
+ return value;
79
+ };
80
+ const at = (id) => `/threads/${encodeURIComponent(id)}`;
81
+ return {
82
+ list: async (project, { archived = false } = {}) => (await call("GET", `/threads?project=${encodeURIComponent(project)}${archived ? "&archived=1" : ""}`)).threads,
83
+ get: (id) => call("GET", at(id)),
84
+ create: (fields) => call("POST", "/threads", fields),
85
+ update: (id, fields) => call("PATCH", at(id), fields),
86
+ attachPr: (id, pr) => call("POST", `${at(id)}/prs`, pr),
87
+ detachPr: (id, prId) => call("DELETE", `${at(id)}/prs/${encodeURIComponent(prId)}`),
88
+ moveSession: (id, session) => call("POST", `${at(id)}/sessions`, { session }),
89
+ sync: (input) => call("POST", "/threads/sync", input),
90
+ };
91
+ }