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
@@ -0,0 +1,117 @@
1
+ import { relative, resolve } from "node:path";
2
+ /**
3
+ * Runtime permission injection that lets an OpenCode agent edit declared extra roots (product
4
+ * worktrees, external projects). OpenCode merges `OPENCODE_CONFIG_CONTENT` after the
5
+ * `.opencode/agents/<name>.md` definitions, so the override survives the agent frontmatter, while
6
+ * `opencode.json` `agent.<name>.permission` would be overwritten by it.
7
+ *
8
+ * OpenCode matches the two permissions in different forms: `external_directory` by the absolute
9
+ * directory path and `edit` by the path relative to its working directory. The injected patterns
10
+ * follow those forms, and only the given roots are allowed; other external directories stay denied.
11
+ */
12
+ export const OPENCODE_CONFIG_CONTENT_ENV = "OPENCODE_CONFIG_CONTENT";
13
+ function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function toPosix(path) {
17
+ return path.replaceAll("\\", "/");
18
+ }
19
+ /** `external_directory` pattern: the absolute root path. */
20
+ export function opencodeExternalDirectoryPattern(root) {
21
+ return `${toPosix(resolve(root))}/**`;
22
+ }
23
+ /** `edit` pattern: the root relative to OpenCode's working directory (e.g. `../app1/**`). */
24
+ export function opencodeEditPattern(root, cwd) {
25
+ const relativePath = toPosix(relative(resolve(cwd), resolve(root)));
26
+ return relativePath ? `${relativePath}/**` : "**";
27
+ }
28
+ /**
29
+ * Merge the extra-root permissions for `agentName` into the current `OPENCODE_CONFIG_CONTENT`.
30
+ * Other keys and agents are preserved. Throws when the current value is not a valid config object.
31
+ */
32
+ export function opencodeExtraRootConfig(current, agentName, roots, cwd) {
33
+ let config = {};
34
+ if (current?.trim()) {
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(current);
38
+ }
39
+ catch (error) {
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: ${message}`, { cause: error });
42
+ }
43
+ if (!isRecord(parsed)) {
44
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: top-level value must be an object`);
45
+ }
46
+ config = parsed;
47
+ }
48
+ const agents = config.agent === undefined ? {} : config.agent;
49
+ if (!isRecord(agents)) {
50
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent must be an object`);
51
+ }
52
+ const selectedAgent = agents[agentName] === undefined ? {} : agents[agentName];
53
+ if (!isRecord(selectedAgent)) {
54
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent.${agentName} must be an object`);
55
+ }
56
+ const permission = selectedAgent.permission === undefined ? {} : selectedAgent.permission;
57
+ if (!isRecord(permission)) {
58
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent.${agentName}.permission must be an object`);
59
+ }
60
+ const externalDirectory = { "*": "deny" };
61
+ const currentEdit = permission.edit;
62
+ let edit = {};
63
+ if (isRecord(currentEdit)) {
64
+ edit = { ...currentEdit };
65
+ }
66
+ else if (typeof currentEdit === "string") {
67
+ edit = { "*": currentEdit };
68
+ }
69
+ else if (currentEdit !== undefined) {
70
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent.${agentName}.permission.edit must be a string or object`);
71
+ }
72
+ for (const root of roots) {
73
+ externalDirectory[opencodeExternalDirectoryPattern(root)] = "allow";
74
+ edit[opencodeEditPattern(root, cwd)] = "allow";
75
+ }
76
+ return JSON.stringify({
77
+ ...config,
78
+ agent: {
79
+ ...agents,
80
+ [agentName]: {
81
+ ...selectedAgent,
82
+ permission: {
83
+ ...permission,
84
+ external_directory: externalDirectory,
85
+ edit,
86
+ },
87
+ },
88
+ },
89
+ });
90
+ }
91
+ /** Agent name from `--agent <name>` / `--agent=<name>` arguments (the last one wins). */
92
+ export function opencodeAgentNameFromArguments(args) {
93
+ let selected;
94
+ for (let index = 0; index < args.length; index += 1) {
95
+ const arg = args[index];
96
+ if (arg === "--agent") {
97
+ selected = args[index + 1];
98
+ index += 1;
99
+ }
100
+ else if (arg.startsWith("--agent=")) {
101
+ selected = arg.slice("--agent=".length);
102
+ }
103
+ }
104
+ const trimmed = selected?.trim();
105
+ return trimmed ? trimmed : undefined;
106
+ }
107
+ /**
108
+ * Agent name in a resolved shell command such as `opencode run --agent opencode-executor ...`.
109
+ * Single or double quotes around the name are accepted; anything else is split on whitespace.
110
+ */
111
+ export function opencodeAgentNameFromCommand(command) {
112
+ const words = command
113
+ .trim()
114
+ .split(/\s+/)
115
+ .map((word) => word.replace(/^(['"])(.*)\1$/, "$2"));
116
+ return opencodeAgentNameFromArguments(words);
117
+ }
@@ -1,5 +1,8 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { join } from "node:path";
3
+ import { performance } from "node:perf_hooks";
4
+ import { StringDecoder } from "node:string_decoder";
5
+ import { recordValidationGateWait, validationMetric, ValidationTestFiles, } from "./validation-metrics.js";
3
6
  import { gitEnvironment } from "./worktree.js";
4
7
  import { acquirePoolSlot, getActiveExecLocksDir, releaseLock } from "./slot-lock.js";
5
8
  import { MAX_CHANGE_FILES, redactSensitiveText } from "./evidence.js";
@@ -306,21 +309,30 @@ async function invokeParentValidation(definition, cwd) {
306
309
  const stderrCapture = { chunks: [], totalBytes: 0 };
307
310
  let settled = false;
308
311
  let timedOut = false;
312
+ const testFiles = new ValidationTestFiles();
313
+ const stdoutDecoder = new StringDecoder("utf8");
309
314
  const child = spawn(definition.command, [...definition.args], {
310
315
  cwd,
311
- env: gitEnvironment(),
316
+ env: { ...gitEnvironment(), SPECDOJO_PARENT_VALIDATION_METRICS: "1" },
312
317
  shell: false,
313
318
  stdio: ["ignore", "pipe", "pipe"],
314
319
  windowsHide: true,
315
320
  });
316
321
  child.stdout.on("data", (chunk) => {
317
322
  appendBounded(stdoutCapture, chunk);
323
+ testFiles.observe(stdoutDecoder.write(chunk));
318
324
  });
319
325
  child.stderr.on("data", (chunk) => {
320
326
  appendBounded(stderrCapture, chunk);
321
327
  });
322
328
  const timer = setTimeout(() => {
323
329
  timedOut = true;
330
+ validationMetric("validation-timeout", {
331
+ id: definition.id,
332
+ cwd,
333
+ timeout_ms: definition.timeoutMs,
334
+ ...testFiles.snapshot(),
335
+ });
324
336
  child.kill("SIGTERM");
325
337
  }, definition.timeoutMs);
326
338
  const finish = (result) => {
@@ -397,6 +409,7 @@ export async function runParentValidationBatch(entries, cwd, invoke = invokePare
397
409
  summary: reason,
398
410
  reason,
399
411
  });
412
+ validationMetric("validation-skipped", { id: definition.id, repo, reason });
400
413
  continue;
401
414
  }
402
415
  const root = repo === PARENT_VALIDATION_PROJECT_REPO
@@ -416,8 +429,38 @@ export async function runParentValidationBatch(entries, cwd, invoke = invokePare
416
429
  });
417
430
  continue;
418
431
  }
419
- const result = await invoke(definition, root);
432
+ const startedAt = new Date().toISOString();
433
+ const started = performance.now();
434
+ validationMetric("validation-start", {
435
+ id: definition.id,
436
+ repo,
437
+ started_at: startedAt,
438
+ timeout_ms: definition.timeoutMs,
439
+ });
440
+ let result;
441
+ try {
442
+ result = await invoke(definition, root);
443
+ }
444
+ catch (error) {
445
+ validationMetric("validation-end", {
446
+ id: definition.id,
447
+ repo,
448
+ started_at: startedAt,
449
+ duration_ms: performance.now() - started,
450
+ error: String(error),
451
+ });
452
+ throw error;
453
+ }
420
454
  const passed = result.exitCode === 0 && !result.error && !result.timedOut;
455
+ validationMetric("validation-end", {
456
+ id: definition.id,
457
+ repo,
458
+ started_at: startedAt,
459
+ duration_ms: performance.now() - started,
460
+ exit_code: result.exitCode,
461
+ timed_out: result.timedOut === true,
462
+ status: passed ? "passed" : "failed",
463
+ });
421
464
  validations.push({
422
465
  id: definition.id,
423
466
  source: "runner",
@@ -483,14 +526,24 @@ export class ParentValidationGate {
483
526
  this.lockRoot = lockRoot;
484
527
  }
485
528
  async run(label, ids, task) {
529
+ const queued = performance.now();
530
+ validationMetric("gate-queued", {
531
+ ids,
532
+ running: [...this.active],
533
+ queued: this.waiters.length,
534
+ });
486
535
  await this.acquire(label, ids);
536
+ const localWaitMs = performance.now() - queued;
487
537
  try {
488
- if (!this.lockRoot)
538
+ if (!this.lockRoot) {
539
+ recordValidationGateWait(queued, localWaitMs);
489
540
  return await task();
541
+ }
490
542
  const slot = await acquirePoolSlot(parentValidationPoolPath(this.lockRoot), this.limit, { actor: "parent-validation", label }, {
491
543
  onWait: () => this.log(` Waiting for parent validation slot held by another exec run: ${label} (${ids.join(", ")})\n`),
492
544
  });
493
545
  try {
546
+ recordValidationGateWait(queued, localWaitMs);
494
547
  return await task();
495
548
  }
496
549
  finally {
@@ -237,6 +237,25 @@ export function gradeFindingsText(projectId, targetPath, includeCause = false) {
237
237
  return "- なし";
238
238
  }
239
239
  }
240
+ // 実践の型を整備する approach。成果物ではなく、成果物が宣言する実践の型そのものを編集対象にする。
241
+ const KATA_MAINTENANCE_APPROACHES = new Set([
242
+ "rulebook-maintenance",
243
+ "recipe-maintenance",
244
+ "sample-maintenance",
245
+ "template-maintenance",
246
+ ]);
247
+ // 実践の型の参照を解決するときの成果物の kind。kind: generated の成果物は CLI が生成するため
248
+ // 既定では実践の型を参照しないが、型の整備の段はカタログが宣言する rulebook 自体を整備するので、
249
+ // generated の扱いを外して宣言どおりに解決する(PJR-DM9B)。
250
+ export function kataRefTargetKind(kind, approach) {
251
+ return kind === "generated" && approach && KATA_MAINTENANCE_APPROACHES.has(approach)
252
+ ? undefined
253
+ : kind;
254
+ }
255
+ // タスクの approach を踏まえて、成果物が宣言する実践の型の参照を解決する。
256
+ export function deliverableKataRefs(deliverable, approach) {
257
+ return resolveKataRefs(deliverable?.deliverable.rulebook, kataRefTargetKind(deliverable?.deliverable.kind, approach));
258
+ }
240
259
  export function gradeFindingTargetPath(approach, deliverable, refs) {
241
260
  if (approach === "rulebook-maintenance")
242
261
  return refs.rulebook;
@@ -262,7 +281,7 @@ export function gradeTargetKind(approach) {
262
281
  // 同じ規則で決めるため、plan 生成と runner の実行対象が食い違わない。
263
282
  export function reviewGradeSubject(catalogPath, task) {
264
283
  const deliverable = task.local_id && catalogPath ? findDeliverableInfo(catalogPath, task.local_id) : null;
265
- const refs = resolveKataRefs(deliverable?.deliverable.rulebook, deliverable?.deliverable.kind);
284
+ const refs = deliverableKataRefs(deliverable, task.approach);
266
285
  const path = gradeFindingTargetPath(task.approach, deliverable, refs);
267
286
  if (!path || path === MISSING)
268
287
  return undefined;
@@ -508,7 +527,7 @@ export function targetDocIds(projectId, deliverable, approach, fallbackLocalId)
508
527
  const kinds = approach ? (TARGET_REF_KINDS[approach] ?? []) : [];
509
528
  if (kinds.length === 0)
510
529
  return ids;
511
- const refs = resolveKataRefs(deliverable.deliverable.rulebook, deliverable.deliverable.kind);
530
+ const refs = deliverableKataRefs(deliverable, approach);
512
531
  for (const kind of kinds) {
513
532
  const refPath = refs[kind];
514
533
  if (refPath !== MISSING)
@@ -2,13 +2,13 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { expandPlanConventions } from "../shared/plan-conventions.js";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { isAuthoringApproach } from "../kata/authoring.js";
5
- import { resolveDeliverableSchemaRef, resolveKataRefs } from "../kata/kata.js";
5
+ import { resolveDeliverableSchemaRef } from "../kata/kata.js";
6
6
  import { registerInputSection } from "../register/input.js";
7
7
  import { isPlanningApproach } from "../register/planning.js";
8
8
  import { DEFAULT_PROJECT_CONTEXT, specdojoRootDir } from "../shared/specdojo-config.js";
9
9
  import { formatMarkdownFile } from "./format.js";
10
10
  import { assertPlanMarkdownlint } from "./plan-markdownlint.js";
11
- import { applicableReviewCriteria, buildInPlaceStem, crossDeliverableTargetDetails, deliverableBasedOn, deliverableBrief, deliverableDependsOn, deliverableName, deliverableOverview, deliverablePath, doneCriteriaChecklist, doneCriteriaGoals, doneCriteriaItems, execDocId, findDeliverableInfo, frontmatter, gradeFindingsText, gradeFindingTargetPath, gradeResultRef, gradeTargetKind, implementationEvidence, injectCommonConventions, kataRefState, loadPlanTemplate, loadRoles, loadViewpoints, MISSING, ownerRoleFields, phaseDescriptionText, projectContextSection, repoRelativePath, reviewDoneCriteriaRows, reviewGradeSummaryText, rulebookIncludesText, targetDocIds, targetDocIdsForTask, } from "./plans-core.js";
11
+ import { applicableReviewCriteria, buildInPlaceStem, crossDeliverableTargetDetails, deliverableBasedOn, deliverableBrief, deliverableDependsOn, deliverableKataRefs, deliverableName, deliverableOverview, deliverablePath, doneCriteriaChecklist, doneCriteriaGoals, doneCriteriaItems, execDocId, findDeliverableInfo, frontmatter, gradeFindingsText, gradeFindingTargetPath, gradeResultRef, gradeTargetKind, implementationEvidence, injectCommonConventions, kataRefState, kataRefTargetKind, loadPlanTemplate, loadRoles, loadViewpoints, MISSING, ownerRoleFields, phaseDescriptionText, projectContextSection, repoRelativePath, reviewDoneCriteriaRows, reviewGradeSummaryText, rulebookIncludesText, targetDocIds, targetDocIdsForTask, } from "./plans-core.js";
12
12
  import { kataCauseFindingsText } from "./plans-kata-findings.js";
13
13
  import { kataReviewSummary, scheduleKataReviewSubjects } from "./review-kata.js";
14
14
  import { isRunRecordPath, resultForPlan, taskRecordPaths } from "./run-records.js";
@@ -36,8 +36,7 @@ function buildEditPlanMarkdown(template, task, deliverable, roleMap, vpMap, proj
36
36
  };
37
37
  const criteria = deliverable?.deliverable.done_criteria ?? [];
38
38
  const ownerRole = ownerRoleFields(task.owner, roleMap, vpMap, deliverable?.deliverable.rulebook);
39
- const refs = planOverrides?.refs ??
40
- resolveKataRefs(deliverable?.deliverable.rulebook, deliverable?.deliverable.kind);
39
+ const refs = planOverrides?.refs ?? deliverableKataRefs(deliverable, task.approach);
41
40
  const usesOptionalImplementationEvidence = task.approach === "draft" ||
42
41
  task.approach === "fully-guided" ||
43
42
  task.approach === "recipe-guided";
@@ -66,7 +65,7 @@ function buildEditPlanMarkdown(template, task, deliverable, roleMap, vpMap, proj
66
65
  _RESULT_REF_: resultRef,
67
66
  _RULEBOOK_REF_: refs.rulebook,
68
67
  _RULEBOOK_STATE_: kataRefState(refs.rulebook),
69
- _RULEBOOK_INCLUDES_: rulebookIncludesText(deliverable?.deliverable.rulebook, deliverable?.deliverable.kind),
68
+ _RULEBOOK_INCLUDES_: rulebookIncludesText(deliverable?.deliverable.rulebook, kataRefTargetKind(deliverable?.deliverable.kind, task.approach)),
70
69
  _RECIPE_REF_: refs.recipe,
71
70
  _RECIPE_STATE_: kataRefState(refs.recipe),
72
71
  _SAMPLE_REF_: refs.sample,
@@ -162,7 +161,7 @@ function buildReviewPlanMarkdown(template, task, deliverable, criteria, vpMap, p
162
161
  ...(task.approach ? { approach: task.approach } : {}),
163
162
  ...(targets.length > 0 ? { targets } : {}),
164
163
  };
165
- const refs = resolveKataRefs(deliverable?.deliverable.rulebook, deliverable?.deliverable.kind);
164
+ const refs = deliverableKataRefs(deliverable, task.approach);
166
165
  const applicableCriteria = applicableReviewCriteria(criteria, vpMap, deliverable?.deliverable.rulebook);
167
166
  const gradeSubjectPath = gradeFindingTargetPath(task.approach, deliverable, refs);
168
167
  const values = {
@@ -180,7 +179,7 @@ function buildReviewPlanMarkdown(template, task, deliverable, criteria, vpMap, p
180
179
  _DELIVERABLE_PATH_: deliverablePath(deliverable),
181
180
  _RESULT_REF_: resultRef,
182
181
  _RULEBOOK_REF_: refs.rulebook,
183
- _RULEBOOK_INCLUDES_: rulebookIncludesText(deliverable?.deliverable.rulebook, deliverable?.deliverable.kind),
182
+ _RULEBOOK_INCLUDES_: rulebookIncludesText(deliverable?.deliverable.rulebook, kataRefTargetKind(deliverable?.deliverable.kind, task.approach)),
184
183
  _RECIPE_REF_: refs.recipe,
185
184
  _SAMPLE_REF_: refs.sample,
186
185
  _TEMPLATE_REF_: refs.template,
@@ -0,0 +1,162 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { DIST_BUILD_FAILURE_MARKER } from "../shared/dist-freshness.js";
4
+ import { matchesParentValidationPaths, runParentValidationBatch, } from "./parent-validation.js";
5
+ import { redactSensitiveText } from "./evidence.js";
6
+ import { gitOutput } from "./worktree.js";
7
+ export function resolvePostIntegrationEntries(value) {
8
+ if (value === undefined)
9
+ return [];
10
+ if (!Array.isArray(value)) {
11
+ throw new Error("pipeline.post_integration in exec-defaults must be an array");
12
+ }
13
+ const seen = new Set();
14
+ return value.map((entry, index) => {
15
+ const where = `pipeline.post_integration[${index}] in exec-defaults`;
16
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
17
+ throw new Error(`${where} must be { id, paths }`);
18
+ }
19
+ const record = entry;
20
+ if (Object.keys(record).some((key) => key !== "id" && key !== "paths")) {
21
+ throw new Error(`${where} accepts only id and paths`);
22
+ }
23
+ if (record.id !== "build-dist")
24
+ throw new Error(`${where}: unknown id (allowed: build-dist)`);
25
+ if (seen.has(record.id))
26
+ throw new Error(`${where}: duplicate id: ${record.id}`);
27
+ seen.add(record.id);
28
+ if (!Array.isArray(record.paths) ||
29
+ record.paths.length === 0 ||
30
+ !record.paths.every((path) => typeof path === "string" && path.trim().length > 0)) {
31
+ throw new Error(`${where}.paths must be a non-empty array of non-empty glob strings`);
32
+ }
33
+ return { id: record.id, paths: record.paths.map((path) => path.trim()) };
34
+ });
35
+ }
36
+ /** Locate the original integration, even if other tasks landed before cleanup resumed. */
37
+ export function integratedCommitRange(repoRoot, branch) {
38
+ const tip = gitOutput(repoRoot, ["rev-parse", "--verify", `${branch}^{commit}`]).trim();
39
+ const outputCommit = gitOutput(repoRoot, [
40
+ "rev-list",
41
+ "--first-parent",
42
+ "--ancestry-path",
43
+ `${tip}..HEAD`,
44
+ ])
45
+ .trim()
46
+ .split("\n")
47
+ .filter(Boolean)
48
+ .at(-1);
49
+ if (!outputCommit)
50
+ throw new Error(`could not locate integrated commit for branch: ${branch}`);
51
+ return {
52
+ baseCommit: gitOutput(repoRoot, ["rev-parse", `${outputCommit}^1`]).trim(),
53
+ outputCommit,
54
+ };
55
+ }
56
+ function recorded(logPath, id, outputCommit) {
57
+ if (!existsSync(logPath))
58
+ return false;
59
+ return readFileSync(logPath, "utf8")
60
+ .split("\n")
61
+ .some((line) => {
62
+ try {
63
+ const record = JSON.parse(line);
64
+ return (record.id === id &&
65
+ record.output_commit === outputCommit &&
66
+ ["passed", "failed", "skipped"].includes(record.status));
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ });
72
+ }
73
+ /** Leave the marker that `dist-freshness` treats as stale after a failed build; clear it on success. */
74
+ export function updateDistBuildFailureMarker(repoRoot, failed, content) {
75
+ const marker = join(repoRoot, "dist", DIST_BUILD_FAILURE_MARKER);
76
+ if (failed) {
77
+ mkdirSync(dirname(marker), { recursive: true });
78
+ writeFileSync(marker, `${content}\n`, "utf8");
79
+ }
80
+ else {
81
+ rmSync(marker, { force: true });
82
+ }
83
+ }
84
+ /** Caller retains the exec/lifecycle lock until this completes. Never undo a merged commit. */
85
+ export async function runPostIntegration(params) {
86
+ const log = params.log ??
87
+ ((line) => {
88
+ process.stdout.write(line);
89
+ });
90
+ const records = [];
91
+ for (const entry of resolvePostIntegrationEntries(params.entries)) {
92
+ const startedAt = new Date().toISOString();
93
+ try {
94
+ if (recorded(params.logPath, entry.id, params.outputCommit))
95
+ continue;
96
+ // --no-renames includes both the old and new names; -z preserves spaces and newlines.
97
+ const changes = gitOutput(params.repoRoot, [
98
+ "diff",
99
+ "--name-only",
100
+ "--no-renames",
101
+ "-z",
102
+ params.baseCommit,
103
+ params.outputCommit,
104
+ "--",
105
+ ])
106
+ .split("\0")
107
+ .filter(Boolean);
108
+ let status = "skipped";
109
+ let summary = "no integrated paths match paths";
110
+ if (changes.some((path) => matchesParentValidationPaths(path, entry.paths))) {
111
+ log(` [post-integration] ${entry.id}: running npm run build\n`);
112
+ const batch = await runParentValidationBatch(["build"], params.repoRoot, params.invoke);
113
+ const validation = batch.validations[0];
114
+ status = validation.status === "passed" ? "passed" : "failed";
115
+ summary = validation.summary;
116
+ }
117
+ records.push({
118
+ id: entry.id,
119
+ command: "npm run build",
120
+ base_commit: params.baseCommit,
121
+ output_commit: params.outputCommit,
122
+ started_at: startedAt,
123
+ completed_at: new Date().toISOString(),
124
+ status,
125
+ summary,
126
+ });
127
+ }
128
+ catch (error) {
129
+ records.push({
130
+ id: entry.id,
131
+ command: "npm run build",
132
+ base_commit: params.baseCommit,
133
+ output_commit: params.outputCommit,
134
+ started_at: startedAt,
135
+ completed_at: new Date().toISOString(),
136
+ status: "failed",
137
+ summary: redactSensitiveText(error instanceof Error ? error.message : String(error)),
138
+ });
139
+ }
140
+ const record = records.at(-1);
141
+ if (record.status !== "skipped") {
142
+ try {
143
+ updateDistBuildFailureMarker(params.repoRoot, record.status === "failed", record.output_commit);
144
+ }
145
+ catch (error) {
146
+ log(` [post-integration] could not update dist failure marker: ${redactSensitiveText(String(error))}\n`);
147
+ }
148
+ }
149
+ log(` [post-integration] ${record.id}: ${record.status}: ${record.summary}\n`);
150
+ if (record.status === "failed") {
151
+ log(" [post-integration] integration kept; fix the build and run npm run build before the next exec run (dist-freshness check remains enabled).\n");
152
+ }
153
+ try {
154
+ mkdirSync(dirname(params.logPath), { recursive: true });
155
+ appendFileSync(params.logPath, `${JSON.stringify(record)}\n`, "utf8");
156
+ }
157
+ catch (error) {
158
+ log(` [post-integration] could not record outcome: ${redactSensitiveText(String(error))}\n`);
159
+ }
160
+ }
161
+ return records;
162
+ }
@@ -0,0 +1,166 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { gitEnvironment } from "../shared/git-environment.js";
4
+ import { selfRunArgs } from "../shared/spawn-self.js";
5
+ import { specdojoRootDir } from "../shared/specdojo-config.js";
6
+ import { addProjectOptions, printCommandError, resolveProjectId } from "./core.js";
7
+ import { runParentValidationBatch } from "./parent-validation.js";
8
+ import { updateDistBuildFailureMarker } from "./post-integration.js";
9
+ import { resolveProjectPaths } from "./project.js";
10
+ import { cancelQueue, createQueueRecord, formatQueueSummary, isQueueFinished, listQueueRecords, loadQueueRecord, queueLockPath, queueRecordPath, queueStepDisplay, runQueue, validateQueueId, writeQueueRecord, } from "./queue.js";
11
+ import { acquireExecRunLock, releaseExecRunLock } from "./run/lock.js";
12
+ /** Spawn the specdojo CLI without a shell and resolve when that process exits. */
13
+ function runSpecdojoStep(argv) {
14
+ const [executable, args] = selfRunArgs(argv);
15
+ return new Promise((resolveOutcome) => {
16
+ const child = spawn(executable, args, {
17
+ cwd: specdojoRootDir(),
18
+ env: gitEnvironment(),
19
+ shell: false,
20
+ stdio: "inherit",
21
+ });
22
+ child.once("error", (error) => resolveOutcome({ exitCode: null, summary: error.message }));
23
+ child.once("close", (code, signal) => resolveOutcome({
24
+ exitCode: code,
25
+ summary: signal ? `terminated by ${signal}` : `exit code ${code ?? "unknown"}`,
26
+ }));
27
+ });
28
+ }
29
+ /** `post-integration build-dist`: the PJR-8KXJ allowlisted build, under the project exec lock. */
30
+ async function runBuildDistStep(executionPath) {
31
+ const handle = await acquireExecRunLock(executionPath, {
32
+ actor: "exec-queue",
33
+ ifBusy: "wait",
34
+ onWait: () => process.stdout.write("[queue] exec busy — waiting to run build-dist\n"),
35
+ });
36
+ if (!handle)
37
+ return { exitCode: null, summary: "could not acquire the exec lock" };
38
+ try {
39
+ const repoRoot = specdojoRootDir();
40
+ const batch = await runParentValidationBatch(["build"], repoRoot);
41
+ const validation = batch.validations[0];
42
+ const failed = validation?.status !== "passed";
43
+ updateDistBuildFailureMarker(repoRoot, failed, "exec queue build-dist");
44
+ return { exitCode: failed ? 1 : 0, summary: validation?.summary ?? "build did not run" };
45
+ }
46
+ finally {
47
+ releaseExecRunLock(handle);
48
+ }
49
+ }
50
+ function executeQueueStep(executionPath) {
51
+ return (step) => step.kind === "post-integration" ? runBuildDistStep(executionPath) : runSpecdojoStep(step.argv);
52
+ }
53
+ export function registerExecQueueCommands(exec) {
54
+ const queue = exec
55
+ .command("queue")
56
+ .description("Reserve grade / exec run / post-integration steps and run them in order");
57
+ // Shared by --step and --step-continue so the order of the options is the order of the steps.
58
+ const collected = [];
59
+ const collect = (onFailure) => (spec) => {
60
+ collected.push({ spec, onFailure });
61
+ return collected;
62
+ };
63
+ const add = queue
64
+ .command("add <queueId>")
65
+ .description("Create a queue file under execution/queues/")
66
+ .option("--step <spec>", 'Step that stops the queue on failure (e.g. "exec run --register PJR-XXXX")', collect("stop"))
67
+ .option("--step-continue <spec>", "Step whose failure does not stop the queue", collect("continue"));
68
+ addProjectOptions(add);
69
+ add.action((queueId, opts) => {
70
+ try {
71
+ const { executionPath } = resolveProjectPaths({ project: opts.project });
72
+ const path = queueRecordPath(executionPath, validateQueueId(queueId));
73
+ if (existsSync(path))
74
+ throw new Error(`Queue already exists: ${path}`);
75
+ const record = createQueueRecord({
76
+ queueId,
77
+ projectId: resolveProjectId(opts),
78
+ steps: collected,
79
+ });
80
+ writeQueueRecord(path, record);
81
+ process.stdout.write(`Created queue: ${path}\n`);
82
+ for (const step of record.steps) {
83
+ process.stdout.write(` ${step.index}. [${step.on_failure}] ${queueStepDisplay(step)}\n`);
84
+ }
85
+ }
86
+ catch (error) {
87
+ printCommandError(error);
88
+ }
89
+ });
90
+ const run = queue.command("run <queueId>").description("Run (or resume) a queue in order");
91
+ addProjectOptions(run);
92
+ run.action(async (queueId, opts) => {
93
+ try {
94
+ const { executionPath } = resolveProjectPaths({ project: opts.project });
95
+ validateQueueId(queueId);
96
+ const record = await runQueue({
97
+ recordPath: queueRecordPath(executionPath, queueId),
98
+ lockDir: queueLockPath(executionPath, queueId),
99
+ execute: executeQueueStep(executionPath),
100
+ });
101
+ process.exitCode = record.state === "succeeded" ? 0 : 1;
102
+ }
103
+ catch (error) {
104
+ printCommandError(error);
105
+ }
106
+ });
107
+ const status = queue
108
+ .command("status [queueId]")
109
+ .description("Show queues, or the steps of one queue");
110
+ addProjectOptions(status);
111
+ status.action((queueId, opts) => {
112
+ try {
113
+ const { executionPath } = resolveProjectPaths({ project: opts.project });
114
+ if (queueId) {
115
+ validateQueueId(queueId);
116
+ const record = loadQueueRecord(queueRecordPath(executionPath, queueId));
117
+ process.stdout.write(`${formatQueueSummary(record, queueLockPath(executionPath, queueId))}\n`);
118
+ for (const step of record.steps) {
119
+ const detail = step.summary ? ` (${step.summary})` : "";
120
+ process.stdout.write(` ${step.index}. ${step.status} [${step.on_failure}] ${queueStepDisplay(step)}${detail}\n`);
121
+ }
122
+ return;
123
+ }
124
+ const { records, errors } = listQueueRecords(executionPath);
125
+ if (records.length === 0)
126
+ process.stdout.write("No queues.\n");
127
+ for (const record of records) {
128
+ process.stdout.write(`${formatQueueSummary(record, queueLockPath(executionPath, record.queue_id))}\n`);
129
+ }
130
+ for (const error of errors)
131
+ process.stderr.write(`ERROR: ${error}\n`);
132
+ if (errors.length)
133
+ process.exitCode = 1;
134
+ }
135
+ catch (error) {
136
+ printCommandError(error);
137
+ }
138
+ });
139
+ const cancel = queue
140
+ .command("cancel <queueId>")
141
+ .description("Cancel a queue; a running queue stops before its next step")
142
+ .requiredOption("--msg <message>", "Reason for cancelling");
143
+ addProjectOptions(cancel);
144
+ cancel.action((queueId, opts) => {
145
+ try {
146
+ const { executionPath } = resolveProjectPaths({ project: opts.project });
147
+ validateQueueId(queueId);
148
+ const record = cancelQueue(queueRecordPath(executionPath, queueId), opts.msg);
149
+ process.stdout.write(`Cancelled queue: ${record.queue_id}\n`);
150
+ }
151
+ catch (error) {
152
+ printCommandError(error);
153
+ }
154
+ });
155
+ }
156
+ /** Unfinished queues appended to `exec status`, so reservations stay visible next to tasks. */
157
+ export function writeActiveQueueSummary(executionPath) {
158
+ const { records } = listQueueRecords(executionPath);
159
+ const active = records.filter((record) => !isQueueFinished(record));
160
+ if (active.length === 0)
161
+ return;
162
+ process.stdout.write("\nqueues:\n");
163
+ for (const record of active) {
164
+ process.stdout.write(` ${formatQueueSummary(record, queueLockPath(executionPath, record.queue_id))}\n`);
165
+ }
166
+ }