@rt-tools/agent-kit 0.37.1 → 0.39.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 (371) hide show
  1. package/README.md +5 -5
  2. package/assets/checks/action-of.mjs +154 -0
  3. package/assets/checks/board-runs.github.mjs +40 -5
  4. package/assets/checks/check-board.github.mjs +38 -7
  5. package/assets/checks/check-state-next.mjs +22 -10
  6. package/assets/checks/check-turn-map.mjs +26 -6
  7. package/assets/checks/check-work-steps.mjs +4 -173
  8. package/assets/checks/decide.mjs +285 -0
  9. package/assets/checks/decision-table.json +21432 -0
  10. package/assets/checks/decision-table.mjs +495 -0
  11. package/assets/checks/epic-window.mjs +98 -0
  12. package/assets/checks/flow-condition.mjs +64 -0
  13. package/assets/checks/flow-data.mjs +135 -0
  14. package/assets/checks/flow-forecast.mjs +334 -0
  15. package/assets/checks/flow-guard-run.mjs +90 -0
  16. package/assets/checks/flow-guard.mjs +496 -0
  17. package/assets/checks/flow-model.mjs +271 -0
  18. package/assets/checks/flow-override.mjs +130 -0
  19. package/assets/checks/flow-plan.mjs +206 -0
  20. package/assets/checks/flow-scaffold.mjs +224 -0
  21. package/assets/checks/flow-step.mjs +495 -0
  22. package/assets/checks/flow-sync.mjs +296 -0
  23. package/assets/checks/flow-syntax.mjs +292 -0
  24. package/assets/checks/flow-verdict.mjs +227 -0
  25. package/assets/checks/merge-read.mjs +239 -0
  26. package/assets/checks/owner-nudges.mjs +389 -0
  27. package/assets/checks/push-inputs.mjs +59 -16
  28. package/assets/checks/record-count.mjs +437 -0
  29. package/assets/checks/record-recount.mjs +187 -0
  30. package/assets/checks/record-turn.mjs +155 -0
  31. package/assets/checks/task-flow-script.mjs +318 -0
  32. package/assets/checks/tree-assignment.mjs +26 -7
  33. package/assets/checks/work-result.mjs +362 -0
  34. package/assets/checks/work-steps-lib.mjs +205 -0
  35. package/assets/commands/night.md +6 -6
  36. package/assets/defaults/gate-map.sh +39 -12
  37. package/assets/defaults/merges.sh +48 -0
  38. package/assets/defaults/project.sh +6 -5
  39. package/assets/defaults/turn-map.md +23 -22
  40. package/assets/docs/GLOSSARY.md +5 -1
  41. package/assets/hooks/ask-judge.md +67 -0
  42. package/assets/hooks/browser-guard-device-id.sh +11 -9
  43. package/assets/hooks/browser-guard-no-asking.sh +12 -6
  44. package/assets/hooks/browser-guard-no-listing.sh +13 -7
  45. package/assets/hooks/browser-guard-no-other-drivers.sh +25 -17
  46. package/assets/hooks/browser-guard-require-select.sh +15 -15
  47. package/assets/hooks/commit-msg.sh +13 -3
  48. package/assets/hooks/conscience-guard.sh +9 -25
  49. package/assets/hooks/decide.sh +141 -0
  50. package/assets/hooks/deny-tail.sh +16 -11
  51. package/assets/hooks/dev-server-guard.sh +27 -20
  52. package/assets/hooks/dispatch.sh +47 -4
  53. package/assets/hooks/docs-guard.sh +31 -200
  54. package/assets/hooks/end-conversation-guard.sh +12 -21
  55. package/assets/hooks/epic-stop-guard.sh +54 -152
  56. package/assets/hooks/exam-guard.sh +32 -65
  57. package/assets/hooks/facts-docs.sh +221 -0
  58. package/assets/hooks/facts-flow.sh +173 -0
  59. package/assets/hooks/facts.sh +374 -0
  60. package/assets/hooks/flow-step-guard.sh +93 -0
  61. package/assets/hooks/git-guard-delivery-body.sh +4 -4
  62. package/assets/hooks/git-guard-delivery-conflict.sh +16 -10
  63. package/assets/hooks/git-guard-delivery-draft.sh +3 -3
  64. package/assets/hooks/git-guard-delivery-epic.sh +18 -9
  65. package/assets/hooks/git-guard-delivery-folder.sh +32 -7
  66. package/assets/hooks/git-guard-delivery-merge.sh +2 -2
  67. package/assets/hooks/git-guard-delivery-merged.sh +12 -1
  68. package/assets/hooks/git-guard-delivery-pipeline.sh +1 -1
  69. package/assets/hooks/git-guard-delivery-rerun.sh +44 -0
  70. package/assets/hooks/git-guard-delivery-signature.sh +82 -45
  71. package/assets/hooks/git-guard-delivery-task.sh +47 -0
  72. package/assets/hooks/git-guard-delivery.sh +112 -101
  73. package/assets/hooks/git-guard-discard.sh +8 -18
  74. package/assets/hooks/git-guard-main.sh +13 -19
  75. package/assets/hooks/git-guard-no-verify.sh +56 -16
  76. package/assets/hooks/git-guard-push-ahead.sh +39 -6
  77. package/assets/hooks/git-guard-push-marks.sh +262 -13
  78. package/assets/hooks/git-guard-push-tests.sh +58 -52
  79. package/assets/hooks/git-guard-tree-assignment.sh +7 -4
  80. package/assets/hooks/guard-note.sh +8 -6
  81. package/assets/hooks/handoff-entry-guard.sh +19 -38
  82. package/assets/hooks/handoff-write.sh +3 -1
  83. package/assets/hooks/hook-input.sh +0 -41
  84. package/assets/hooks/metric-marks.sh +19 -7
  85. package/assets/hooks/observe.sh +1 -1
  86. package/assets/hooks/override-write-guard.sh +27 -9
  87. package/assets/hooks/pre-push.sh +40 -12
  88. package/assets/hooks/prose-style-guard.sh +6 -19
  89. package/assets/hooks/pull-merges.sh +76 -0
  90. package/assets/hooks/push-ahead-call-guard.sh +447 -0
  91. package/assets/hooks/push-set.sh +38 -8
  92. package/assets/hooks/qa-dataid-guard.sh +7 -17
  93. package/assets/hooks/record-turn.sh +52 -0
  94. package/assets/hooks/rerun-guard.sh +11 -16
  95. package/assets/hooks/reuse-first-guard.sh +7 -21
  96. package/assets/hooks/role-calls.sh +25 -3
  97. package/assets/hooks/rule-source-guard.sh +54 -21
  98. package/assets/hooks/skill-gate-rearm.sh +18 -5
  99. package/assets/hooks/skill-gate.sh +156 -20
  100. package/assets/hooks/skill-loaded.sh +18 -3
  101. package/assets/hooks/sql-guard-target.sh +2 -2
  102. package/assets/hooks/sql-guard-write.sh +12 -12
  103. package/assets/hooks/sql-guard.sh +58 -16
  104. package/assets/hooks/task-context-load.sh +3 -1
  105. package/assets/hooks/task-flow-context.sh +5 -18
  106. package/assets/hooks/task-flow-draft-guard.sh +25 -74
  107. package/assets/hooks/task-flow-guard.sh +28 -130
  108. package/assets/hooks/tree-assignment-guard.sh +25 -14
  109. package/assets/hooks/turn-entry-load.sh +3 -1
  110. package/assets/hooks/turn-exit-guard.sh +92 -452
  111. package/assets/hooks/turn-exit-role.sh +3 -1
  112. package/assets/hooks/turn-judge.md +113 -0
  113. package/assets/hooks/window-fill-guard.sh +22 -41
  114. package/assets/patterns/doc-style-human.md +36 -76
  115. package/assets/patterns/git-workflow-commit.azure.md +9 -155
  116. package/assets/patterns/git-workflow-commit.github.md +11 -269
  117. package/assets/patterns/git-workflow-commit.gitlab.md +9 -161
  118. package/assets/patterns/git-workflow-docker.md +8 -231
  119. package/assets/patterns/git-workflow-freshness.md +8 -56
  120. package/assets/patterns/git-workflow-merge.md +6 -176
  121. package/assets/patterns/git-workflow-migration.md +5 -75
  122. package/assets/patterns/git-workflow-pr-body.github.md +6 -159
  123. package/assets/patterns/git-workflow-pr-ready.md +9 -70
  124. package/assets/patterns/git-workflow-pr.azure.md +13 -285
  125. package/assets/patterns/git-workflow-pr.github.md +13 -251
  126. package/assets/patterns/git-workflow-pr.gitlab.md +13 -286
  127. package/assets/patterns/git-workflow-restart.md +5 -42
  128. package/assets/patterns/git-workflow-secrets.md +10 -76
  129. package/assets/patterns/git-workflow-stack.md +7 -207
  130. package/assets/patterns/status-report-table.github.md +1 -1
  131. package/assets/patterns/task-flow-archive.md +12 -233
  132. package/assets/patterns/task-flow-close.md +16 -292
  133. package/assets/patterns/task-flow-cycle.md +13 -39
  134. package/assets/patterns/task-flow-graph.needs-graph.md +8 -62
  135. package/assets/patterns/task-flow-handoff.md +13 -161
  136. package/assets/patterns/task-flow-resume.md +18 -218
  137. package/assets/patterns/task-flow-start.md +9 -247
  138. package/assets/patterns/turn-entry-map.md +2 -2
  139. package/assets/pitfalls/agent-kit-extend.md +200 -0
  140. package/assets/pitfalls/agent-kit.2.md +323 -0
  141. package/assets/pitfalls/angular-patterns.md +98 -0
  142. package/assets/pitfalls/browser-verification.md +265 -0
  143. package/assets/pitfalls/component-structure.md +98 -0
  144. package/assets/pitfalls/dependencies.md +92 -0
  145. package/assets/pitfalls/deploy-flow.azure.md +171 -0
  146. package/assets/pitfalls/deploy-flow.github.md +211 -0
  147. package/assets/pitfalls/deploy-flow.gitlab.md +173 -0
  148. package/assets/pitfalls/doc-style-human.md +112 -0
  149. package/assets/pitfalls/doc-style.2.md +286 -0
  150. package/assets/pitfalls/entity-conventions.needs-admin.md +96 -0
  151. package/assets/pitfalls/entity-models.md +89 -0
  152. package/assets/pitfalls/epic-flow.md +92 -0
  153. package/assets/pitfalls/git-workflow-commit.azure.md +190 -0
  154. package/assets/pitfalls/git-workflow-commit.github.md +307 -0
  155. package/assets/pitfalls/git-workflow-commit.gitlab.md +196 -0
  156. package/assets/pitfalls/git-workflow-docker.md +275 -0
  157. package/assets/pitfalls/git-workflow-freshness.md +88 -0
  158. package/assets/pitfalls/git-workflow-hosting.azure.md +31 -0
  159. package/assets/pitfalls/git-workflow-hosting.github.md +32 -0
  160. package/assets/pitfalls/git-workflow-hosting.gitlab.md +31 -0
  161. package/assets/pitfalls/git-workflow-merge.md +220 -0
  162. package/assets/pitfalls/git-workflow-migration.md +103 -0
  163. package/assets/pitfalls/git-workflow-pr-body.github.md +185 -0
  164. package/assets/pitfalls/git-workflow-pr-ready.md +104 -0
  165. package/assets/pitfalls/git-workflow-pr.2.azure.md +172 -0
  166. package/assets/pitfalls/git-workflow-pr.2.github.md +184 -0
  167. package/assets/pitfalls/git-workflow-pr.2.gitlab.md +180 -0
  168. package/assets/pitfalls/git-workflow-pr.azure.md +159 -0
  169. package/assets/pitfalls/git-workflow-pr.github.md +107 -0
  170. package/assets/pitfalls/git-workflow-pr.gitlab.md +151 -0
  171. package/assets/pitfalls/git-workflow-push.azure.md +30 -0
  172. package/assets/pitfalls/git-workflow-push.github.md +30 -0
  173. package/assets/pitfalls/git-workflow-push.gitlab.md +30 -0
  174. package/assets/pitfalls/git-workflow-queue.azure.md +30 -0
  175. package/assets/pitfalls/git-workflow-queue.github.md +30 -0
  176. package/assets/pitfalls/git-workflow-queue.gitlab.md +30 -0
  177. package/assets/pitfalls/git-workflow-restart.md +72 -0
  178. package/assets/pitfalls/git-workflow-secrets.md +114 -0
  179. package/assets/pitfalls/git-workflow-stack.md +254 -0
  180. package/assets/pitfalls/git-workflow.2.azure.md +291 -0
  181. package/assets/pitfalls/git-workflow.2.github.md +294 -0
  182. package/assets/pitfalls/git-workflow.2.gitlab.md +278 -0
  183. package/assets/pitfalls/lib-layers.md +114 -0
  184. package/assets/pitfalls/lists.md +117 -0
  185. package/assets/pitfalls/mockups.needs-mockups.md +87 -0
  186. package/assets/pitfalls/navigation.md +94 -0
  187. package/assets/pitfalls/observability.needs-app.md +186 -0
  188. package/assets/pitfalls/platform-access.md +94 -0
  189. package/assets/pitfalls/queue-audit.github.md +78 -0
  190. package/assets/pitfalls/reuse-first.md +201 -0
  191. package/assets/pitfalls/spec-driven.2.md +318 -0
  192. package/assets/pitfalls/styling-bem.2.md +125 -0
  193. package/assets/pitfalls/task-flow-archive.md +265 -0
  194. package/assets/pitfalls/task-flow-close.2.md +166 -0
  195. package/assets/pitfalls/task-flow-close.md +167 -0
  196. package/assets/pitfalls/task-flow-cycle.md +73 -0
  197. package/assets/pitfalls/task-flow-graph.needs-graph.md +98 -0
  198. package/assets/pitfalls/task-flow-handoff.md +200 -0
  199. package/assets/pitfalls/task-flow-handover.md +30 -0
  200. package/assets/pitfalls/task-flow-owner.md +58 -0
  201. package/assets/pitfalls/task-flow-plan.md +29 -0
  202. package/assets/pitfalls/task-flow-resume.md +257 -0
  203. package/assets/pitfalls/task-flow-start.md +287 -0
  204. package/assets/pitfalls/task-flow.2.md +303 -0
  205. package/assets/pitfalls/task-flow.md +4 -4
  206. package/assets/pitfalls/testing.2.md +279 -0
  207. package/assets/pitfalls/turn-conduct.md +16 -17
  208. package/assets/pitfalls/typescript-conventions.md +161 -0
  209. package/assets/pitfalls/write-a-skill.md +128 -0
  210. package/assets/rules/angular-patterns.md +21 -86
  211. package/assets/rules/autonomous-work.md +2 -2
  212. package/assets/rules/browser-verification.md +28 -256
  213. package/assets/rules/component-structure.md +25 -87
  214. package/assets/rules/dependencies.md +20 -78
  215. package/assets/rules/deploy-flow.azure.md +26 -156
  216. package/assets/rules/deploy-flow.github.md +34 -200
  217. package/assets/rules/deploy-flow.gitlab.md +27 -159
  218. package/assets/rules/doc-style.md +32 -286
  219. package/assets/rules/entity-conventions.needs-admin.md +26 -82
  220. package/assets/rules/entity-models.md +14 -63
  221. package/assets/rules/epic-flow.md +24 -63
  222. package/assets/rules/git-workflow-hosting.azure.md +26 -0
  223. package/assets/rules/git-workflow-hosting.github.md +38 -0
  224. package/assets/rules/git-workflow-hosting.gitlab.md +27 -0
  225. package/assets/rules/git-workflow-push.azure.md +28 -0
  226. package/assets/rules/git-workflow-push.github.md +28 -0
  227. package/assets/rules/git-workflow-push.gitlab.md +28 -0
  228. package/assets/rules/git-workflow-queue.azure.md +23 -0
  229. package/assets/rules/git-workflow-queue.github.md +30 -0
  230. package/assets/rules/git-workflow-queue.gitlab.md +23 -0
  231. package/assets/rules/git-workflow.azure.md +21 -282
  232. package/assets/rules/git-workflow.github.md +24 -284
  233. package/assets/rules/git-workflow.gitlab.md +21 -269
  234. package/assets/rules/lib-layers.md +30 -103
  235. package/assets/rules/lists.md +21 -105
  236. package/assets/rules/mockups.needs-mockups.md +25 -64
  237. package/assets/rules/navigation.md +10 -69
  238. package/assets/rules/observability.needs-app.md +43 -172
  239. package/assets/rules/platform-access.md +28 -75
  240. package/assets/rules/queue-audit.github.md +25 -52
  241. package/assets/rules/reuse-first.md +20 -195
  242. package/assets/rules/spec-driven.md +35 -308
  243. package/assets/rules/styling-bem.md +20 -117
  244. package/assets/rules/task-flow-handover.md +24 -0
  245. package/assets/rules/task-flow-owner.md +34 -0
  246. package/assets/rules/task-flow-plan.md +38 -0
  247. package/assets/rules/task-flow.md +22 -300
  248. package/assets/rules/testing.md +32 -273
  249. package/assets/rules/turn-conduct.md +105 -106
  250. package/assets/rules/turn-entry.md +2 -2
  251. package/assets/rules/typescript-conventions.md +41 -147
  252. package/assets/samples/tasks/_template/plan.md +30 -6
  253. package/assets/samples/tasks/_template/progress.md +0 -1
  254. package/assets/skills/agent-kit-extend.md +25 -168
  255. package/assets/skills/agent-kit.md +27 -299
  256. package/assets/skills/write-a-skill.md +20 -106
  257. package/assets/task-flow/flow.js +184 -0
  258. package/assets/task-flow/flow.md +101 -0
  259. package/assets/task-flow/measure/agreement.mjs +24 -0
  260. package/assets/task-flow/measure/ci.mjs +184 -0
  261. package/assets/task-flow/measure/copy.mjs +22 -0
  262. package/assets/task-flow/measure/epic-of.mjs +50 -0
  263. package/assets/task-flow/measure/epic-text.mjs +35 -0
  264. package/assets/task-flow/measure/epic.mjs +114 -0
  265. package/assets/task-flow/measure/folder.mjs +16 -0
  266. package/assets/task-flow/measure/footprint.mjs +28 -0
  267. package/assets/task-flow/measure/grill.mjs +21 -0
  268. package/assets/task-flow/measure/host.mjs +8 -0
  269. package/assets/task-flow/measure/owner.mjs +27 -0
  270. package/assets/task-flow/measure/plan.mjs +27 -0
  271. package/assets/task-flow/measure/pr.mjs +20 -0
  272. package/assets/task-flow/measure/progress.mjs +50 -0
  273. package/assets/task-flow/measure/session.mjs +252 -0
  274. package/assets/task-flow/measure/task.mjs +23 -0
  275. package/assets/task-flow/measure/text.mjs +77 -0
  276. package/assets/task-flow/source/git.mjs +254 -0
  277. package/assets/task-flow/source/host.mjs +277 -0
  278. package/assets/task-flow/source/marks.mjs +56 -0
  279. package/assets/task-flow/source/owner.mjs +94 -0
  280. package/assets/task-flow/source/records.mjs +116 -0
  281. package/assets/task-flow/source/session.mjs +269 -0
  282. package/assets/task-flow/source/steps.mjs +28 -0
  283. package/assets/task-flow/source/tree.mjs +42 -0
  284. package/bin/agent-kit.d.ts.map +1 -1
  285. package/bin/agent-kit.js +30 -0
  286. package/bin/agent-kit.js.map +1 -1
  287. package/lib/agent-checks.d.ts +55 -0
  288. package/lib/agent-checks.d.ts.map +1 -0
  289. package/lib/agent-checks.js +221 -0
  290. package/lib/agent-checks.js.map +1 -0
  291. package/lib/assets.d.ts.map +1 -1
  292. package/lib/assets.js +7 -2
  293. package/lib/assets.js.map +1 -1
  294. package/lib/cargo.d.ts +29 -0
  295. package/lib/cargo.d.ts.map +1 -1
  296. package/lib/cargo.js +27 -1
  297. package/lib/cargo.js.map +1 -1
  298. package/lib/cascade.d.ts.map +1 -1
  299. package/lib/cascade.js +3 -1
  300. package/lib/cascade.js.map +1 -1
  301. package/lib/commands.d.ts.map +1 -1
  302. package/lib/commands.js +78 -2
  303. package/lib/commands.js.map +1 -1
  304. package/lib/config.d.ts +18 -0
  305. package/lib/config.d.ts.map +1 -1
  306. package/lib/config.js +18 -1
  307. package/lib/config.js.map +1 -1
  308. package/lib/epic-window-send.d.ts +74 -0
  309. package/lib/epic-window-send.d.ts.map +1 -0
  310. package/lib/epic-window-send.js +166 -0
  311. package/lib/epic-window-send.js.map +1 -0
  312. package/lib/hooks-map.d.ts +4 -0
  313. package/lib/hooks-map.d.ts.map +1 -1
  314. package/lib/hooks-map.js +2 -2
  315. package/lib/hooks-map.js.map +1 -1
  316. package/lib/integrity.d.ts +3 -0
  317. package/lib/integrity.d.ts.map +1 -1
  318. package/lib/integrity.js +7 -0
  319. package/lib/integrity.js.map +1 -1
  320. package/lib/metric-lines.d.ts +2 -1
  321. package/lib/metric-lines.d.ts.map +1 -1
  322. package/lib/metric-lines.js +49 -1
  323. package/lib/metric-lines.js.map +1 -1
  324. package/lib/metric-send-mark.d.ts +6 -3
  325. package/lib/metric-send-mark.d.ts.map +1 -1
  326. package/lib/metric-send-mark.js +15 -5
  327. package/lib/metric-send-mark.js.map +1 -1
  328. package/lib/metric-send.d.ts +6 -2
  329. package/lib/metric-send.d.ts.map +1 -1
  330. package/lib/metric-send.js +47 -13
  331. package/lib/metric-send.js.map +1 -1
  332. package/lib/metrics.d.ts +17 -0
  333. package/lib/metrics.d.ts.map +1 -1
  334. package/lib/metrics.js +26 -15
  335. package/lib/metrics.js.map +1 -1
  336. package/lib/observations.js +3 -3
  337. package/lib/observations.js.map +1 -1
  338. package/lib/outcomes.d.ts +5 -2
  339. package/lib/outcomes.d.ts.map +1 -1
  340. package/lib/outcomes.js +5 -4
  341. package/lib/outcomes.js.map +1 -1
  342. package/lib/push-gate.d.ts +13 -0
  343. package/lib/push-gate.d.ts.map +1 -1
  344. package/lib/push-gate.js +11 -7
  345. package/lib/push-gate.js.map +1 -1
  346. package/lib/push-set-usefulness.d.ts +78 -0
  347. package/lib/push-set-usefulness.d.ts.map +1 -0
  348. package/lib/push-set-usefulness.js +225 -0
  349. package/lib/push-set-usefulness.js.map +1 -0
  350. package/lib/sync.d.ts +10 -0
  351. package/lib/sync.d.ts.map +1 -1
  352. package/lib/sync.js +14 -1
  353. package/lib/sync.js.map +1 -1
  354. package/lib/work-result.d.ts +43 -0
  355. package/lib/work-result.d.ts.map +1 -0
  356. package/lib/work-result.js +39 -0
  357. package/lib/work-result.js.map +1 -0
  358. package/package.json +1 -1
  359. package/assets/hooks/claim-guard.sh +0 -212
  360. package/assets/hooks/grill-gate-ask.sh +0 -26
  361. package/assets/hooks/grill-gate-bypass.sh +0 -61
  362. package/assets/hooks/grill-gate-options.sh +0 -50
  363. package/assets/hooks/grill-gate.sh +0 -482
  364. package/assets/hooks/postmortem-guard.sh +0 -124
  365. package/assets/hooks/proposal-guard.sh +0 -154
  366. package/assets/hooks/stand-login-guard.sh +0 -107
  367. package/assets/hooks/turn-exit-epic.sh +0 -173
  368. package/assets/hooks/turn-exit-patterns.sh +0 -123
  369. package/assets/hooks/turn-exit-verdict.sh +0 -149
  370. package/assets/hooks/waiting-turn-guard.sh +0 -320
  371. package/assets/hooks/work-start-guard.sh +0 -175
@@ -0,0 +1,495 @@
1
+ /**
2
+ * A step of the plan measured by its check — the engine command `step`.
3
+ *
4
+ * The check is taken from the commit that added the plan, not from the working copy: a plan edited
5
+ * after it is written would measure what was never approved. Every file of the task folder that the
6
+ * commit holds, except the progress, must still match it, otherwise the step is refused: a script of
7
+ * the folder edited after the plan would answer what the step needs. A command of the work itself is
8
+ * never a check, and an expected result in no form of `expect` is refused before anything runs. The
9
+ * command runs with a limit; past it the step does not match.
10
+ *
11
+ * A check is replaced only by a decision in the progress the owner allowed in the window on its edit:
12
+ *
13
+ * - **Проверка шага 2.4 заменена:** `<command>` → <expected>
14
+ *
15
+ * A matched step writes its mark: the branch, the step, the fingerprint of the plan, the head and the
16
+ * last line of the output. A step that does not match drops a mark left before, so a mark always
17
+ * says what the last measurement said.
18
+ */
19
+ import { spawn, spawnSync } from 'node:child_process';
20
+ import { availableParallelism, tmpdir } from 'node:os';
21
+ import { createHash } from 'node:crypto';
22
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
23
+
24
+ import { dirname, join } from 'node:path';
25
+ import { fileURLToPath, pathToFileURL } from 'node:url';
26
+
27
+ import { compareExpected, isWriteCommand } from './flow-data.mjs';
28
+
29
+ // The sources of the description lie next to the engine where it is laid out, one level up in the package.
30
+ const HERE = dirname(fileURLToPath(import.meta.url));
31
+ const source = (name) => [join(HERE, `task-flow/source/${name}`), join(HERE, `../task-flow/source/${name}`)].find((path) => existsSync(path));
32
+ const records = await import(pathToFileURL(source('records.mjs')).href);
33
+ const { liveRun, putBack, release, rewritePutBack } = await import(pathToFileURL(source('git.mjs')).href);
34
+
35
+ /** The record directories of this repository and the test of an approval mark, shared by the checks. */
36
+ export const openRecords = (root = process.cwd()) => records.openAt(root);
37
+ export const approvalFault = records.approvalFault;
38
+
39
+ /** The limit of one check, in milliseconds: past it the step does not match. */
40
+ export const STEP_LIMIT_MS = 540_000;
41
+
42
+ /** The budget of the rerun before a PR, in milliseconds: a second run of a group starts only within it. */
43
+ export const RERUN_BUDGET_MS = 1_500_000;
44
+
45
+ /** The progress changes every turn and is the one file of the folder not judged against the plan. */
46
+ const PROGRESS = 'progress.md';
47
+
48
+ /** A taken-apart folder put back for one run, or null; a live, broken or stray folder on disk refuses the step. */
49
+ export function restoreFolder(git, folder) {
50
+ const restored = putBack(git, folder);
51
+ if (restored?.busy) throw new StepRefused(`the task folder is put back by the live run ${restored.busy}: measure after it ends`);
52
+ if (restored?.left) throw new StepRefused(`${folder} is left by a broken step run and was edited after it: read it, remove it, then measure`);
53
+ if (restored?.stray) throw new StepRefused(`the task folder is taken apart by ${restored.removedBy.slice(0, 9)}, and ${folder} still holds ${restored.stray.join(', ')}: remove them, then measure`);
54
+ return restored;
55
+ }
56
+
57
+ /** The versions of a file in its history up to the head, or up to `removedFrom` when the head lacks it, oldest first. */
58
+ const versionsOf = (source, path) =>
59
+ (spawnSync('git', ['log', '--reverse', '--format=%H', (!source.existsAtHead(path) && source.removedFrom?.(path)) || 'HEAD', '--', path], { encoding: 'utf8' }).stdout ?? '').split('\n').filter(Boolean).map((sha) => source.versionAt(path, sha));
60
+
61
+ const doneLine = (number) => new RegExp(`^\\s*-\\s+\\[x\\]\\s+${number.replace('.', '\\.')}\\s`, 'm');
62
+
63
+ /**
64
+ * The progress as step `number` saw it: the version before the first one marking it done, with the
65
+ * replacements of `latest` (the last version has every step done). With no such version, `latest`.
66
+ */
67
+ export function progressOfStep(versions, latest, number) {
68
+ const first = versions.findIndex((text) => text !== null && doneLine(number).test(text));
69
+ const chosen = (first > 0 && versions[first - 1]) || latest;
70
+ return chosen === latest ? chosen : withReplacements(chosen, latest);
71
+ }
72
+
73
+ /** The move of a step on a taken-apart folder whose fix lies in the folder: the revert of its taking-apart. */
74
+ export const revertMove = (removedBy) =>
75
+ `fix what the step measures and measure it again; a fix that lies in the folder — a check replaced in the progress, a folder file edited after the plan — needs the folder back: \`git revert --no-edit ${removedBy}\` takes back the whole commit, the archive record too; then take the folder apart again`;
76
+
77
+ /** A replacement of a step check in the progress. */
78
+ const REPLACEMENT = /^-\s+\*\*(?:Проверка шага|Check of step)\s+(\d+\.\d+)\s+(?:заменена|replaced):\*\*\s+`(.+)`\s+→\s+(.+?)(?:\s+·\s+(?:слово владельца|the owner's word):\s+«.+»)?\s*$/u;
79
+
80
+ /** A step the engine does not measure, with the reason. */
81
+ export class StepRefused extends Error {
82
+ constructor(message) {
83
+ super(message);
84
+ this.name = 'StepRefused';
85
+ }
86
+ }
87
+
88
+ /** The last `count` lines of a text that are not empty. */
89
+ const tail = (text, count) =>
90
+ (text ?? '')
91
+ .split('\n')
92
+ .map((line) => line.trimEnd())
93
+ .filter((line) => line !== '')
94
+ .slice(-count);
95
+
96
+ const lastLine = (output) => tail(output, 1)[0] ?? '';
97
+
98
+ const readFile = (path) => (existsSync(path) ? readFileSync(path, 'utf8') : null);
99
+
100
+ /** Runs a check: its exit code and output, or the mark that the limit ran out; `cwd` is where it runs. */
101
+ export function runCheck(command, limitMs = STEP_LIMIT_MS, cwd = undefined) {
102
+ const out = spawnSync('bash', ['-c', command], { cwd, encoding: 'utf8', timeout: limitMs, killSignal: 'SIGKILL', maxBuffer: 64 * 1024 * 1024 });
103
+ const timedOut = out.error?.code === 'ETIMEDOUT';
104
+ return { code: timedOut ? null : out.status, output: out.stdout ?? '', errors: out.stderr ?? '', timedOut };
105
+ }
106
+
107
+ /** Runs a check without blocking: the same answer as `runCheck`, so that the checks of `--done` run side by side. */
108
+ export function runCheckAsync(command, limitMs = STEP_LIMIT_MS) {
109
+ return new Promise((resolve) => {
110
+ const child = spawn('bash', ['-c', command], { stdio: ['ignore', 'pipe', 'pipe'] });
111
+ let output = '';
112
+ let errors = '';
113
+ let timedOut = false;
114
+ const timer = setTimeout(() => {
115
+ timedOut = true;
116
+ child.kill('SIGKILL');
117
+ }, limitMs);
118
+ child.stdout.setEncoding('utf8');
119
+ child.stdout.on('data', (chunk) => (output += chunk));
120
+ child.stderr.setEncoding('utf8');
121
+ child.stderr.on('data', (chunk) => (errors += chunk));
122
+ child.on('close', (code) => {
123
+ clearTimeout(timer);
124
+ resolve({ code: timedOut ? null : code, output, errors, timedOut });
125
+ });
126
+ });
127
+ }
128
+
129
+ /**
130
+ * The plan of the checked-out branch as its commit wrote it: the commit that added the plan. A branch
131
+ * of `words.legacyBranches` takes the newest commit that changed it — its plan was approved, and
132
+ * edited by the owner's word, before the engine existed.
133
+ */
134
+ export function planOfBranch(git, words = {}) {
135
+ const branch = git.branch();
136
+ const folder = `docs/tasks/${branch}`;
137
+ const path = `${folder}/plan.md`;
138
+ const legacy = (words.legacyBranches ?? []).includes(branch);
139
+ const sha = legacy
140
+ ? ([...git.commits()].reverse().find((c) => c.added.includes(path) || c.modified.includes(path))?.sha ?? null)
141
+ : git.addedBy(path);
142
+ if (!sha) throw new StepRefused(`no commit of the branch added ${path}`);
143
+ const text = git.versionAt(path, sha);
144
+ return { branch, folder, sha, text, fingerprint: createHash('sha256').update(text).digest('hex').slice(0, 16) };
145
+ }
146
+
147
+ /** The files of the task folder that differ from the commit of the plan; the progress is not judged. */
148
+ export function changedSincePlan(git, plan, read = readFile) {
149
+ return git
150
+ .filesAt(plan.folder, plan.sha)
151
+ .filter((path) => !path.endsWith(`/${PROGRESS}`))
152
+ .filter((path) => read(path) !== git.versionAt(path, plan.sha));
153
+ }
154
+
155
+ /**
156
+ * The check of a step after the decisions of the progress. A replacement line reaches the progress
157
+ * only through the owner's window on the edit (the guard answers `ask`), so the line itself is the
158
+ * owner's word: no quote is looked for. A quote of the older form is read and ignored. Of two lines
159
+ * for one step the later wins, here and in the rerun alike.
160
+ */
161
+ export function replacedCheck(progressText, number, step) {
162
+ let last = null;
163
+ for (const line of (progressText ?? '').split('\n')) {
164
+ const m = line.match(REPLACEMENT);
165
+ if (m && m[1] === number) last = { command: m[2], expected: m[3], replaced: true };
166
+ }
167
+ return last ?? { command: step.command, expected: step.expected, replaced: false };
168
+ }
169
+
170
+ /**
171
+ * The progress text `text` with its replacement lines swapped for those of `latest`, the last
172
+ * version of the progress in the history. A replacement is the owner's decision about a check, not
173
+ * a part of the work the check measures: it holds on every version the rerun uses. A line the last
174
+ * version no longer carries stays away, and a step replaced twice keeps the later line.
175
+ */
176
+ export function withReplacements(text, latest) {
177
+ const isReplacement = (line) => REPLACEMENT.test(line);
178
+ const kept = (text ?? '').split('\n').filter((line) => !isReplacement(line));
179
+ const lastOfStep = new Map();
180
+ for (const line of (latest ?? '').split('\n')) if (isReplacement(line)) lastOfStep.set(line.match(REPLACEMENT)[1], line);
181
+ const added = [...lastOfStep.values()];
182
+ if (added.length === 0) return kept.join('\n');
183
+ return `${kept.join('\n').replace(/\n*$/, '\n')}\n${added.join('\n')}\n`;
184
+ }
185
+
186
+ /** The signs of a failed network in what a check printed. */
187
+ const NETWORK = /ENOTFOUND|ECONNREFUSED|ECONNRESET|EAI_AGAIN|ETIMEDOUT|getaddrinfo|Could not resolve host|network is unreachable|Failed to connect/i;
188
+
189
+ /** What a run gave, in the words of the line: the code for the exit form, the last line otherwise. */
190
+ const gotOf = (run, form, limitMs, matched = true) => {
191
+ if (run.timedOut) return `the limit of ${limitMs / 1000} s ran out`;
192
+ const network = !matched && NETWORK.test(`${run.output}\n${run.errors ?? ''}`) ? ' — the cause is the network' : '';
193
+ if (form === 'exit') return `exit ${run.code}${network}`;
194
+ return (run.code === 0 ? lastLine(run.output) : `exit ${run.code}, ${lastLine(run.output)}`) + network;
195
+ };
196
+
197
+ /** The step ready to run: its plan, its check and the expected result, or a refusal before anything runs. */
198
+ function prepareStep({ git, steps }, model, number, read) {
199
+ const plan = planOfBranch(git, model.words);
200
+ const changed = changedSincePlan(git, plan, read);
201
+ if (changed.length > 0) throw new StepRefused(`the task folder differs from the commit of the plan: ${changed.join(', ')}`);
202
+ const planned = steps.ofPlan(plan.text).find((s) => s.number === number);
203
+ if (!planned) throw new StepRefused(`the plan names no step ${number}`);
204
+ const progress = `${plan.folder}/${PROGRESS}`;
205
+ const step = { number, ...replacedCheck(read(progress) ?? git.lastVersion(progress), number, planned) };
206
+ if (step.command === null) throw new StepRefused(`step ${number} has no check line`);
207
+ if (isWriteCommand(step.command, model.words)) throw new StepRefused(`the check of step ${number} is a command of the work: ${step.command}`);
208
+ if (compareExpected(model.expect, step.expected, 0, '') === null) throw new StepRefused(`the expected result of step ${number} is in no form: ${step.expected}`);
209
+ return { plan, step };
210
+ }
211
+
212
+ /**
213
+ * The progress with step `number` marked done and, when no step is current, the first one not begun
214
+ * made current. A progress that names no such step comes back as it was.
215
+ */
216
+ export function markedProgress(text, number) {
217
+ const own = new RegExp(`^(\\s*-\\s+\\[)[ >x](\\]\\s+${number.replace('.', '\\.')}\\s)`);
218
+ const lines = text.split('\n');
219
+ const at = lines.findIndex((line) => own.test(line));
220
+ // A step already done is measured again, not marked again: the progress stays as it was.
221
+ if (at < 0 || /^\s*-\s+\[x\]/.test(lines[at])) return text;
222
+ lines[at] = lines[at].replace(own, '$1x$2');
223
+ if (!lines.some((line) => /^\s*-\s+\[>\]\s+\d+\.\d+\s/.test(line))) {
224
+ const next = lines.findIndex((line) => /^\s*-\s+\[ \]\s+\d+\.\d+\s/.test(line));
225
+ if (next >= 0) lines[next] = lines[next].replace('[ ]', '[>]');
226
+ }
227
+ return lines.join('\n');
228
+ }
229
+
230
+ /**
231
+ * The verdict of a run: the mark is written and the step marked done, or the mark is dropped; the
232
+ * result is returned with the command, its output and errors. `keepMark` leaves the mark of a step
233
+ * that did not match, for a run that is repeated; `restored` leaves a folder put back unmarked.
234
+ */
235
+ function settleStep({ git, marks }, model, { plan, step }, run, limitMs, { keepMark = false, restored = false } = {}) {
236
+ const verdict = run.timedOut ? { form: null, matched: false } : compareExpected(model.expect, step.expected, run.code, run.output);
237
+ if (verdict.matched) {
238
+ marks.writeStep(plan.branch, step.number, { branch: plan.branch, step: step.number, plan: plan.fingerprint, head: git.head(), line: lastLine(run.output), replaced: step.replaced, matched: true });
239
+ // Only the engine marks a step done: the guard refuses a hand mark.
240
+ const progress = `${plan.folder}/${PROGRESS}`;
241
+ const text = restored ? null : readFile(progress);
242
+ if (text !== null) {
243
+ const marked = markedProgress(text, step.number);
244
+ if (marked !== text) writeFileSync(progress, marked);
245
+ }
246
+ } else if (!keepMark) marks.dropStep(plan.branch, step.number);
247
+ const got = gotOf(run, verdict.form, limitMs, verdict.matched);
248
+ return { number: step.number, expected: step.expected, got, matched: verdict.matched, timedOut: run.timedOut, command: step.command, output: run.output, errors: run.errors ?? '', tap: run.tap ?? '' };
249
+ }
250
+
251
+ /**
252
+ * The command with `tee <file>` before its last pipe, so the output a closing `grep` only counts is
253
+ * kept for the line of an unmatched step. Null unless the pipe is certain: a `|` of `case`, `((`,
254
+ * `[[` or `>|`, a backslash in a quote and `PIPESTATUS` change their meaning under a `tee`.
255
+ */
256
+ export function tapped(command, file) {
257
+ if (/\bcase\b|\(\(|\[\[|>\||PIPESTATUS|\\/.test(command)) return null;
258
+ let quote = null;
259
+ let at = -1;
260
+ for (let i = 0; i < command.length; i++) {
261
+ const c = command[i];
262
+ if (quote) quote = c === quote ? null : quote;
263
+ else if (c === "'" || c === '"') quote = c;
264
+ else if (c === '|' && command[i + 1] !== '|' && command[i - 1] !== '|' && command[i + 1] !== '&') at = i;
265
+ }
266
+ return at < 0 || !/^\|\s*grep\b/.test(command.slice(at)) ? null : `${command.slice(0, at)}| tee '${file}' ${command.slice(at)}`;
267
+ }
268
+
269
+ /**
270
+ * Measures one step of the plan: `{ number, expected, got, matched, removedBy }`, and writes or drops
271
+ * its mark. A taken-apart folder comes back for the run with the progress of the step's measurement; a
272
+ * step the last progress of the history does not mark done is refused with the move of the revert.
273
+ */
274
+ export function measureStep(sources, model, number, limitMs = STEP_LIMIT_MS, read = readFile) {
275
+ const plan = planOfBranch(sources.git, model.words);
276
+ if (!sources.steps.ofPlan(plan.text).some((s) => s.number === number)) throw new StepRefused(`the plan names no step ${number}`);
277
+ const restored = restoreFolder(sources.git, plan.folder);
278
+ try {
279
+ if (restored) {
280
+ const progressPath = `${plan.folder}/${PROGRESS}`;
281
+ const latest = readFile(progressPath);
282
+ if (latest === null || !doneLine(number).test(latest)) {
283
+ const back = `\`git revert --no-edit ${restored.removedBy}\``;
284
+ throw new StepRefused(`${number} is not marked done in the history, and the task folder is taken apart by ${restored.removedBy.slice(0, 9)}: bring the folder back — ${back} — then do the step, measure it and take the folder apart again`);
285
+ }
286
+ rewritePutBack(progressPath, progressOfStep(versionsOf(sources.git, progressPath), latest, number));
287
+ }
288
+ const ready = preparedOn(sources, model, number, read, restored?.removedBy);
289
+ const result = settleStep(sources, model, ready, runCheck(ready.step.command, limitMs), limitMs, { restored: restored !== null });
290
+ return { ...result, removedBy: restored?.removedBy ?? null };
291
+ } finally {
292
+ release(restored);
293
+ }
294
+ }
295
+
296
+ /** `prepareStep` on a folder put back: a folder file edited after the plan gets the move of the revert. */
297
+ function preparedOn(sources, model, number, read, removedBy) {
298
+ try {
299
+ return prepareStep(sources, model, number, read);
300
+ } catch (error) {
301
+ if (!removedBy || !(error instanceof StepRefused) || !error.message.startsWith('the task folder differs')) throw error;
302
+ throw new StepRefused(`${error.message}, and the folder is taken apart by ${removedBy.slice(0, 9)}: ${revertMove(removedBy)}`);
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Measures the steps side by side, at most `width` at once, each within the limit: results in the order
308
+ * of `numbers`, a refused one as `{ number, refused }`; `settle` goes to each verdict, `settle.tap` to `tapped`.
309
+ */
310
+ export async function measureSteps(sources, model, numbers, limitMs = STEP_LIMIT_MS, width = availableParallelism(), read = readFile, settle = {}) {
311
+ const results = new Array(numbers.length);
312
+ let next = 0;
313
+ const worker = async () => {
314
+ while (next < numbers.length) {
315
+ const index = next++;
316
+ const number = numbers[index];
317
+ try {
318
+ const ready = preparedOn(sources, model, number, read, settle.removedBy);
319
+ const file = join(tmpdir(), `rt-step-${process.pid}-${number}.out`);
320
+ const command = (settle.tap && tapped(ready.step.command, file)) || ready.step.command;
321
+ const started = Date.now();
322
+ const run = await runCheckAsync(command, limitMs);
323
+ if (command !== ready.step.command) run.tap = readFile(file) ?? '';
324
+ rmSync(file, { force: true });
325
+ results[index] = { ...settleStep(sources, model, ready, run, limitMs, settle), ms: Date.now() - started };
326
+ } catch (error) {
327
+ if (!(error instanceof StepRefused)) throw error;
328
+ results[index] = { number, refused: error.message };
329
+ }
330
+ }
331
+ };
332
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(width, numbers.length)) }, worker));
333
+ return results;
334
+ }
335
+
336
+ /** The steps the progress marks done: the working copy, or the last version in the history. */
337
+ export function doneSteps({ git, steps }, model, read = readFile) {
338
+ const plan = planOfBranch(git, model.words);
339
+ const path = `${plan.folder}/${PROGRESS}`;
340
+ const text = read(path) ?? git.lastVersion(path) ?? '';
341
+ return steps.ofProgress(text).steps.filter((s) => s.mark === 'x').map((s) => s.number);
342
+ }
343
+
344
+ /** The line of one measured step; it always ends with the verdict. */
345
+ export const stepLine = (result) => `ожидалось ${result.expected} · получено ${result.got} · ${result.matched ? 'совпало' : 'не совпало'}`;
346
+
347
+ /**
348
+ * The command `step <N.M>` or `step --done`: prints a line per step and returns the exit code — 0
349
+ * when every measured step matched, 1 when one did not or was refused. `--done` runs the checks side
350
+ * by side, prefixes each line with the number of its step and ends with the line
351
+ * `steps re-measured N, matched M`.
352
+ */
353
+ export async function runStepCommand(sources, model, target, mode = '') {
354
+ if (mode === '--pr') return runBeforePull(sources, model);
355
+ if (target !== '--done') {
356
+ try {
357
+ const result = measureStep(sources, model, target);
358
+ console.log(stepLine(result));
359
+ if (!result.matched && result.removedBy) console.log([...detailLines(result), `step: ${revertMove(result.removedBy)}`].join('\n'));
360
+ return result.matched ? 0 : 1;
361
+ } catch (error) {
362
+ if (!(error instanceof StepRefused)) throw error;
363
+ console.log(`step: ${error.message}`);
364
+ return 1;
365
+ }
366
+ }
367
+ let numbers;
368
+ try {
369
+ // A taken-apart folder: the done steps are measured the way the rerun before a PR measures them.
370
+ const folder = planOfBranch(sources.git, model.words).folder;
371
+ if (!existsSync(folder) || liveRun(folder)) return runBeforePull(sources, model);
372
+ numbers = doneSteps(sources, model);
373
+ } catch (error) {
374
+ if (!(error instanceof StepRefused)) throw error;
375
+ console.log(`step: ${error.message}`);
376
+ return 1;
377
+ }
378
+ const results = await measureSteps(sources, model, numbers);
379
+ for (const result of results) console.log(`${result.number} ${result.refused ? `step: ${result.refused}` : stepLine(result)}`);
380
+ const matched = results.filter((result) => result.matched).length;
381
+ console.log(`steps re-measured ${results.length}, matched ${matched}`);
382
+ return matched === results.length ? 0 : 1;
383
+ }
384
+
385
+ /** The tracked files the working copy changed, as `git status` names them. */
386
+ const trackedChanges = () =>
387
+ (spawnSync('git', ['status', '--porcelain', '--untracked-files=no'], { encoding: 'utf8' }).stdout ?? '').split('\n').filter(Boolean).sort();
388
+
389
+ /** A line of a suite that names a failure. */
390
+ const FAILURE = /\bFAIL\b|\bnot ok\b|\b[Ee]rror\b|провал/;
391
+
392
+ /**
393
+ * The lines under an unmatched step: its command, the last lines of its output and of its errors, and
394
+ * of what a pipe fed its last command — the lines naming a failure, or the last ones; each cut at 300.
395
+ */
396
+ export const detailLines = (result) => {
397
+ const fed = (result.tap ?? '').split('\n').filter((line) => FAILURE.test(line) && !/\b0 провалов/.test(line));
398
+ const lines = (name, list) => list.map((line) => ` ${name}: ${line.slice(0, 300)}`);
399
+ return [
400
+ ...lines('command', [result.command]),
401
+ ...lines('output', tail(result.output, 3)),
402
+ ...lines('errors', tail(result.errors, 3)),
403
+ ...lines('before the last pipe', fed.length > 0 ? tail(fed.join('\n'), 3) : tail(result.tap, 3)),
404
+ ];
405
+ };
406
+
407
+ /**
408
+ * The rerun before a PR: every step the progress marks done is measured once more on the folder put
409
+ * back, whatever mark lies on disk; a check that changes a tracked file does not match. A mismatch
410
+ * runs again in its group within the budget and loses its mark only then. 0 when every step matched.
411
+ */
412
+ export async function runBeforePull(sources, model) {
413
+ let plan;
414
+ try {
415
+ plan = planOfBranch(sources.git, model.words);
416
+ } catch (error) {
417
+ if (!(error instanceof StepRefused)) throw error;
418
+ console.log(`step: ${error.message} — nothing to measure before the PR`);
419
+ return 0;
420
+ }
421
+ if (sources.steps.ofPlan(plan.text).every((s) => s.command === null)) {
422
+ console.log('step: the plan names no checks — nothing to measure before the PR');
423
+ return 0;
424
+ }
425
+ const started = Date.now();
426
+ const before = trackedChanges();
427
+ let restored = null;
428
+ try {
429
+ // A taken-apart folder: its last version comes back for the run and leaves after it.
430
+ restored = restoreFolder(sources.git, plan.folder);
431
+ const numbers = doneSteps(sources, model);
432
+ // The suites shorten the limit and the budget; the work always runs with its own.
433
+ const limit = Number(process.env.RT_FLOW_STEP_LIMIT_MS) || STEP_LIMIT_MS;
434
+ const budget = Number(process.env.RT_FLOW_RERUN_BUDGET_MS) || RERUN_BUDGET_MS;
435
+ // A restored folder brings the progress back as it stood when each step was measured.
436
+ const progressPath = `${plan.folder}/${PROGRESS}`;
437
+ const latest = restored ? readFile(progressPath) : null;
438
+ const versions = latest === null ? [] : versionsOf(sources.git, progressPath);
439
+ const groups = new Map();
440
+ for (const number of numbers) {
441
+ const text = latest === null ? null : progressOfStep(versions, latest, number);
442
+ groups.set(text, [...(groups.get(text) ?? []), number]);
443
+ }
444
+ const settle = { keepMark: true, restored: restored !== null, removedBy: restored?.removedBy, tap: true };
445
+ // A second run of a group starts only when its longest first run still fits the budget, and
446
+ // runs no longer than the budget left.
447
+ const spent = new Map();
448
+ const runGroups = async (wanted, settled, again) => {
449
+ const out = [];
450
+ for (const [text, group] of groups) {
451
+ const todo = group.filter((number) => wanted.includes(number));
452
+ const left = budget - (Date.now() - started);
453
+ if (todo.length === 0 || (again && (spent.get(text) ?? 0) > left)) continue;
454
+ if (text !== null) rewritePutBack(progressPath, text);
455
+ const done = await measureSteps(sources, model, todo, again ? Math.min(limit, left) : limit, undefined, readFile, settled);
456
+ spent.set(text, Math.max(0, ...done.map((r) => r.ms ?? 0)));
457
+ out.push(...done);
458
+ }
459
+ return out;
460
+ };
461
+ const first = await runGroups(numbers, settle, false);
462
+ const again = first.filter((r) => !r.refused && !r.matched && !r.timedOut).map((r) => r.number);
463
+ const second = await runGroups(again, { ...settle, keepMark: false }, true);
464
+ // A second run refused keeps the first mismatch: the step did not match, and its lines stay.
465
+ const results = first.map((r) => {
466
+ const s = second.find((x) => x.number === r.number);
467
+ return s && !s.refused ? s : { ...r, refusedAgain: s?.refused };
468
+ });
469
+ results.sort((a, b) => numbers.indexOf(a.number) - numbers.indexOf(b.number));
470
+ // A step that did not match and did not run again loses its mark here.
471
+ for (const r of results) if (!r.refused && !r.matched) sources.marks.dropStep(plan.branch, r.number);
472
+ const changed = trackedChanges().filter((line) => !before.includes(line));
473
+ for (const result of results) {
474
+ console.log(`${result.number} ${result.refused ? `step: ${result.refused}` : stepLine(result)}`);
475
+ const runs = second.some((s) => s.number === result.number && !s.refused) ? 'twice' : 'once';
476
+ const again = result.refusedAgain ? [` second run: step: ${result.refusedAgain}`] : [];
477
+ if (!result.refused && !result.matched) console.log([` runs: ${runs}`, ...again, ...detailLines(result)].join('\n'));
478
+ else if (result.matched && runs === 'twice') console.log(' matched on the second run');
479
+ }
480
+ if (changed.length > 0) console.log(`step: the checks changed tracked files — ${changed.join(', ')}: a check measures, it does not edit`);
481
+ const failed = results.filter((r) => !r.refused && !r.matched).map((r) => r.number);
482
+ if (restored && failed.length > 0) {
483
+ console.log(`step: ${failed.join(', ')} did not match, and the task folder is taken apart by ${restored.removedBy.slice(0, 9)}: ${revertMove(restored.removedBy)}`);
484
+ }
485
+ const matched = changed.length > 0 ? 0 : results.filter((result) => result.matched).length;
486
+ console.log(`steps re-measured ${results.length}, matched ${matched}`);
487
+ return matched === results.length && changed.length === 0 ? 0 : 1;
488
+ } catch (error) {
489
+ if (!(error instanceof StepRefused)) throw error;
490
+ console.log(`step: ${error.message}`);
491
+ return 1;
492
+ } finally {
493
+ release(restored);
494
+ }
495
+ }