specdojo 0.8.0 → 0.9.1

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 (292) hide show
  1. package/.github/agents/specdojo-orchestrator.md +4 -1
  2. package/CHANGELOG.md +77 -0
  3. package/dist/catalog/catalog.js +16 -14
  4. package/dist/commands/agent.js +5 -3
  5. package/dist/commands/build.js +69 -10
  6. package/dist/commands/git.js +206 -0
  7. package/dist/commands/init.js +4 -2
  8. package/dist/commands/orchestrator.js +5 -77
  9. package/dist/commands/where.js +25 -0
  10. package/dist/dashboard/dashboard.js +5 -3
  11. package/dist/dashboard/routines.js +4 -7
  12. package/dist/dashboard/shared.js +2 -2
  13. package/dist/dashboard/timeline.js +14 -14
  14. package/dist/deliverable/trash.js +2 -1
  15. package/dist/docs/index-command.js +2 -2
  16. package/dist/docs/yaml-business-tables.js +243 -0
  17. package/dist/docs/yaml-interface-tables.js +106 -0
  18. package/dist/docs/yaml-pages-command.js +5 -3
  19. package/dist/docs/yaml-pages.js +146 -3
  20. package/dist/docs/yaml-table-shared.js +70 -0
  21. package/dist/docs/yaml-tables.js +39 -0
  22. package/dist/exec/agent-config.js +9 -0
  23. package/dist/exec/agent-protected-config.js +2 -0
  24. package/dist/exec/commands.js +31 -18
  25. package/dist/exec/events.js +34 -14
  26. package/dist/exec/evidence.js +13 -3
  27. package/dist/exec/opencode-permissions.js +117 -0
  28. package/dist/exec/parent-validation.js +56 -3
  29. package/dist/exec/plans-core.js +21 -2
  30. package/dist/exec/plans-generation.js +6 -7
  31. package/dist/exec/post-integration.js +162 -0
  32. package/dist/exec/queue-command.js +166 -0
  33. package/dist/exec/queue.js +285 -0
  34. package/dist/exec/register-foreign-wait.js +82 -0
  35. package/dist/exec/repo-integration-sync.js +17 -5
  36. package/dist/exec/repo-trace.js +2 -1
  37. package/dist/exec/reporter.js +2 -2
  38. package/dist/exec/results.js +24 -4
  39. package/dist/exec/review-kata.js +4 -1
  40. package/dist/exec/run/agent-pipeline.js +3 -2
  41. package/dist/exec/run/agent.js +12 -6
  42. package/dist/exec/run/change-scope.js +365 -0
  43. package/dist/exec/run/deferred-cleanup.js +31 -0
  44. package/dist/exec/run/in-place.js +5 -2
  45. package/dist/exec/run/job-lock.js +66 -0
  46. package/dist/exec/run/job-sequence.js +137 -0
  47. package/dist/exec/run/job.js +56 -19
  48. package/dist/exec/run/lifecycle-commands.js +1 -1
  49. package/dist/exec/run/lock.js +22 -1
  50. package/dist/exec/run/register-command.js +8 -5
  51. package/dist/exec/run/register-mode.js +68 -8
  52. package/dist/exec/run/register-resume.js +68 -14
  53. package/dist/exec/run/register-state.js +13 -8
  54. package/dist/exec/run/register-worktree.js +140 -125
  55. package/dist/exec/run/schedule-mode.js +75 -14
  56. package/dist/exec/run/schedule-prepare.js +3 -0
  57. package/dist/exec/run/schedule-task.js +88 -38
  58. package/dist/exec/run/shared.js +5 -0
  59. package/dist/exec/schedule/schedule.js +116 -4
  60. package/dist/exec/shared.js +2 -2
  61. package/dist/exec/smoke.js +190 -0
  62. package/dist/exec/strategy.js +13 -3
  63. package/dist/exec/task-repos.js +19 -4
  64. package/dist/exec/task-view.js +6 -4
  65. package/dist/exec/trial-commands.js +5 -2
  66. package/dist/exec/trial-core.js +6 -1
  67. package/dist/exec/validation-metrics.js +181 -0
  68. package/dist/exec/worktree-cleanup-lock.js +26 -0
  69. package/dist/exec/worktree-command.js +12 -2
  70. package/dist/exec/worktree-ops-commit.js +2 -2
  71. package/dist/exec/worktree.js +13 -2
  72. package/dist/grade/command-apply.js +3 -3
  73. package/dist/grade/command-inspect.js +5 -3
  74. package/dist/grade/command-plan.js +1 -1
  75. package/dist/grade/command-run.js +5 -1
  76. package/dist/grade/run.js +64 -8
  77. package/dist/job/definition.js +84 -8
  78. package/dist/job/job.js +79 -23
  79. package/dist/register/authoring-sources.js +22 -16
  80. package/dist/register/maintenance-commands.js +2 -2
  81. package/dist/register/register.js +31 -7
  82. package/dist/register/renumber.js +1 -3
  83. package/dist/routine/definition.js +9 -0
  84. package/dist/routine/routine.js +137 -43
  85. package/dist/routine/status.js +62 -0
  86. package/dist/schedule/schedule.js +38 -39
  87. package/dist/shared/agent-types.js +5 -0
  88. package/dist/shared/cross-process-lock.js +9 -1
  89. package/dist/shared/dist-freshness.js +8 -2
  90. package/dist/shared/git-environment.js +2 -1
  91. package/dist/shared/git.js +44 -1
  92. package/dist/shared/lefthook-scaffold.js +3 -0
  93. package/dist/shared/local-config.js +244 -0
  94. package/dist/shared/specdojo-config.js +34 -20
  95. package/dist/shared/specdojo-gitignore.js +1 -0
  96. package/dist/shared/text.js +17 -1
  97. package/dist/shared/where-alias.js +13 -0
  98. package/dist/specdojo.js +4 -0
  99. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +2 -0
  100. package/docs/ja/specdojo/guides/exec-config-guide.md +23 -4
  101. package/docs/ja/specdojo/guides/exec-operation-guide.md +44 -1
  102. package/docs/ja/specdojo/guides/job-sequence-guide.md +77 -0
  103. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +1 -1
  104. package/docs/ja/specdojo/guides/quick-start-guide.md +3 -3
  105. package/docs/ja/specdojo/guides/register-operation-guide.md +1 -1
  106. package/docs/ja/specdojo/guides/routine-operation-guide.md +11 -6
  107. package/docs/ja/specdojo/guides/schedule-design-guide.md +20 -17
  108. package/docs/ja/specdojo/guides/waza-guide.md +12 -8
  109. package/docs/ja/specdojo/recipes/bac-recipe.md +66 -49
  110. package/docs/ja/specdojo/recipes/bes-recipe.md +90 -54
  111. package/docs/ja/specdojo/recipes/bps-recipe.md +88 -139
  112. package/docs/ja/specdojo/recipes/br-recipe.md +40 -47
  113. package/docs/ja/specdojo/recipes/cdfd-overview-recipe.md +97 -109
  114. package/docs/ja/specdojo/recipes/cdfd-recipe.md +85 -146
  115. package/docs/ja/specdojo/recipes/cdfd-uc-recipe.md +91 -110
  116. package/docs/ja/specdojo/recipes/cnd-recipe.md +79 -69
  117. package/docs/ja/specdojo/recipes/cpd-recipe.md +78 -64
  118. package/docs/ja/specdojo/recipes/cxd-recipe.md +92 -75
  119. package/docs/ja/specdojo/recipes/ifd-recipe.md +79 -68
  120. package/docs/ja/specdojo/recipes/ifx-cmd-recipe.md +78 -105
  121. package/docs/ja/specdojo/recipes/ifx-index-recipe.md +105 -71
  122. package/docs/ja/specdojo/recipes/pm-communication-plan-recipe.md +60 -49
  123. package/docs/ja/specdojo/recipes/pm-members-recipe.md +50 -51
  124. package/docs/ja/specdojo/recipes/pm-organization-recipe.md +59 -51
  125. package/docs/ja/specdojo/recipes/pm-plan-recipe.md +69 -56
  126. package/docs/ja/specdojo/recipes/pm-quality-management-plan-recipe.md +37 -56
  127. package/docs/ja/specdojo/recipes/pm-raci-recipe.md +39 -53
  128. package/docs/ja/specdojo/recipes/pm-roles-recipe.md +52 -79
  129. package/docs/ja/specdojo/recipes/prj-assumptions-constraints-dependencies-recipe.md +64 -93
  130. package/docs/ja/specdojo/recipes/prj-charter-recipe.md +71 -106
  131. package/docs/ja/specdojo/recipes/prj-comparison-of-alternatives-recipe.md +78 -157
  132. package/docs/ja/specdojo/recipes/prj-issues-and-approach-recipe.md +62 -111
  133. package/docs/ja/specdojo/recipes/prj-scope-recipe.md +67 -123
  134. package/docs/ja/specdojo/recipes/prj-stakeholder-register-recipe.md +60 -96
  135. package/docs/ja/specdojo/recipes/prj-success-criteria-and-acceptance-criteria-recipe.md +61 -105
  136. package/docs/ja/specdojo/recipes/stsd-recipe.md +79 -109
  137. package/docs/ja/specdojo/recipes/sysd-critical-flows-recipe.md +78 -55
  138. package/docs/ja/specdojo/recipes/sysd-cross-cutting-policy-recipe.md +82 -73
  139. package/docs/ja/specdojo/recipes/sysd-index-recipe.md +78 -59
  140. package/docs/ja/specdojo/recipes/tsd-recipe.md +149 -129
  141. package/docs/ja/specdojo/references/command-reference.md +258 -118
  142. package/docs/ja/specdojo/references/deliverables-reference.md +21 -12
  143. package/docs/ja/specdojo/references/specdojo-config-reference.md +47 -10
  144. package/docs/ja/specdojo/rulebooks/atc-index-rulebook.md +101 -257
  145. package/docs/ja/specdojo/rulebooks/atc-rulebook.md +102 -228
  146. package/docs/ja/specdojo/rulebooks/bac-rulebook.md +19 -28
  147. package/docs/ja/specdojo/rulebooks/bdd-rulebook.md +16 -67
  148. package/docs/ja/specdojo/rulebooks/bds-rulebook.md +30 -51
  149. package/docs/ja/specdojo/rulebooks/bes-index-rulebook.md +41 -61
  150. package/docs/ja/specdojo/rulebooks/bes-rulebook.md +22 -50
  151. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +24 -56
  152. package/docs/ja/specdojo/rulebooks/br-rulebook.md +13 -38
  153. package/docs/ja/specdojo/rulebooks/ccd-mermaid-rulebook.md +41 -76
  154. package/docs/ja/specdojo/rulebooks/cdfd-d2-rulebook.md +18 -93
  155. package/docs/ja/specdojo/rulebooks/cdfd-mermaid-rulebook.md +18 -52
  156. package/docs/ja/specdojo/rulebooks/cdfd-overview-rulebook.md +109 -147
  157. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +80 -108
  158. package/docs/ja/specdojo/rulebooks/cdfd-uc-rulebook.md +21 -46
  159. package/docs/ja/specdojo/rulebooks/cdr-rulebook.md +144 -0
  160. package/docs/ja/specdojo/rulebooks/cdsd-rulebook.md +27 -48
  161. package/docs/ja/specdojo/rulebooks/cdt-rulebook.md +37 -50
  162. package/docs/ja/specdojo/rulebooks/clis-rulebook.md +52 -69
  163. package/docs/ja/specdojo/rulebooks/cnd-mermaid-rulebook.md +33 -86
  164. package/docs/ja/specdojo/rulebooks/cnd-rulebook.md +16 -32
  165. package/docs/ja/specdojo/rulebooks/cop-index-rulebook.md +45 -131
  166. package/docs/ja/specdojo/rulebooks/cop-rulebook.md +69 -275
  167. package/docs/ja/specdojo/rulebooks/cpd-mermaid-rulebook.md +20 -112
  168. package/docs/ja/specdojo/rulebooks/cpd-rulebook.md +23 -56
  169. package/docs/ja/specdojo/rulebooks/cxd-mermaid-rulebook.md +12 -145
  170. package/docs/ja/specdojo/rulebooks/cxd-rulebook.md +39 -47
  171. package/docs/ja/specdojo/rulebooks/dct-index-rulebook.md +37 -56
  172. package/docs/ja/specdojo/rulebooks/dct-rulebook.md +118 -175
  173. package/docs/ja/specdojo/rulebooks/dec-rulebook.md +5 -14
  174. package/docs/ja/specdojo/rulebooks/dmd-index-rulebook.md +22 -66
  175. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +36 -94
  176. package/docs/ja/specdojo/rulebooks/dss-rulebook.md +59 -81
  177. package/docs/ja/specdojo/rulebooks/etc-index-rulebook.md +31 -131
  178. package/docs/ja/specdojo/rulebooks/etc-rulebook.md +50 -104
  179. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +51 -61
  180. package/docs/ja/specdojo/rulebooks/ifd-mermaid-rulebook.md +38 -45
  181. package/docs/ja/specdojo/rulebooks/ifx-api-rulebook.md +14 -20
  182. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +26 -38
  183. package/docs/ja/specdojo/rulebooks/ifx-file-rulebook.md +26 -107
  184. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +42 -49
  185. package/docs/ja/specdojo/rulebooks/ifx-msg-rulebook.md +14 -22
  186. package/docs/ja/specdojo/rulebooks/imp-business-rulebook.md +21 -44
  187. package/docs/ja/specdojo/rulebooks/imp-data-rulebook.md +41 -64
  188. package/docs/ja/specdojo/rulebooks/imp-interface-rulebook.md +14 -38
  189. package/docs/ja/specdojo/rulebooks/imp-operations-rulebook.md +34 -61
  190. package/docs/ja/specdojo/rulebooks/imp-test-rulebook.md +27 -50
  191. package/docs/ja/specdojo/rulebooks/itc-index-rulebook.md +70 -199
  192. package/docs/ja/specdojo/rulebooks/itc-rulebook.md +65 -153
  193. package/docs/ja/specdojo/rulebooks/mip-index-rulebook.md +74 -150
  194. package/docs/ja/specdojo/rulebooks/mm-rulebook.md +11 -23
  195. package/docs/ja/specdojo/rulebooks/mtp-rulebook.md +99 -176
  196. package/docs/ja/specdojo/rulebooks/nfr-availability-rulebook.md +35 -61
  197. package/docs/ja/specdojo/rulebooks/nfr-index-rulebook.md +75 -117
  198. package/docs/ja/specdojo/rulebooks/nfr-integrity-rulebook.md +31 -60
  199. package/docs/ja/specdojo/rulebooks/nfr-maintainability-rulebook.md +26 -81
  200. package/docs/ja/specdojo/rulebooks/nfr-operations-rulebook.md +32 -70
  201. package/docs/ja/specdojo/rulebooks/nfr-performance-rulebook.md +45 -87
  202. package/docs/ja/specdojo/rulebooks/nfr-reliability-rulebook.md +48 -101
  203. package/docs/ja/specdojo/rulebooks/nfr-security-safety-rulebook.md +44 -80
  204. package/docs/ja/specdojo/rulebooks/nfr-usability-rulebook.md +59 -127
  205. package/docs/ja/specdojo/rulebooks/opd-index-rulebook.md +31 -50
  206. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +42 -109
  207. package/docs/ja/specdojo/rulebooks/opr-index-rulebook.md +29 -42
  208. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +29 -87
  209. package/docs/ja/specdojo/rulebooks/otp-index-rulebook.md +62 -84
  210. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +11 -61
  211. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +91 -106
  212. package/docs/ja/specdojo/rulebooks/pm-change-request-log-rulebook.md +25 -34
  213. package/docs/ja/specdojo/rulebooks/pm-communication-plan-rulebook.md +30 -53
  214. package/docs/ja/specdojo/rulebooks/pm-issue-log-rulebook.md +23 -35
  215. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +27 -45
  216. package/docs/ja/specdojo/rulebooks/pm-organization-rulebook.md +37 -45
  217. package/docs/ja/specdojo/rulebooks/pm-plan-rulebook.md +45 -46
  218. package/docs/ja/specdojo/rulebooks/pm-quality-management-plan-rulebook.md +37 -48
  219. package/docs/ja/specdojo/rulebooks/pm-raci-rulebook.md +25 -29
  220. package/docs/ja/specdojo/rulebooks/pm-risk-register-rulebook.md +28 -35
  221. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +36 -41
  222. package/docs/ja/specdojo/rulebooks/pr-rulebook.md +5 -18
  223. package/docs/ja/specdojo/rulebooks/prj-assumptions-constraints-dependencies-rulebook.md +16 -37
  224. package/docs/ja/specdojo/rulebooks/prj-charter-rulebook.md +23 -97
  225. package/docs/ja/specdojo/rulebooks/prj-comparison-of-alternatives-rulebook.md +39 -57
  226. package/docs/ja/specdojo/rulebooks/prj-issues-and-approach-rulebook.md +43 -116
  227. package/docs/ja/specdojo/rulebooks/prj-scope-rulebook.md +16 -51
  228. package/docs/ja/specdojo/rulebooks/prj-stakeholder-register-rulebook.md +47 -92
  229. package/docs/ja/specdojo/rulebooks/prj-success-criteria-and-acceptance-criteria-rulebook.md +25 -84
  230. package/docs/ja/specdojo/rulebooks/sac-rulebook.md +44 -107
  231. package/docs/ja/specdojo/rulebooks/sf-index-rulebook.md +39 -49
  232. package/docs/ja/specdojo/rulebooks/sf-rulebook.md +42 -49
  233. package/docs/ja/specdojo/rulebooks/sld-rulebook.md +64 -89
  234. package/docs/ja/specdojo/rulebooks/stc-index-rulebook.md +90 -189
  235. package/docs/ja/specdojo/rulebooks/stc-rulebook.md +45 -105
  236. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +6 -12
  237. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +49 -68
  238. package/docs/ja/specdojo/rulebooks/sysd-critical-flows-rulebook.md +51 -60
  239. package/docs/ja/specdojo/rulebooks/sysd-cross-cutting-policy-rulebook.md +46 -50
  240. package/docs/ja/specdojo/rulebooks/sysd-index-rulebook.md +39 -64
  241. package/docs/ja/specdojo/rulebooks/sysd-rulebook.md +47 -60
  242. package/docs/ja/specdojo/rulebooks/trc-requirements-to-specs-rulebook.md +69 -70
  243. package/docs/ja/specdojo/rulebooks/trc-requirements-to-tests-rulebook.md +65 -72
  244. package/docs/ja/specdojo/rulebooks/tsd-index-rulebook.md +35 -46
  245. package/docs/ja/specdojo/rulebooks/tsd-rulebook.md +49 -66
  246. package/docs/ja/specdojo/rulebooks/tsp-index-rulebook.md +64 -139
  247. package/docs/ja/specdojo/rulebooks/uis-rulebook.md +41 -108
  248. package/docs/ja/specdojo/rulebooks/utc-index-rulebook.md +49 -144
  249. package/docs/ja/specdojo/rulebooks/utc-rulebook.md +67 -155
  250. package/docs/ja/specdojo/samples/bds-sample.md +58 -71
  251. package/docs/ja/specdojo/samples/bes-index-sample.md +20 -37
  252. package/docs/ja/specdojo/samples/bes-sample.md +43 -53
  253. package/docs/ja/specdojo/samples/bps-sample.md +42 -54
  254. package/docs/ja/specdojo/samples/br-sample.md +40 -52
  255. package/docs/ja/specdojo/samples/ccd-sample.md +0 -1
  256. package/docs/ja/specdojo/samples/cdr-sample.md +78 -0
  257. package/docs/ja/specdojo/samples/cdsd-sample.md +47 -63
  258. package/docs/ja/specdojo/samples/clis-sample.md +70 -77
  259. package/docs/ja/specdojo/samples/dec-sample.md +2 -3
  260. package/docs/ja/specdojo/samples/ifx-api-sample.yaml +0 -2
  261. package/docs/ja/specdojo/samples/ifx-msg-sample.yaml +0 -2
  262. package/docs/ja/specdojo/samples/job-sequence.yaml +67 -0
  263. package/docs/ja/specdojo/samples/mip-index-sample.md +98 -20
  264. package/docs/ja/specdojo/samples/pm-communication-plan-sample.md +26 -19
  265. package/docs/ja/specdojo/samples/pm-organization-sample.md +39 -50
  266. package/docs/ja/specdojo/samples/pm-plan-sample.md +61 -67
  267. package/docs/ja/specdojo/samples/pm-quality-management-plan-sample.md +31 -45
  268. package/docs/ja/specdojo/samples/pm-raci-sample.md +31 -37
  269. package/docs/ja/specdojo/samples/prj-assumptions-constraints-dependencies-sample.md +32 -48
  270. package/docs/ja/specdojo/samples/prj-charter-sample.md +42 -59
  271. package/docs/ja/specdojo/samples/prj-comparison-of-alternatives-sample.md +55 -61
  272. package/docs/ja/specdojo/samples/prj-success-criteria-and-acceptance-criteria-sample.md +30 -33
  273. package/docs/ja/specdojo/samples/sf-index-sample.md +13 -55
  274. package/docs/ja/specdojo/samples/sf-sample.md +73 -85
  275. package/docs/ja/specdojo/samples/sld-sample.md +60 -79
  276. package/docs/ja/specdojo/samples/uis-sample.md +98 -121
  277. package/docs/ja/specdojo/standards/job-definition-standard.md +24 -9
  278. package/docs/ja/specdojo/templates/cdr-template.md +58 -0
  279. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +2 -1
  280. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +42 -5
  281. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +35 -0
  282. package/docs/specdojo/schemas/v1/job-run.schema.yaml +23 -0
  283. package/docs/specdojo/schemas/v1/job.schema.yaml +63 -2
  284. package/docs/specdojo/schemas/v1/sch-strategy.schema.yaml +2 -2
  285. package/package.json +9 -6
  286. package/templates/antigravity/orchestrator.md +4 -1
  287. package/templates/claude/agents/specdojo-orchestrator.md +4 -1
  288. package/templates/codex/agents/specdojo-orchestrator.toml +4 -1
  289. package/templates/codex/orchestrator.md +4 -1
  290. package/templates/init-exec-defaults.yaml +13 -0
  291. package/templates/lefthook/tools/specdojo-pre-commit.mjs +8 -0
  292. package/templates/opencode/agents/specdojo-orchestrator.md +5 -2
@@ -8,6 +8,7 @@ import { loadConfig, resolveAgentMember, } from "../../shared/specdojo-config.js
8
8
  import { integrationCommitSkipHooks } from "../commit-hook-skips.js";
9
9
  import { gradeCheckpointPaths } from "../grade-checkpoint.js";
10
10
  import { pipelineStateLocation, readPipelineState } from "../pipeline-state.js";
11
+ import { integratedCommitRange, runPostIntegration } from "../post-integration.js";
11
12
  import { buildInPlaceStem } from "../plans.js";
12
13
  import { resolveProductBranches } from "../product-branches.js";
13
14
  import { registerProductMessage } from "../register-product-message.js";
@@ -16,18 +17,21 @@ import { generateRegisterPlan, requireRunnableRegisterItem, resolveRegisterRunTa
16
17
  import { commitProductWorktrees, integrateTaskRepositories, PROJECT_REPO_NAME, projectMergeBlockers, RepoIntegrationError, } from "../repo-integration.js";
17
18
  import { productIntegrationTrace, recordResultTrace, registerProjectMergeMessage, traceKey, } from "../repo-trace.js";
18
19
  import { readResultFrontmatterSnapshot, scaffoldResult, updateResultStatus } from "../results.js";
19
- import { recordPathForRead, recordRef, taskRecordPaths } from "../run-records.js";
20
+ import { recordPathForRead, recordRef, runLogPath, taskRecordPaths } from "../run-records.js";
20
21
  import { qualifyTaskId } from "../shared.js";
21
22
  import { configuredProductRepos, integrationBranchOverrideRecord, reserveProductBranches, withProductRepoPrompt, } from "../task-repos.js";
22
23
  import { checkpointAndEnsureWorktree, assertCommitScope, commitTargetPaths, commitWorktreeChanges, discardStaleExecWorktree, isExecBranchMergedIntoCurrent, mergeWorktreeIntoCurrent, removeWorktree, taskTargetsAtHead, WorktreeRemovedBranchDeletionError, UncommittedChangesError, worktreeStatusPaths, } from "../worktree-ops.js";
23
24
  import { findExecWorktree, gitOutput, } from "../worktree.js";
25
+ import { isWorktreeCleanupInProgress, releaseWorktreeCleanupLock, tryAcquireWorktreeCleanupLock, worktreeCleanupInProgressReason, } from "../worktree-cleanup-lock.js";
24
26
  import { runAgentPipeline } from "./agent-pipeline.js";
27
+ import { DeferredCleanup, runWithDeferredCleanup } from "./deferred-cleanup.js";
25
28
  import { agentEnvironment, expandPromptRefs, extractBlockReason, pathInsideWorktree, reportProductWorktrees, runWithRetry, } from "./agent.js";
26
29
  import { commitSubject, integrateLogPath, recordIntegrateStage, recordRepoIntegration, repoRelativePath, } from "./mode-shared.js";
27
30
  import { isRegisterPipelineRequested, registerReporterManagedPaths, registerRunnerManagedPaths, resolveRegisterCommand, resolveRegisterPipelineCommand, spawnRegisterTransition, } from "./register-core.js";
28
31
  import { runRegisterPostReview } from "./register-post-review.js";
29
32
  import { commitRegisterState, rebuildRootRegisterViews, registerPathsInsideWorktree, registerWaitSummary, } from "./register-state.js";
30
33
  import { downgradeUnfilledResult } from "./schedule-prepare.js";
34
+ import { appendScopeWaitNotes } from "./change-scope.js";
31
35
  import { rateLimitRecoveryReason, resolvePinnedRateLimitRunOptions, } from "./shared.js";
32
36
  // 全体再実行が既存 run の未統合成果を破棄しないための保護。既存 worktree に再開可能な run
33
37
  // (executor 成功済みで reporter か統合が未完了)が残っている場合だけ理由を返し、呼び出し側が
@@ -56,35 +60,30 @@ export function protectResumableRegisterWorktree(context, opts, taskId, worktree
56
60
  `its changes are still unintegrated in ${worktree.path}. ` +
57
61
  `Resume the ${stage} stage with --resume, or discard the worktree with --force-restart.`);
58
62
  }
59
- // cleanup の再開までに別項目の commit が積まれても、対象 exec branch を最初に取り込んだ
60
- // first-parent commit(runner が作った merge commit)だけを post-review の差分範囲にする。
61
- function integratedRegisterCommitRange(repoRoot, branch) {
62
- const tip = gitOutput(repoRoot, ["rev-parse", "--verify", `${branch}^{commit}`]).trim();
63
- const outputCommit = gitOutput(repoRoot, [
64
- "rev-list",
65
- "--first-parent",
66
- "--ancestry-path",
67
- `${tip}..HEAD`,
68
- ])
69
- .split("\n")
70
- .map((line) => line.trim())
71
- .filter(Boolean)
72
- .at(-1);
73
- if (!outputCommit) {
74
- throw new Error(`could not locate integrated commit for register branch: ${branch}`);
75
- }
76
- const baseCommit = gitOutput(repoRoot, ["rev-parse", `${outputCommit}^1`]).trim();
77
- return { baseCommit, outputCommit };
78
- }
79
63
  // register worktree 実行の Phase 3(成果物統合と状態遷移)。成功なら worktree の成果物を
80
64
  // commit → worktree 側で register review → 統合ブランチへ merge commit 1件 → worktree 撤去、
81
65
  // 失敗なら worktree を保持したまま waiting へ戻す(wait commit 1件)。通常実行・reporter 再開・
82
66
  // 統合再開で同じ後処理を通す。統合ブランチの first-parent に増えるのは、成功時の merge commit
83
67
  // (start → review の遷移事象、plan / result、成果物を含む)か失敗時の wait commit だけになる。
84
- export async function finalizeRegisterWorktreeRun(params) {
68
+ // 撤去は lifecycleLock の外で行い、その後の派生ビューの再生成と post-review はロックを取り直して
69
+ // 行う(PJR-NHT7)。
70
+ export function finalizeRegisterWorktreeRun(params) {
71
+ return runWithDeferredCleanup(params.lifecycleLock, () => integrateRegisterWorktreeRun(params));
72
+ }
73
+ async function integrateRegisterWorktreeRun(params) {
85
74
  const { context, registerPaths, item, ticketPath, worktree, stem, agentResult, actor } = params;
86
75
  const { projectId, schedulePath, executionPath, repoRoot } = context;
87
76
  const wtContext = { repoRoot, schedulePath, executionPath };
77
+ const postIntegration = (baseCommit, outputCommit) => runPostIntegration({
78
+ entries: context.execDefaults.pipeline?.post_integration,
79
+ repoRoot,
80
+ baseCommit,
81
+ outputCommit,
82
+ logPath: runLogPath(resolve(repoRoot, repoRelativePath(worktree.path, params.worktreeResultPath)), "post-integration.log"),
83
+ });
84
+ const bookkeepingPaths = typeof params.bookkeepingPaths === "function"
85
+ ? params.bookkeepingPaths()
86
+ : params.bookkeepingPaths;
88
87
  const worktreeRegisterPaths = registerPathsInsideWorktree(repoRoot, worktree.path, registerPaths);
89
88
  const worktreeTicketPath = ticketPath
90
89
  ? pathInsideWorktree(repoRoot, worktree.path, ticketPath)
@@ -99,7 +98,7 @@ export async function finalizeRegisterWorktreeRun(params) {
99
98
  reasonMaxLength,
100
99
  actor,
101
100
  worktree,
102
- bookkeepingPaths: params.bookkeepingPaths,
101
+ bookkeepingPaths,
103
102
  });
104
103
  const postReview = async (baseCommit, outputCommit) => {
105
104
  if (!context.postReview)
@@ -131,6 +130,66 @@ export async function finalizeRegisterWorktreeRun(params) {
131
130
  reason: reviewed.reason,
132
131
  };
133
132
  };
133
+ const blockedInReview = (error, prefix) => {
134
+ const reason = sanitizeRegisterConclusion(`${prefix}: ${error instanceof Error ? error.message : String(error)}`, error instanceof UncommittedChangesError ? 4000 : undefined);
135
+ const integrateFailedAt = new Date().toISOString();
136
+ recordIntegrateStage(params.pipelineStatePath, integrateFailedAt, () => ({
137
+ status: "failed",
138
+ completed_at: integrateFailedAt,
139
+ }));
140
+ process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
141
+ return {
142
+ id: item.id,
143
+ title: item.title,
144
+ outcome: "failure",
145
+ transition: "review",
146
+ commit: "incomplete",
147
+ reason,
148
+ ...(error instanceof UncommittedChangesError ? { uncommittedFiles: error.files.length } : {}),
149
+ };
150
+ };
151
+ // merge の後の撤去をロックの外へ回す。root はすでに review で、撤去だけが失敗した場合は
152
+ // review を維持して `--resume` で cleanup だけをやり直す。撤去後の branch 削除だけが失敗した
153
+ // 場合は、成果の統合を取り消さず cleanup 警告として扱う。worktree ごとのロックは
154
+ // exec-lifecycle のロックの中で取り、同じ項目の再実行・再開が撤去と重ならないようにする。
155
+ const deferCleanup = (baseCommit, outputCommit) => {
156
+ const worktreeTaskId = qualifyTaskId(projectId, item.id);
157
+ const cleanupLock = tryAcquireWorktreeCleanupLock(executionPath, worktreeTaskId, actor);
158
+ if (!cleanupLock) {
159
+ rebuildRootRegisterViews(projectId, item.id);
160
+ return blockedInReview(new Error(worktreeCleanupInProgressReason(worktreeTaskId)), "integrate cleanup failed");
161
+ }
162
+ return new DeferredCleanup(() => {
163
+ try {
164
+ removeWorktree({ context: wtContext, worktree, taskId: stem, deleteBranch: true });
165
+ }
166
+ finally {
167
+ releaseWorktreeCleanupLock(cleanupLock);
168
+ }
169
+ }, async (outcome) => {
170
+ if (!outcome.ok) {
171
+ if (!(outcome.error instanceof WorktreeRemovedBranchDeletionError)) {
172
+ rebuildRootRegisterViews(projectId, item.id);
173
+ return blockedInReview(outcome.error, "integrate cleanup failed");
174
+ }
175
+ process.stderr.write(`Warning: ${outcome.error.message}; run exec worktree prune.\n`);
176
+ }
177
+ // review は merge で root の個票に入る。非追跡の派生ビューだけ root で作り直す。
178
+ rebuildRootRegisterViews(projectId, item.id);
179
+ const reviewed = await postReview(baseCommit, outputCommit);
180
+ if (reviewed)
181
+ return reviewed;
182
+ const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
183
+ process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
184
+ return {
185
+ id: item.id,
186
+ title: item.title,
187
+ outcome: "success",
188
+ transition: "review",
189
+ commit: `committed ${sha}`,
190
+ };
191
+ });
192
+ };
134
193
  const completedAt = new Date().toISOString();
135
194
  const worktreeResultPath = params.worktreeResultPath;
136
195
  const scopeLogPath = integrateLogPath(params.pipelineStatePath) ??
@@ -143,7 +202,12 @@ export async function finalizeRegisterWorktreeRun(params) {
143
202
  // exec branch here would force a second merge commit for the same task.
144
203
  if (params.resumedIntegration &&
145
204
  isExecBranchMergedIntoCurrent({ context: wtContext, worktree })) {
146
- const { baseCommit, outputCommit } = integratedRegisterCommitRange(repoRoot, worktree.branch);
205
+ await params.opts.onScopeIntegrated?.();
206
+ const worktreeTaskId = qualifyTaskId(projectId, item.id);
207
+ if (isWorktreeCleanupInProgress(executionPath, worktreeTaskId)) {
208
+ return blockedInReview(new Error(worktreeCleanupInProgressReason(worktreeTaskId)), "integrate cleanup failed");
209
+ }
210
+ const { baseCommit, outputCommit } = integratedCommitRange(repoRoot, worktree.branch);
147
211
  try {
148
212
  assertCommitScope(wtContext, worktree, stem, { scopeLogPath });
149
213
  const lifecyclePaths = new Set([worktreeResultPath, params.pipelineStatePath]
@@ -165,46 +229,12 @@ export async function finalizeRegisterWorktreeRun(params) {
165
229
  ]);
166
230
  }
167
231
  process.stdout.write(` [integrate] already merged: ${worktree.branch} (skipping transitions, commit, and merge)\n`);
168
- removeWorktree({ context: wtContext, worktree, taskId: stem, deleteBranch: true });
169
232
  }
170
233
  catch (error) {
171
- if (error instanceof WorktreeRemovedBranchDeletionError) {
172
- process.stderr.write(`Warning: ${error.message}; run exec worktree prune.\n`);
173
- }
174
- else {
175
- const reason = sanitizeRegisterConclusion(`integrate cleanup failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof UncommittedChangesError ? 4000 : undefined);
176
- const integrateFailedAt = new Date().toISOString();
177
- recordIntegrateStage(params.pipelineStatePath, integrateFailedAt, () => ({
178
- status: "failed",
179
- completed_at: integrateFailedAt,
180
- }));
181
- process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
182
- return {
183
- id: item.id,
184
- title: item.title,
185
- outcome: "failure",
186
- transition: "review",
187
- commit: "incomplete",
188
- reason,
189
- ...(error instanceof UncommittedChangesError
190
- ? { uncommittedFiles: error.files.length }
191
- : {}),
192
- };
193
- }
234
+ return blockedInReview(error, "integrate cleanup failed");
194
235
  }
195
- rebuildRootRegisterViews(projectId, item.id);
196
- const reviewed = await postReview(baseCommit, outputCommit);
197
- if (reviewed)
198
- return reviewed;
199
- const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
200
- process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
201
- return {
202
- id: item.id,
203
- title: item.title,
204
- outcome: "success",
205
- transition: "review",
206
- commit: `committed ${sha}`,
207
- };
236
+ await postIntegration(baseCommit, outputCommit);
237
+ return deferCleanup(baseCommit, outputCommit);
208
238
  }
209
239
  await updateResultStatus(worktreeResultPath, "complete", completedAt);
210
240
  const baseCommit = gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim();
@@ -303,8 +333,8 @@ export async function finalizeRegisterWorktreeRun(params) {
303
333
  context: wtContext,
304
334
  worktree,
305
335
  taskId: stem,
306
- releasePaths: params.bookkeepingPaths,
307
- ownedPaths: params.bookkeepingPaths,
336
+ releasePaths: bookkeepingPaths,
337
+ ownedPaths: bookkeepingPaths,
308
338
  }),
309
339
  beforeProjectMerge: () => {
310
340
  // review は exec branch 側(worktree)で記録し、最後の project merge commit に
@@ -344,79 +374,49 @@ export async function finalizeRegisterWorktreeRun(params) {
344
374
  worktree,
345
375
  taskId: stem,
346
376
  message: mergeMessage,
347
- releaseRootPaths: [...params.bookkeepingPaths],
377
+ releaseRootPaths: [...bookkeepingPaths],
348
378
  // waiting を複数回経た項目では、wait 時の同期後も統合先と exec branch の双方で
349
379
  // 記帳ファイルが変わる。項目自身の記帳ファイルだけの競合は exec branch 側で解決する。
350
- resolveConflictsWithBranchPaths: [...params.bookkeepingPaths],
380
+ resolveConflictsWithBranchPaths: [...bookkeepingPaths],
351
381
  failureLogPath: integrateLogPath(params.pipelineStatePath),
352
382
  }),
353
383
  record: (repo, patch) => recordRepoIntegration(params.pipelineStatePath, repo, patch),
354
384
  failureLogPath: integrateLogPath(params.pipelineStatePath),
355
385
  lockPath: schedulePath,
356
386
  });
357
- // 撤去も統合の一部として扱う。merge 前に失敗した場合は waiting へ戻し、merge 後の撤去
358
- // だけが失敗した場合は review を維持して `--resume` で cleanup だけをやり直す。撤去後の
359
- // branch 削除だけが失敗した場合は、成果の統合を取り消さず cleanup 警告として扱う。
360
- removeWorktree({ context: wtContext, worktree, taskId: stem, deleteBranch: true });
361
387
  }
362
388
  catch (error) {
363
- if (error instanceof WorktreeRemovedBranchDeletionError) {
364
- // The task changes are already merged and the worktree is gone. Treat the integration as
365
- // complete while preserving an explicit cleanup warning in the run log.
366
- process.stderr.write(`Warning: ${error.message}; run exec worktree prune.\n`);
367
- }
368
- else {
369
- const reason = sanitizeRegisterConclusion(`integrate failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof UncommittedChangesError ? 4000 : undefined);
370
- const integrateFailedAt = new Date().toISOString();
371
- recordIntegrateStage(params.pipelineStatePath, integrateFailedAt, () => ({
372
- status: "failed",
373
- completed_at: integrateFailedAt,
374
- }));
375
- // The merge may already have succeeded and only worktree removal failed. Root now contains
376
- // the complete result and review transition; adding a wait commit would create a second
377
- // first-parent entry and a resume would create a third. Keep review intact and let
378
- // integration resume perform cleanup only.
379
- if (isExecBranchMergedIntoCurrent({ context: wtContext, worktree })) {
380
- rebuildRootRegisterViews(projectId, item.id);
381
- process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
382
- return {
383
- id: item.id,
384
- title: item.title,
385
- outcome: "failure",
386
- transition: "review",
387
- commit: "incomplete",
388
- reason,
389
- ...(error instanceof UncommittedChangesError
390
- ? { uncommittedFiles: error.files.length }
391
- : {}),
392
- };
393
- }
394
- await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
395
- process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
396
- const scopeError = error instanceof UncommittedChangesError;
397
- const summary = waitSummary(reason, scopeError ? 4000 : undefined);
398
- return {
399
- ...summary,
400
- commit: "incomplete",
401
- ...(scopeError ? { uncommittedFiles: error.files.length } : {}),
402
- };
389
+ // The merge may already have succeeded and only a later step failed. Root now contains the
390
+ // complete result and review transition; adding a wait commit would create a second
391
+ // first-parent entry and a resume would create a third. Keep review intact and let
392
+ // integration resume perform cleanup only.
393
+ if (isExecBranchMergedIntoCurrent({ context: wtContext, worktree })) {
394
+ await params.opts.onScopeIntegrated?.();
395
+ rebuildRootRegisterViews(projectId, item.id);
396
+ return blockedInReview(error, "integrate failed");
403
397
  }
398
+ const reason = sanitizeRegisterConclusion(`integrate failed: ${error instanceof Error ? error.message : String(error)}`, error instanceof UncommittedChangesError ? 4000 : undefined);
399
+ const integrateFailedAt = new Date().toISOString();
400
+ recordIntegrateStage(params.pipelineStatePath, integrateFailedAt, () => ({
401
+ status: "failed",
402
+ completed_at: integrateFailedAt,
403
+ }));
404
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
405
+ process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
406
+ const scopeError = error instanceof UncommittedChangesError;
407
+ const summary = waitSummary(reason, scopeError ? 4000 : undefined);
408
+ return {
409
+ ...summary,
410
+ commit: "incomplete",
411
+ ...(scopeError ? { uncommittedFiles: error.files.length } : {}),
412
+ };
404
413
  }
405
- // review は merge で root の個票に入る。非追跡の派生ビューだけ root で作り直す。
406
- rebuildRootRegisterViews(projectId, item.id);
407
414
  const outputCommit = gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim();
408
- const reviewed = await postReview(baseCommit, outputCommit);
409
- if (reviewed)
410
- return reviewed;
411
- const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
412
- process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
413
- return {
414
- id: item.id,
415
- title: item.title,
416
- outcome: "success",
417
- transition: "review",
418
- commit: `committed ${sha}`,
419
- };
415
+ await postIntegration(baseCommit, outputCommit);
416
+ await params.opts.onScopeIntegrated?.();
417
+ // post-review の差分範囲は、撤去を待つ間に別項目の commit が積まれても変わらないよう、
418
+ // merge の直後の HEAD で固定する。
419
+ return deferCleanup(baseCommit, outputCommit);
420
420
  }
421
421
  // 失敗 / rate limit: worktree は保持し(調査・再開のため)、waiting へ遷移する。
422
422
  const baseReason = params.runnerBlockReason
@@ -497,6 +497,19 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
497
497
  commit: "skipped",
498
498
  reason,
499
499
  };
500
+ // 前の run の統合の後の撤去がロックの外で進んでいる間は、同じ worktree を破棄しない。
501
+ if (isWorktreeCleanupInProgress(executionPath, worktreeTaskId)) {
502
+ const busy = worktreeCleanupInProgressReason(worktreeTaskId);
503
+ process.stderr.write(`${busy}\n`);
504
+ return {
505
+ id: item.id,
506
+ title: item.title,
507
+ outcome: "failure",
508
+ transition: "none",
509
+ commit: "off",
510
+ reason: sanitizeRegisterConclusion(busy),
511
+ };
512
+ }
500
513
  // executor が成功した run の worktree を、全体再実行が破棄しないよう保護する。
501
514
  // discardStaleExecWorktree は worktree と exec ブランチを強制削除するため、未コミットの
502
515
  // executor 成果が失われる。この場合は何も壊さずに中断し、再開か明示的な破棄を促す。
@@ -527,6 +540,7 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
527
540
  item,
528
541
  stem,
529
542
  });
543
+ appendScopeWaitNotes(planPath, opts.changeScopeWaits);
530
544
  const prompt = expandPromptRefs(readPlanFile(planPath));
531
545
  const { resultPath, supersededPaths } = await scaffoldResult({
532
546
  executionPath,
@@ -666,7 +680,8 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
666
680
  transitionReason = rateLimitRecoveryReason(outcome.rateLimitEvents) || undefined;
667
681
  }
668
682
  // Phase 3: 成果物統合と状態遷移(root で直列化)。通常実行と再開経路で共通化する。
669
- const finalize = async () => finalizeRegisterWorktreeRun({
683
+ // worktree の撤去は finalize がロックの外で行う。
684
+ return finalizeRegisterWorktreeRun({
670
685
  context,
671
686
  opts,
672
687
  registerPaths,
@@ -683,6 +698,6 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
683
698
  pipelineStatePath,
684
699
  runnerBlockReason: pipelineBlockReason,
685
700
  transitionReason,
701
+ lifecycleLock,
686
702
  });
687
- return lifecycleLock ? lifecycleLock.runExclusive(finalize) : finalize();
688
703
  }
@@ -1,21 +1,24 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { basename, join } from "node:path";
3
3
  import { createProviderCapacityTracker, loadExecDefaultsConfig } from "../agent-config.js";
4
4
  import { activateResolvedProjectPaths, resolveProjectPaths } from "../project.js";
5
5
  import { claimOwnerOf, readAllEventFiles, foldEventsToState } from "../events.js";
6
- import { buildScheduleIndex, findStaleGeneratedTracks } from "../schedule/schedule.js";
6
+ import { buildScheduleIndex, findEditedGeneratedTrackWarnings, findStaleGeneratedTracks, } from "../schedule/schedule.js";
7
7
  import { buildInitialStateFromStrategy } from "../schedule/initial.js";
8
8
  import { scheduleTrackNames } from "../schedule/gantt-chart-scope.js";
9
9
  import { readReadySnapshot } from "../schedule/ready.js";
10
10
  import { specdojoRootDir } from "../../shared/specdojo-config.js";
11
11
  import { extractLocalId, extractPhaseSuffix } from "../../schedule/phase-sets.js";
12
12
  import { resolveWorktreeBase } from "../worktree.js";
13
- import { buildPhaseModeIndex, resolveAgentAssignment, resolveAgentPipeline, resolveApproach, resolveTaskCapabilities, resolveTaskExecution, resolveTaskMode, resolveTaskProficiency, } from "../strategy.js";
13
+ import { buildPhaseModeIndex, resolveAgentPipeline, resolveApproach, resolveScheduledTaskAgent, resolveTaskCapabilities, resolveTaskExecution, resolveTaskMode, resolveTaskProficiency, } from "../strategy.js";
14
14
  import { SerialAsyncLock, buildTaskPhaseMap, configuredWorktreeBase, parseParallel, resolveExecDefaultsPath, runCompletionDrivenWorkerPool, } from "./shared.js";
15
15
  import { loadRosterForExecutionPath } from "./agent.js";
16
16
  import { prepareSingleTask } from "./schedule-prepare.js";
17
17
  import { runPreparedTask, runPreparedTaskSafely, } from "./schedule-task.js";
18
18
  import { spawnIndexBuild, spawnRefresh, spawnScheduleBuild } from "./mode-shared.js";
19
+ import { ChangeScopeGate, inferChangeScope, parseUnknownScopePolicy, scopePlanMetadata, } from "./change-scope.js";
20
+ import { targetDocIdsForScheduledTask } from "../plans.js";
21
+ import { findRunRecord } from "../run-records.js";
19
22
  // Rebuild only generated tracks whose strategy input is missing a generated track or has a newer
20
23
  // mtime. The same structured detector feeds exec validate warnings, keeping manual validation and
21
24
  // cycle automation on one freshness rule. No output is emitted when every track is fresh.
@@ -61,6 +64,11 @@ export async function runBatchMode(opts) {
61
64
  throw new Error(`Unknown schedule track: ${track}. Available tracks: ${tracks.join(", ")}`);
62
65
  }
63
66
  }
67
+ // A directly edited track only warns: runs resolve agents from the strategy regardless, and the
68
+ // same difference also appears after a catalog change that has not been rebuilt yet.
69
+ for (const warning of findEditedGeneratedTrackWarnings(schedulePath, repoRoot)) {
70
+ process.stdout.write(`[run] WARN: ${warning}\n`);
71
+ }
64
72
  const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
65
73
  const roster = loadRosterForExecutionPath(executionPath);
66
74
  const { localIdToPhaseSets, phaseSetSuffixToId } = buildTaskPhaseMap(schedulePath);
@@ -69,6 +77,12 @@ export async function runBatchMode(opts) {
69
77
  const maxRounds = opts.maxRounds ? Math.max(1, parseInt(opts.maxRounds, 10) || 1) : null;
70
78
  const dryRun = !!opts.dryRun;
71
79
  const strategy = opts.strategy ?? "critical-first";
80
+ const scopeGate = new ChangeScopeGate(executionPath, parseUnknownScopePolicy(opts.unknownScope));
81
+ const scopeLeases = new Map();
82
+ const attempted = new Set();
83
+ // A non-loop run still launches at most --parallel tasks, but defers overlapping preparation
84
+ // until a prior task integrates instead of forking both worktrees from the same HEAD.
85
+ let batchBudget = parallel;
72
86
  const prepareReadyTasks = async (capacity, limit) => {
73
87
  if (!existsSync(readyJsonPath)) {
74
88
  process.stdout.write(`ready.json not found: ${readyJsonPath}\nRun: specdojo exec refresh\n`);
@@ -95,29 +109,70 @@ export async function runBatchMode(opts) {
95
109
  return { preparedTasks: [], readyCount: 0 };
96
110
  const preparedTasks = [];
97
111
  for (const taskId of orderedIds) {
98
- if (preparedTasks.length >= limit)
112
+ if (preparedTasks.length >= limit || (!loop && batchBudget <= 0))
99
113
  break;
100
114
  const task = taskMap.get(taskId);
101
- if (!task)
115
+ if (!task || attempted.has(taskId) || scopeLeases.has(taskId))
102
116
  continue;
117
+ let lease;
103
118
  try {
104
- const prepared = await prepareSingleTask(task, projectId, repoRoot, schedulePath, executionPath, roster, localIdToPhaseSets, phaseSetSuffixToId, opts.by, { edit: opts.editBy, review: opts.reviewBy }, { executor: opts.executorBy, reporter: opts.reporterBy }, opts.by, dryRun, false, worktreeBase, planGenPaths, execDefaults, capacity.hasCapacity, undefined, opts);
119
+ if (!dryRun) {
120
+ const planPath = findRunRecord(executionPath, "plan", taskId);
121
+ const plan = planPath ? readFileSync(planPath, "utf8") : "";
122
+ const metadata = scopePlanMetadata(plan);
123
+ const scope = inferChangeScope({
124
+ targets: [
125
+ ...new Set([
126
+ ...(metadata.targets ?? []),
127
+ ...(targetDocIdsForScheduledTask(catalogPath ?? "", task, projectId ?? "") ?? []),
128
+ ]),
129
+ ],
130
+ approach: task.approach ?? metadata.approach,
131
+ text: plan,
132
+ projectId: projectId ?? "",
133
+ repoRoot,
134
+ catalogPath,
135
+ schedulePath,
136
+ });
137
+ const acquired = await scopeGate.tryAcquire(taskId, scope);
138
+ if (!acquired)
139
+ continue;
140
+ lease = acquired;
141
+ }
142
+ const prepared = await prepareSingleTask(task, projectId, repoRoot, schedulePath, executionPath, roster, localIdToPhaseSets, phaseSetSuffixToId, opts.by, { edit: opts.editBy, review: opts.reviewBy }, { executor: opts.executorBy, reporter: opts.reporterBy }, opts.by, dryRun, false, worktreeBase, planGenPaths, execDefaults, capacity.hasCapacity, undefined, { ...opts, changeScopeWaits: lease?.waits });
105
143
  // "deferred": every candidate provider is at its cap; try it again after a slot frees.
106
- if (prepared === "deferred")
144
+ if (prepared === "deferred") {
145
+ await lease?.finish(true);
107
146
  continue;
147
+ }
148
+ attempted.add(taskId);
108
149
  if (typeof prepared !== "string") {
109
150
  preparedTasks.push(prepared);
151
+ if (lease) {
152
+ const reserved = lease;
153
+ scopeLeases.set(taskId, reserved);
154
+ prepared.onScopeIntegrated = () => reserved.finish(true);
155
+ }
110
156
  capacity.reserve(prepared.agentCandidates[0]?.provider);
157
+ batchBudget--;
158
+ }
159
+ else {
160
+ await lease?.finish(prepared === "success");
161
+ if (prepared === "failure")
162
+ process.exitCode = 1;
111
163
  }
112
164
  }
113
165
  catch (error) {
166
+ attempted.add(taskId);
167
+ await lease?.finish(false);
114
168
  const message = error instanceof Error ? error.message : String(error);
115
169
  process.stderr.write(`[run] setup error for ${task.id}: ${message}\n`);
170
+ process.exitCode = 1;
116
171
  }
117
172
  }
118
173
  return { preparedTasks, readyCount: orderedIds.length };
119
174
  };
120
- if (!loop || dryRun) {
175
+ if (dryRun) {
121
176
  const capacity = createProviderCapacityTracker(execDefaults);
122
177
  const { preparedTasks, readyCount } = await prepareReadyTasks(capacity, parallel);
123
178
  if (preparedTasks.length === 0) {
@@ -142,14 +197,16 @@ export async function runBatchMode(opts) {
142
197
  const scheduleAvailable = async (openSlots) => {
143
198
  if (stopNewTasks || openSlots <= 0)
144
199
  return [];
145
- if (maxRounds !== null && schedulingPass >= maxRounds) {
200
+ if (!loop && batchBudget <= 0)
201
+ return [];
202
+ if (loop && maxRounds !== null && schedulingPass >= maxRounds) {
146
203
  process.stdout.write(`[run] reached max-rounds ${maxRounds} — drain running tasks\n`);
147
204
  stopNewTasks = true;
148
205
  return [];
149
206
  }
150
207
  schedulingPass++;
151
208
  const roundSuffix = ` (round ${schedulingPass}${maxRounds !== null ? `/${maxRounds}` : "/-"})`;
152
- if (schedulingPass > 1) {
209
+ if (loop && schedulingPass > 1) {
153
210
  // Rebuild doc-index before refresh so deliverables created by the previous round (e.g. a
154
211
  // newly authored document referenced by wikilink) are resolvable when this round's tasks
155
212
  // are prepared, instead of only becoming resolvable on a later, out-of-band index build.
@@ -187,7 +244,9 @@ export async function runBatchMode(opts) {
187
244
  maxParallel: parallel,
188
245
  fillSlots: (openSlots) => lifecycleLock.runExclusive(() => scheduleAvailable(openSlots)),
189
246
  runItem: (prepared) => runPreparedTaskSafely(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun, lifecycleLock),
190
- onSettled: (prepared, outcome) => {
247
+ onSettled: async (prepared, outcome) => {
248
+ await scopeLeases.get(prepared.task.id)?.finish(outcome.result === "success");
249
+ scopeLeases.delete(prepared.task.id);
191
250
  capacity.release(prepared.agentCandidates[0]?.provider);
192
251
  if (outcome.result === "failure")
193
252
  process.exitCode = 1;
@@ -279,9 +338,11 @@ export async function runManualMode(opts) {
279
338
  task.agent_pipeline =
280
339
  task.agent_pipeline ??
281
340
  resolveAgentPipeline(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
282
- task.agent =
283
- task.agent ??
284
- resolveAgentAssignment(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
341
+ const agent = resolveScheduledTaskAgent(task, phaseModeIndex);
342
+ if (agent === undefined)
343
+ delete task.agent;
344
+ else
345
+ task.agent = agent;
285
346
  }
286
347
  // If the task is already in "doing" state and --by is not specified,
287
348
  // use the actor who claimed it and their command to avoid re-selecting a different agent.
@@ -1,4 +1,5 @@
1
1
  import { withPlanConventionsFiles } from "../../shared/plan-conventions.js";
2
+ import { appendScopeWaitNotes } from "./change-scope.js";
2
3
  import { existsSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
  import { ensureReviewGrade, reviewGradeFreshness, } from "../../review/grade.js";
@@ -348,6 +349,8 @@ export async function prepareSingleTask(task, projectId, repoRoot, schedulePath,
348
349
  task,
349
350
  ...(reviewGradeOutcome ? { reviewGradeOutcome } : {}),
350
351
  });
352
+ if (!dryRun)
353
+ appendScopeWaitNotes(recordPathForRead(executionPath, "plan", task.id), rateLimitOverrides.changeScopeWaits);
351
354
  const planPrompt = loadPrompt(executionPath, task.id);
352
355
  if (!planPrompt) {
353
356
  process.stdout.write(` Plan not found for ${task.id}.\n`);