@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
package/lib/reflect.js ADDED
@@ -0,0 +1,962 @@
1
+ /**
2
+ * Session-end reflector (Harness² Phase 1, docs/harness-improvement.md): a digest of a finished session's
3
+ * transcript goes to a cheap model, which posts at most a few lessons per session, each citing its observation.
4
+ * Lessons land in the project's harness lesson library (lib/lessons.ts). Evidence rule: no observation, no
5
+ * lesson; a thin session writes nothing. The runner sweeps ended sessions on a schedule (runner/main.mjs);
6
+ * `temmo reflect run` does one sweep by hand.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { closeSync, globSync, openSync, readFileSync, readdirSync, readSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { DatabaseSync } from "node:sqlite";
12
+ import { autoDefaults, isValidName, listProjects, loadProjects, stateDir } from "./config.js";
13
+ import { sessionActivity } from "./session-activity.js";
14
+ import { DETAIL_MAX, openTasks, TITLE_MAX } from "./tasks.js";
15
+ import { argv, cursorBinary, FALLBACK_MODEL, formatHarnessModel, isHarness, parseHarnessModel } from "./harness.js";
16
+ import { claudeConfigDir } from "./claude-socket.js";
17
+ import { cleanLesson, lessonKey, lessonsDir, markPromoted, rankLessons, readLessons, readProjectLessons, reinforceLessons, storeLessons, LESSONS_PER_SESSION, NOTE_TAG, } from "./lessons.js";
18
+ import { cleanName, listSessions } from "./sessions/registry.js";
19
+ import { childEnv } from "./sessions/launch.js";
20
+ import { logSurfaceEdit, readSurfaceLog, recentSurfaceEdits } from "./harness-surface.js";
21
+ import { updateJson } from "./store.js";
22
+ /** Total digest size handed to the model. */
23
+ export const DIGEST_MAX_CHARS = 20_000;
24
+ /** Per-line caps inside the digest: an operator prompt, an assistant line, an error excerpt, the closing text. */
25
+ const USER_LINE_MAX = 500;
26
+ const ASSISTANT_LINE_MAX = 200;
27
+ const ERROR_LINE_MAX = 300;
28
+ const CLOSING_MAX = 1_200;
29
+ /** Transcripts are read whole up to this size; a bigger one contributes its head and its tail. */
30
+ const TRANSCRIPT_MAX_BYTES = 16 * 1024 * 1024;
31
+ // A local model (Halogen through OpenCode) takes 60-100 s on a full digest, more while other sessions share the GPU.
32
+ const REFLECT_TIMEOUT_MS = 240_000;
33
+ /** Registry events that mark a session end: the runner's own, and the harness SessionEnd hook. */
34
+ export const ENDED_EVENTS = new Set(["ended", "SessionEnd"]);
35
+ // A session on the shared `opencode serve` gets no SessionEnd until it is deleted: its last turn's Stop, once the
36
+ // registry calls it offline (idle past the shared-process window), is its end.
37
+ function hasEnded(session) {
38
+ if (session.online)
39
+ return false;
40
+ return ENDED_EVENTS.has(session.event || "") || (session.harness === "opencode" && session.event === "Stop");
41
+ }
42
+ /** Only sessions that ended within this window are reflected; an old backlog is left alone. */
43
+ export const END_WINDOW_MS = 24 * 3_600_000;
44
+ /** Library entries the brief lists for reinforcement, most-reinforced first. */
45
+ const LIBRARY_IN_BRIEF = 20;
46
+ /** Sessions one sweep reflects at most, oldest end first. */
47
+ export const SWEEP_LIMIT = 3;
48
+ /** A session whose reflection keeps failing is retried this many times per end, then left alone. */
49
+ const MAX_TRIES = 3;
50
+ /** The sweep tick's checkpointed step name; also the schedule's firstStep. */
51
+ export const SWEEP_STEP = "reflect.sweep";
52
+ export const DEFAULT_EVERY_MINUTES = 15;
53
+ const truthy = (value) => /^(1|true|on|yes)$/i.test(String(value ?? "").trim());
54
+ const falsy = (value) => /^(0|false|off|no)$/i.test(String(value ?? "").trim());
55
+ /** The reflector is on unless defaults.json sets reflect false or TEMMO_REFLECT names off. */
56
+ export function reflectEnabled(env = process.env) {
57
+ if (env.TEMMO_REFLECT !== undefined && env.TEMMO_REFLECT !== "")
58
+ return !falsy(env.TEMMO_REFLECT);
59
+ return autoDefaults(env)?.reflect !== false;
60
+ }
61
+ /** The sweep interval in ms: defaults.json reflectEveryMinutes (1..1440), else 15. */
62
+ export function reflectEveryMs(env = process.env) {
63
+ const raw = autoDefaults(env)?.reflectEveryMinutes;
64
+ const minutes = Number.isSafeInteger(raw) && raw >= 1 && raw <= 1_440 ? raw : DEFAULT_EVERY_MINUTES;
65
+ return minutes * 60_000;
66
+ }
67
+ /** The reflecting model: TEMMO_REFLECT_MODEL, else defaults.json reflectModel, else the configured Cursor model, else the house cheap default. */
68
+ export function reflectModel(env = process.env) {
69
+ const raw = String(env.TEMMO_REFLECT_MODEL || autoDefaults(env)?.reflectModel || formatHarnessModel(cursorReflectModel(env))).trim();
70
+ const [harness] = raw.split(":");
71
+ if (!isHarness(harness))
72
+ return { harness: "cursor", model: FALLBACK_MODEL };
73
+ return parseHarnessModel(raw) ?? { harness, model: "" };
74
+ }
75
+ function cursorReflectModel(env) {
76
+ const cursor = autoDefaults(env)?.models?.cursor;
77
+ return { harness: "cursor", model: typeof cursor === "string" && cursor.trim() ? cursor.trim() : FALLBACK_MODEL };
78
+ }
79
+ // The reflector only reads its brief: Cursor's ask mode and OpenCode's plan agent keep it from editing files or
80
+ // running commands. Other harnesses never reflect.
81
+ const READ_ONLY_ARGS = { cursor: ["--mode", "ask"], opencode: ["--agent", "plan"] };
82
+ /**
83
+ * The model a failed reflection retries on once (a local model server that is down, or a Cursor plan out of usage,
84
+ * would otherwise spend the session's tries): the configured Cursor model, else the first defaults.json fallbacks
85
+ * entry that can reflect read-only. Null when none differs from reflectModel, or when defaults.json sets
86
+ * reflectFallback false to keep digests off any other model.
87
+ */
88
+ export function reflectFallback(env = process.env) {
89
+ const defaults = autoDefaults(env);
90
+ if (defaults?.reflectFallback === false)
91
+ return null;
92
+ const chosen = reflectModel(env);
93
+ const chain = Array.isArray(defaults?.fallbacks) ? defaults.fallbacks.flatMap((raw) => {
94
+ const parsed = typeof raw === "string" ? parseHarnessModel(raw.trim()) : null;
95
+ return parsed ? [parsed] : [];
96
+ }) : [];
97
+ return [cursorReflectModel(env), ...chain].find((m) => READ_ONLY_ARGS[m.harness] && !(m.harness === chosen.harness && m.model === chosen.model)) ?? null;
98
+ }
99
+ // ---------- transcript digests ----------
100
+ const safeId = (id) => (typeof id === "string" && /^[\w.-]{1,128}$/.test(id) ? id : "");
101
+ const clip = (text, max) => (text.length > max ? `${text.slice(0, max)}...` : text);
102
+ const oneLine = (value) => String(value ?? "").replace(/\s+/g, " ").trim();
103
+ // The file whole, or its head and tail joined when it is huge; a digest of a long session keeps both ends.
104
+ function readCapped(file) {
105
+ try {
106
+ const size = statSync(file).size;
107
+ if (size <= TRANSCRIPT_MAX_BYTES)
108
+ return readFileSync(file, "utf8");
109
+ const head = Buffer.alloc(4 * 1024 * 1024);
110
+ const tail = Buffer.alloc(12 * 1024 * 1024);
111
+ const fd = openSync(file, "r");
112
+ try {
113
+ readSync(fd, head, 0, head.length, 0);
114
+ readSync(fd, tail, 0, tail.length, size - tail.length);
115
+ }
116
+ finally {
117
+ closeSync(fd);
118
+ }
119
+ return `${head.toString("utf8")}\n[transcript trimmed]\n${tail.toString("utf8")}`;
120
+ }
121
+ catch {
122
+ return "";
123
+ }
124
+ }
125
+ const parseLine = (line) => { try {
126
+ return JSON.parse(line);
127
+ }
128
+ catch {
129
+ return null;
130
+ } };
131
+ /** The Claude transcript of a session: its launch-cwd project dir first, else any project dir holding it. */
132
+ export function claudeTranscriptFile(nativeId, cwd, env = process.env) {
133
+ const id = safeId(nativeId);
134
+ if (!id)
135
+ return "";
136
+ const dir = join(claudeConfigDir(env), "projects");
137
+ const direct = join(dir, cwd.replace(/[^a-zA-Z0-9]/g, "-"), `${id}.jsonl`);
138
+ if (statSync(direct, { throwIfNoEntry: false })?.isFile())
139
+ return direct;
140
+ let names = [];
141
+ try {
142
+ names = readdirSync(dir);
143
+ }
144
+ catch {
145
+ return "";
146
+ }
147
+ for (const name of names) {
148
+ const found = join(dir, name, `${id}.jsonl`);
149
+ if (statSync(found, { throwIfNoEntry: false })?.isFile())
150
+ return found;
151
+ }
152
+ return "";
153
+ }
154
+ /** The Codex rollout of a session: the file under CODEX_HOME/sessions whose name carries the id. */
155
+ export function codexTranscriptFile(nativeId, env = process.env) {
156
+ const id = safeId(nativeId);
157
+ if (!id)
158
+ return "";
159
+ const home = env.CODEX_HOME || join(env.HOME || "", ".codex");
160
+ try {
161
+ for (const file of globSync(join(home, "sessions/**/*.jsonl"))) {
162
+ if (String(file).includes(id))
163
+ return String(file);
164
+ }
165
+ }
166
+ catch { /* no sessions dir yet */ }
167
+ return "";
168
+ }
169
+ /** The Cursor agent transcript of a session: ~/.cursor/projects/<cwd slug>/agent-transcripts first, else any project's. */
170
+ export function cursorTranscriptFile(nativeId, cwd, env = process.env) {
171
+ const id = safeId(nativeId);
172
+ if (!id)
173
+ return "";
174
+ const dir = join(env.HOME || "", ".cursor", "projects");
175
+ const inProject = (name) => [join(dir, name, "agent-transcripts", id, `${id}.jsonl`), join(dir, name, "agent-transcripts", `${id}.jsonl`)]
176
+ .find((file) => statSync(file, { throwIfNoEntry: false })?.isFile()) ?? "";
177
+ const slug = cwd.replace(/^\/+/, "").replace(/[^a-zA-Z0-9]+/g, "-");
178
+ const direct = slug ? inProject(slug) : "";
179
+ if (direct)
180
+ return direct;
181
+ let names = [];
182
+ try {
183
+ names = readdirSync(dir);
184
+ }
185
+ catch {
186
+ return "";
187
+ }
188
+ for (const name of names) {
189
+ const found = inProject(name);
190
+ if (found)
191
+ return found;
192
+ }
193
+ return "";
194
+ }
195
+ // user and error lines always survive; assistant lines fill from the newest backward; the last one is the outcome.
196
+ function renderDigest(events, maxChars, lastAssistant = "") {
197
+ const closing = lastAssistant ? `final assistant text: ${lastAssistant}` : "";
198
+ const body = renderEvents(events, Math.max(0, maxChars - closing.length - 1));
199
+ if (!closing || body.includes(lastAssistant.slice(0, 80)))
200
+ return body;
201
+ return (body ? `${body}\n${closing}` : closing).slice(0, maxChars);
202
+ }
203
+ function renderEvents(events, maxChars) {
204
+ const indexOf = new Map();
205
+ events.forEach((event, i) => indexOf.set(event, i));
206
+ const kept = [];
207
+ let used = 0;
208
+ for (const event of events) {
209
+ if (event.kind === "user" || event.kind === "error") {
210
+ kept.push(event);
211
+ used += event.text.length + 1;
212
+ }
213
+ }
214
+ const extra = [];
215
+ for (const event of [...events].reverse()) {
216
+ if (event.kind !== "assistant" && event.kind !== "tool")
217
+ continue;
218
+ if (used + event.text.length + 1 > maxChars)
219
+ break;
220
+ extra.push(event);
221
+ used += event.text.length + 1;
222
+ }
223
+ const merged = [...kept, ...extra].sort((a, b) => (indexOf.get(a) ?? 0) - (indexOf.get(b) ?? 0));
224
+ const prefix = { user: "operator: ", assistant: "assistant: ", tool: "tool: ", error: "tool error: " };
225
+ return merged.map((e) => prefix[e.kind] + e.text).join("\n").slice(0, maxChars);
226
+ }
227
+ const LESSON_NOTE = new RegExp(`<${NOTE_TAG}>[\\s\\S]*?</${NOTE_TAG}>`, "g");
228
+ // The session-start context a hook or plugin appends to a prompt as plain lines (lib/mode.ts, lib/format.ts,
229
+ // lib/family.ts, lib/blocked.ts). Relayed operator answers and peer messages also start with [temmo] and stay.
230
+ const SESSION_CONTEXT = /^\[(?:temmo|ai-collab)\] (?:Operator AFK mode is|Your sender identity is|To hand work to another agent|Native subagents run|You were started by the agent|When auto mode or a hook blocks)[^\n]*$/gm;
231
+ // The lesson note a start appended and the session-start context: the reflector reads neither as the operator's words.
232
+ const stripInjected = (text) => String(text ?? "").replace(LESSON_NOTE, " ").replace(SESSION_CONTEXT, " ");
233
+ // A user text block minus what the harness injects (reminders, hook context, slash-command wrappers).
234
+ function operatorText(text) {
235
+ const stripped = stripInjected(text).replace(/<(system-reminder|task-notification|local-command-stdout|local-command-caveat|command-message|command-name)>[\s\S]*?<\/\1>/g, " ")
236
+ .replace(/\[Request interrupted by user[^\]]*\]/g, " ");
237
+ return oneLine(stripped);
238
+ }
239
+ /** Claude Code transcript lines: operator prompts, assistant text, tool calls, and tool failures. */
240
+ export function digestClaudeText(text, maxChars = DIGEST_MAX_CHARS) {
241
+ const events = [];
242
+ let lastAssistant = "";
243
+ for (const line of text.split("\n")) {
244
+ const entry = parseLine(line);
245
+ // api-request-blob entries replay whole requests; meta and compact-summary entries are harness text.
246
+ if (!entry || (entry.type !== "user" && entry.type !== "assistant") || entry.isSidechain === true || entry.isMeta === true || entry.isCompactSummary === true)
247
+ continue;
248
+ const message = entry.message;
249
+ if (!message || typeof message !== "object")
250
+ continue;
251
+ const blocks = typeof message.content === "string" ? [{ type: "text", text: message.content }] : Array.isArray(message.content) ? message.content : [];
252
+ if (message.role === "user") {
253
+ for (const block of blocks) {
254
+ const typed = block?.type === "text" ? operatorText(block.text) : "";
255
+ if (typed)
256
+ events.push({ kind: "user", text: clip(typed, USER_LINE_MAX) });
257
+ if (block?.type === "tool_result" && block.is_error === true) {
258
+ const body = Array.isArray(block.content) ? block.content.map((c) => oneLine(c?.text)).filter(Boolean).join(" ") : oneLine(block.content);
259
+ if (body)
260
+ events.push({ kind: "error", text: clip(body, ERROR_LINE_MAX) });
261
+ }
262
+ }
263
+ }
264
+ else if (message.role === "assistant") {
265
+ for (const block of blocks) {
266
+ if (block?.type === "text" && oneLine(block.text)) {
267
+ const line2 = clip(oneLine(block.text), ASSISTANT_LINE_MAX);
268
+ events.push({ kind: "assistant", text: line2 });
269
+ lastAssistant = clip(oneLine(block.text), CLOSING_MAX);
270
+ }
271
+ else if (block?.type === "tool_use") {
272
+ const input = block.input ?? {};
273
+ const detail = oneLine(input.command ?? input.file_path ?? input.pattern ?? input.path ?? "");
274
+ events.push({ kind: "tool", text: clip(detail ? `${block.name} ${detail}` : String(block.name ?? "tool"), ASSISTANT_LINE_MAX) });
275
+ }
276
+ }
277
+ }
278
+ }
279
+ return renderDigest(events, maxChars, lastAssistant);
280
+ }
281
+ // Cursor wraps the typed prompt in <user_query> beside injected context (timestamp, reminders, attached files).
282
+ function cursorOperatorText(text) {
283
+ const raw = stripInjected(text);
284
+ const query = raw.match(/<user_query>([\s\S]*?)<\/user_query>/);
285
+ if (query)
286
+ return oneLine(query[1]);
287
+ return oneLine(raw.replace(/<([a-z_]+)>[\s\S]*?<\/\1>/g, " "));
288
+ }
289
+ /** Cursor agent transcript lines: operator prompts and assistant text (Cursor logs no tool calls there). */
290
+ export function digestCursorText(text, maxChars = DIGEST_MAX_CHARS) {
291
+ const events = [];
292
+ let lastAssistant = "";
293
+ for (const line of text.split("\n")) {
294
+ const entry = parseLine(line);
295
+ if (!entry || (entry.role !== "user" && entry.role !== "assistant"))
296
+ continue;
297
+ const content = entry.message?.content;
298
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content : [];
299
+ for (const block of blocks) {
300
+ if (block?.type !== "text")
301
+ continue;
302
+ if (entry.role === "user") {
303
+ const typed = cursorOperatorText(block.text);
304
+ if (typed)
305
+ events.push({ kind: "user", text: clip(typed, USER_LINE_MAX) });
306
+ }
307
+ else if (oneLine(block.text)) {
308
+ events.push({ kind: "assistant", text: clip(oneLine(block.text), ASSISTANT_LINE_MAX) });
309
+ lastAssistant = clip(oneLine(block.text), CLOSING_MAX);
310
+ }
311
+ }
312
+ }
313
+ return renderDigest(events, maxChars, lastAssistant);
314
+ }
315
+ /** Codex rollout lines: user and agent messages, shell commands, and failed commands with their output. */
316
+ export function digestCodexText(text, maxChars = DIGEST_MAX_CHARS) {
317
+ const events = [];
318
+ let lastAssistant = "";
319
+ const entries = text.split("\n").map(parseLine);
320
+ const items = entries.some((entry) => entry?.payload?.type === "item_completed");
321
+ for (const entry of entries) {
322
+ const payload = entry?.payload;
323
+ if (!payload || typeof payload !== "object")
324
+ continue;
325
+ if (items) {
326
+ const item = payload.type === "item_completed" ? payload.item : null;
327
+ const said = Array.isArray(item?.content) ? oneLine(item.content.map((c) => c?.text ?? "").join(" ")) : "";
328
+ if (item?.type === "UserMessage" && oneLine(stripInjected(said)))
329
+ events.push({ kind: "user", text: clip(oneLine(stripInjected(said)), USER_LINE_MAX) });
330
+ else if (item?.type === "AgentMessage" && said) {
331
+ events.push({ kind: "assistant", text: clip(said, ASSISTANT_LINE_MAX) });
332
+ lastAssistant = clip(said, CLOSING_MAX);
333
+ }
334
+ else if (item?.type === "CommandExecution") {
335
+ const command = oneLine(Array.isArray(item.command) ? item.command.at(-1) : item.command);
336
+ if (item.status === "failed" || (item.exit_code !== undefined && Number(item.exit_code) !== 0)) {
337
+ events.push({ kind: "error", text: clip(`${command} -> exit ${item.exit_code}: ${oneLine(item.aggregated_output)}`, ERROR_LINE_MAX) });
338
+ }
339
+ else if (command)
340
+ events.push({ kind: "tool", text: clip(`shell ${command}`, ASSISTANT_LINE_MAX) });
341
+ }
342
+ else if (item?.type === "McpToolCall" && item.tool) {
343
+ events.push({ kind: item.result?.isError === true || item.status === "failed" ? "error" : "tool", text: clip(`${item.server}.${item.tool}`, ASSISTANT_LINE_MAX) });
344
+ }
345
+ continue;
346
+ }
347
+ if (payload.type === "user_message" && oneLine(stripInjected(payload.message)))
348
+ events.push({ kind: "user", text: clip(oneLine(stripInjected(payload.message)), USER_LINE_MAX) });
349
+ else if (payload.type === "agent_message" && oneLine(payload.message)) {
350
+ events.push({ kind: "assistant", text: clip(oneLine(payload.message), ASSISTANT_LINE_MAX) });
351
+ lastAssistant = clip(oneLine(payload.message), CLOSING_MAX);
352
+ }
353
+ else if (payload.type === "command_execution") {
354
+ const command = oneLine(payload.command);
355
+ if (payload.status && payload.status !== "success") {
356
+ events.push({ kind: "error", text: clip(`${command} -> ${oneLine(payload.aggregated_output)}`, ERROR_LINE_MAX) });
357
+ }
358
+ else if (command)
359
+ events.push({ kind: "tool", text: clip(`shell ${command}`, ASSISTANT_LINE_MAX) });
360
+ }
361
+ else if ((payload.type === "function_call" || payload.type === "custom_tool_call") && payload.name) {
362
+ events.push({ kind: "tool", text: clip(String(payload.name), ASSISTANT_LINE_MAX) });
363
+ }
364
+ }
365
+ return renderDigest(events, maxChars, lastAssistant);
366
+ }
367
+ /** OpenCode session lines from its SQLite store: message texts and tool parts, errors marked. */
368
+ export function digestOpencodeText(nativeId, env = process.env, maxChars = DIGEST_MAX_CHARS) {
369
+ const id = safeId(nativeId);
370
+ if (!id)
371
+ return "";
372
+ const file = join(env.XDG_DATA_HOME || join(env.HOME || "", ".local", "share"), "opencode", "opencode.db");
373
+ let db;
374
+ try {
375
+ db = new DatabaseSync(file, { readOnly: true });
376
+ }
377
+ catch {
378
+ return "";
379
+ }
380
+ try {
381
+ const events = [];
382
+ let lastAssistant = "";
383
+ const messages = db.prepare("select id, data from message where session_id = ? order by time_created").all(id);
384
+ if (!messages.length)
385
+ return digestOpencodeV2(db, id, maxChars);
386
+ const parts = db.prepare("select message_id, data from part where message_id in (select id from message where session_id = ?)").all(id);
387
+ const byMessage = new Map();
388
+ for (const row of parts) {
389
+ const part = parseLine(row.data);
390
+ if (!part)
391
+ continue;
392
+ const list = byMessage.get(row.message_id) ?? [];
393
+ list.push(part);
394
+ byMessage.set(row.message_id, list);
395
+ }
396
+ for (const row of messages) {
397
+ const message = parseLine(row.data);
398
+ const role = message?.role;
399
+ if (role !== "user" && role !== "assistant")
400
+ continue;
401
+ for (const part of byMessage.get(row.id) ?? []) {
402
+ if (part?.type === "text" && oneLine(part.text)) {
403
+ const text2 = oneLine(role === "user" ? stripInjected(part.text) : part.text);
404
+ if (!text2)
405
+ continue;
406
+ if (role === "user")
407
+ events.push({ kind: "user", text: clip(text2, USER_LINE_MAX) });
408
+ else {
409
+ events.push({ kind: "assistant", text: clip(text2, ASSISTANT_LINE_MAX) });
410
+ lastAssistant = clip(text2, CLOSING_MAX);
411
+ }
412
+ }
413
+ else if (part?.type === "tool") {
414
+ const state = part.state ?? {};
415
+ if (state.status === "error")
416
+ events.push({ kind: "error", text: clip(`${part.tool} ${oneLine(state.error ?? state.output)}`, ERROR_LINE_MAX) });
417
+ else
418
+ events.push({ kind: "tool", text: clip(String(part.tool ?? "tool"), ASSISTANT_LINE_MAX) });
419
+ }
420
+ }
421
+ }
422
+ return renderDigest(events, maxChars, lastAssistant);
423
+ }
424
+ catch {
425
+ return "";
426
+ }
427
+ finally {
428
+ try {
429
+ db.close();
430
+ }
431
+ catch { /* already closed */ }
432
+ }
433
+ }
434
+ // OpenCode 2.x: one session_message row per turn. user and synthetic rows (an operator answer relayed by a hook)
435
+ // carry text; assistant rows carry content parts. A completed shell call that exited nonzero counts as a failure.
436
+ function digestOpencodeV2(db, id, maxChars) {
437
+ let rows;
438
+ try {
439
+ rows = db.prepare("select type, data from session_message where session_id = ? order by seq").all(id);
440
+ }
441
+ catch {
442
+ return "";
443
+ }
444
+ const events = [];
445
+ let lastAssistant = "";
446
+ for (const row of rows) {
447
+ const data = parseLine(row.data);
448
+ if (row.type === "user" || row.type === "synthetic") {
449
+ const text = oneLine(stripInjected(data?.text));
450
+ if (text)
451
+ events.push({ kind: "user", text: clip(text, USER_LINE_MAX) });
452
+ continue;
453
+ }
454
+ if (row.type !== "assistant" || !Array.isArray(data?.content))
455
+ continue;
456
+ for (const part of data.content) {
457
+ if (part?.type === "text" && oneLine(part.text)) {
458
+ const text = oneLine(part.text);
459
+ events.push({ kind: "assistant", text: clip(text, ASSISTANT_LINE_MAX) });
460
+ lastAssistant = clip(text, CLOSING_MAX);
461
+ }
462
+ else if (part?.type === "tool") {
463
+ const state = part.state ?? {};
464
+ const exit = state.metadata?.exit;
465
+ const name = String(part.name ?? "tool");
466
+ if (state.status === "error")
467
+ events.push({ kind: "error", text: clip(`${name} ${oneLine(state.error?.message ?? state.error)}`, ERROR_LINE_MAX) });
468
+ else if (typeof exit === "number" && exit !== 0)
469
+ events.push({ kind: "error", text: clip(`${name} exited ${exit}`, ERROR_LINE_MAX) });
470
+ else
471
+ events.push({ kind: "tool", text: clip(name, ASSISTANT_LINE_MAX) });
472
+ }
473
+ }
474
+ }
475
+ return renderDigest(events, maxChars, lastAssistant);
476
+ }
477
+ /** The digest of one finished session: {file, digest}; an empty digest means nothing to reflect on. */
478
+ export function digestTranscript(harness, { nativeId = "", cwd = "", env = process.env, maxChars = DIGEST_MAX_CHARS } = {}) {
479
+ if (harness === "opencode")
480
+ return { file: "", digest: digestOpencodeText(nativeId, env, maxChars) };
481
+ if (harness === "cursor") {
482
+ const file = cursorTranscriptFile(nativeId, cwd, env);
483
+ return { file, digest: file ? digestCursorText(readCapped(file), maxChars) : "" };
484
+ }
485
+ if (harness !== "claude" && harness !== "codex")
486
+ return { file: "", digest: "" };
487
+ const file = harness === "codex" ? codexTranscriptFile(nativeId, env) : claudeTranscriptFile(nativeId, cwd, env);
488
+ if (!file)
489
+ return { file: "", digest: "" };
490
+ const text = readCapped(file);
491
+ const digest = harness === "codex" ? digestCodexText(text, maxChars) : digestClaudeText(text, maxChars);
492
+ return { file, digest };
493
+ }
494
+ /**
495
+ * The digest of a session from its steps on the project's activity topic: prompts, assistant text, tool calls and
496
+ * failed calls. Every runner-owned session publishes these, so this reaches sessions whose transcript stayed in an
497
+ * OpenShell sandbox, and harnesses with no transcript reader.
498
+ */
499
+ export async function activityDigest(bus, address, { maxChars = DIGEST_MAX_CHARS, since = "24h" } = {}) {
500
+ const events = [];
501
+ let lastAssistant = "";
502
+ for (const step of await sessionActivity(bus, address, { since })) {
503
+ const text = oneLine(step.type === "prompt" ? stripInjected(step.text) : step.text);
504
+ if (step.type === "prompt" && text)
505
+ events.push({ kind: "user", text: clip(text, USER_LINE_MAX) });
506
+ else if (step.type === "text" && text) {
507
+ events.push({ kind: "assistant", text: clip(text, ASSISTANT_LINE_MAX) });
508
+ lastAssistant = clip(text, CLOSING_MAX);
509
+ }
510
+ else if (step.type === "tool_call")
511
+ events.push({ kind: "tool", text: clip(step.tool ?? "tool", ASSISTANT_LINE_MAX) });
512
+ else if (step.type === "error")
513
+ events.push({ kind: "error", text: clip(`${step.tool ?? ""} ${text}`.trim(), ERROR_LINE_MAX) });
514
+ }
515
+ return renderDigest(events, maxChars, lastAssistant);
516
+ }
517
+ // ---------- the reflection turn ----------
518
+ /**
519
+ * The reflector's brief: one session digest in, a JSON array of evidence-backed lessons out. With a library, the
520
+ * brief lists its entries and asks for {reinforces, evidence} where the session shows a listed contrast again.
521
+ */
522
+ export function buildReflectPrompt({ project, harness, digest, outcome = "", library = [], surface = [] }) {
523
+ const lines = [
524
+ `You are reading the record of one finished agent session: project "${project}", harness "${harness}". Write entries for a library that future ${harness} sessions on this project read at start. Write at most ${LESSONS_PER_SESSION}; zero or one is usual.`,
525
+ "",
526
+ "Read the session for behavioral contrasts: an operator correction and what changed after it, a command that failed and the change that made it pass, a retry loop and what ended it, an approach abandoned for another. An outcome alone is not a contrast.",
527
+ "",
528
+ "Each entry has four fields:",
529
+ "- cue: the SHAPE OF SITUATION the lesson applies to, so it can fire on a different task. The pattern, not this session's facts. One line, under 150 characters.",
530
+ "- lesson: the operation a future session should perform, stated so it can be applied and checked. Name what it concerns: an instruction file (AGENTS.md, CLAUDE.md), a skill, a hook or guardrail, a tool or command, or the first prompt. Under 300 characters.",
531
+ "- evidence: the observation it rests on, a short quote or a concrete description of what happened before and after. Under 300 characters.",
532
+ "- confidence: high, medium or low, and why. One observation is weak evidence.",
533
+ "",
534
+ "Too generic is useless (\"be thorough\", \"test your code\"); too specific never fires again (\"line 42 of foo.ts had a typo\"). Aim between: \"when a browser test checks UI text, rebuild the production bundle first, because the fixture serves the built app\".",
535
+ "",
536
+ "Rules:",
537
+ "- No observation, no lesson. If the session shows no concrete, reusable contrast, answer []. Most sessions show none.",
538
+ "- Skip what a hook or instruction already enforces when the session complied at once: the harness already carries it. Record it only when the session lost real time to it.",
539
+ "- Skip facts that hold only for this task, and anything already lost to the session ending (temporary files, one-off ids).",
540
+ "- When the contrast is procedural — a command sequence, a recipe, a chore repeated by hand — make the lesson name an executable target (a script under .ai-collab/scripts, a skill step), not prose: an agent runs a script; it must re-derive advice.",
541
+ "- Entries are advisory context for future sessions, not instructions to obey.",
542
+ "",
543
+ ];
544
+ if (library.length) {
545
+ lines.push("The library already holds these entries:", ...library.map((l, i) => `${i + 1}. When ${(l.cue ?? "any session").replace(/^when\s+/i, "")}: ${clip(l.lesson, 200)}`), "", "If this session shows the same contrast as a listed entry, do not restate it: answer {\"reinforces\": <its number>, \"evidence\": \"...\"} with this session's own observation. A new entry must differ from every listed one.", "");
546
+ }
547
+ if (surface.length) {
548
+ lines.push("Recent harness surface edits (this project's memory, guidance, skills, scripts):", ...surface.map((e, i) => `${i + 1}. ${e.path}${e.note ? ` — ${clip(e.note, 100)}` : ""}`), "", "Where this session's record bears on a listed edit, judge it with {\"surface\": <its number>, \"verdict\": \"helped\"|\"unused\"|\"recurred\", \"evidence\": \"...\"}: helped, the session followed or benefited from the edit; unused, the edit's situation arose and the session neither used nor needed it; recurred, the problem the edit addresses happened again anyway. Judge only edits the session actually bears on.", "");
549
+ }
550
+ const shapes = ['{"cue": "...", "lesson": "...", "evidence": "...", "confidence": "..."}'];
551
+ if (library.length)
552
+ shapes.push('{"reinforces": 2, "evidence": "..."}');
553
+ if (surface.length)
554
+ shapes.push('{"surface": 1, "verdict": "helped", "evidence": "..."}');
555
+ lines.push("Answer with one JSON array and nothing else:", `[${shapes.join(", ")}]`);
556
+ if (outcome)
557
+ lines.push("", `What the session was working on: ${outcome}`);
558
+ lines.push("", "Session digest (chronological, trimmed):", digest);
559
+ const text = lines.join("\n");
560
+ return text.length <= DIGEST_MAX_CHARS + 4_000 ? text : text.slice(0, DIGEST_MAX_CHARS + 4_000);
561
+ }
562
+ // Every top-level [...] span in the text, brackets inside JSON strings skipped, so prose around the array cannot break it.
563
+ function arraySpans(text) {
564
+ const spans = [];
565
+ let depth = 0;
566
+ let start = -1;
567
+ let quoted = false;
568
+ for (let i = 0; i < text.length; i++) {
569
+ const ch = text[i];
570
+ if (quoted) {
571
+ if (ch === "\\")
572
+ i++;
573
+ else if (ch === '"')
574
+ quoted = false;
575
+ }
576
+ else if (ch === '"' && depth > 0)
577
+ quoted = true;
578
+ else if (ch === "[") {
579
+ if (depth++ === 0)
580
+ start = i;
581
+ }
582
+ else if (ch === "]" && depth > 0 && --depth === 0)
583
+ spans.push(text.slice(start, i + 1));
584
+ }
585
+ return spans;
586
+ }
587
+ /** What a reflector may judge a recent surface edit to be, per the brief. */
588
+ export const SURFACE_VERDICTS = new Set(["helped", "unused", "recurred"]);
589
+ /**
590
+ * The lesson array in a model reply (fenced, bare, or among prose): the first top-level span that parses as an
591
+ * array. Entries missing a cue, a lesson or evidence are dropped (Harness²'s has_experience rule).
592
+ */
593
+ export function parseReflectReply(reply) {
594
+ const text = String(reply ?? "");
595
+ const spans = arraySpans(text);
596
+ if (!spans.length)
597
+ return { lessons: [], reinforces: [], verdicts: [], error: "the answer holds no JSON array" };
598
+ let list = null;
599
+ let failure = "";
600
+ for (const span of spans) {
601
+ try {
602
+ const parsed = JSON.parse(span);
603
+ if (Array.isArray(parsed)) {
604
+ list = parsed;
605
+ break;
606
+ }
607
+ }
608
+ catch (error) {
609
+ failure ||= error.message;
610
+ }
611
+ }
612
+ if (!list)
613
+ return { lessons: [], reinforces: [], verdicts: [], error: failure ? `not valid JSON: ${failure}` : "the answer is not a JSON array" };
614
+ const lessons = list.map((entry) => cleanLesson(entry, { requireCue: true })).filter((l) => l !== null).slice(0, LESSONS_PER_SESSION);
615
+ // {reinforces: n, evidence}: the session showed library entry n again; without its own evidence it counts for nothing.
616
+ const reinforces = list
617
+ .filter((entry) => Number.isSafeInteger(entry?.reinforces) && entry.reinforces > 0 && typeof entry.evidence === "string" && entry.evidence.trim())
618
+ .map((entry) => ({ index: entry.reinforces, evidence: String(entry.evidence) }))
619
+ .slice(0, LESSONS_PER_SESSION);
620
+ // {surface: n, verdict, evidence}: the session bears on surface edit n; evidence is required, as everywhere.
621
+ const verdicts = list
622
+ .filter((entry) => Number.isSafeInteger(entry?.surface) && entry.surface > 0 && SURFACE_VERDICTS.has(entry?.verdict) && typeof entry.evidence === "string" && entry.evidence.trim())
623
+ .map((entry) => ({ index: entry.surface, verdict: String(entry.verdict), evidence: String(entry.evidence) }))
624
+ .slice(0, LESSONS_PER_SESSION);
625
+ return { lessons, reinforces, verdicts };
626
+ }
627
+ const defaultExec = (file, args, options) => new Promise((resolve) => {
628
+ execFile(file, args, { ...options, timeout: REFLECT_TIMEOUT_MS, maxBuffer: 1 << 20, shell: false }, (error, stdout, stderr) => resolve({
629
+ code: error ? (typeof error.code === "number" ? error.code : 1) : 0,
630
+ stdout: String(stdout || ""),
631
+ stderr: String(stderr || ""),
632
+ }));
633
+ });
634
+ /** One read-only one-shot model turn (the reflector's and the prober's workhorse): the brief goes in as one argument, stdout comes back; `run` stands in for execFile in tests. */
635
+ export async function askReflect(prompt, { harness, model = "", env = process.env, run }) {
636
+ const command = argv(harness, "author", { prompt, model });
637
+ if (!command)
638
+ return { status: "failed", detail: `unknown harness "${harness}"` };
639
+ const [binary, authorArgs] = command;
640
+ const exec = run ?? defaultExec;
641
+ // A real Cursor turn runs the CLI cursorBinary resolves: the launcher names may belong to the Grok Build binary.
642
+ const file = exec === defaultExec && harness === "cursor" ? cursorBinary(childEnv(env).PATH, env.HOME || undefined) : binary;
643
+ const readOnly = READ_ONLY_ARGS[harness] ?? [];
644
+ const args = [...authorArgs.slice(0, -1), ...readOnly, authorArgs.at(-1)];
645
+ try {
646
+ const result = await exec(file, args, { env: childEnv(env), cwd: env.HOME || process.cwd() });
647
+ const reply = String(result?.stdout ?? "").trim();
648
+ if (result?.code !== 0) {
649
+ const why = (reply || String(result?.stderr ?? "")).replace(/\s+/g, " ").slice(0, 300);
650
+ return { status: "failed", detail: `${file} exited ${result?.code}${why ? `: ${why}` : ""}` };
651
+ }
652
+ if (!reply)
653
+ return { status: "failed", detail: `${file} answered nothing` };
654
+ return { status: "answered", reply };
655
+ }
656
+ catch (error) {
657
+ return { status: "failed", detail: String(error?.message || error) };
658
+ }
659
+ }
660
+ /**
661
+ * Reflect one finished session: digest its transcript, ask the cheap model for lessons, and store the ones
662
+ * that cite an observation. Thin evidence writes nothing. `run` injects the model call in tests.
663
+ */
664
+ export async function reflectSession({ project, harness, nativeId = "", cwd = "", outcome = "", stateDir: sd, env = process.env, now = Date.now, run = null, bus = null, address = "", root = "" }) {
665
+ let { digest } = digestTranscript(harness, { nativeId, cwd, env });
666
+ if (!digest && bus && address)
667
+ digest = await activityDigest(bus, address).catch(() => "");
668
+ if (!digest)
669
+ return { status: "no-transcript", added: 0 };
670
+ const dir = lessonsDir(sd, project, harness);
671
+ const library = rankLessons(readLessons(dir).filter((l) => l.cue)).slice(0, LIBRARY_IN_BRIEF);
672
+ const surface = root ? recentSurfaceEdits(root) : [];
673
+ const prompt = buildReflectPrompt({ project, harness, digest, outcome, library, surface });
674
+ const chosen = reflectModel(env);
675
+ let answer = await askReflect(prompt, { harness: chosen.harness, model: chosen.model, env, run });
676
+ let via = "";
677
+ const fallback = answer.status === "failed" ? reflectFallback(env) : null;
678
+ if (answer.status === "failed" && fallback) {
679
+ via = `${formatHarnessModel(chosen)} failed (${answer.detail}); answered by ${formatHarnessModel(fallback)}`;
680
+ const retry = await askReflect(prompt, { harness: fallback.harness, model: fallback.model, env, run });
681
+ if (retry.status === "failed")
682
+ return { status: "failed", added: 0, detail: `${answer.detail}; ${formatHarnessModel(fallback)}: ${retry.detail}` };
683
+ answer = retry;
684
+ }
685
+ if (answer.status !== "answered")
686
+ return { status: "failed", added: 0, detail: answer.detail };
687
+ const result = storeReply(answer.reply, { dir, harness, library, now });
688
+ if (root && surface.length)
689
+ recordSurfaceVerdicts(root, answer.reply, surface, now);
690
+ return via ? { ...result, detail: result.detail ? `${via}; ${result.detail}` : via } : result;
691
+ }
692
+ // The evaluation log: verdicts the model judged against recent surface edits join the surface log,
693
+ // so an edit accumulates hit/miss evidence from later sessions instead of faith (MemPro's log).
694
+ function recordSurfaceVerdicts(root, reply, surface, now) {
695
+ const { verdicts } = parseReflectReply(reply);
696
+ for (const v of verdicts) {
697
+ const edit = surface[v.index - 1];
698
+ if (edit)
699
+ logSurfaceEdit(root, { t: now(), op: "verdict", path: edit.path, verdict: v.verdict, evidence: v.evidence.slice(0, 300) });
700
+ }
701
+ }
702
+ function storeReply(reply, { dir, harness, library, now }) {
703
+ const { lessons, reinforces, error } = parseReflectReply(reply);
704
+ const hits = reinforces.flatMap(({ index, evidence }) => library[index - 1] ? [{ key: lessonKey(library[index - 1].lesson), evidence }] : []);
705
+ if (!lessons.length && !hits.length) {
706
+ if (error)
707
+ return { status: "failed", added: 0, detail: error };
708
+ return { status: "no-lessons", added: 0 };
709
+ }
710
+ const { reinforced } = hits.length ? reinforceLessons(dir, harness, hits, { now }) : { reinforced: 0 };
711
+ const added = lessons.length ? storeLessons(dir, harness, lessons, { now }).added : 0;
712
+ if (!added && reinforced)
713
+ return { status: "reinforced", added: 0, reinforced };
714
+ return { status: "stored", added, ...(reinforced ? { reinforced } : {}) };
715
+ }
716
+ // The project's reflection markers: address -> the session end last reflected, how often it was tried, and whether it finished.
717
+ function markReflected(file, address, at, ok) {
718
+ updateJson(file, (current) => {
719
+ const markers = current && typeof current === "object" ? current : {};
720
+ const previous = markers[address];
721
+ const sameEnd = previous && previous.at === at;
722
+ return { ...markers, [address]: { at, tries: sameEnd ? previous.tries + 1 : 1, done: ok } };
723
+ });
724
+ }
725
+ function needsReflection(markers, address, at) {
726
+ const previous = markers[address];
727
+ if (!previous)
728
+ return true;
729
+ if (previous.at !== at)
730
+ return true;
731
+ return !previous.done && previous.tries < MAX_TRIES;
732
+ }
733
+ /**
734
+ * One sweep: every project's sessions that ended within the window and were not reflected yet (or failed and
735
+ * may retry), oldest end first, at most `limit` in all. Each reflection is one cheap-model turn; a session
736
+ * that fails MAX_TRIES times per end is left alone. Resolves {reflected, stored, failed}.
737
+ */
738
+ export async function reflectSweep({ env = process.env, log = () => { }, now = Date.now, limit = SWEEP_LIMIT, run = null } = {}) {
739
+ const sd = stateDir(env);
740
+ const due = [];
741
+ for (const project of listProjects(env)) {
742
+ if (typeof project?.project !== "string" || !project.project)
743
+ continue;
744
+ const markerFile = join(sd, project.project, "harness-lessons", "reflected.json");
745
+ const markers = readProjectMarkers(markerFile);
746
+ for (const session of listSessions({ stateDir: sd, project: project.project, peers: [] })) {
747
+ if (!hasEnded(session))
748
+ continue;
749
+ const at = Number(session.seenAt) || 0;
750
+ if (!at || now() - at > END_WINDOW_MS)
751
+ continue;
752
+ if (!safeId(session.sessionId) || !session.cwd)
753
+ continue;
754
+ if (!needsReflection(markers, session.id, at))
755
+ continue;
756
+ due.push({ project: project.project, root: typeof project.root === "string" ? project.root : "", session, markerFile });
757
+ }
758
+ }
759
+ due.sort((a, b) => (Number(a.session.seenAt) || 0) - (Number(b.session.seenAt) || 0));
760
+ let reflected = 0;
761
+ let stored = 0;
762
+ let failed = 0;
763
+ const picked = due.slice(0, Math.max(0, limit));
764
+ const buses = new Map(picked.length ? loadProjects(env, { host: "runner" }).map((cfg) => [cfg.project, cfg]) : []);
765
+ for (const item of picked) {
766
+ const at = Number(item.session.seenAt) || now();
767
+ const result = await reflectSession({
768
+ project: item.project, harness: item.session.harness, nativeId: item.session.sessionId, cwd: item.session.cwd,
769
+ outcome: cleanName(item.session.activity || item.session.name || ""), stateDir: sd, env, now, run,
770
+ bus: buses.get(item.project) ?? null, address: item.session.id, root: item.root,
771
+ });
772
+ // A busy marker file only means this session may be reflected again next sweep; the lessons stay stored.
773
+ try {
774
+ markReflected(item.markerFile, item.session.id, at, result.status !== "failed");
775
+ }
776
+ catch (error) {
777
+ log(`reflect: marker write failed: ${error.message}`);
778
+ }
779
+ reflected += 1;
780
+ stored += result.added;
781
+ if (result.status === "failed")
782
+ failed += 1;
783
+ log(`reflect: ${item.project} ${item.session.id} ${result.status}${result.detail ? ` (${result.detail})` : ""}`);
784
+ }
785
+ await promoteLessons({ env, stateDir: sd, log, now });
786
+ await promoteSurfaceVerdicts({ env, log, now });
787
+ return { reflected, stored, failed };
788
+ }
789
+ /** Lessons seen in at least this many sessions are proposed for a harness file. */
790
+ export const PROMOTE_AT = 3;
791
+ /** Proposals are on unless defaults.json sets promoteLessons false or TEMMO_PROMOTE names off. */
792
+ export function promoteEnabled(env = process.env) {
793
+ if (env.TEMMO_PROMOTE !== undefined && env.TEMMO_PROMOTE !== "")
794
+ return !falsy(env.TEMMO_PROMOTE);
795
+ return autoDefaults(env)?.promoteLessons !== false;
796
+ }
797
+ function promotionTask(harness, lesson) {
798
+ const cue = (lesson.cue ?? "any session").replace(/^when\s+/i, "");
799
+ const seen = lesson.seen ?? 1;
800
+ const detail = [
801
+ `Seen in ${seen} ${harness} sessions, last on ${new Date(lesson.lastAt ?? lesson.at).toISOString().slice(0, 10)}.`,
802
+ `When ${cue}: ${lesson.lesson}`,
803
+ `Evidence: ${lesson.evidence}`,
804
+ ...(lesson.also ?? []).map((e) => `Also: ${e}`),
805
+ `Each session above showed this contrast on its own, which is the evidence Harness² asks for before a lesson changes a harness file. Accept: make the change the lesson names (AGENTS.md, a skill, a hook) and close this task. Reject: close it with a note; the lesson stays advisory in the ${harness} start note.`,
806
+ ].join(" | ");
807
+ return { title: `Fold a recurring ${harness} lesson into the harness: ${cue}`.slice(0, TITLE_MAX), detail: detail.slice(0, DETAIL_MAX) };
808
+ }
809
+ /**
810
+ * Proposes each lesson seen in PROMOTE_AT or more sessions as a task on its project's board, once: the operator-gated
811
+ * half of Harness²'s harness edits. A task with the same title already on the board is reused, so a sweep cut between
812
+ * the add and the mark files nothing twice. Resolves the count of new proposals.
813
+ */
814
+ export async function promoteLessons({ env = process.env, stateDir: sd, log = () => { }, now = Date.now }) {
815
+ if (!promoteEnabled(env))
816
+ return 0;
817
+ let promoted = 0;
818
+ for (const entry of listProjects(env)) {
819
+ const project = entry?.project;
820
+ if (typeof project !== "string" || !isValidName(project))
821
+ continue;
822
+ for (const [harness, lessons] of Object.entries(readProjectLessons(sd, project))) {
823
+ for (const lesson of lessons) {
824
+ if ((lesson.seen ?? 1) < PROMOTE_AT || lesson.promoted)
825
+ continue;
826
+ try {
827
+ const tasks = openTasks(project, env);
828
+ const { title, detail } = promotionTask(harness, lesson);
829
+ const task = tasks.list().find((t) => t.title === title) ?? await tasks.add({ title, detail, priority: "P2" }, now());
830
+ markPromoted(lessonsDir(sd, project, harness), harness, lessonKey(lesson.lesson), task.id);
831
+ promoted += 1;
832
+ log(`reflect: ${project} ${harness} lesson proposed as task ${task.id}`);
833
+ }
834
+ catch (error) {
835
+ log(`reflect: proposing a ${project} ${harness} lesson failed: ${error.message}`);
836
+ }
837
+ }
838
+ }
839
+ }
840
+ return promoted;
841
+ }
842
+ /** A surface path with this many "recurred" verdicts since its last proposal is proposed for revert or fix. */
843
+ export const SURFACE_RECURRED_AT = 2;
844
+ function surfaceVerdictTask(path, evidences) {
845
+ const detail = [
846
+ `${evidences.length} sessions judged this surface edit "recurred": the problem it addresses happened again anyway.`,
847
+ ...evidences.map((e) => `Evidence: ${e}`),
848
+ `Accept: read the file and its history (temmo harness-surface history ${path}), then fix it or restore an older version (temmo harness-surface restore ${path} <id>) and close this task. Reject: close with a note when the verdicts misread the sessions.`,
849
+ ].join(" | ");
850
+ return { title: `Surface edit keeps recurring: ${path}`.slice(0, TITLE_MAX), detail: detail.slice(0, DETAIL_MAX) };
851
+ }
852
+ /**
853
+ * Proposes each surface path with SURFACE_RECURRED_AT or more "recurred" verdicts since its last
854
+ * proposal as one operator-gated task to fix or restore the edit (MemPro's recurring-failure diagnosis:
855
+ * the evaluation log gets teeth). A "proposed" line in the surface log resets the count, so a standing
856
+ * verdict set is proposed once; verdicts after it count toward the next proposal. Resolves the count.
857
+ */
858
+ export async function promoteSurfaceVerdicts({ env = process.env, log = () => { }, now = Date.now }) {
859
+ if (!promoteEnabled(env))
860
+ return 0;
861
+ let proposed = 0;
862
+ for (const entry of listProjects(env)) {
863
+ const project = entry?.project;
864
+ const root = entry?.root;
865
+ if (typeof project !== "string" || !isValidName(project) || typeof root !== "string" || !root)
866
+ continue;
867
+ const pending = new Map();
868
+ for (const e of readSurfaceLog(root, 500)) {
869
+ if (e.op === "verdict" && e.verdict === "recurred") {
870
+ pending.set(e.path, [...(pending.get(e.path) ?? []), String(e.evidence || "").slice(0, 200)]);
871
+ }
872
+ else if (e.op === "proposed" && pending.has(e.path)) {
873
+ pending.delete(e.path);
874
+ }
875
+ }
876
+ for (const [path, evidences] of pending) {
877
+ if (evidences.length < SURFACE_RECURRED_AT)
878
+ continue;
879
+ try {
880
+ const tasks = openTasks(project, env);
881
+ const { title, detail } = surfaceVerdictTask(path, evidences.slice(-3));
882
+ const task = tasks.list().find((t) => t.title === title) ?? await tasks.add({ title, detail, priority: "P2" }, now());
883
+ logSurfaceEdit(root, { t: now(), op: "proposed", path, note: `task ${task.id}` });
884
+ proposed += 1;
885
+ log(`reflect: ${project} surface ${path} proposed as task ${task.id}`);
886
+ }
887
+ catch (error) {
888
+ log(`reflect: proposing a ${project} surface fix for ${path} failed: ${error.message}`);
889
+ }
890
+ }
891
+ }
892
+ return proposed;
893
+ }
894
+ function readProjectMarkers(file) {
895
+ let markers;
896
+ try {
897
+ markers = JSON.parse(readFileSync(file, "utf8"));
898
+ }
899
+ catch {
900
+ return {};
901
+ }
902
+ if (!markers || typeof markers !== "object" || Array.isArray(markers))
903
+ return {};
904
+ const out = {};
905
+ for (const [address, value] of Object.entries(markers)) {
906
+ if (value && typeof value === "object" && Number.isSafeInteger(value.at))
907
+ out[address] = { at: value.at, tries: Number(value.tries) || 1, done: value.done === true };
908
+ }
909
+ return out;
910
+ }
911
+ /**
912
+ * The runner's scheduled tick body: one checkpointed sweep step, not re-run after a cut (the next sweep picks
913
+ * up whatever this one missed). Mirrors runner/schedules.ts tickFn's shape.
914
+ */
915
+ export function reflectTick({ env = process.env, log = () => { }, now = Date.now } = {}) {
916
+ return async (scheduledTime, actualTime, wf) => {
917
+ const started = now();
918
+ const result = await wf.step(SWEEP_STEP, () => reflectSweep({ env, log, now }), {
919
+ onCut: () => ({ cut: "runner restarted during the sweep; not re-run" }),
920
+ });
921
+ log(`reflect: ok in ${now() - started} ms`);
922
+ return { ...result, scheduledTime: scheduledTime.toISOString(), actualTime: actualTime.toISOString() };
923
+ };
924
+ }
925
+ // ---------- the CLI ----------
926
+ /** `temmo reflect [run [--limit N] | show [harness]]`: sweep by hand, or print the library. */
927
+ export async function reflectCli({ cfg, words, out, err, env = process.env, now = Date.now, run = null }) {
928
+ const sub = words[0] ?? "run";
929
+ if (sub === "show") {
930
+ const all = readProjectLessons(cfg.stateDir, cfg.project);
931
+ const harnesses = words[1] ? [words[1]] : Object.keys(all).sort();
932
+ for (const harness of harnesses) {
933
+ const lessons = all[harness] ?? [];
934
+ out.write(`${harness}: ${lessons.length} lesson(s)\n`);
935
+ for (const lesson of lessons) {
936
+ out.write(` - ${lesson.cue ? `When ${lesson.cue.replace(/^when\s+/i, "")}: ` : ""}${lesson.lesson}\n Evidence: ${lesson.evidence}\n`);
937
+ if (lesson.confidence)
938
+ out.write(` Confidence: ${lesson.confidence}\n`);
939
+ if (lesson.seen)
940
+ out.write(` Seen: ${lesson.seen} sessions${lesson.promoted ? `; proposed for the harness as task ${lesson.promoted}` : ""}\n`);
941
+ }
942
+ }
943
+ return 0;
944
+ }
945
+ if (sub !== "run") {
946
+ err.write("usage: temmo reflect [run [--limit N] | show [harness]]\n");
947
+ return 2;
948
+ }
949
+ let limit = SWEEP_LIMIT;
950
+ const limitAt = words.indexOf("--limit");
951
+ if (limitAt >= 0) {
952
+ const value = Number.parseInt(words[limitAt + 1] ?? "", 10);
953
+ if (!Number.isSafeInteger(value) || value < 0) {
954
+ err.write("reflect: --limit needs a number\n");
955
+ return 2;
956
+ }
957
+ limit = value;
958
+ }
959
+ const result = await reflectSweep({ env, log: (line) => out.write(line + "\n"), now, limit, run });
960
+ out.write(`reflect: ${result.reflected} session(s) reflected, ${result.stored} lesson(s) stored, ${result.failed} failed\n`);
961
+ return 0;
962
+ }