orkeon-code 0.0.0-stage → 1.0.0-rc.2

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 (552) hide show
  1. package/.orkeon-runtime +10 -0
  2. package/.orkeon-version +1 -0
  3. package/LICENSE.md +21 -0
  4. package/NOTICE.md +17 -0
  5. package/README.fr.md +163 -0
  6. package/README.md +156 -2
  7. package/config/appsettings.anthropic.example.json +77 -0
  8. package/config/appsettings.example.json +71 -0
  9. package/config/appsettings.jev.example.json +131 -0
  10. package/config/appsettings.kev.example.json +133 -0
  11. package/config/appsettings.liquid.example.json +132 -0
  12. package/config/appsettings.ollama-whisper.example.json +93 -0
  13. package/config/appsettings.ollama.example.json +70 -0
  14. package/config/appsettings.whisper.example.json +32 -0
  15. package/mcp/whisper/README.md +294 -0
  16. package/mcp/whisper/pyproject.toml +32 -0
  17. package/mcp/whisper/uv.lock +1641 -0
  18. package/mcp/whisper/whisper_mcp.py +1053 -0
  19. package/orkeon-code +1092 -0
  20. package/orkeon-code.mjs +71 -0
  21. package/orkeon-code.ps1 +939 -0
  22. package/package.json +58 -4
  23. package/scripts/install.ps1 +156 -0
  24. package/scripts/install.sh +148 -0
  25. package/scripts/session-start.ork.ts +90 -0
  26. package/scripts/session-start.sh +74 -0
  27. package/scripts/setup-fixture.sh +88 -0
  28. package/src/commands/.orkeon/orkeon-cli.d.ts +559 -0
  29. package/src/commands/_lib/args.ts +194 -0
  30. package/src/commands/_lib/dev/dev-batches.ts +366 -0
  31. package/src/commands/_lib/dev/dev-implement.ts +185 -0
  32. package/src/commands/_lib/dev/dev-source.ts +61 -0
  33. package/src/commands/_lib/dev/dev.ts +341 -0
  34. package/src/commands/_lib/dev/markers.ts +7 -0
  35. package/src/commands/_lib/dev/messages.ts +112 -0
  36. package/src/commands/_lib/dev-step.ts +145 -0
  37. package/src/commands/_lib/dispatch.ts +254 -0
  38. package/src/commands/_lib/effort.ts +15 -0
  39. package/src/commands/_lib/git/branch.ts +94 -0
  40. package/src/commands/_lib/git/commit.ts +90 -0
  41. package/src/commands/_lib/git/diff.ts +107 -0
  42. package/src/commands/_lib/git/messages.ts +54 -0
  43. package/src/commands/_lib/git/review.ts +108 -0
  44. package/src/commands/_lib/memory/memory-admit.ts +148 -0
  45. package/src/commands/_lib/memory/memory.ts +52 -0
  46. package/src/commands/_lib/memory/messages.ts +32 -0
  47. package/src/commands/_lib/messages.ts +48 -0
  48. package/src/commands/_lib/pr-context.ts +32 -0
  49. package/src/commands/_lib/project/analyze.ts +24 -0
  50. package/src/commands/_lib/project/messages.ts +8 -0
  51. package/src/commands/_lib/session/export.ts +105 -0
  52. package/src/commands/_lib/session/messages.ts +87 -0
  53. package/src/commands/_lib/session/prompts.ts +4 -0
  54. package/src/commands/_lib/session/resume.ts +151 -0
  55. package/src/commands/_lib/session/tasks.ts +181 -0
  56. package/src/commands/_lib/settings/advisor.ts +75 -0
  57. package/src/commands/_lib/settings/agents.ts +137 -0
  58. package/src/commands/_lib/settings/choices.ts +8 -0
  59. package/src/commands/_lib/settings/config.ts +141 -0
  60. package/src/commands/_lib/settings/effort.ts +147 -0
  61. package/src/commands/_lib/settings/hooks.ts +50 -0
  62. package/src/commands/_lib/settings/messages.ts +408 -0
  63. package/src/commands/_lib/settings/mode.ts +100 -0
  64. package/src/commands/_lib/settings/model.ts +181 -0
  65. package/src/commands/_lib/settings/output-style.ts +39 -0
  66. package/src/commands/_lib/settings/permissions.ts +287 -0
  67. package/src/commands/_lib/settings/route.ts +63 -0
  68. package/src/commands/_lib/settings/session-config.ts +49 -0
  69. package/src/commands/_lib/settings/skills.ts +93 -0
  70. package/src/commands/_lib/settings/theme.ts +42 -0
  71. package/src/commands/_lib/speech/messages.ts +58 -0
  72. package/src/commands/_lib/speech/prompts.ts +4 -0
  73. package/src/commands/_lib/speech/say.ts +95 -0
  74. package/src/commands/_lib/speech/transcribe.ts +121 -0
  75. package/src/commands/_lib/speech/voice.ts +142 -0
  76. package/src/commands/_lib/status/cache.ts +31 -0
  77. package/src/commands/_lib/status/context.ts +57 -0
  78. package/src/commands/_lib/status/doctor.ts +205 -0
  79. package/src/commands/_lib/status/messages.ts +100 -0
  80. package/src/commands/_lib/status/meta.ts +24 -0
  81. package/src/commands/_lib/status/status.ts +128 -0
  82. package/src/commands/_lib/status/usage-tools.ts +48 -0
  83. package/src/commands/_lib/status/usage.ts +128 -0
  84. package/src/commands/_lib/view.ts +34 -0
  85. package/src/commands/dev/dev-batches.cmd.ts +109 -0
  86. package/src/commands/dev/dev-learn.cmd.ts +29 -0
  87. package/src/commands/dev/dev-plan.cmd.ts +51 -0
  88. package/src/commands/dev/dev-spec.cmd.ts +54 -0
  89. package/src/commands/dev/dev-status.cmd.ts +16 -0
  90. package/src/commands/git/branch.cmd.ts +27 -0
  91. package/src/commands/git/commit.cmd.ts +48 -0
  92. package/src/commands/git/diff.cmd.ts +26 -0
  93. package/src/commands/git/review.cmd.ts +36 -0
  94. package/src/commands/memory/memory.cmd.ts +48 -0
  95. package/src/commands/project/analyze.cmd.ts +32 -0
  96. package/src/commands/project/debug-tool-call.cmd.ts +62 -0
  97. package/src/commands/project/files.cmd.ts +22 -0
  98. package/src/commands/project/init-verifiers.cmd.ts +14 -0
  99. package/src/commands/project/init.cmd.ts +14 -0
  100. package/src/commands/project/verify.cmd.ts +27 -0
  101. package/src/commands/session/assistant.cmd.ts +40 -0
  102. package/src/commands/session/btw.cmd.ts +18 -0
  103. package/src/commands/session/clear.cmd.ts +19 -0
  104. package/src/commands/session/compact.cmd.ts +16 -0
  105. package/src/commands/session/copy.cmd.ts +45 -0
  106. package/src/commands/session/exit.cmd.ts +9 -0
  107. package/src/commands/session/export.cmd.ts +28 -0
  108. package/src/commands/session/rename.cmd.ts +18 -0
  109. package/src/commands/session/resume.cmd.ts +19 -0
  110. package/src/commands/session/rewind.cmd.ts +25 -0
  111. package/src/commands/session/summary.cmd.ts +27 -0
  112. package/src/commands/session/tasks.cmd.ts +46 -0
  113. package/src/commands/settings/advisor.cmd.ts +38 -0
  114. package/src/commands/settings/agents.cmd.ts +19 -0
  115. package/src/commands/settings/config.cmd.ts +19 -0
  116. package/src/commands/settings/effort.cmd.ts +19 -0
  117. package/src/commands/settings/fast.cmd.ts +18 -0
  118. package/src/commands/settings/hooks.cmd.ts +17 -0
  119. package/src/commands/settings/mode.cmd.ts +20 -0
  120. package/src/commands/settings/model.cmd.ts +21 -0
  121. package/src/commands/settings/output-style.cmd.ts +19 -0
  122. package/src/commands/settings/permissions.cmd.ts +25 -0
  123. package/src/commands/settings/proactive.cmd.ts +16 -0
  124. package/src/commands/settings/route.cmd.ts +16 -0
  125. package/src/commands/settings/skills.cmd.ts +17 -0
  126. package/src/commands/settings/theme.cmd.ts +14 -0
  127. package/src/commands/speech/say.cmd.ts +24 -0
  128. package/src/commands/speech/transcribe.cmd.ts +29 -0
  129. package/src/commands/speech/voice.cmd.ts +30 -0
  130. package/src/commands/status/context.cmd.ts +18 -0
  131. package/src/commands/status/doctor.cmd.ts +27 -0
  132. package/src/commands/status/release-notes.cmd.ts +9 -0
  133. package/src/commands/status/status.cmd.ts +25 -0
  134. package/src/commands/status/usage.cmd.ts +21 -0
  135. package/src/crews/.orkeon/orkeon.d.ts +4391 -0
  136. package/src/crews/_probe-shared-memory/domain/messages.ts +54 -0
  137. package/src/crews/_probe-shared-memory/domain/probe-verdict.ts +188 -0
  138. package/src/crews/_probe-shared-memory/domain/prompts.ts +5 -0
  139. package/src/crews/_probe-shared-memory/probe.ork.ts +100 -0
  140. package/src/crews/advisor/application/messages.ts +4 -0
  141. package/src/crews/advisor/application/prompts.ts +4 -0
  142. package/src/crews/advisor/application/run-advisor.ts +41 -0
  143. package/src/crews/advisor/crew.ork.ts +44 -0
  144. package/src/crews/advisor/domain/advice.ts +119 -0
  145. package/src/crews/advisor/domain/messages.ts +8 -0
  146. package/src/crews/advisor/domain/prompts.ts +26 -0
  147. package/src/crews/agent-run/application/messages.ts +18 -0
  148. package/src/crews/agent-run/application/run-agent-run.ts +43 -0
  149. package/src/crews/agent-run/crew.ork.ts +67 -0
  150. package/src/crews/analyze/application/messages.ts +27 -0
  151. package/src/crews/analyze/application/prompts.ts +4 -0
  152. package/src/crews/analyze/application/run-analyze.ts +120 -0
  153. package/src/crews/analyze/crew.ork.ts +41 -0
  154. package/src/crews/analyze/domain/harvest.ts +269 -0
  155. package/src/crews/analyze/domain/prompts.ts +86 -0
  156. package/src/crews/code-review/application/lens-material.ts +24 -0
  157. package/src/crews/code-review/application/messages.ts +17 -0
  158. package/src/crews/code-review/application/prompts.ts +126 -0
  159. package/src/crews/code-review/application/review.ts +74 -0
  160. package/src/crews/code-review/application/run-code-review.ts +121 -0
  161. package/src/crews/code-review/crew.ork.ts +52 -0
  162. package/src/crews/code-review/domain/lenses.ts +154 -0
  163. package/src/crews/code-review/domain/messages.ts +25 -0
  164. package/src/crews/code-review/domain/prompts.ts +58 -0
  165. package/src/crews/code-review/domain/report.ts +58 -0
  166. package/src/crews/code-review/domain/scope.ts +106 -0
  167. package/src/crews/dev-batches/application/messages.ts +127 -0
  168. package/src/crews/dev-batches/application/plan-close.ts +181 -0
  169. package/src/crews/dev-batches/application/prompts.ts +10 -0
  170. package/src/crews/dev-batches/application/run-dev-batches.ts +676 -0
  171. package/src/crews/dev-batches/application/run-wave.ts +452 -0
  172. package/src/crews/dev-batches/application/seed-harvest.ts +163 -0
  173. package/src/crews/dev-batches/crew.ork.ts +146 -0
  174. package/src/crews/dev-batches/domain/batch-waves.ts +70 -0
  175. package/src/crews/dev-batches/domain/batches-budget.ts +52 -0
  176. package/src/crews/dev-batches/domain/batches-log.ts +52 -0
  177. package/src/crews/dev-batches/domain/markers.ts +5 -0
  178. package/src/crews/dev-batches/domain/messages.ts +6 -0
  179. package/src/crews/dev-batches/domain/wave-order.ts +44 -0
  180. package/src/crews/dev-change/application/change-material.ts +44 -0
  181. package/src/crews/dev-change/application/evidence.ts +172 -0
  182. package/src/crews/dev-change/application/messages.ts +81 -0
  183. package/src/crews/dev-change/application/prompts.ts +101 -0
  184. package/src/crews/dev-change/application/run-dev-change.ts +324 -0
  185. package/src/crews/dev-change/crew.ork.ts +114 -0
  186. package/src/crews/dev-change/domain/change-answer.ts +163 -0
  187. package/src/crews/dev-change/domain/change-render.ts +77 -0
  188. package/src/crews/dev-change/domain/markers.ts +28 -0
  189. package/src/crews/dev-change/domain/messages.ts +16 -0
  190. package/src/crews/dev-implement/application/close.ts +186 -0
  191. package/src/crews/dev-implement/application/count-open-steps.ts +24 -0
  192. package/src/crews/dev-implement/application/locate-sheet.ts +82 -0
  193. package/src/crews/dev-implement/application/messages.ts +161 -0
  194. package/src/crews/dev-implement/application/observe.ts +52 -0
  195. package/src/crews/dev-implement/application/prompts.ts +9 -0
  196. package/src/crews/dev-implement/application/report-writes.ts +46 -0
  197. package/src/crews/dev-implement/application/run-dev-implement.ts +822 -0
  198. package/src/crews/dev-implement/application/run-role.ts +27 -0
  199. package/src/crews/dev-implement/application/suite-job.ts +122 -0
  200. package/src/crews/dev-implement/application/touched.ts +74 -0
  201. package/src/crews/dev-implement/crew.ork.ts +69 -0
  202. package/src/crews/dev-implement/domain/contracts.ts +255 -0
  203. package/src/crews/dev-implement/domain/correction.ts +103 -0
  204. package/src/crews/dev-implement/domain/cycles.ts +36 -0
  205. package/src/crews/dev-implement/domain/implement-budget.ts +29 -0
  206. package/src/crews/dev-implement/domain/markers.ts +23 -0
  207. package/src/crews/dev-implement/domain/messages.ts +58 -0
  208. package/src/crews/dev-implement/domain/prompts.ts +93 -0
  209. package/src/crews/dev-implement/domain/roles.ts +49 -0
  210. package/src/crews/dev-implement/domain/sheet-edits.ts +76 -0
  211. package/src/crews/dev-implement/domain/sheet-ticks.ts +23 -0
  212. package/src/crews/dev-implement/domain/step-checks.ts +137 -0
  213. package/src/crews/dev-implement/domain/step-section.ts +129 -0
  214. package/src/crews/dev-learn/application/learn-backlog.ts +58 -0
  215. package/src/crews/dev-learn/application/learn-prompt-fit.ts +63 -0
  216. package/src/crews/dev-learn/application/messages.ts +51 -0
  217. package/src/crews/dev-learn/application/prompts.ts +99 -0
  218. package/src/crews/dev-learn/application/run-dev-learn.ts +558 -0
  219. package/src/crews/dev-learn/crew.ork.ts +53 -0
  220. package/src/crews/dev-learn/domain/learn-answer.ts +233 -0
  221. package/src/crews/dev-learn/domain/messages.ts +65 -0
  222. package/src/crews/dev-learn/domain/owner-lines.ts +89 -0
  223. package/src/crews/dev-learn/domain/proposals-render.ts +95 -0
  224. package/src/crews/dev-plan/application/anchor-paths.ts +113 -0
  225. package/src/crews/dev-plan/application/inventory.ts +174 -0
  226. package/src/crews/dev-plan/application/messages.ts +88 -0
  227. package/src/crews/dev-plan/application/plan-prompt-fit.ts +44 -0
  228. package/src/crews/dev-plan/application/prompts.ts +141 -0
  229. package/src/crews/dev-plan/application/run-dev-plan.ts +483 -0
  230. package/src/crews/dev-plan/crew.ork.ts +112 -0
  231. package/src/crews/dev-plan/domain/inventory-model.ts +95 -0
  232. package/src/crews/dev-plan/domain/markers.ts +18 -0
  233. package/src/crews/dev-plan/domain/messages.ts +118 -0
  234. package/src/crews/dev-plan/domain/plan-answer.ts +753 -0
  235. package/src/crews/dev-plan/domain/plan-render.ts +306 -0
  236. package/src/crews/dev-plan/domain/prompts.ts +44 -0
  237. package/src/crews/dev-spec/application/messages.ts +30 -0
  238. package/src/crews/dev-spec/application/prompts.ts +93 -0
  239. package/src/crews/dev-spec/application/run-dev-spec.ts +237 -0
  240. package/src/crews/dev-spec/application/spec-material.ts +42 -0
  241. package/src/crews/dev-spec/crew.ork.ts +110 -0
  242. package/src/crews/dev-spec/domain/markers.ts +30 -0
  243. package/src/crews/dev-spec/domain/messages.ts +39 -0
  244. package/src/crews/dev-spec/domain/spec-answer.ts +252 -0
  245. package/src/crews/dev-spec/domain/spec-render.ts +76 -0
  246. package/src/crews/dev-verify/application/audit-brief.ts +187 -0
  247. package/src/crews/dev-verify/application/audit.ts +267 -0
  248. package/src/crews/dev-verify/application/capture.ts +311 -0
  249. package/src/crews/dev-verify/application/messages.ts +119 -0
  250. package/src/crews/dev-verify/application/prompts.ts +209 -0
  251. package/src/crews/dev-verify/application/run-dev-verify.ts +423 -0
  252. package/src/crews/dev-verify/application/run-gate.ts +204 -0
  253. package/src/crews/dev-verify/crew.ork.ts +103 -0
  254. package/src/crews/dev-verify/domain/audit-answer.ts +154 -0
  255. package/src/crews/dev-verify/domain/auditor-charter.ts +21 -0
  256. package/src/crews/dev-verify/domain/capture-sections.ts +138 -0
  257. package/src/crews/dev-verify/domain/commands.ts +103 -0
  258. package/src/crews/dev-verify/domain/gate.ts +131 -0
  259. package/src/crews/dev-verify/domain/markers.ts +16 -0
  260. package/src/crews/dev-verify/domain/mechanical-table.ts +156 -0
  261. package/src/crews/dev-verify/domain/messages.ts +92 -0
  262. package/src/crews/dev-verify/domain/runtime-cut.ts +13 -0
  263. package/src/crews/dev-verify/domain/sheet-facts.ts +4 -0
  264. package/src/crews/dev-verify/domain/text.ts +20 -0
  265. package/src/crews/dev-verify/domain/verdict.ts +127 -0
  266. package/src/crews/git-commit/application/draft.ts +133 -0
  267. package/src/crews/git-commit/application/messages.ts +15 -0
  268. package/src/crews/git-commit/application/prompts.ts +47 -0
  269. package/src/crews/git-commit/application/run-git-commit.ts +117 -0
  270. package/src/crews/git-commit/crew.ork.ts +53 -0
  271. package/src/crews/git-commit/domain/commit.ts +200 -0
  272. package/src/crews/git-commit/domain/markers.ts +4 -0
  273. package/src/crews/git-commit/domain/messages.ts +48 -0
  274. package/src/crews/init-verifiers/application/authoring.ts +90 -0
  275. package/src/crews/init-verifiers/application/messages.ts +13 -0
  276. package/src/crews/init-verifiers/application/prompts.ts +107 -0
  277. package/src/crews/init-verifiers/application/run-init-verifiers.ts +26 -0
  278. package/src/crews/init-verifiers/crew.ork.ts +35 -0
  279. package/src/crews/init-verifiers/domain/commands-section.ts +36 -0
  280. package/src/crews/init-verifiers/domain/readiness.ts +23 -0
  281. package/src/crews/main-loop/application/auto-compact.ts +78 -0
  282. package/src/crews/main-loop/application/context-gather.ts +133 -0
  283. package/src/crews/main-loop/application/messages.ts +81 -0
  284. package/src/crews/main-loop/application/prompts.ts +12 -0
  285. package/src/crews/main-loop/application/run-main-loop.ts +383 -0
  286. package/src/crews/main-loop/application/turn-context.ts +111 -0
  287. package/src/crews/main-loop/crew.ork.ts +124 -0
  288. package/src/crews/main-loop/domain/autocompact.ts +27 -0
  289. package/src/crews/main-loop/domain/prompt-assembly.ts +338 -0
  290. package/src/crews/main-loop/domain/prompts.ts +336 -0
  291. package/src/crews/main-loop/domain/turn-chains.ts +130 -0
  292. package/src/crews/project-init/application/detect.ts +123 -0
  293. package/src/crews/project-init/application/messages.ts +15 -0
  294. package/src/crews/project-init/application/prompts.ts +105 -0
  295. package/src/crews/project-init/application/run-project-init.ts +31 -0
  296. package/src/crews/project-init/crew.ork.ts +36 -0
  297. package/src/crews/project-init/domain/conventions.ts +36 -0
  298. package/src/crews/project-init/domain/existing-files.ts +65 -0
  299. package/src/crews/project-init/domain/messages.ts +13 -0
  300. package/src/crews/project-init/domain/package-map.ts +73 -0
  301. package/src/crews/project-init/domain/prompts.ts +10 -0
  302. package/src/crews/session-compact/application/prompts.ts +5 -0
  303. package/src/crews/session-compact/crew.ork.ts +56 -0
  304. package/src/crews/shared-memory-admit/application/prompts.ts +5 -0
  305. package/src/crews/shared-memory-admit/crew.ork.ts +49 -0
  306. package/src/crews/speech/application/messages.ts +3 -0
  307. package/src/crews/speech/application/prompts.ts +3 -0
  308. package/src/crews/speech/application/run-speech.ts +26 -0
  309. package/src/crews/speech/crew.ork.ts +38 -0
  310. package/src/shared/application/agents/child-agent.ts +259 -0
  311. package/src/shared/application/agents/messages.ts +35 -0
  312. package/src/shared/application/agents/route-agent.ts +115 -0
  313. package/src/shared/application/agents/run-sub-agent.ts +119 -0
  314. package/src/shared/application/answer-language.ts +14 -0
  315. package/src/shared/application/attached-skills.ts +36 -0
  316. package/src/shared/application/compaction/compact-session.ts +242 -0
  317. package/src/shared/application/compaction/extract-memories.ts +38 -0
  318. package/src/shared/application/compaction/messages.ts +20 -0
  319. package/src/shared/application/compaction/prune-context.ts +94 -0
  320. package/src/shared/application/compaction/pruned-llm.ts +35 -0
  321. package/src/shared/application/compaction/restore-context.ts +78 -0
  322. package/src/shared/application/config-store.ts +123 -0
  323. package/src/shared/application/dev/brief-inventory.ts +115 -0
  324. package/src/shared/application/dev/close-batch.ts +85 -0
  325. package/src/shared/application/dev/find-repo-pack.ts +78 -0
  326. package/src/shared/application/dev/learn-decision.ts +254 -0
  327. package/src/shared/application/dev/load-dev-context.ts +265 -0
  328. package/src/shared/application/dev/measure-access-cost.ts +69 -0
  329. package/src/shared/application/dev/messages.ts +132 -0
  330. package/src/shared/application/dev/phase-timer.ts +54 -0
  331. package/src/shared/application/dev/plan-source.ts +116 -0
  332. package/src/shared/application/dev/preflight.ts +71 -0
  333. package/src/shared/application/dev/project-files.ts +17 -0
  334. package/src/shared/application/dev/prompts.ts +34 -0
  335. package/src/shared/application/dev/question-round.ts +60 -0
  336. package/src/shared/application/dev/resolve-work-folder.ts +134 -0
  337. package/src/shared/application/dev/script-tool-slot.ts +27 -0
  338. package/src/shared/application/dev/settle-questions.ts +57 -0
  339. package/src/shared/application/dev/source-review.ts +67 -0
  340. package/src/shared/application/dev/source-step.ts +152 -0
  341. package/src/shared/application/dev/spend.ts +55 -0
  342. package/src/shared/application/dev/step-precedents.ts +90 -0
  343. package/src/shared/application/dev/tool-call-policy.ts +87 -0
  344. package/src/shared/application/dev/tool-callbacks.ts +262 -0
  345. package/src/shared/application/dev/tool-trace-recorder.ts +46 -0
  346. package/src/shared/application/dev/verdict-sources.ts +50 -0
  347. package/src/shared/application/dev/wrapped-tools.ts +147 -0
  348. package/src/shared/application/extra-tools.ts +71 -0
  349. package/src/shared/application/git/batch-worktree.ts +102 -0
  350. package/src/shared/application/git/commit-files.ts +191 -0
  351. package/src/shared/application/git/merge-batch.ts +67 -0
  352. package/src/shared/application/git/messages.ts +75 -0
  353. package/src/shared/application/git/open-pull-request.ts +52 -0
  354. package/src/shared/application/host-context.ts +59 -0
  355. package/src/shared/application/host-layout-store.ts +45 -0
  356. package/src/shared/application/instructions-file.ts +19 -0
  357. package/src/shared/application/json-file.ts +34 -0
  358. package/src/shared/application/llm-profile.ts +36 -0
  359. package/src/shared/application/messages.ts +14 -0
  360. package/src/shared/application/permission-rules.ts +169 -0
  361. package/src/shared/application/ports/approvals.ts +20 -0
  362. package/src/shared/application/ports/clock.ts +5 -0
  363. package/src/shared/application/ports/code-index.ts +93 -0
  364. package/src/shared/application/ports/crew.ts +60 -0
  365. package/src/shared/application/ports/decision.ts +14 -0
  366. package/src/shared/application/ports/files.ts +21 -0
  367. package/src/shared/application/ports/human.ts +38 -0
  368. package/src/shared/application/ports/llm.ts +83 -0
  369. package/src/shared/application/ports/memory.ts +30 -0
  370. package/src/shared/application/ports/progress.ts +23 -0
  371. package/src/shared/application/ports/runtime.ts +15 -0
  372. package/src/shared/application/ports/session.ts +74 -0
  373. package/src/shared/application/ports/shared-memory.ts +26 -0
  374. package/src/shared/application/ports/shell.ts +40 -0
  375. package/src/shared/application/ports/telemetry.ts +45 -0
  376. package/src/shared/application/ports/theme.ts +11 -0
  377. package/src/shared/application/ports/tools.ts +46 -0
  378. package/src/shared/application/ports/usage.ts +45 -0
  379. package/src/shared/application/ports.ts +29 -0
  380. package/src/shared/application/project-manifests.ts +106 -0
  381. package/src/shared/application/session-io.ts +85 -0
  382. package/src/shared/application/session-state.ts +36 -0
  383. package/src/shared/application/shared-memory/admit-entries.ts +179 -0
  384. package/src/shared/application/shared-memory/harvest-after-gaps.ts +69 -0
  385. package/src/shared/application/shared-memory/harvest-mistakes.ts +45 -0
  386. package/src/shared/application/shared-memory/import-agent-memory.ts +119 -0
  387. package/src/shared/application/shared-memory/memory-files.ts +111 -0
  388. package/src/shared/application/shared-memory/memory-settings.ts +94 -0
  389. package/src/shared/application/shared-memory/messages.ts +63 -0
  390. package/src/shared/application/shared-memory/push-candidate.ts +149 -0
  391. package/src/shared/application/shared-memory/recall-precedents.ts +70 -0
  392. package/src/shared/application/skills/messages.ts +4 -0
  393. package/src/shared/application/skills/suggest-skills.ts +102 -0
  394. package/src/shared/application/state-snapshot.ts +38 -0
  395. package/src/shared/application/workflow/messages.ts +8 -0
  396. package/src/shared/application/workflow/workflow-state.ts +136 -0
  397. package/src/shared/domain/agent-policy/behavior-flags.ts +162 -0
  398. package/src/shared/domain/agent-policy/extra-tools.ts +67 -0
  399. package/src/shared/domain/agent-policy/memory-categories.ts +6 -0
  400. package/src/shared/domain/agent-policy/messages.ts +66 -0
  401. package/src/shared/domain/agent-policy/mode-policy.ts +51 -0
  402. package/src/shared/domain/agent-policy/output-styles.ts +11 -0
  403. package/src/shared/domain/agent-policy/path-rules.ts +299 -0
  404. package/src/shared/domain/agent-policy/permission.ts +625 -0
  405. package/src/shared/domain/agent-policy/prompts.ts +17 -0
  406. package/src/shared/domain/agent-policy/reasoning.ts +59 -0
  407. package/src/shared/domain/agent-policy/rule-sets.ts +416 -0
  408. package/src/shared/domain/agent-policy/tool-access.ts +91 -0
  409. package/src/shared/domain/agent-registry.ts +143 -0
  410. package/src/shared/domain/agents/built-in-charters.ts +43 -0
  411. package/src/shared/domain/agents/chain.ts +30 -0
  412. package/src/shared/domain/agents/charter.ts +64 -0
  413. package/src/shared/domain/agents/exclusive.ts +25 -0
  414. package/src/shared/domain/agents/instances.ts +252 -0
  415. package/src/shared/domain/agents/messages.ts +39 -0
  416. package/src/shared/domain/agents/model-route.ts +199 -0
  417. package/src/shared/domain/agents/prompts.ts +20 -0
  418. package/src/shared/domain/code-intel-contract.ts +357 -0
  419. package/src/shared/domain/code-intel-routing.ts +60 -0
  420. package/src/shared/domain/compact-outcome.ts +46 -0
  421. package/src/shared/domain/compaction-thresholds.ts +162 -0
  422. package/src/shared/domain/compaction.ts +288 -0
  423. package/src/shared/domain/config-schema.ts +434 -0
  424. package/src/shared/domain/context-prune.ts +176 -0
  425. package/src/shared/domain/decision/questions.ts +102 -0
  426. package/src/shared/domain/dev/access-cost.ts +230 -0
  427. package/src/shared/domain/dev/artefacts.ts +50 -0
  428. package/src/shared/domain/dev/batches-concurrency.ts +35 -0
  429. package/src/shared/domain/dev/batches-state.ts +49 -0
  430. package/src/shared/domain/dev/build-commands.ts +45 -0
  431. package/src/shared/domain/dev/call-guard.ts +342 -0
  432. package/src/shared/domain/dev/carried-text.ts +47 -0
  433. package/src/shared/domain/dev/design-rules.ts +100 -0
  434. package/src/shared/domain/dev/learn-proposals.ts +176 -0
  435. package/src/shared/domain/dev/learn-state.ts +94 -0
  436. package/src/shared/domain/dev/markers.ts +107 -0
  437. package/src/shared/domain/dev/messages.ts +259 -0
  438. package/src/shared/domain/dev/path-args.ts +42 -0
  439. package/src/shared/domain/dev/path-rebase.ts +93 -0
  440. package/src/shared/domain/dev/phase-timing.ts +50 -0
  441. package/src/shared/domain/dev/plan-checks.ts +191 -0
  442. package/src/shared/domain/dev/plan-format.ts +170 -0
  443. package/src/shared/domain/dev/project-files.ts +29 -0
  444. package/src/shared/domain/dev/prompts/brief-blocks.ts +20 -0
  445. package/src/shared/domain/dev/prompts.ts +251 -0
  446. package/src/shared/domain/dev/questions.ts +267 -0
  447. package/src/shared/domain/dev/reading-rule.ts +41 -0
  448. package/src/shared/domain/dev/repo-pack.ts +240 -0
  449. package/src/shared/domain/dev/review-answer.ts +173 -0
  450. package/src/shared/domain/dev/review-brief.ts +54 -0
  451. package/src/shared/domain/dev/reviewer-charter.ts +35 -0
  452. package/src/shared/domain/dev/sheet-facts.ts +81 -0
  453. package/src/shared/domain/dev/spec-format.ts +182 -0
  454. package/src/shared/domain/dev/step-budget.ts +74 -0
  455. package/src/shared/domain/dev/step-rules.ts +109 -0
  456. package/src/shared/domain/dev/test-commands.ts +94 -0
  457. package/src/shared/domain/dev/test-output.ts +33 -0
  458. package/src/shared/domain/dev/test-paths.ts +40 -0
  459. package/src/shared/domain/dev/tool-guards.ts +65 -0
  460. package/src/shared/domain/dev/trait-pattern.ts +87 -0
  461. package/src/shared/domain/dev/verdict-format.ts +162 -0
  462. package/src/shared/domain/dev/whitespace.ts +35 -0
  463. package/src/shared/domain/dev/work-folder.ts +68 -0
  464. package/src/shared/domain/dev/yaml-subset.ts +385 -0
  465. package/src/shared/domain/error-text.ts +13 -0
  466. package/src/shared/domain/git/close.ts +274 -0
  467. package/src/shared/domain/git/messages.ts +20 -0
  468. package/src/shared/domain/git/pull-request.ts +96 -0
  469. package/src/shared/domain/git/worktree.ts +46 -0
  470. package/src/shared/domain/host-layout.ts +147 -0
  471. package/src/shared/domain/host-paths.ts +399 -0
  472. package/src/shared/domain/index-languages.ts +16 -0
  473. package/src/shared/domain/instructions-file.ts +18 -0
  474. package/src/shared/domain/iso-day.ts +4 -0
  475. package/src/shared/domain/llm-failure.ts +134 -0
  476. package/src/shared/domain/llm-profile.ts +44 -0
  477. package/src/shared/domain/marked-message.ts +29 -0
  478. package/src/shared/domain/markers.ts +30 -0
  479. package/src/shared/domain/messages.ts +291 -0
  480. package/src/shared/domain/model-catalog.ts +79 -0
  481. package/src/shared/domain/permission-modes.ts +99 -0
  482. package/src/shared/domain/prelude.ts +92 -0
  483. package/src/shared/domain/project-manifests.ts +84 -0
  484. package/src/shared/domain/prompts.ts +233 -0
  485. package/src/shared/domain/search-routing.ts +77 -0
  486. package/src/shared/domain/secret-patterns.ts +46 -0
  487. package/src/shared/domain/session-keys.ts +92 -0
  488. package/src/shared/domain/session-start.ts +61 -0
  489. package/src/shared/domain/severity.ts +72 -0
  490. package/src/shared/domain/sha1.ts +61 -0
  491. package/src/shared/domain/shared-memory/agent-memory-import.ts +145 -0
  492. package/src/shared/domain/shared-memory/candidates.ts +40 -0
  493. package/src/shared/domain/shared-memory/entry.ts +151 -0
  494. package/src/shared/domain/shared-memory/front-matter.ts +187 -0
  495. package/src/shared/domain/shared-memory/gate.ts +45 -0
  496. package/src/shared/domain/shared-memory/harvest.ts +64 -0
  497. package/src/shared/domain/shared-memory/layout.ts +190 -0
  498. package/src/shared/domain/shared-memory/markers.ts +9 -0
  499. package/src/shared/domain/shared-memory/messages.ts +66 -0
  500. package/src/shared/domain/shared-memory/precedents-block.ts +82 -0
  501. package/src/shared/domain/shared-memory/prompts.ts +28 -0
  502. package/src/shared/domain/shared-memory/refused.ts +84 -0
  503. package/src/shared/domain/shared-memory/verdict-rows.ts +134 -0
  504. package/src/shared/domain/skills/prompts.ts +4 -0
  505. package/src/shared/domain/skills/shortlist.ts +149 -0
  506. package/src/shared/domain/snip-turns.ts +33 -0
  507. package/src/shared/domain/speech.ts +21 -0
  508. package/src/shared/domain/strip.ts +88 -0
  509. package/src/shared/domain/tool-trace.ts +120 -0
  510. package/src/shared/domain/types.ts +67 -0
  511. package/src/shared/domain/verifiers.ts +33 -0
  512. package/src/shared/domain/vfs.ts +16 -0
  513. package/src/shared/domain/workflow/prompts.ts +15 -0
  514. package/src/shared/domain/workflow/state-file.ts +142 -0
  515. package/src/shared/infrastructure/globals.ts +57 -0
  516. package/src/shared/infrastructure/orkeon/approvals.ts +24 -0
  517. package/src/shared/infrastructure/orkeon/child-agents.ts +122 -0
  518. package/src/shared/infrastructure/orkeon/chooser.ts +32 -0
  519. package/src/shared/infrastructure/orkeon/code-index.ts +120 -0
  520. package/src/shared/infrastructure/orkeon/crew-host.ts +27 -0
  521. package/src/shared/infrastructure/orkeon/crew-memory.ts +12 -0
  522. package/src/shared/infrastructure/orkeon/decision-model.ts +31 -0
  523. package/src/shared/infrastructure/orkeon/dev-deps.ts +179 -0
  524. package/src/shared/infrastructure/orkeon/files.ts +58 -0
  525. package/src/shared/infrastructure/orkeon/github-pull-requests.ts +30 -0
  526. package/src/shared/infrastructure/orkeon/host-context.ts +36 -0
  527. package/src/shared/infrastructure/orkeon/host-provider.ts +22 -0
  528. package/src/shared/infrastructure/orkeon/human-input.ts +55 -0
  529. package/src/shared/infrastructure/orkeon/llm-profile.ts +58 -0
  530. package/src/shared/infrastructure/orkeon/llm.ts +164 -0
  531. package/src/shared/infrastructure/orkeon/markers.ts +6 -0
  532. package/src/shared/infrastructure/orkeon/memory-store.ts +41 -0
  533. package/src/shared/infrastructure/orkeon/memory-tools.ts +129 -0
  534. package/src/shared/infrastructure/orkeon/messages.ts +15 -0
  535. package/src/shared/infrastructure/orkeon/permission-rules.ts +42 -0
  536. package/src/shared/infrastructure/orkeon/progress.ts +24 -0
  537. package/src/shared/infrastructure/orkeon/prompts.ts +47 -0
  538. package/src/shared/infrastructure/orkeon/reasoning.ts +40 -0
  539. package/src/shared/infrastructure/orkeon/run-state.ts +17 -0
  540. package/src/shared/infrastructure/orkeon/runtime-info.ts +30 -0
  541. package/src/shared/infrastructure/orkeon/runtime-tools.ts +60 -0
  542. package/src/shared/infrastructure/orkeon/script-tools.ts +129 -0
  543. package/src/shared/infrastructure/orkeon/session-store.ts +94 -0
  544. package/src/shared/infrastructure/orkeon/session-switch.ts +23 -0
  545. package/src/shared/infrastructure/orkeon/shared-memory.ts +61 -0
  546. package/src/shared/infrastructure/orkeon/shell-jobs.ts +81 -0
  547. package/src/shared/infrastructure/orkeon/shell.ts +39 -0
  548. package/src/shared/infrastructure/orkeon/telemetry.ts +63 -0
  549. package/src/shared/infrastructure/orkeon/tool-catalogue.ts +76 -0
  550. package/src/shared/infrastructure/orkeon/tool-results.ts +120 -0
  551. package/src/shared/infrastructure/orkeon/usage.ts +74 -0
  552. package/src/shared/infrastructure/orkeon/wiring.ts +174 -0
@@ -0,0 +1,822 @@
1
+ // dev-implement F<n>: the steps of one batch sheet, each as RED by the test author then GREEN by
2
+ // the implementer, two acts of the crew's one agent with their own tools and rules. Consecutive
3
+ // steps on one test file are one cycle: every RED first, then one GREEN and one Cost for them all.
4
+ // Code makes each brief from the sheet, observes the tree before and after each act, runs the
5
+ // tests itself, measures the cost of what changed, and ticks a box only once what it stands for was
6
+ // seen. After the last cycle the batch's files are refreshed in the code index, then the build, then
7
+ // the whole suite once per batch (the affected projects after, the sheet's and the graph's), run as
8
+ // shell jobs and write the logs dev-verify reads; a batch all ticked and green hands
9
+ // over to dev-verify (the `next` of its answer, `resume` after a GAPS verdict). A correction
10
+ // (`— correction: <finding>`) is first appended to the sheet as a new step. Any failed check stops
11
+ // the batch with BLOCKED and ticks nothing more.
12
+ //
13
+ // The answer is JSON: `{ lines, next? }`, read by the command's `completed`.
14
+ import type { AffectedTests, Clock, CostIndex, Files, Llm, Logger, Shell, ShellJobs } from "../../../shared/application/ports.ts";
15
+ import { isoDay } from "../../../shared/domain/iso-day.ts";
16
+ import type { ConfigStore } from "../../../shared/application/config-store.ts";
17
+ import type { PullRequestOpener } from "../../../shared/application/git/commit-files.ts";
18
+ import { loadDevContext } from "../../../shared/application/dev/load-dev-context.ts";
19
+ import { createWrappedTools } from "../../../shared/application/dev/wrapped-tools.ts";
20
+ import { measureAccessCost } from "../../../shared/application/dev/measure-access-cost.ts";
21
+ import type { CostFile } from "../../../shared/application/dev/measure-access-cost.ts";
22
+ import { addedLines } from "../../../shared/domain/dev/access-cost.ts";
23
+ import { hasTestLayout, isTestPath } from "../../../shared/domain/dev/test-paths.ts";
24
+ import { auditCommand, closeCommand, gapsRoundsOf, lastVerdict, parseVerdictFile } from "../../../shared/domain/dev/verdict-format.ts";
25
+ import { shellQuote } from "../../../shared/domain/git/close.ts";
26
+ import type { CarriedText } from "../../../shared/domain/dev/carried-text.ts";
27
+ import { tidyWhitespace } from "../../../shared/domain/dev/whitespace.ts";
28
+ import type { WrappedRun, WrappedTools } from "../../../shared/application/dev/wrapped-tools.ts";
29
+ import { stepRules } from "../../../shared/domain/dev/step-rules.ts";
30
+ import { policyFor } from "../../../shared/domain/agent-policy/mode-policy.ts";
31
+ import { parseSessionRules } from "../../../shared/domain/git/pull-request.ts";
32
+ import { shellRuleGuard } from "../../../shared/domain/dev/tool-guards.ts";
33
+ import type { RepoPack, RepoPackLayout } from "../../../shared/domain/dev/repo-pack.ts";
34
+ import { existingStubsOf, testFileOf, greenContract, projectCommandFor, redContract, staleBlock, stubsOf, testCommandFor } from "../domain/contracts.ts";
35
+ import { openSteps, parseImplementSheet } from "../domain/step-section.ts";
36
+ import type { ImplementSheet, ImplementStep } from "../domain/step-section.ts";
37
+ import { addedFailure, changedPaths, failureCount, greenProblem, readCost, redProblem, under } from "../domain/step-checks.ts";
38
+ import { cyclesLine, cyclesOf, stepsLabel } from "../domain/cycles.ts";
39
+ import type { Cycle } from "../domain/cycles.ts";
40
+ import { addCorrection } from "../domain/correction.ts";
41
+ import { addAssumptions, assumptionsOf } from "../domain/sheet-edits.ts";
42
+ import type { ObservedRun } from "../domain/step-checks.ts";
43
+ import { tickBox } from "../domain/sheet-ticks.ts";
44
+ import type { TddBox } from "../domain/sheet-ticks.ts";
45
+ import { IMPLEMENTER, TEST_AUTHOR } from "../domain/roles.ts";
46
+ import type { RoleName } from "../domain/roles.ts";
47
+ import { SLICE_SECONDS, SUITE_LIMIT_SECONDS } from "../domain/implement-budget.ts";
48
+ import { askLine, runRole } from "./run-role.ts";
49
+ import { NOTHING_RECALLED, noPrecedents, precedentsLine, recallQuery, sheetTitle } from "../../../shared/application/dev/step-precedents.ts";
50
+ import type { Recalled, StepPrecedents } from "../../../shared/application/dev/step-precedents.ts";
51
+ import { snapshot } from "./observe.ts";
52
+ import { logText, NO_VERDICT_EXIT, runSuite } from "./suite-job.ts";
53
+ import { locateSheet } from "./locate-sheet.ts";
54
+ import type { LocatedSheet } from "./locate-sheet.ts";
55
+ import { prContextOf, readTouchedRecord, recordTouched, verdictMarkOf } from "./touched.ts";
56
+ import type { PrContext } from "./touched.ts";
57
+ import { closeDevBatch } from "./close.ts";
58
+ import { BATCHES_ACTIVE_RECORD, batchesRunCode } from "../../../shared/domain/dev/batches-state.ts";
59
+ import { WORKSPACE, workspaceRelative } from "../../../shared/domain/vfs.ts";
60
+ import { askCostLine } from "./prompts.ts";
61
+ import {
62
+ BUILD_LINE_NOT_RUN, FAILURE_NOT_CHECKED, NO_PRODUCTION_CHANGED, NO_REPOSITORY_PACK, NO_TEST_LAYOUT, SHEET_PUT_BACK, TEST_NOT_RUN,
63
+ WHOLE_SUITE_EVERY_TEST, WHOLE_SUITE_NO_TEST_PROJECT, affectedDone, affectedExited, affectedRefused, affectedStillRunning, firstAndMore,
64
+ assumptionsNotWritten, assumptionsWritten, batchGreen, batchIsFn, blockedLine, buildDone, buildExited, buildRefused,
65
+ buildStillRunning, cannotBeReadColonReason, correctionAppended, correctionProblem, correctionStillOpen, costDone, costFlagged, costMeasured,
66
+ measuredNotComputed, gapsRoundsWarned, graphAdded, graphNotRead, graphProjectsLeftOut, greenDone, indexNotIndexed, indexNotRefreshed,
67
+ indexRefreshed, indexReindexFailed, notPushedInRun, notRun, readOnlyMode, readOnlyModeAtClose, redDone, restoreCouldNotRun,
68
+ restored, restoreExited, restoreNoVerdict, restoreRefused, restoreStillRunning, roleChangedPlanFolder, runTitle, sheetMalformed,
69
+ sheetNotPutBack, sheetNotWritten, shownLog, stepActProblem, testDone, testExited, testRefused, testStillRunning, whitespaceFixed,
70
+ whitespaceNotWritten, wholeSuiteUnplaced, workFolderOutsideMounts,
71
+ } from "./messages.ts";
72
+
73
+ export interface DevImplementInputs {
74
+ batch?: unknown; plan?: unknown; close?: unknown; pr?: unknown; push?: unknown;
75
+ /** The finding of a correction (`— correction: <finding>`): appended to the sheet as a new step first. */
76
+ correction?: unknown;
77
+ /** The `stale: <question> — <evidence>` lines /dev-batches hands a batch's first launch (its review's Major rows):
78
+ * they end the RED and GREEN prompts. */
79
+ stale?: readonly string[];
80
+ /** The session's mode and rules at the launch: a read-only mode is refused, a deny on the push keeps the commit local. */
81
+ permissionMode?: unknown; permissionRules?: unknown;
82
+ /** Whether the github tool is registered (the close opens the pull request itself). */
83
+ githubTool?: unknown;
84
+ /** Carried to the audit the run chains: the /hooks registry, the /effort level, and `memoryRecall: false`. */
85
+ hooks?: unknown; effort?: unknown; memoryRecall?: unknown;
86
+ }
87
+
88
+ const flag = (v: unknown): boolean => v === true || v === "true";
89
+
90
+ /** The crew's inputs as the run reads them. `push: false` is kept: /dev-batches sends it on every batch's close, so
91
+ * that the plan's branch is pushed once, at the run's own close (L-7); any other value pushes, as before. */
92
+ export function implementInputs(args: Record<string, unknown>): DevImplementInputs {
93
+ return {
94
+ batch: args.batch, plan: args.plan, close: flag(args.close), pr: flag(args.pr), correction: args.correction,
95
+ stale: Array.isArray(args.stale) ? args.stale.filter((l): l is string => typeof l === "string") : undefined,
96
+ push: args.push === false || args.push === "false" ? false : undefined,
97
+ permissionMode: args.permissionMode, permissionRules: args.permissionRules, githubTool: args.githubTool,
98
+ hooks: args.hooks, effort: args.effort, memoryRecall: args.memoryRecall,
99
+ };
100
+ }
101
+
102
+ export interface DevImplementDeps {
103
+ files: Files; shell: Shell; config: Pick<ConfigStore, "readValue">; jobs: ShellJobs;
104
+ /** A role's Llm, built with that role's callbacks over the pack's layout; `wrote` hears the path of each
105
+ * file_write or edit_file call those callbacks let through; `writable` names the paths the role's own denies
106
+ * leave open (the test author's stubs). */
107
+ roleLlm(role: RoleName, layout: RepoPackLayout, wrote: (path: string) => void, writable: readonly string[]): Pick<Llm, "act">;
108
+ log: Logger;
109
+ /** The slot run_tests and run_build read: bound to this run's wrapped tools. */
110
+ toolSlot?: { bind(tools: WrappedTools): () => void };
111
+ /** The close's pull-request opener, for the context read at the launch; none: the command is handed over. */
112
+ openerFor?(context: PrContext): PullRequestOpener | undefined;
113
+ /** The code index the measured cost reads, refreshed after the batch, and asked for the affected tests; none: the
114
+ * cost is not computed (the stated line decides) and the affected tests are the sheet's. */
115
+ costIndex?: CostIndex;
116
+ /** The time now: the close's done marks carry its UTC day. */
117
+ clock: Clock;
118
+ /** The shared memory's code-triggered recall (T3 before each red act, T5 on a correction); absent, none. */
119
+ precedents?: StepPrecedents;
120
+ }
121
+
122
+ export interface ImplementAnswer {
123
+ lines: string[];
124
+ next?: { crew: "dev-verify"; input: { batch: string; plan: string; mode: "fast" | "resume"; hooks?: unknown; effort?: unknown; memoryRecall?: false } };
125
+ }
126
+
127
+ const RESTORE_TIMEOUT_SECONDS = 900;
128
+ const BATCH = /^F\d+$/;
129
+ const GAPS_ROUNDS_WARNED = 2;
130
+
131
+ const answer = (lines: string[], next?: ImplementAnswer["next"]): string =>
132
+ JSON.stringify(next === undefined ? { lines } : { lines, next });
133
+ const blocked = (lines: string[], line: string): string => answer([...lines, blockedLine(line)]);
134
+ const reasonOf = (e: unknown): string => String((e as Error)?.message ?? e).split("\n")[0];
135
+
136
+ interface Run {
137
+ deps: DevImplementDeps;
138
+ pack: RepoPack;
139
+ isTest: (path: string) => boolean;
140
+ located: LocatedSheet;
141
+ sheetPath: string;
142
+ sheetText: string;
143
+ sheet: ImplementSheet;
144
+ tools: WrappedTools;
145
+ wrote: (path: string) => void;
146
+ /** Folders whose writes are code's own (the work folder, the plan folder): never a role's change. */
147
+ ownFolders: string[];
148
+ /** The plan folder, relative to /workspace, and its logs folder, the one part of it a role's runs write. */
149
+ planFolder: string;
150
+ planLogs: string;
151
+ logFolder: string;
152
+ /** The paths the running act's write tools named, relative to /workspace. */
153
+ written: Set<string>;
154
+ verdictMark: string;
155
+ touched: Set<string>;
156
+ /** The steps this run ran an act of: the affected projects. */
157
+ ran: ImplementStep[];
158
+ lines: string[];
159
+ /** T5: the mistakes recalled for the correction this run carries, in each role's prompt; every recall, for the end. */
160
+ correction: Recalled;
161
+ recalled: Recalled[];
162
+ /** The stale lines of the launch, as the block that ends each role's prompt ("" without any). */
163
+ stale: Recalled;
164
+ }
165
+
166
+ /** A role's prompt with the precedents recalled for it, each block after the contract. */
167
+ function withPrecedents(prompt: string, recalled: readonly Recalled[]): string {
168
+ const blocks = recalled.map((r) => r.block.trimEnd()).filter((b) => b !== "");
169
+ return blocks.length === 0 ? prompt : [prompt.trimEnd(), ...blocks].join("\n\n");
170
+ }
171
+
172
+ /** T3, before a step's red act: the code structures and mistakes recalled from the sheet's title, the step's title
173
+ * and the paths it touches. */
174
+ async function recallForRed(run: Run, step: ImplementStep): Promise<Recalled> {
175
+ const paths = [...(step.anchor?.testFiles ?? []), ...(step.anchor?.production ?? [])].map((a) => a.path);
176
+ const recalled = await (run.deps.precedents ?? noPrecedents)("T3", recallQuery([sheetTitle(run.sheetText), step.title, ...paths]));
177
+ run.recalled.push(recalled);
178
+ return recalled;
179
+ }
180
+
181
+ function observedRun(run: WrappedRun): ObservedRun {
182
+ return run.ok ? { ran: true, exit: run.exit, timedOut: run.timedOut, log: run.log } : { ran: false, reason: run.refused };
183
+ }
184
+
185
+ async function writeSheet(run: Run, text: string): Promise<string | null> {
186
+ try {
187
+ await run.deps.files.write(run.sheetPath, text);
188
+ } catch (e) {
189
+ return sheetNotWritten(reasonOf(e));
190
+ }
191
+ run.sheetText = text;
192
+ return null;
193
+ }
194
+
195
+ async function tick(run: Run, step: ImplementStep, box: TddBox): Promise<string | null> {
196
+ const ticked = tickBox(run.sheetText, step.number, box);
197
+ if (!ticked.ok) return ticked.problem;
198
+ return writeSheet(run, ticked.text);
199
+ }
200
+
201
+ /** Ticks `box` on every step, in order; the first problem stops. */
202
+ async function tickAll(run: Run, steps: readonly ImplementStep[], box: TddBox): Promise<string | null> {
203
+ for (const step of steps) {
204
+ const failed = await tick(run, step, box);
205
+ if (failed !== null) return failed;
206
+ }
207
+ return null;
208
+ }
209
+
210
+ /** The `Assumption:` lines of a role's answer, written under `## Assumptions` once each. */
211
+ async function keepAssumptions(run: Run, text: string): Promise<void> {
212
+ const { text: next, added } = addAssumptions(run.sheetText, assumptionsOf(text));
213
+ if (added.length === 0) return;
214
+ const failed = await writeSheet(run, next);
215
+ run.lines.push(failed === null
216
+ ? assumptionsWritten(added)
217
+ : assumptionsNotWritten(failed, added));
218
+ }
219
+
220
+ /** A path a write tool named, relative to /workspace. */
221
+ export function workspacePath(path: string): string {
222
+ return workspaceRelative(path.trim()).replace(/^(\.\/)+/, "").replace(/\/+$/, "");
223
+ }
224
+
225
+ /** Puts the sheet back as code last wrote it; a problem when it cannot. */
226
+ async function sheetPutBack(run: Run): Promise<string | null> {
227
+ let now: string | null = null;
228
+ try {
229
+ now = await run.deps.files.read(run.sheetPath);
230
+ } catch {
231
+ now = null;
232
+ }
233
+ if (now === run.sheetText) return null;
234
+ try {
235
+ await run.deps.files.write(run.sheetPath, run.sheetText);
236
+ return SHEET_PUT_BACK;
237
+ } catch (e) {
238
+ return sheetNotPutBack(reasonOf(e));
239
+ }
240
+ }
241
+
242
+ /** One act of a role, between two snapshots: the paths it changed, or why not. A path is the role's when its
243
+ * write tools named it and the tree shows it changed (or it is too large to read); what its runs of run_tests
244
+ * or run_build produced is not. Any change to the plan folder but its logs stops the step, the sheet put back. */
245
+ async function act(
246
+ run: Run, role: RoleName, prompt: string, writable: readonly string[] = [],
247
+ ): Promise<{ text: string; changed: string[] } | string> {
248
+ const before = await snapshot(run.deps);
249
+ if (!before.ok) return before.problem;
250
+ const spec = role === "test-author" ? TEST_AUTHOR : IMPLEMENTER;
251
+ run.written.clear();
252
+ const said = await runRole(run.deps.roleLlm(role, run.pack.layout, run.wrote, writable), spec, prompt);
253
+ const after = await snapshot(run.deps);
254
+ const seen = after.ok ? new Set(changedPaths(before.snapshot, after.snapshot)) : new Set<string>();
255
+ const planChanges = [...new Set([...seen, ...run.written])]
256
+ .filter((p) => under(p, run.planFolder) && !under(p, run.planLogs)).sort();
257
+ const putBack = await sheetPutBack(run);
258
+ if (planChanges.length > 0 || putBack !== null) {
259
+ return roleChangedPlanFolder(role, planChanges.join(", ") || run.located.name, putBack);
260
+ }
261
+ if (!said.ok) return said.reason;
262
+ if (!after.ok) return after.problem;
263
+ const unread = (p: string): boolean => after.snapshot.get(p) === null;
264
+ const changed = [...run.written]
265
+ .filter((p) => seen.has(p) || unread(p))
266
+ .filter((p) => !run.ownFolders.some((f) => under(p, f)))
267
+ .sort();
268
+ await keepAssumptions(run, said.text);
269
+ await tidyChanged(run, changed);
270
+ return { text: said.text, changed };
271
+ }
272
+
273
+ /** The whitespace `git diff --check` would refuse, put right in the files the role changed: a node insert at the
274
+ * end of a module leaves a blank line after the last member, and the gate would stop the batch for it. */
275
+ async function tidyChanged(run: Run, changed: readonly string[]): Promise<void> {
276
+ for (const path of changed) {
277
+ let text: string;
278
+ try {
279
+ text = await run.deps.files.read(`${WORKSPACE}/${path}`);
280
+ } catch {
281
+ continue;
282
+ }
283
+ const tidy = tidyWhitespace(text);
284
+ if (tidy.fixed.length === 0) continue;
285
+ try {
286
+ await run.deps.files.write(`${WORKSPACE}/${path}`, tidy.text);
287
+ run.lines.push(whitespaceFixed(path, tidy.fixed));
288
+ } catch (error) {
289
+ run.lines.push(whitespaceNotWritten(path, tidy.fixed, error instanceof Error ? error.message.split("\n")[0] : String(error)));
290
+ }
291
+ }
292
+ }
293
+
294
+ function contractInput(run: Run, step: ImplementStep, testCommand: string, carried: readonly CarriedText[], cycle?: readonly ImplementStep[]) {
295
+ return {
296
+ code: run.located.code, sheetPath: `${run.located.dir}/${run.located.name}`, sheet: run.sheet, step,
297
+ ...(cycle === undefined ? {} : { cycle }), layout: run.pack.layout, testCommand, carried,
298
+ };
299
+ }
300
+
301
+ /** What a role's brief carries: the sheet, then each of `paths` that exists (a test file, a production file; one to
302
+ * create is left out). */
303
+ async function carriedFor(run: Run, paths: readonly (string | null)[]): Promise<CarriedText[]> {
304
+ const sheet = `${run.located.dir}/${run.located.name}`;
305
+ const out: CarriedText[] = [{ title: sheet, path: sheet, text: run.sheetText }];
306
+ for (const path of new Set(paths)) {
307
+ if (path === null) continue;
308
+ try {
309
+ out.push({ title: path, path, text: await run.deps.files.read(`${WORKSPACE}/${path}`) });
310
+ } catch {
311
+ // To create, or unreadable: the role's own.
312
+ }
313
+ }
314
+ return out;
315
+ }
316
+
317
+ /** The lines `git diff -U0` adds to each changed production file; an untracked file (no diff), or one whose diff
318
+ * cannot be read, counts whole. */
319
+ async function costFiles(run: Run, paths: readonly string[]): Promise<CostFile[]> {
320
+ const out: CostFile[] = [];
321
+ for (const path of paths) {
322
+ let added: Set<number> | null = null;
323
+ try {
324
+ const r = await run.deps.shell.run(`git diff -U0 HEAD -- ${shellQuote(path)}`);
325
+ if (r.exitCode === 0 && r.stdout.trim() !== "") added = addedLines(r.stdout);
326
+ } catch {
327
+ added = null;
328
+ }
329
+ out.push({ path, added });
330
+ }
331
+ return out;
332
+ }
333
+
334
+ /** The measured cost of the cycle's production changes, after its stated Cost line passed: a problem when the
335
+ * measure flags a port call or a memory filter on an added line; else the line it adds to the run's. */
336
+ async function measuredCost(run: Run, production: readonly string[]): Promise<{ problem: string } | { line: string }> {
337
+ if (production.length === 0) return { line: NO_PRODUCTION_CHANGED };
338
+ const cost = await measureAccessCost(run.deps.costIndex, run.pack, [], await costFiles(run, production), run.isTest);
339
+ if (cost.state === "not-computed") return { line: measuredNotComputed(cost.reason) };
340
+ if (cost.exit === 2) {
341
+ return { problem: costFlagged(cost.costLine, cost.flagged) };
342
+ }
343
+ return { line: costMeasured(cost.costLine) };
344
+ }
345
+
346
+ /** The step's `to create` production paths that are still to create: neither written in this run nor present in the
347
+ * tree. A path an earlier GREEN implemented is never a stub again. */
348
+ async function openStubs(run: Run, step: ImplementStep): Promise<string[]> {
349
+ const out: string[] = [];
350
+ for (const path of stubsOf(step)) {
351
+ if (run.touched.has(path)) continue;
352
+ try {
353
+ await run.deps.files.read(`${WORKSPACE}/${path}`, 1);
354
+ } catch {
355
+ out.push(path);
356
+ }
357
+ }
358
+ return out;
359
+ }
360
+
361
+ /** The failures each RED-ticked step of the batch left, by step number: a rerun's baseline (`<batch>-red-failures.json`
362
+ * in the logs folder). Unreadable, it is empty. */
363
+ const redCountsPath = (run: Run): string => `${run.logFolder}/${run.sheet.batch}-red-failures.json`;
364
+
365
+ async function readRedCounts(run: Run): Promise<Record<string, number>> {
366
+ try {
367
+ const parsed = JSON.parse(await run.deps.files.read(redCountsPath(run))) as unknown;
368
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
369
+ return Object.fromEntries(Object.entries(parsed).filter((e): e is [string, number] => Number.isInteger(e[1]) && (e[1] as number) >= 0));
370
+ } catch {
371
+ return {};
372
+ }
373
+ }
374
+
375
+ /** Records the failures a ticked RED left; a count the tail does not show, or a write that fails, records nothing
376
+ * (a rerun then takes the suite's own run as its baseline). */
377
+ async function recordRedCount(run: Run, step: ImplementStep, count: number | null): Promise<void> {
378
+ if (count === null) return;
379
+ const counts = { ...await readRedCounts(run), [String(step.number)]: count };
380
+ try {
381
+ await run.deps.files.write(redCountsPath(run), `${JSON.stringify(counts)}\n`);
382
+ } catch {
383
+ // the record is a help to a rerun, never a verdict
384
+ }
385
+ }
386
+
387
+ async function runCycle(run: Run, cycle: Cycle): Promise<string | null> {
388
+ const steps = cycle.steps;
389
+ const label = stepsLabel(steps);
390
+ const command = testCommandFor(run.pack.commands, steps[0]);
391
+ if (!command.ok) return `${label}: ${command.reason}`;
392
+ const production = new Set<string>();
393
+
394
+ const toRed = steps.filter((s) => !s.tdd?.red);
395
+ // A rerun after BLOCKED: a step of the cycle is RED-ticked already and its tests fail. One run before the first new
396
+ // RED is the baseline its tests must add a failure to, as the run of that step would have been. The tests the
397
+ // BLOCKED step wrote before it stopped fail in that run too: the count the last ticked step recorded, when lower,
398
+ // is the baseline.
399
+ let red: WrappedRun | null = null;
400
+ let before: string | number | null = null;
401
+ if (toRed.length > 0 && toRed.length < steps.length) {
402
+ red = await run.tools.runTests({ command: command.command });
403
+ const ticked = steps.filter((s) => s.tdd?.red).at(-1);
404
+ const recorded = ticked === undefined ? undefined : (await readRedCounts(run))[String(ticked.number)];
405
+ const observed = red.ok ? failureCount(red.tail) : null;
406
+ before = recorded !== undefined && observed !== null && recorded < observed ? recorded : red.ok ? red.tail : null;
407
+ }
408
+ // A stub a RED of this cycle wrote stays open to its later REDs, this run's or a rerun's: the cycle's GREEN, the only
409
+ // one that fills it, has not run.
410
+ const stubbed = new Set(steps.filter((s) => s.tdd?.red).flatMap((s) => [...stubsOf(s), ...existingStubsOf(s)]).filter((p) => run.touched.has(p)));
411
+ for (const step of toRed) {
412
+ const stubs = [...new Set([...await openStubs(run, step), ...existingStubsOf(step), ...stubbed])];
413
+ const t3 = await recallForRed(run, step);
414
+ const carried = await carriedFor(run, [testFileOf(step)]);
415
+ const done = await act(run, "test-author", withPrecedents(redContract({ ...contractInput(run, step, command.command, carried), stubs }), [t3, run.correction, run.stale]), stubs);
416
+ if (typeof done === "string") return stepActProblem(step.number, "RED", done);
417
+ run.ran.push(step);
418
+ const earlier = before;
419
+ red = await run.tools.runTests({ command: command.command });
420
+ const problem = redProblem(done.changed, run.isTest, observedRun(red), stubs);
421
+ if (problem !== null) return stepActProblem(step.number, "RED", `${problem}${logOf(red)}`);
422
+ // A later step of the cycle: its file failed already, so its own tests must add a failure.
423
+ const added = earlier !== null && red.ok ? addedFailure(earlier, red.tail) : "ok";
424
+ if (typeof added === "object") return stepActProblem(step.number, "RED", `${added.problem}${logOf(red)}`);
425
+ done.changed.forEach((p) => { run.touched.add(p); if (!run.isTest(p)) production.add(p); });
426
+ const failed = await tick(run, step, "RED");
427
+ if (failed !== null) return stepActProblem(step.number, "RED", failed);
428
+ before = red.ok ? red.tail : null;
429
+ await recordRedCount(run, step, red.ok ? failureCount(red.tail) : null);
430
+ const wroteStubs = done.changed.filter((p) => !run.isTest(p));
431
+ wroteStubs.forEach((p) => stubbed.add(p));
432
+ const unchecked = added === "unknown" ? FAILURE_NOT_CHECKED : "";
433
+ run.lines.push(redDone(step.number, done.changed.filter(run.isTest).join(", "), wroteStubs, unchecked));
434
+ }
435
+
436
+ let costText: string | null = null;
437
+ const green = steps.filter((s) => !s.tdd?.green);
438
+ if (green.length > 0) {
439
+ red ??= await run.tools.runTests({ command: command.command });
440
+ const redTail = red.ok ? { tail: red.tail, log: red.log } : { tail: notRun(red.refused), log: null };
441
+ const greenLabel = stepsLabel(green);
442
+ // The production files too: a stub RED wrote, an existing module, so that GREEN opens none of them.
443
+ const productionFiles = green.flatMap((s) => (s.anchor?.production ?? []).filter((r) => r.state !== "member").map((r) => r.path));
444
+ const carried = await carriedFor(run, [...green.map(testFileOf), ...productionFiles]);
445
+ const done = await act(run, "implementer", withPrecedents(greenContract(contractInput(run, green[0], command.command, carried, green), redTail), [run.correction, run.stale]));
446
+ if (typeof done === "string") return `${greenLabel} GREEN: ${done}`;
447
+ run.ran.push(...green.filter((s) => !run.ran.includes(s)));
448
+ const after = await run.tools.runTests({ command: command.command });
449
+ const problem = greenProblem(done.changed, run.isTest, observedRun(after), observedRun(red));
450
+ if (problem !== null) return `${greenLabel} GREEN: ${problem}${logOf(after)}`;
451
+ done.changed.forEach((p) => { run.touched.add(p); production.add(p); });
452
+ const failed = await tickAll(run, green, "GREEN");
453
+ if (failed !== null) return `${greenLabel} GREEN: ${failed}`;
454
+ run.lines.push(greenDone(greenLabel, done.changed.join(", ")));
455
+ costText = done.text;
456
+ }
457
+
458
+ const costed = steps.filter((s) => !s.tdd?.cost);
459
+ if (costed.length > 0) {
460
+ const costLabel = stepsLabel(costed);
461
+ let cost = readCost(costText ?? "");
462
+ if (!cost.ok && cost.line === undefined) {
463
+ const asked = await askLine(run.deps.roleLlm("implementer", run.pack.layout, run.wrote, []), IMPLEMENTER,
464
+ askCostLine(`${label[0].toUpperCase()}${label.slice(1)}`, run.located.code, run.sheet.batch));
465
+ if (!asked.ok) return `${costLabel} COST: ${asked.reason}`;
466
+ cost = readCost(asked.text);
467
+ }
468
+ if (!cost.ok) return `${costLabel} COST: ${cost.problem}`;
469
+ const measured = await measuredCost(run, [...production].sort());
470
+ if ("problem" in measured) return `${costLabel} COST: ${measured.problem}`;
471
+ const failed = await tickAll(run, costed, "COST");
472
+ if (failed !== null) return `${costLabel} COST: ${failed}`;
473
+ run.lines.push(costDone(costLabel, cost.line, measured.line));
474
+ }
475
+ return null;
476
+ }
477
+
478
+ function logOf(run: WrappedRun): string {
479
+ return run.ok && run.log !== null ? shownLog(run.log.replace(`${WORKSPACE}/`, "")) : "";
480
+ }
481
+
482
+ const shownPath = (path: string | null): string => (path === null ? "" : shownLog(path.replace(`${WORKSPACE}/`, "")));
483
+
484
+ /** The pack's restore, once, before any act: true when it ran green, null when the pack has none. */
485
+ async function restore(
486
+ run: Pick<Run, "deps" | "pack" | "logFolder" | "lines">, batch: string,
487
+ ): Promise<{ problem: string } | { restored: boolean }> {
488
+ const command = run.pack.commands.restore?.trim();
489
+ if (!command) return { restored: false };
490
+ const refusal = shellRuleGuard(stepRules("dev-implement"))(command);
491
+ if (refusal !== null) return { problem: restoreRefused(refusal) };
492
+ let r;
493
+ try {
494
+ r = await run.deps.shell.run(command, { timeoutSeconds: RESTORE_TIMEOUT_SECONDS });
495
+ } catch (e) {
496
+ return { problem: restoreCouldNotRun(command, reasonOf(e)) };
497
+ }
498
+ const log = `${run.logFolder}/${batch}-restore.txt`;
499
+ const output = [r.stdout.trimEnd(), r.stderr.trimEnd()].filter((t) => t !== "").join("\n");
500
+ try {
501
+ await run.deps.files.write(log, logText(command, r.timedOut === true ? [restoreNoVerdict(RESTORE_TIMEOUT_SECONDS)] : [], output, r.timedOut === true ? NO_VERDICT_EXIT : r.exitCode));
502
+ } catch {
503
+ // the log is a help, never a verdict
504
+ }
505
+ if (r.timedOut === true) return { problem: restoreStillRunning(command, RESTORE_TIMEOUT_SECONDS) };
506
+ if (r.exitCode !== 0) return { problem: restoreExited(command, r.exitCode, shownPath(log)) };
507
+ run.lines.push(restored(command));
508
+ return { restored: true };
509
+ }
510
+
511
+ type SuiteResult = { problem: string } | { ok: true; whole: boolean };
512
+
513
+ async function oneSuite(run: Run, label: string, command: string, log: string | null) {
514
+ return runSuite(
515
+ { jobs: run.deps.jobs, shell: run.deps.shell, files: run.deps.files },
516
+ { label, command, log, limitSeconds: SUITE_LIMIT_SECONDS, sliceSeconds: SLICE_SECONDS },
517
+ );
518
+ }
519
+
520
+ /** The affected tests: `commands.test_project` once per distinct Project cell of the steps this run ran (of every
521
+ * step when it ran none), then once per test project the graph adds, their logs written together to
522
+ * `F<n>-test-affected.txt`. Null when the sheet's cannot be named; a graph project that cannot be is left out, and named. */
523
+ function affectedCommands(
524
+ run: Run, graph: readonly string[] = [],
525
+ ): { commands: string[]; fromGraph: string[]; leftOut: string[] } | null {
526
+ if (!run.pack.commands.testProject?.trim()) return null;
527
+ const steps = run.ran.length > 0 ? run.ran : run.sheet.steps.filter((s) => s.tdd !== null);
528
+ const projects = [...new Set(steps.flatMap((s) => s.tests.map((t) => t.project.trim())).filter((p) => p !== ""))];
529
+ const commands: string[] = [];
530
+ for (const project of projects) {
531
+ const c = projectCommandFor(run.pack.commands, project);
532
+ if (!c.ok) return null;
533
+ if (!commands.includes(c.command)) commands.push(c.command);
534
+ }
535
+ if (commands.length === 0) return null;
536
+ const fromGraph: string[] = [];
537
+ const leftOut: string[] = [];
538
+ for (const project of graph) {
539
+ const c = projectCommandFor(run.pack.commands, project.trim());
540
+ if (!c.ok) leftOut.push(`${project.trim()} (${c.reason})`);
541
+ else if (!commands.includes(c.command)) { commands.push(c.command); fromGraph.push(project.trim()); }
542
+ }
543
+ return { commands, fromGraph, leftOut };
544
+ }
545
+
546
+ /** The batch's touched files refreshed in the code index (incremental_reindex), so that the graph the affected tests,
547
+ * the next batch and the audit read holds the tree as it is now. True when it was; never blocks: a line says what
548
+ * happened, none when no index is wired or nothing was touched. */
549
+ async function refreshIndex(run: Run): Promise<boolean> {
550
+ const index = run.deps.costIndex;
551
+ if (index === undefined || run.touched.size === 0) return false;
552
+ const files = [...run.touched].sort().map((p) => `${WORKSPACE}/${p}`);
553
+ try {
554
+ const roots = (await index.roots()).map((r) => (r.length > 1 ? r.replace(/\/+$/, "") : r));
555
+ if (!roots.includes(WORKSPACE)) {
556
+ run.lines.push(indexNotIndexed(WORKSPACE));
557
+ return false;
558
+ }
559
+ const errors = await index.refresh(WORKSPACE, files);
560
+ if (errors.length > 0) {
561
+ run.lines.push(indexReindexFailed(reasonOf(errors[0])));
562
+ return false;
563
+ }
564
+ } catch (e) {
565
+ run.lines.push(indexNotRefreshed(reasonOf(e)));
566
+ return false;
567
+ }
568
+ run.lines.push(indexRefreshed(files.length, run.sheet.batch));
569
+ return true;
570
+ }
571
+
572
+ /** What the graph says the batch's touched files reach (affected_tests), on a refreshed index; null when it cannot be
573
+ * asked or fails, said in a line: the sheet's Project cells then decide alone. */
574
+ async function graphAffected(run: Run): Promise<AffectedTests | null> {
575
+ const index = run.deps.costIndex;
576
+ if (index?.affected === undefined) return null;
577
+ try {
578
+ // Relative to the indexed root: affected_tests looks each file up as `<root>/<file>`, an absolute path never resolves.
579
+ return await index.affected([...run.touched].sort());
580
+ } catch (e) {
581
+ run.lines.push(graphNotRead(reasonOf(e)));
582
+ return null;
583
+ }
584
+ }
585
+
586
+ /** The build, then the whole suite (the first time the batch goes green) or its affected projects, as jobs. */
587
+ async function suites(run: Run, suiteGreen: boolean): Promise<SuiteResult> {
588
+ const guard = shellRuleGuard(stepRules("dev-implement"));
589
+ const batch = run.sheet.batch;
590
+ const affectedLog = `${run.logFolder}/${batch}-test-affected.txt`;
591
+
592
+ // The tree changed whatever the build says: the index is refreshed first, so a red build leaves no stale graph.
593
+ const indexed = await refreshIndex(run);
594
+ const build = run.pack.commands.build?.trim();
595
+ if (!build) run.lines.push(BUILD_LINE_NOT_RUN);
596
+ else {
597
+ const refusal = guard(build);
598
+ if (refusal !== null) return { problem: buildRefused(refusal) };
599
+ const outcome = await oneSuite(run, "build", build, `${run.logFolder}/${batch}-build.txt`);
600
+ if (outcome.status === "not-run") return { problem: outcome.reason };
601
+ if (outcome.status === "running") return { problem: buildStillRunning(outcome.seconds, shownPath(outcome.log)) };
602
+ if (outcome.status === "failed") return { problem: buildExited(build, outcome.exit, shownPath(outcome.log), outcome.tail) };
603
+ run.lines.push(buildDone(build, outcome.how === "blocking", shownPath(outcome.log)));
604
+ }
605
+
606
+ const graph = suiteGreen && indexed ? await graphAffected(run) : null;
607
+ const affected = suiteGreen && graph?.all !== true ? affectedCommands(run, graph?.projects ?? []) : null;
608
+ if (affected !== null && affected.leftOut.length > 0) {
609
+ run.lines.push(graphProjectsLeftOut(affected.leftOut));
610
+ }
611
+ if (affected !== null) {
612
+ const texts: string[] = [];
613
+ let exit = 0;
614
+ for (const command of affected.commands) {
615
+ const refusal = guard(command);
616
+ if (refusal !== null) return { problem: affectedRefused(refusal) };
617
+ const outcome = await oneSuite(run, "affected tests", command, null);
618
+ if (outcome.status === "not-run") return { problem: outcome.reason };
619
+ texts.push(outcome.text.trimEnd());
620
+ if (outcome.status === "running") {
621
+ await writeLogQuietly(run, affectedLog, `${texts.join("\n")}\n`);
622
+ return { problem: affectedStillRunning(outcome.seconds, shownPath(affectedLog)) };
623
+ }
624
+ if (outcome.status === "failed") {
625
+ if (exit === 0) exit = outcome.exit;
626
+ await writeLogQuietly(run, affectedLog, `${texts.join("\n")}\nexit=${exit}\n`);
627
+ return { problem: affectedExited(command, outcome.exit, shownPath(affectedLog), outcome.tail) };
628
+ }
629
+ }
630
+ await writeLogQuietly(run, affectedLog, `${texts.join("\n")}\nexit=${exit}\n`);
631
+ const byGraph = graph === null ? ""
632
+ : graphAdded(affected.fromGraph, graph.classes.length);
633
+ run.lines.push(affectedDone(affected.commands, batch, byGraph, shownPath(affectedLog)));
634
+ return { ok: true, whole: false };
635
+ }
636
+
637
+ const test = run.pack.commands.test?.trim();
638
+ if (!test) {
639
+ run.lines.push(TEST_NOT_RUN);
640
+ return { ok: true, whole: false };
641
+ }
642
+ const refusal = guard(test);
643
+ if (refusal !== null) return { problem: testRefused(refusal) };
644
+ // A whole-suite run empties the affected log: the audit then reads this one.
645
+ await writeLogQuietly(run, affectedLog, "");
646
+ const outcome = await oneSuite(run, "test", test, `${run.logFolder}/${batch}-test.txt`);
647
+ if (outcome.status === "not-run") return { problem: outcome.reason };
648
+ if (outcome.status === "running") return { problem: testStillRunning(outcome.seconds, shownPath(outcome.log)) };
649
+ if (outcome.status === "failed") return { problem: testExited(test, outcome.exit, shownPath(outcome.log), outcome.tail) };
650
+ const again = !suiteGreen ? ""
651
+ : graph?.all === true && graph.unresolved.length > 0
652
+ ? wholeSuiteUnplaced(cutList(graph.unresolved))
653
+ : graph?.all === true ? WHOLE_SUITE_EVERY_TEST
654
+ : WHOLE_SUITE_NO_TEST_PROJECT;
655
+ run.lines.push(testDone(test, outcome.how === "blocking", again, shownPath(outcome.log)));
656
+ return { ok: true, whole: true };
657
+ }
658
+
659
+ /** At most three paths, then how many more. */
660
+ function cutList(paths: readonly string[]): string {
661
+ const shown = paths.slice(0, 3).join(", ");
662
+ return paths.length > 3 ? firstAndMore(shown, paths.length - 3) : shown;
663
+ }
664
+
665
+ async function writeLogQuietly(run: Run, path: string, text: string): Promise<void> {
666
+ try {
667
+ await run.deps.files.write(path, text);
668
+ } catch {
669
+ // the log is a help, never a verdict
670
+ }
671
+ }
672
+
673
+ /** The verdicts of the batch's verdict file: its mark, the last verdict, and the GAPS rounds since the last VALID. */
674
+ async function verdictState(files: Pick<Files, "read">, path: string): Promise<{ mark: string; last: "VALID" | "GAPS" | null; gapsRounds: number }> {
675
+ let text: string | null;
676
+ try {
677
+ text = await files.read(path);
678
+ } catch {
679
+ text = null;
680
+ }
681
+ if (text === null) return { mark: verdictMarkOf(null), last: null, gapsRounds: 0 };
682
+ return { mark: verdictMarkOf(text), last: lastVerdict(parseVerdictFile(text))?.verdict ?? null, gapsRounds: gapsRoundsOf(text) };
683
+ }
684
+
685
+ export async function runDevImplement(input: DevImplementInputs, deps: DevImplementDeps): Promise<string> {
686
+ const batch = String(input.batch ?? "").trim();
687
+ if (!BATCH.test(batch)) return blocked([], batchIsFn(batch));
688
+ const plan = typeof input.plan === "string" && input.plan.trim() !== "" ? input.plan.trim() : null;
689
+ const inputContext = prContextOf(input);
690
+ const mode = typeof input.permissionMode === "string" ? input.permissionMode.trim() : "";
691
+ if (mode !== "" && policyFor(mode).readOnly) {
692
+ return blocked([], readOnlyMode(mode));
693
+ }
694
+
695
+ const context = await loadDevContext({ files: deps.files, shell: deps.shell, config: deps.config });
696
+ const lines = context.warnings.slice(0, 5).map((w) => `⚠ ${w}`);
697
+ if (context.pack === null) return blocked(lines, NO_REPOSITORY_PACK);
698
+ if (context.work.vfsPath === null) return blocked(lines, workFolderOutsideMounts(context.work.folder));
699
+ const pack = context.pack.pack;
700
+
701
+ const located = await locateSheet(deps.files, context.work.folder, batch, plan);
702
+ if (typeof located === "string") return blocked(lines, located);
703
+ const sheetPath = `${WORKSPACE}/${located.dir}/${located.name}`;
704
+ const record = await readTouchedRecord(deps.files, located.code, batch);
705
+
706
+ if (input.close === true) {
707
+ // The chained close carries the session's context read again before its launch (Orkeon #220); a close that
708
+ // names none (a typed --close, a hop whose read failed) takes the one the run saved in the batch record.
709
+ const pr = inputContext ?? record.pr;
710
+ const closeMode = pr?.permissionMode.trim() ?? "";
711
+ if (closeMode !== "" && policyFor(closeMode).readOnly) {
712
+ return blocked(lines, readOnlyModeAtClose(closeMode, closeCommand(located.code, batch)));
713
+ }
714
+ const opener = pr !== null && pr.githubTool ? deps.openerFor?.(pr) : undefined;
715
+ // A batch of a /dev-batches run in progress is committed, never pushed, even when its close is typed (after a
716
+ // GAPS stop, a refused hop): the run's own close pushes the plan's branch once.
717
+ const inRun = input.push !== false && batchesRunCode(await deps.files.read(BATCHES_ACTIVE_RECORD).catch(() => "")) === located.code;
718
+ if (inRun) lines.push(notPushedInRun(located.code));
719
+ return answer([...lines, ...await closeDevBatch({ ...deps, opener }, {
720
+ pack, work: context.work, located, batch, touched: record.touched, verdictMark: record.verdictMark,
721
+ openPr: input.pr === true, push: input.push !== false && !inRun, today: isoDay(deps.clock()),
722
+ ...(pr === null ? {} : { rules: parseSessionRules(pr.permissionRules) }),
723
+ })]);
724
+ }
725
+
726
+ if (!hasTestLayout(pack.layout)) {
727
+ return blocked(lines, NO_TEST_LAYOUT);
728
+ }
729
+ let sheetText: string;
730
+ try {
731
+ sheetText = await deps.files.read(sheetPath);
732
+ } catch (e) {
733
+ return blocked(lines, cannotBeReadColonReason(`${located.dir}/${located.name}`, reasonOf(e)));
734
+ }
735
+ const verdictPath = `${WORKSPACE}/${located.dir}/${located.prefix}-VERIFY-${batch}.md`;
736
+ const verdicts = await verdictState(deps.files, verdictPath);
737
+
738
+ const finding = typeof input.correction === "string" ? input.correction.trim() : "";
739
+ if (finding !== "") {
740
+ const edit = addCorrection(sheetText, finding);
741
+ if (!edit.ok) return blocked(lines, correctionProblem(edit.reason));
742
+ if (edit.appended) {
743
+ try {
744
+ await deps.files.write(sheetPath, edit.text);
745
+ } catch (e) {
746
+ return blocked(lines, correctionProblem(sheetNotWritten(reasonOf(e))));
747
+ }
748
+ lines.push(correctionAppended(located.name, edit.step, edit.title));
749
+ } else {
750
+ lines.push(correctionStillOpen(edit.step, edit.title));
751
+ }
752
+ sheetText = edit.text;
753
+ if (verdicts.gapsRounds >= GAPS_ROUNDS_WARNED) {
754
+ lines.push(gapsRoundsWarned(verdicts.gapsRounds));
755
+ }
756
+ }
757
+ const sheet = parseImplementSheet(sheetText);
758
+ if (sheet.problems.length > 0) return blocked(lines, sheetMalformed(sheet.problems));
759
+
760
+ const logFolder = `${context.work.vfsPath}/${located.code}/logs`;
761
+ const written = new Set<string>();
762
+ const wrote = (path: string): void => { if (path.trim() !== "") written.add(workspacePath(path)); };
763
+ const pr = inputContext ?? record.pr;
764
+ const runLines = [...lines, runTitle(batch, located.code, `${located.dir}/${located.name}`)];
765
+ const open = openSteps(sheet);
766
+ let restored = false;
767
+ if (open.length > 0) {
768
+ const r = await restore({ deps, pack, logFolder, lines: runLines }, batch);
769
+ if ("problem" in r) return blocked(runLines, r.problem);
770
+ restored = r.restored;
771
+ }
772
+ // Built after the restore, which tells run_build the tree was restored already.
773
+ const tools = createWrappedTools(
774
+ { shell: deps.shell, files: deps.files },
775
+ { commands: pack.commands, rules: stepRules("dev-implement"), logFolder, batch, ...(restored ? { restored: true } : {}) },
776
+ );
777
+ const run: Run = {
778
+ deps, pack, isTest: (p) => isTestPath(p, pack.layout), located, sheetPath, sheetText, sheet, tools, wrote,
779
+ ownFolders: [context.work.folder, located.dir], planFolder: located.dir, planLogs: `${context.work.folder}/${located.code}/logs`,
780
+ logFolder, written, verdictMark: verdicts.mark, touched: new Set(record.touched), ran: [], lines: runLines,
781
+ correction: NOTHING_RECALLED, recalled: [],
782
+ stale: { block: staleBlock(Array.isArray(input.stale) ? input.stale : []), ids: [] },
783
+ };
784
+ // T5: a correction run carries the mistakes recalled from its finding to both roles.
785
+ if (finding !== "" && open.length > 0) {
786
+ run.correction = await (deps.precedents ?? noPrecedents)("T5", recallQuery([finding]));
787
+ run.recalled.push(run.correction);
788
+ }
789
+ const save = (suiteGreen: boolean): Promise<void> =>
790
+ recordTouched(deps.files, located.code, batch, [...run.touched], run.verdictMark, { suiteGreen, pr });
791
+ const release = deps.toolSlot?.bind(tools) ?? (() => {});
792
+ try {
793
+ const cycles = cyclesOf(open);
794
+ if (cycles.length > 0) run.lines.push(cyclesLine(cycles));
795
+ for (const cycle of cycles) {
796
+ const problem = await runCycle(run, cycle);
797
+ await save(record.suiteGreen);
798
+ if (problem !== null) return blocked(run.lines, problem);
799
+ }
800
+ const result = await suites(run, record.suiteGreen);
801
+ if ("problem" in result) {
802
+ await save(record.suiteGreen);
803
+ return blocked(run.lines, result.problem);
804
+ }
805
+ await save(record.suiteGreen || result.whole);
806
+ } finally {
807
+ release();
808
+ }
809
+ const recalledLine = precedentsLine(run.recalled);
810
+ if (recalledLine !== "") run.lines.push(recalledLine);
811
+ const planArg = plan ?? located.code;
812
+ const auditMode = verdicts.last === "GAPS" ? "resume" : "fast";
813
+ run.lines.push(batchGreen(batch, auditCommand(planArg, batch, auditMode)));
814
+ return answer(run.lines, {
815
+ crew: "dev-verify",
816
+ input: {
817
+ batch, plan: planArg, mode: auditMode,
818
+ ...(input.hooks === undefined ? {} : { hooks: input.hooks }), ...(input.effort === undefined || input.effort === null ? {} : { effort: input.effort }),
819
+ ...(input.memoryRecall === false ? { memoryRecall: false as const } : {}),
820
+ },
821
+ });
822
+ }