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
@@ -1,21 +1,38 @@
1
1
  import { relative, resolve, sep } from "node:path";
2
+ import { ChangeScopeGate } from "./change-scope.js";
2
3
  import { enforceExecutorReportContract, executorStageResumeHint, recordExecutorEvidence, recordReporterFailureOutput, writeExecutorEvidence, } from "../evidence.js";
3
4
  import { integrationCommitSkipHooks } from "../commit-hook-skips.js";
5
+ import { integratedCommitRange, runPostIntegration } from "../post-integration.js";
4
6
  import { reviewTaskBlockReason } from "../review-completion.js";
5
7
  import { limitEventMeta } from "../limit.js";
6
8
  import { createPipelineState, loadPipelineResumeCheckpoint, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "../pipeline-state.js";
7
9
  import { commitProductWorktrees, integrateTaskRepositories, PROJECT_REPO_NAME, projectMergeBlockers, RepoIntegrationError, } from "../repo-integration.js";
8
10
  import { deriveReporterFacts, evidenceForReporter, runReporterWithFormatRetry, } from "../reporter.js";
9
11
  import { readResultFrontmatterSnapshot, renderReporterResult, updateResultStatus, } from "../results.js";
10
- import { recordPathForRead, snapshotRunAttempt } from "../run-records.js";
12
+ import { recordPathForRead, runLogPath, snapshotRunAttempt, taskRecordPaths, } from "../run-records.js";
11
13
  import { withProductRepoPrompt } from "../task-repos.js";
12
14
  import { branchOwnedRunRecordPaths } from "../trailing-records.js";
13
15
  import { assertCommitScope, commitTargetPaths, commitWorktreeChanges, isExecBranchMergedIntoCurrent, mergeWorktreeIntoCurrent, releaseRootWorkingCopies, removeWorktree, taskTargetsAtHead, WorktreeRemovedBranchDeletionError, worktreeStatusPaths, } from "../worktree-ops.js";
14
16
  import { gitOutput } from "../worktree.js";
15
17
  import { refreshParentValidationsForReporterResume } from "./agent-pipeline.js";
18
+ import { DeferredCleanup, runWithDeferredCleanup } from "./deferred-cleanup.js";
16
19
  import { agentEnvironment, appendParentValidationsToExecutorEvidence, buildExecutorPrompt, extractBlockReason, pathInsideWorktree, resumedTargetCoverageFailure, runWithRetry, } from "./agent.js";
17
20
  import { commitSubject, integrateLogPath, pipelineRecoveryMeta, recordIntegrateStage, recordRepoIntegration, repoRelativePath, spawnBlock, spawnComplete, stageActorMeta, } from "./mode-shared.js";
18
21
  import { downgradeUnfilledResult, enforceScheduleKataReview, readCompletionPreflight, } from "./schedule-prepare.js";
22
+ import { execLifecyclePoolPath } from "./lock.js";
23
+ import { CrossProcessMutex } from "../../shared/cross-process-lock.js";
24
+ // 統合の段(commit・merge・記帳)は root の index と HEAD を書き換える。register ... --commit と
25
+ // specdojo git -- commit は project の lifecycle ロックの下で stage・commit(hook を含む)を行う。
26
+ // 統合も同じロックを取り、記帳の commit の途中に stage 済みのファイルを stagedMergeBlocker で
27
+ // 拒否しない(PJR-Y3XS)。プロセス内の直列化(schedule の準備との排他)は外側の lock が担う。
28
+ export function withExecLifecycleMutex(inner, executionPath, owner) {
29
+ const mutex = new CrossProcessMutex(execLifecyclePoolPath(executionPath), owner, {
30
+ onWait: () => process.stdout.write(" Waiting for the register lifecycle lock held by another operation\n"),
31
+ });
32
+ return {
33
+ runExclusive: (fn) => inner ? inner.runExclusive(() => mutex.runExclusive(fn)) : mutex.runExclusive(fn),
34
+ };
35
+ }
19
36
  export async function runPreparedTask(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun, lifecycleLock) {
20
37
  if (dryRun)
21
38
  return "success";
@@ -291,7 +308,7 @@ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePat
291
308
  evidence: reporterEvidence,
292
309
  mode: prepared.task.mode ?? "edit",
293
310
  invoke: async (reporterPrompt) => {
294
- const outcome = await runWithRetry(prepared.reporterCandidates ?? [], reporterPrompt, execDefaults, prepared.worktree.path, agentEnvironment(repoRoot, prepared.worktree.path, schedulePath, executionPath, prepared.worktree.repos), worktreeResultPath, prepared.reporterRateLimitOptions);
311
+ const outcome = await runWithRetry(prepared.reporterCandidates ?? [], reporterPrompt, execDefaults, prepared.worktree.path, agentEnvironment(repoRoot, prepared.worktree.path, schedulePath, executionPath, prepared.worktree.repos), worktreeResultPath, prepared.reporterRateLimitOptions, "reporter");
295
312
  reporterAttempts += outcome.attempts;
296
313
  reporterActor = outcome.actor ?? reporterActor;
297
314
  reporterRateLimitEvents.push(...outcome.rateLimitEvents);
@@ -420,6 +437,31 @@ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePat
420
437
  process.stdout.write(` Blocked before integration: ${prepared.task.id} (worktree kept: ${prepared.worktree.path})\n`);
421
438
  return "failure";
422
439
  }
440
+ // 統合の段の失敗を block として記帳する。merge の前の失敗と、merge の後の撤去の失敗で共通。
441
+ const blockIntegration = async (error) => {
442
+ const reason = integrationBlockReason(prepared.task.id, error instanceof Error ? error.message : String(error), prepared.worktree.path);
443
+ const integrateFailedAt = new Date().toISOString();
444
+ recordIntegrateStage(pipelineStatePath, integrateFailedAt, () => ({
445
+ status: "failed",
446
+ completed_at: integrateFailedAt,
447
+ }));
448
+ if (worktreeResultPath)
449
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
450
+ spawnBlock(projectId, prepared.task.id, prepared.claimActor, reason, {
451
+ ...(pipelineStateRef
452
+ ? pipelineRecoveryMeta({
453
+ stage: "integrate",
454
+ evidenceRef: executorEvidenceRef,
455
+ stateRef: pipelineStateRef,
456
+ runId: pipelineState?.run_id ?? prepared.pipelineRunId,
457
+ })
458
+ : { limit_deferred: "false" }),
459
+ ...stageActorMeta(prepared.claimActor, prepared.actor),
460
+ });
461
+ process.stderr.write(`${reason}\n`);
462
+ process.stdout.write(` Blocked: ${prepared.task.id} (worktree kept: ${prepared.worktree.path})\n`);
463
+ return "failure";
464
+ };
423
465
  // A previous attempt may have merged successfully and failed only while removing the
424
466
  // worktree. In that case the branch is already contained in HEAD: do not create another
425
467
  // commit or merge. Discard only runner-owned lifecycle diffs left by the failure handler,
@@ -454,6 +496,13 @@ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePat
454
496
  // of the checkpoint files so they do not linger as reverse diffs.
455
497
  releaseRootWorkingCopies(repoRoot, (prepared.checkpointPaths ?? []).map((path) => repoRelativePath(repoRoot, path)));
456
498
  process.stdout.write(` [integrate] already merged: ${prepared.worktree.branch} (skipping commit and merge)\n`);
499
+ await runPostIntegration({
500
+ entries: execDefaults.pipeline?.post_integration,
501
+ repoRoot,
502
+ ...integratedCommitRange(repoRoot, prepared.worktree.branch),
503
+ logPath: runLogPath(prepared.resultPath ??
504
+ taskRecordPaths(executionPath, prepared.task.id, prepared.pipelineRunId).result, "post-integration.log"),
505
+ });
457
506
  }
458
507
  else {
459
508
  // Record completion and integration start before the first commit. The succeeded state
@@ -511,6 +560,7 @@ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePat
511
560
  pending: [...productNames, PROJECT_REPO_NAME],
512
561
  });
513
562
  }
563
+ const baseCommit = gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim();
514
564
  integrateTaskRepositories({
515
565
  worktree: prepared.worktree,
516
566
  mergeMessage,
@@ -560,47 +610,44 @@ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePat
560
610
  failureLogPath: integrateLogPath(pipelineStatePath),
561
611
  lockPath: schedulePath,
562
612
  });
613
+ await runPostIntegration({
614
+ entries: execDefaults.pipeline?.post_integration,
615
+ repoRoot,
616
+ baseCommit,
617
+ outputCommit: gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim(),
618
+ logPath: runLogPath(prepared.resultPath ??
619
+ taskRecordPaths(executionPath, prepared.task.id, prepared.pipelineRunId).result, "post-integration.log"),
620
+ });
563
621
  }
564
- removeWorktree({
565
- context,
566
- worktree: prepared.worktree,
567
- taskId: prepared.task.id,
568
- deleteBranch: true,
569
- });
570
622
  }
571
623
  catch (error) {
572
- if (error instanceof WorktreeRemovedBranchDeletionError) {
624
+ if (isExecBranchMergedIntoCurrent({ context, worktree: prepared.worktree })) {
625
+ await prepared.onScopeIntegrated?.();
626
+ await new ChangeScopeGate(executionPath).clearIntegrated(prepared.task.id);
627
+ }
628
+ return blockIntegration(error);
629
+ }
630
+ await prepared.onScopeIntegrated?.();
631
+ await new ChangeScopeGate(executionPath).clearIntegrated(prepared.task.id);
632
+ // PJR-NHT7: 撤去はロックの外で行い、完了の記帳はロックを取り直して行う。
633
+ return new DeferredCleanup(() => removeWorktree({
634
+ context,
635
+ worktree: prepared.worktree,
636
+ taskId: prepared.task.id,
637
+ deleteBranch: true,
638
+ }), async (outcome) => {
639
+ if (!outcome.ok) {
640
+ if (!(outcome.error instanceof WorktreeRemovedBranchDeletionError)) {
641
+ return blockIntegration(outcome.error);
642
+ }
573
643
  // The task changes are already merged and the worktree is gone. Keep task completion
574
644
  // independent from branch housekeeping, but make the residue and recovery command clear.
575
- process.stderr.write(`Warning: ${error.message}; run exec worktree prune.\n`);
576
- }
577
- else {
578
- const reason = integrationBlockReason(prepared.task.id, error instanceof Error ? error.message : String(error), prepared.worktree.path);
579
- const integrateFailedAt = new Date().toISOString();
580
- recordIntegrateStage(pipelineStatePath, integrateFailedAt, () => ({
581
- status: "failed",
582
- completed_at: integrateFailedAt,
583
- }));
584
- if (worktreeResultPath)
585
- await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
586
- spawnBlock(projectId, prepared.task.id, prepared.claimActor, reason, {
587
- ...(pipelineStateRef
588
- ? pipelineRecoveryMeta({
589
- stage: "integrate",
590
- evidenceRef: executorEvidenceRef,
591
- stateRef: pipelineStateRef,
592
- runId: pipelineState?.run_id ?? prepared.pipelineRunId,
593
- })
594
- : { limit_deferred: "false" }),
595
- ...stageActorMeta(prepared.claimActor, prepared.actor),
596
- });
597
- process.stderr.write(`${reason}\n`);
598
- process.stdout.write(` Blocked: ${prepared.task.id} (worktree kept: ${prepared.worktree.path})\n`);
599
- return "failure";
645
+ process.stderr.write(`Warning: ${outcome.error.message}; run exec worktree prune.\n`);
600
646
  }
601
- }
602
- spawnComplete(projectId, prepared.task.id, prepared.claimActor);
603
- process.stdout.write(` Done: ${prepared.task.id}\n`);
647
+ spawnComplete(projectId, prepared.task.id, prepared.claimActor);
648
+ process.stdout.write(` Done: ${prepared.task.id}\n`);
649
+ return "success";
650
+ });
604
651
  }
605
652
  else if (effectiveResult === "rate_limit") {
606
653
  // Keep the worktree for the due-time resume path; do not merge partial changes.
@@ -667,7 +714,10 @@ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePat
667
714
  }
668
715
  return effectiveResult;
669
716
  };
670
- return lifecycleLock ? lifecycleLock.runExclusive(finalize) : finalize();
717
+ return runWithDeferredCleanup(withExecLifecycleMutex(lifecycleLock, executionPath, {
718
+ actor: prepared.claimActor,
719
+ label: `integrate ${prepared.task.id}`,
720
+ }), finalize);
671
721
  }
672
722
  // 統合の段の失敗の理由(検査の名前・commit の対象外のパス・merge の失敗など、失敗した操作の
673
723
  // メッセージ)に、worktree の成果を保ったまま続ける次の操作を足す。block の理由と result の
@@ -243,6 +243,10 @@ export function selectCandidates(requirements, roster, taskMode, busyActors, exe
243
243
  // are skipped during auto-selection.
244
244
  if (m.disabled === true)
245
245
  return false;
246
+ // Opt-in tier: never enter an automatic primary/fallback pool implicitly, even when
247
+ // every ordinary member is busy. Named selections resolve outside this function.
248
+ if (m.proficiency === "frontier" && proficiency !== "frontier")
249
+ return false;
246
250
  const caps = m.capabilities ?? [];
247
251
  if (!required.every((c) => caps.includes(c)))
248
252
  return false;
@@ -415,6 +419,7 @@ export async function withProjectExecRunLock(opts, commandLabel, action, sharing
415
419
  const handle = await acquireExecRunLock(resolvedPaths.executionPath, {
416
420
  actor: opts.by ?? `exec-${commandLabel}`,
417
421
  ifBusy: policy,
422
+ waitTimeoutMs: opts.lockWaitMs,
418
423
  shareable: sharing.shareable || sharing.join,
419
424
  ...(sharing.join ? { join: { limit: joinLimit } } : {}),
420
425
  onWait: () => process.stdout.write(sharing.join
@@ -1,7 +1,7 @@
1
1
  import { existsSync, statSync, writeFileSync } from "node:fs";
2
2
  import { basename, extname, join } from "node:path";
3
3
  import { computeReadyIds, foldEventsToState, isExecEventV1, validateEventShape, } from "../events.js";
4
- import { ensureDir, formatDays, listFilesRecursive, readJson, toArtifactPath, toScheduleFilePath, writeJson, } from "../shared.js";
4
+ import { ensureDir, formatDays, listFilesRecursive, readJson, readYaml, toArtifactPath, toScheduleFilePath, writeJson, } from "../shared.js";
5
5
  import { eventsDirForProject, executionRootForProject, generatedDirForProject, } from "../project.js";
6
6
  import { buildGanttChartMarkdown, buildGanttChartSvg, buildProgressSummaryLines, } from "./gantt-chart.js";
7
7
  import { buildScheduleIndex } from "./index.js";
@@ -10,7 +10,9 @@ import { computeCpm, topoSort } from "./cpm.js";
10
10
  import { buildReadySnapshot, orderReadyIds, writeReadyFiles, selectNextTask } from "./ready.js";
11
11
  import { writeScheduleHashAndDiff } from "./hash.js";
12
12
  import { buildInitialStateFromStrategy } from "./initial.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
+ import { buildScheduleTrack } from "../../schedule/build.js";
15
+ import { specdojoRootDir } from "../../shared/specdojo-config.js";
14
16
  export function findStaleGeneratedTracks(projectPath) {
15
17
  const files = listFilesRecursive(projectPath);
16
18
  const trackFiles = new Map();
@@ -43,6 +45,113 @@ export function findStaleGeneratedTrackWarnings(projectPath) {
43
45
  : `${basename(stale.strategyFile)} is newer than ${basename(stale.trackFile)}. ` +
44
46
  `Run: specdojo schedule build --track ${stale.track} --force before exec refresh.`);
45
47
  }
48
+ function normalizeYamlValue(value) {
49
+ return JSON.parse(JSON.stringify(value ?? null));
50
+ }
51
+ function asRecordList(value) {
52
+ if (!Array.isArray(value))
53
+ return [];
54
+ return value.filter((item) => typeof item === "object" && item !== null && !Array.isArray(item));
55
+ }
56
+ // Phase tasks carry no explicit id in the track; identify them the same way the schedule index
57
+ // does (local_id + phase suffix), qualified by phase set and cycle so repeated phases stay apart.
58
+ function taskKey(task, index) {
59
+ if (typeof task.id === "string" && task.id)
60
+ return task.id;
61
+ if (typeof task.local_id !== "string" || !task.local_id)
62
+ return `tasks[${index}]`;
63
+ const parts = [`${task.local_id}-${String(task.phase_suffix ?? "")}`];
64
+ if (task.phase_set !== undefined)
65
+ parts.push(`phase_set=${String(task.phase_set)}`);
66
+ if (task.cycle !== undefined)
67
+ parts.push(`cycle=${String(task.cycle)}`);
68
+ if (task.iteration !== undefined)
69
+ parts.push(`iteration=${String(task.iteration)}`);
70
+ return parts.join(" ");
71
+ }
72
+ function diffTrackTasks(generated, actual) {
73
+ const expectedTasks = new Map(asRecordList(generated).map((t, i) => [taskKey(t, i), t]));
74
+ const actualTasks = new Map(asRecordList(actual).map((t, i) => [taskKey(t, i), t]));
75
+ const differences = [];
76
+ const ids = [...new Set([...expectedTasks.keys(), ...actualTasks.keys()])].sort();
77
+ for (const id of ids) {
78
+ const expected = expectedTasks.get(id);
79
+ const current = actualTasks.get(id);
80
+ if (!current) {
81
+ differences.push(`${id}: missing`);
82
+ continue;
83
+ }
84
+ if (!expected) {
85
+ differences.push(`${id}: not generated`);
86
+ continue;
87
+ }
88
+ const fields = [...new Set([...Object.keys(expected), ...Object.keys(current)])].sort();
89
+ for (const field of fields) {
90
+ if (JSON.stringify(expected[field]) !== JSON.stringify(current[field])) {
91
+ differences.push(`${id}: ${field}`);
92
+ }
93
+ }
94
+ }
95
+ return differences;
96
+ }
97
+ // Detect generated tracks whose content no longer matches what `schedule build` would produce from
98
+ // the strategy (and catalogs), such as a direct edit of the track. Tracks that are missing or older
99
+ // than their strategy are reported by findStaleGeneratedTracks instead, and a strategy that cannot be
100
+ // built is left to `schedule build` to report, so this detector never duplicates those messages.
101
+ export function findEditedGeneratedTracks(projectPath, baseDir = specdojoRootDir()) {
102
+ const staleTracks = new Set(findStaleGeneratedTracks(projectPath).map((stale) => stale.track));
103
+ const files = listFilesRecursive(projectPath);
104
+ const trackFiles = new Map();
105
+ for (const file of files) {
106
+ const match = basename(file).match(/^sch-track-(.+)\.yaml$/);
107
+ if (match)
108
+ trackFiles.set(match[1], file);
109
+ }
110
+ const edited = [];
111
+ for (const strategyFile of files) {
112
+ const match = basename(strategyFile).match(/^sch-strategy-(.+)\.yaml$/);
113
+ if (!match)
114
+ continue;
115
+ const track = match[1];
116
+ const trackFile = trackFiles.get(track);
117
+ if (!trackFile || staleTracks.has(track))
118
+ continue;
119
+ let generated;
120
+ try {
121
+ generated = buildScheduleTrack(strategyFile, baseDir);
122
+ }
123
+ catch {
124
+ continue;
125
+ }
126
+ if (generated.errors.length > 0)
127
+ continue;
128
+ const actual = readYaml(trackFile);
129
+ if (typeof actual !== "object" || actual === null || Array.isArray(actual))
130
+ continue;
131
+ const actualDoc = actual;
132
+ const differences = diffTrackTasks(normalizeYamlValue(generated.tasks), actualDoc.tasks);
133
+ const expectedSettings = generated.startDate !== null ? { start_date: generated.startDate } : {};
134
+ if (JSON.stringify(normalizeYamlValue(expectedSettings)) !==
135
+ JSON.stringify(normalizeYamlValue(actualDoc.settings ?? {}))) {
136
+ differences.push("settings");
137
+ }
138
+ if (differences.length > 0)
139
+ edited.push({ track, strategyFile, trackFile, differences });
140
+ }
141
+ return edited.sort((a, b) => a.track.localeCompare(b.track));
142
+ }
143
+ const MAX_REPORTED_TRACK_DIFFERENCES = 10;
144
+ export function findEditedGeneratedTrackWarnings(projectPath, baseDir = specdojoRootDir()) {
145
+ return findEditedGeneratedTracks(projectPath, baseDir).map((edited) => {
146
+ const shown = edited.differences.slice(0, MAX_REPORTED_TRACK_DIFFERENCES);
147
+ const rest = edited.differences.length - shown.length;
148
+ return (`${basename(edited.trackFile)} (track ${edited.track}) differs from the result rebuilt from ` +
149
+ `${basename(edited.strategyFile)} (direct edit, or a catalog change not rebuilt yet; ` +
150
+ `change the strategy instead of the track): ` +
151
+ `${shown.join(", ")}${rest > 0 ? ` (+${rest} more)` : ""}. ` +
152
+ `Run: specdojo schedule build --track ${edited.track} --force`);
153
+ });
154
+ }
46
155
  export function validateAll(projectPath) {
47
156
  const errors = [];
48
157
  const warnings = [];
@@ -52,6 +161,7 @@ export function validateAll(projectPath) {
52
161
  warnings.push(`No schedule nodes loaded from sch-*.yaml under: ${projectPath}`);
53
162
  }
54
163
  warnings.push(...findStaleGeneratedTrackWarnings(projectPath));
164
+ warnings.push(...findEditedGeneratedTrackWarnings(projectPath));
55
165
  for (const node of schedule.nodes.values()) {
56
166
  for (const dep of node.depends_on) {
57
167
  if (!schedule.nodes.has(dep)) {
@@ -238,8 +348,10 @@ export function writeGeneratedCore(projectPath, events, schedule, cpm) {
238
348
  const agentPipeline = resolveAgentPipeline(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
239
349
  if (agentPipeline !== undefined)
240
350
  task.agent_pipeline = agentPipeline;
241
- const agent = resolveAgentAssignment(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
242
- if (agent !== undefined)
351
+ const agent = resolveScheduledTaskAgent(task, phaseModeIndex);
352
+ if (agent === undefined)
353
+ delete task.agent;
354
+ else
243
355
  task.agent = agent;
244
356
  }
245
357
  writeReadyFiles(projectPath, readySnapshot);
@@ -1,11 +1,11 @@
1
1
  export { toArtifactPath, toPortablePath } from "../shared/artifact-path.js";
2
2
  export { ensureDir, listFilesRecursive, readJson, readYaml, writeJson } from "../shared/fs.js";
3
- export { displayWidth, escapeMarkdownInline, expandTemplate, inlineCodeAnglePlaceholders, padEndDisplay, redactSensitiveText, stripTerminalControlSequences, } from "../shared/text.js";
3
+ export { displayWidth, escapeMarkdownInline, expandTemplate, inlineCodeAnglePlaceholders, inlineCodeFrontmatterAnglePlaceholders, padEndDisplay, redactSensitiveText, stripTerminalControlSequences, } from "../shared/text.js";
4
4
  export { formatDateOnlyUtc, isUtcIsoSeconds, normalizeDateOnly, nowUtcIsoSeconds, } from "../shared/time.js";
5
5
  export { randomHex } from "../shared/random.js";
6
6
  export { isSchYamlFilename, toScheduleFilePath } from "../shared/schedule-paths.js";
7
7
  export function tsForFilenameUtc(ts) {
8
- return ts.replace(/[-:]/g, "").replace("T", "T");
8
+ return ts.replace(/[-:]/g, "");
9
9
  }
10
10
  // worktree/branch 生成専用。project 修飾した task ID(`<projectId>:<taskId>`)を返す。
11
11
  // projectId が未解決(env path override 等)の場合は bare のままにして後方互換を保つ。
@@ -0,0 +1,190 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { atomicWriteFile, registerEventActor } from "../register/core.js";
4
+ import { readRegisterEventsFromContent, registerEventFilePath, } from "../register/events.js";
5
+ import { resolveRegisterPaths, runRegisterMutationInCurrentWorktree, } from "../register/register.js";
6
+ import { loadItemForUpdate } from "../register/update.js";
7
+ import { CrossProcessMutex } from "../shared/cross-process-lock.js";
8
+ import { loadExecDefaultsConfig } from "./agent-config.js";
9
+ import { resolveProjectPaths } from "./project.js";
10
+ import { normalizePjrId, parseRegisterIds, requireRunnableRegisterItem } from "./register.js";
11
+ import { loadRosterForExecutionPath } from "./run/agent.js";
12
+ import { spawnSelf } from "./run/mode-shared.js";
13
+ import { resolveRegisterPipelineCommand } from "./run/register-core.js";
14
+ import { resolveExecDefaultsPath } from "./run/shared.js";
15
+ // New tickets delimit the list explicitly. The legacy JSEY completion condition remains usable.
16
+ export function appendSmokeTargets(content, targets) {
17
+ const marked = /<!-- specdojo:smoke-targets -->[\s\S]*?<!-- \/specdojo:smoke-targets -->/g;
18
+ const legacy = /(PJR-[0-9A-Z]{4}(?:・PJR-[0-9A-Z]{4})*)(?=のうち)/g;
19
+ const markedLists = [...content.matchAll(marked)];
20
+ const lists = markedLists.length ? markedLists : [...content.matchAll(legacy)];
21
+ if (lists.length !== 1)
22
+ throw new Error("Expected one smoke target list; delimit it with <!-- specdojo:smoke-targets --> and <!-- /specdojo:smoke-targets -->");
23
+ const match = lists[0];
24
+ const list = match[0];
25
+ const existing = new Set(list.match(/PJR-[0-9A-Z]{4}/g) ?? []);
26
+ const added = [...new Set(targets)].filter((id) => !existing.has(id));
27
+ if (!added.length)
28
+ return content;
29
+ const updated = markedLists.length
30
+ ? list.replace(/\s*<!-- \/specdojo:smoke-targets -->$/, `\n${added.join("・")}\n<!-- /specdojo:smoke-targets -->`)
31
+ : list.slice(0, -1) + "・" + added.join("・") + ")";
32
+ return content.slice(0, match.index) + updated + content.slice(match.index + list.length);
33
+ }
34
+ export function verifySmokeEvents(before, after, actor) {
35
+ if (before.some((event, index) => JSON.stringify(event) !== JSON.stringify(after[index])))
36
+ throw new Error("Register event history changed during smoke run");
37
+ const fresh = after.slice(before.length);
38
+ const starts = fresh.filter((event) => event.action === "start");
39
+ const reviews = fresh.filter((event) => event.action === "review");
40
+ if (starts.length !== 1 || reviews.length !== 1)
41
+ throw new Error("Expected one new start and one new review event from this run");
42
+ const start = starts[0];
43
+ const review = reviews[0];
44
+ if (fresh.indexOf(start) >= fresh.indexOf(review) ||
45
+ fresh.at(-1) !== review ||
46
+ start.to_status !== "in-progress" ||
47
+ review.from_status !== "in-progress" ||
48
+ review.to_status !== "review" ||
49
+ fresh.some((event) => event.action === "wait" || event.action === "reopen"))
50
+ throw new Error("Smoke run did not proceed from start to review without interruption");
51
+ if (start.actor !== actor || review.actor !== actor)
52
+ throw new Error(`Expected concrete actor ${actor}; start=${start.actor}, review=${review.actor}`);
53
+ return { start, review };
54
+ }
55
+ function readEvents(paths, id) {
56
+ const path = registerEventFilePath(paths.projectRegisterPath, id);
57
+ return readRegisterEventsFromContent(readFileSync(path, "utf8"), path);
58
+ }
59
+ function checkTickets(paths, id, targets) {
60
+ if (targets.includes(id))
61
+ throw new Error("Smoke item cannot also be a target");
62
+ for (const target of targets) {
63
+ const view = loadItemForUpdate(paths, target);
64
+ if (!["review", "done"].includes(view.item.status))
65
+ throw new Error(`Target ${target} must be review or done; actual=${view.item.status}`);
66
+ }
67
+ const view = loadItemForUpdate(paths, id);
68
+ if (!["done", "open", "review"].includes(view.item.status))
69
+ throw new Error(`Smoke item ${id} must be done, open or review; actual=${view.item.status}. Resolve or resume the existing run first.`);
70
+ if (requireRunnableRegisterItem({ ...view.item, status: "open" }) !== "edit")
71
+ throw new Error(`Smoke item ${id} must be an edit task`);
72
+ appendSmokeTargets(readFileSync(view.ticketPath, "utf8"), targets);
73
+ return view;
74
+ }
75
+ export async function runExecSmoke(opts) {
76
+ let stage = "preflight";
77
+ const step = (name, description) => {
78
+ stage = name;
79
+ process.stdout.write(`[smoke:${name}] ${description}\n`);
80
+ };
81
+ try {
82
+ const id = normalizePjrId(opts.register);
83
+ const targets = parseRegisterIds(opts.targets).ids;
84
+ if (!targets.length)
85
+ throw new Error("--targets requires at least one item ID");
86
+ const paths = resolveRegisterPaths(opts);
87
+ const project = paths.projectId;
88
+ const executionPath = paths.executionPath;
89
+ const projectPaths = resolveProjectPaths({ project });
90
+ const defaults = loadExecDefaultsConfig(resolveExecDefaultsPath({}, projectPaths.schedulePath), executionPath);
91
+ const roster = loadRosterForExecutionPath(executionPath);
92
+ const { executor } = resolveRegisterPipelineCommand(roster, opts, defaults);
93
+ const actor = executor.actor;
94
+ const by = registerEventActor({ project, by: opts.by });
95
+ const view = checkTickets(paths, id, targets);
96
+ readEvents(paths, id);
97
+ const reason = `${targets.join("・")} の統合後の動作確認`;
98
+ const runArgs = [
99
+ "exec",
100
+ "run",
101
+ "--project",
102
+ project,
103
+ "--register",
104
+ id,
105
+ "--worktree",
106
+ "--executor-by",
107
+ opts.executorBy,
108
+ "--reporter-by",
109
+ opts.reporterBy,
110
+ "--on-rate-limit",
111
+ "stop",
112
+ ];
113
+ if (opts.worktreeBase)
114
+ runArgs.push("--worktree-base", opts.worktreeBase);
115
+ if (opts.dryRun) {
116
+ const content = readFileSync(view.ticketPath, "utf8");
117
+ step("targets", appendSmokeTargets(content, targets) === content
118
+ ? `Would keep ${view.ticketPath}; all targets are already listed, no target commit needed`
119
+ : `Would append missing IDs from ${targets.join(", ")} to ${view.ticketPath} and commit the ticket under exec-lifecycle lock`);
120
+ step("reopen", view.item.status === "done"
121
+ ? `Would register reopen ${id} --by ${by} --commit`
122
+ : `Would skip reopen (${view.item.status})`);
123
+ step("run", `Would run specdojo ${runArgs.join(" ")}`);
124
+ step("verify", `Would require new start → review events with concrete actor ${actor}; leave items for register close`);
125
+ return;
126
+ }
127
+ const mutex = new CrossProcessMutex(join(executionPath, "exec", ".locks", "exec-smoke"), {
128
+ actor: by,
129
+ label: `smoke ${id}`,
130
+ });
131
+ await mutex.runExclusive(async () => {
132
+ step("targets", `Record ${targets.join(", ")} in ${id}`);
133
+ await runRegisterMutationInCurrentWorktree("smoke-targets", { project, by, commit: true }, (context) => {
134
+ const current = checkTickets(context.paths, id, targets);
135
+ const path = current.ticketPath;
136
+ const eventPath = registerEventFilePath(context.paths.projectRegisterPath, id);
137
+ context.assertCommitTargetsClean([path, eventPath]);
138
+ const content = readFileSync(path, "utf8");
139
+ const updated = appendSmokeTargets(content, targets);
140
+ if (updated !== content)
141
+ atomicWriteFile(path, updated);
142
+ return { id, title: current.item.title };
143
+ });
144
+ step("reopen", `Open ${id} if terminal`);
145
+ if (loadItemForUpdate(paths, id).item.status === "done") {
146
+ if (!spawnSelf([
147
+ "register",
148
+ "reopen",
149
+ "--project",
150
+ project,
151
+ "--id",
152
+ id,
153
+ "--by",
154
+ by,
155
+ "--reason",
156
+ reason,
157
+ "--commit",
158
+ ]))
159
+ throw new Error(`register reopen failed for ${id}; see command output above`);
160
+ }
161
+ const before = readEvents(paths, id);
162
+ step("run", `Run ${id} with ${opts.executorBy} (${actor})`);
163
+ if (!spawnSelf(runArgs))
164
+ throw new Error(`exec run failed for ${id}; see command output above; inspect the run before retrying`);
165
+ step("verify", "Check this run's events and final item status");
166
+ const { start, review } = verifySmokeEvents(before, readEvents(paths, id), actor);
167
+ if (loadItemForUpdate(paths, id).item.status !== "review")
168
+ throw new Error(`${id} did not reach review`);
169
+ process.stdout.write(`Smoke passed: ${id}; targets=${targets.join(",")}; actor=${actor}; start=${start.id}; review=${review.id}\nClose ${id} and the targets with register close after checking their completion conditions.\n`);
170
+ });
171
+ }
172
+ catch (error) {
173
+ process.stderr.write(`[smoke:${stage}] failed: ${error instanceof Error ? error.message : String(error)}\n`);
174
+ process.exitCode = 1;
175
+ }
176
+ }
177
+ export function registerExecSmokeCommand(exec) {
178
+ exec
179
+ .command("smoke")
180
+ .description("Record integration targets, reopen a smoke item, run it in a worktree, and verify concrete event actors")
181
+ .option("--project <id>", "Project id")
182
+ .requiredOption("--register <id>", "Smoke register item ID (project-specific)")
183
+ .requiredOption("--targets <ids>", "Comma-separated integrated register item IDs")
184
+ .requiredOption("--executor-by <nickname>", "Executor nickname or alias")
185
+ .requiredOption("--reporter-by <nickname>", "Reporter nickname or alias")
186
+ .option("--by <actor>", "Actor for target recording and reopen", "specdojo-orchestrator")
187
+ .option("--worktree-base <path>", "Base directory for execution worktrees")
188
+ .option("--dry-run", "Print steps without writing, committing or launching agents", false)
189
+ .action(runExecSmoke);
190
+ }
@@ -1,4 +1,5 @@
1
1
  import { listFilesRecursive, readYaml } from "./shared.js";
2
+ import { isProficiency } from "../shared/agent-types.js";
2
3
  import { extractPhaseSuffix, normalizePhaseSetSelection, phaseSetNames, } from "../schedule/phase-sets.js";
3
4
  function isTaskMode(value) {
4
5
  return value === "edit" || value === "review";
@@ -25,9 +26,6 @@ function isApproach(value) {
25
26
  value === "finalize" ||
26
27
  value === "bootstrap-finalize");
27
28
  }
28
- function isProficiency(value) {
29
- return value === "low" || value === "normal" || value === "high" || value === "expert";
30
- }
31
29
  function isExecution(value) {
32
30
  return value === "agent" || value === "human";
33
31
  }
@@ -330,6 +328,18 @@ export function resolveAgentAssignment(localId, taskId, index, phaseSuffix, phas
330
328
  }
331
329
  return undefined;
332
330
  }
331
+ /**
332
+ * Resolves the agent pinned on a scheduled task for ready.json, task views and runs alike.
333
+ * A track generated from a strategy takes the strategy as the source of truth, so the agent copied
334
+ * into the track (or a cached ready.json) is ignored there: a pass agent, then
335
+ * `owner_rules[].phase_overrides[].agent`, then the phase agent. Only a task whose track has no
336
+ * strategy keeps the agent written on the task itself. CLI overrides and auto-selection apply later.
337
+ */
338
+ export function resolveScheduledTaskAgent(task, index) {
339
+ if (taskTrack(task.id, index) === undefined)
340
+ return task.agent;
341
+ return resolveAgentAssignment(task.local_id, task.id, index, task.phase_suffix, task.phase_set);
342
+ }
333
343
  /** Resolves the optional executor/reporter pipeline declared on a phase. */
334
344
  export function resolveAgentPipeline(localId, taskId, index, phaseSuffix, phaseSet) {
335
345
  // Cross-deliverable-pass tasks (target_local_ids, no single local_id) declare
@@ -3,6 +3,7 @@ import { existsSync, readdirSync, rmdirSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { getProjectRepos, getProjectSchedulePath, loadConfig, PROJECT_REPO_WORKTREE_DIRNAME, resolveRepoRoot, specdojoRootDir, } from "../shared/specdojo-config.js";
5
5
  import { ensureExecWorktree, execWorktreePath, findExecWorktree, generateWorktreeArtifacts, gitOutput, gitResult, installWorktreeDependencies, listRegisteredWorktrees, worktreeNameFromTaskId, } from "./worktree.js";
6
+ import { OPENCODE_CONFIG_CONTENT_ENV, opencodeAgentNameFromCommand, opencodeExtraRootConfig, } from "./opencode-permissions.js";
6
7
  import { assertProductBranchAvailable, existingProductTaskBranch, forgetProductBranch, productBranchExists, productBranchRecords, recordedProductBranch, reserveProductBranch, } from "./product-branch-records.js";
7
8
  // PJR-98G4: 1 つのタスクがプロジェクトリポジトリと宣言済みのプロダクトリポジトリ(`repos`)を
8
9
  // 変更する場合の worktree を扱う。`repos` を持たない project では、ここの関数はどれも空の結果を
@@ -555,8 +556,8 @@ function shellQuote(value) {
555
556
  }
556
557
  /**
557
558
  * Provider arguments that add the product worktrees as extra roots with write access. The agent
558
- * keeps the project worktree as cwd. Returns [] for providers without a launch flag. OpenCode's
559
- * orchestrator entry injects `permission.external_directory` through its runtime config instead.
559
+ * keeps the project worktree as cwd. Returns [] for providers without a launch flag. OpenCode has
560
+ * no such flag; withAgentExtraRoots injects its permissions through `OPENCODE_CONFIG_CONTENT`.
560
561
  */
561
562
  export function agentExtraRootArguments(provider, dirs) {
562
563
  if (dirs.length === 0)
@@ -580,8 +581,22 @@ export function agentExtraRootArguments(provider, dirs) {
580
581
  return [];
581
582
  }
582
583
  }
583
- /** Append the extra-root arguments to a resolved shell command (unchanged when there are none). */
584
- export function withAgentExtraRoots(command, provider, dirs) {
584
+ /**
585
+ * Give the agent write access to the extra roots in a resolved shell command (unchanged when there
586
+ * are none). Most providers get launch arguments appended. OpenCode gets an
587
+ * `OPENCODE_CONFIG_CONTENT` assignment prefixed to the command, scoped to the `--agent` in the
588
+ * command and merged with the inherited value from `options.env`; `edit` patterns are relative
589
+ * to `options.cwd`, the agent's working directory.
590
+ */
591
+ export function withAgentExtraRoots(command, provider, dirs, options = {}) {
592
+ if (provider === "opencode" && dirs.length > 0) {
593
+ const agentName = opencodeAgentNameFromCommand(command);
594
+ if (!agentName) {
595
+ throw new Error(`OpenCode command needs --agent <name> to scope the product worktree permissions: ${command}`);
596
+ }
597
+ const config = opencodeExtraRootConfig((options.env ?? process.env)[OPENCODE_CONFIG_CONTENT_ENV], agentName, dirs, options.cwd ?? process.cwd());
598
+ return `${OPENCODE_CONFIG_CONTENT_ENV}=${shellQuote(config)} ${command}`;
599
+ }
585
600
  const args = agentExtraRootArguments(provider, dirs);
586
601
  if (args.length === 0)
587
602
  return command;