specdojo 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (531) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +82 -38
  3. package/dist/agent-response.js +27 -0
  4. package/dist/agent.js +124 -0
  5. package/dist/build-command.js +149 -0
  6. package/dist/build-if-stale.js +35 -0
  7. package/dist/catalog-build.js +1079 -0
  8. package/dist/catalog-generate.js +226 -0
  9. package/dist/catalog-paths.js +31 -0
  10. package/dist/catalog-plan-generate.js +301 -0
  11. package/dist/catalog-plan-prompt.js +73 -0
  12. package/dist/catalog-plan.js +471 -0
  13. package/dist/catalog-scaffold.js +255 -0
  14. package/dist/catalog-types.js +4 -0
  15. package/dist/catalog.js +606 -0
  16. package/dist/dashboard.js +980 -0
  17. package/dist/deliverable-trash.js +148 -0
  18. package/dist/deliverable.js +97 -0
  19. package/dist/dist-freshness.js +150 -0
  20. package/dist/doc-index.js +424 -0
  21. package/dist/exec-agent-config.js +172 -0
  22. package/dist/exec-agent-git-state.js +136 -0
  23. package/dist/exec-agent-protected-config.js +276 -0
  24. package/dist/exec-events.js +250 -112
  25. package/dist/exec-evidence.js +317 -0
  26. package/dist/exec-format.js +45 -0
  27. package/dist/exec-limit.js +202 -0
  28. package/dist/exec-parent-validation.js +169 -0
  29. package/dist/exec-pipeline-state.js +160 -0
  30. package/dist/exec-plans.js +1016 -0
  31. package/dist/exec-project.js +25 -11
  32. package/dist/exec-protection-handoff.js +169 -0
  33. package/dist/exec-provider-scaffold.js +99 -0
  34. package/dist/exec-register-resume.js +196 -0
  35. package/dist/exec-register.js +281 -0
  36. package/dist/exec-reporter.js +329 -0
  37. package/dist/exec-results.js +510 -0
  38. package/dist/exec-run-lock.js +149 -0
  39. package/dist/exec-run.js +4953 -0
  40. package/dist/exec-schedule-calendar.js +86 -9
  41. package/dist/exec-schedule-cpm.js +30 -12
  42. package/dist/exec-schedule-gantt-chart-render.js +428 -0
  43. package/dist/exec-schedule-gantt-chart-scope.js +111 -0
  44. package/dist/exec-schedule-gantt-chart.js +2 -0
  45. package/dist/exec-schedule-hash.js +34 -25
  46. package/dist/exec-schedule-index.js +200 -67
  47. package/dist/exec-schedule-initial.js +100 -0
  48. package/dist/exec-schedule-progress.js +51 -26
  49. package/dist/exec-schedule-ready.js +71 -27
  50. package/dist/exec-schedule.js +171 -93
  51. package/dist/exec-shared.js +146 -25
  52. package/dist/exec-strategy.js +547 -0
  53. package/dist/exec-task-view.js +64 -0
  54. package/dist/exec-trial.js +895 -0
  55. package/dist/exec-worktree-command.js +426 -0
  56. package/dist/exec-worktree-ops.js +847 -0
  57. package/dist/exec-worktree.js +359 -0
  58. package/dist/exec.js +744 -192
  59. package/dist/frontmatter-namespace.js +48 -0
  60. package/dist/git-environment.js +23 -0
  61. package/dist/grade-result.js +137 -0
  62. package/dist/grade.js +2456 -0
  63. package/dist/index-command.js +103 -0
  64. package/dist/job.js +1081 -0
  65. package/dist/kata-command.js +303 -0
  66. package/dist/kata.js +187 -0
  67. package/dist/package-paths.js +15 -0
  68. package/dist/practice-id.js +24 -0
  69. package/dist/register-date.js +122 -0
  70. package/dist/register-events.js +363 -0
  71. package/dist/register-history.js +323 -0
  72. package/dist/register-item.js +455 -0
  73. package/dist/register-migrate-timestamps.js +176 -0
  74. package/dist/register.js +2199 -0
  75. package/dist/review-plan.js +199 -0
  76. package/dist/review-types.js +1 -0
  77. package/dist/role-types.js +1 -0
  78. package/dist/routine.js +814 -0
  79. package/dist/schedule-approach.js +252 -0
  80. package/dist/schedule-build.js +552 -0
  81. package/dist/schedule-phase-sets.js +73 -0
  82. package/dist/schedule-strategy-generate.js +812 -0
  83. package/dist/schedule-strategy-profiles.js +276 -0
  84. package/dist/schedule.js +420 -0
  85. package/dist/spawn-self.js +28 -0
  86. package/dist/specdojo-config.js +133 -39
  87. package/dist/specdojo.js +55 -7
  88. package/dist/template-frontmatter.js +89 -0
  89. package/dist/template-resolution.js +92 -0
  90. package/dist/timeline-build.js +334 -0
  91. package/dist/timeline.js +107 -0
  92. package/dist/watch.js +313 -0
  93. package/dist/yaml-pages-command.js +28 -0
  94. package/dist/yaml-pages.js +180 -0
  95. package/dist/yaml-schema-modeline.js +49 -0
  96. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +600 -0
  97. package/docs/ja/specdojo/exec-templates/xep-bootstrap-template.md +120 -0
  98. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +37 -0
  99. package/docs/ja/specdojo/exec-templates/xep-cross-deliverable-dedup-template.md +51 -0
  100. package/docs/ja/specdojo/exec-templates/xep-freeform-template.md +74 -0
  101. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +109 -0
  102. package/docs/ja/specdojo/exec-templates/xep-job-template.md +43 -0
  103. package/docs/ja/specdojo/exec-templates/xep-recipe-guided-template.md +82 -0
  104. package/docs/ja/specdojo/exec-templates/xep-recipe-maintenance-template.md +86 -0
  105. package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +42 -0
  106. package/docs/ja/specdojo/exec-templates/xep-register-template.md +49 -0
  107. package/docs/ja/specdojo/exec-templates/xep-retrofit-template.md +98 -0
  108. package/docs/ja/specdojo/exec-templates/xep-rulebook-maintenance-template.md +86 -0
  109. package/docs/ja/specdojo/exec-templates/xep-sample-maintenance-template.md +86 -0
  110. package/docs/ja/specdojo/exec-templates/xep-template-maintenance-template.md +86 -0
  111. package/docs/ja/specdojo/exec-templates/xep-template.md +66 -0
  112. package/docs/ja/specdojo/exec-templates/xer-cross-deliverable-dedup-template.md +31 -0
  113. package/docs/ja/specdojo/exec-templates/xer-human-bootstrap-finalize-template.md +40 -0
  114. package/docs/ja/specdojo/exec-templates/xer-human-finalize-template.md +30 -0
  115. package/docs/ja/specdojo/exec-templates/xer-template.md +19 -0
  116. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +70 -0
  117. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +97 -0
  118. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +76 -0
  119. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +73 -0
  120. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +74 -0
  121. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +74 -0
  122. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +73 -0
  123. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +73 -0
  124. package/docs/ja/specdojo/exec-templates/xrp-template.md +67 -0
  125. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +7 -0
  126. package/docs/ja/specdojo/exec-templates/xrr-template.md +21 -0
  127. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +7 -0
  128. package/docs/ja/specdojo/guides/branch-workflow-guide.md +354 -0
  129. package/docs/ja/specdojo/guides/docs-editing-guide.md +327 -0
  130. package/docs/ja/specdojo/guides/docs-structure-guide.md +519 -0
  131. package/docs/ja/specdojo/guides/exec-config-guide.md +589 -0
  132. package/docs/ja/specdojo/guides/exec-operation-guide.md +440 -0
  133. package/docs/ja/specdojo/guides/exec-worktree-guide.md +318 -0
  134. package/docs/ja/specdojo/guides/kata-guide.md +89 -0
  135. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +127 -0
  136. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +228 -0
  137. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +111 -0
  138. package/docs/ja/specdojo/guides/quick-start-guide.md +473 -0
  139. package/docs/ja/specdojo/guides/register-operation-guide.md +418 -0
  140. package/docs/ja/specdojo/guides/review-guide.md +428 -0
  141. package/docs/ja/specdojo/guides/routine-operation-guide.md +282 -0
  142. package/docs/ja/specdojo/guides/ryu-guide.md +230 -0
  143. package/docs/ja/specdojo/guides/schedule-design-guide.md +429 -0
  144. package/docs/ja/specdojo/guides/schedule-operation-guide.md +151 -0
  145. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +257 -0
  146. package/docs/ja/specdojo/guides/timeline-design-guide.md +160 -0
  147. package/docs/ja/specdojo/guides/track-design-guide.md +215 -0
  148. package/docs/ja/specdojo/guides/use-case-guide.md +133 -0
  149. package/docs/ja/specdojo/guides/waza-guide.md +224 -0
  150. package/docs/ja/specdojo/index.md +33 -0
  151. package/docs/ja/specdojo/philosophy/needs-to-implementation-philosophy.md +212 -0
  152. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +242 -0
  153. package/docs/ja/specdojo/recipes/cdfd-overview-recipe.md +198 -0
  154. package/docs/ja/specdojo/recipes/cdfd-recipe.md +218 -0
  155. package/docs/ja/specdojo/recipes/cdfd-uc-recipe.md +198 -0
  156. package/docs/ja/specdojo/recipes/exec-human-finalize-recipe.md +100 -0
  157. package/docs/ja/specdojo/recipes/ifx-cmd-recipe.md +148 -0
  158. package/docs/ja/specdojo/recipes/pm-communication-plan-recipe.md +97 -0
  159. package/docs/ja/specdojo/recipes/pm-members-recipe.md +149 -0
  160. package/docs/ja/specdojo/recipes/pm-organization-recipe.md +96 -0
  161. package/docs/ja/specdojo/recipes/pm-plan-recipe.md +98 -0
  162. package/docs/ja/specdojo/recipes/pm-quality-management-plan-recipe.md +97 -0
  163. package/docs/ja/specdojo/recipes/pm-raci-recipe.md +96 -0
  164. package/docs/ja/specdojo/recipes/pm-roles-recipe.md +136 -0
  165. package/docs/ja/specdojo/recipes/prj-assumptions-constraints-dependencies-recipe.md +162 -0
  166. package/docs/ja/specdojo/recipes/prj-charter-recipe.md +187 -0
  167. package/docs/ja/specdojo/recipes/prj-comparison-of-alternatives-recipe.md +235 -0
  168. package/docs/ja/specdojo/recipes/prj-issues-and-approach-recipe.md +205 -0
  169. package/docs/ja/specdojo/recipes/prj-overview-recipe.md +289 -0
  170. package/docs/ja/specdojo/recipes/prj-scope-recipe.md +201 -0
  171. package/docs/ja/specdojo/recipes/prj-stakeholder-register-recipe.md +168 -0
  172. package/docs/ja/specdojo/recipes/prj-success-criteria-and-acceptance-criteria-recipe.md +179 -0
  173. package/docs/ja/specdojo/recipes/stsd-recipe.md +138 -0
  174. package/docs/ja/specdojo/references/command-reference.md +718 -0
  175. package/docs/ja/specdojo/references/deliverables-reference.md +407 -0
  176. package/docs/ja/specdojo/references/directory-layout-reference.md +280 -0
  177. package/docs/ja/specdojo/references/specdojo-config-reference.md +133 -0
  178. package/docs/ja/specdojo/rulebooks/atc-index-rulebook.md +372 -0
  179. package/docs/ja/specdojo/rulebooks/atc-rulebook.md +302 -0
  180. package/docs/ja/specdojo/rulebooks/bac-rulebook.md +331 -0
  181. package/docs/ja/specdojo/rulebooks/bdd-rulebook.md +134 -0
  182. package/docs/ja/specdojo/rulebooks/bds-rulebook.md +207 -0
  183. package/docs/ja/specdojo/rulebooks/bes-index-rulebook.md +102 -0
  184. package/docs/ja/specdojo/rulebooks/bes-rulebook.md +131 -0
  185. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +269 -0
  186. package/docs/ja/specdojo/rulebooks/br-rulebook.md +187 -0
  187. package/docs/ja/specdojo/rulebooks/ccd-mermaid-rulebook.md +279 -0
  188. package/docs/ja/specdojo/rulebooks/cdfd-mermaid-rulebook.md +219 -0
  189. package/docs/ja/specdojo/rulebooks/cdfd-overview-rulebook.md +233 -0
  190. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +182 -0
  191. package/docs/ja/specdojo/rulebooks/cdfd-uc-rulebook.md +171 -0
  192. package/docs/ja/specdojo/rulebooks/cdsd-rulebook.md +105 -0
  193. package/docs/ja/specdojo/rulebooks/cld-rulebook.md +195 -0
  194. package/docs/ja/specdojo/rulebooks/cnd-mermaid-rulebook.md +285 -0
  195. package/docs/ja/specdojo/rulebooks/cnd-rulebook.md +292 -0
  196. package/docs/ja/specdojo/rulebooks/cop-index-rulebook.md +171 -0
  197. package/docs/ja/specdojo/rulebooks/cop-rulebook.md +325 -0
  198. package/docs/ja/specdojo/rulebooks/cpd-mermaid-rulebook.md +266 -0
  199. package/docs/ja/specdojo/rulebooks/cpd-rulebook.md +294 -0
  200. package/docs/ja/specdojo/rulebooks/cstd-rulebook.md +21 -0
  201. package/docs/ja/specdojo/rulebooks/cxd-mermaid-rulebook.md +401 -0
  202. package/docs/ja/specdojo/rulebooks/cxd-rulebook.md +311 -0
  203. package/docs/ja/specdojo/rulebooks/dct-index-rulebook.md +158 -0
  204. package/docs/ja/specdojo/rulebooks/dct-rulebook.md +287 -0
  205. package/docs/ja/specdojo/rulebooks/dec-rulebook.md +62 -0
  206. package/docs/ja/specdojo/rulebooks/dmd-index-rulebook.md +100 -0
  207. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +298 -0
  208. package/docs/ja/specdojo/rulebooks/etc-index-rulebook.md +379 -0
  209. package/docs/ja/specdojo/rulebooks/etc-rulebook.md +310 -0
  210. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +86 -0
  211. package/docs/ja/specdojo/rulebooks/ifd-mermaid-rulebook.md +297 -0
  212. package/docs/ja/specdojo/rulebooks/ifx-api-rulebook.md +79 -0
  213. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +213 -0
  214. package/docs/ja/specdojo/rulebooks/ifx-file-rulebook.md +311 -0
  215. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +94 -0
  216. package/docs/ja/specdojo/rulebooks/ifx-msg-rulebook.md +81 -0
  217. package/docs/ja/specdojo/rulebooks/imp-business-rulebook.md +117 -0
  218. package/docs/ja/specdojo/rulebooks/imp-data-rulebook.md +118 -0
  219. package/docs/ja/specdojo/rulebooks/imp-interface-rulebook.md +116 -0
  220. package/docs/ja/specdojo/rulebooks/imp-operations-rulebook.md +116 -0
  221. package/docs/ja/specdojo/rulebooks/imp-test-rulebook.md +116 -0
  222. package/docs/ja/specdojo/rulebooks/itc-index-rulebook.md +421 -0
  223. package/docs/ja/specdojo/rulebooks/itc-rulebook.md +307 -0
  224. package/docs/ja/specdojo/rulebooks/mip-index-rulebook.md +312 -0
  225. package/docs/ja/specdojo/rulebooks/mm-rulebook.md +63 -0
  226. package/docs/ja/specdojo/rulebooks/mtp-rulebook.md +353 -0
  227. package/docs/ja/specdojo/rulebooks/nfr-availability-rulebook.md +184 -0
  228. package/docs/ja/specdojo/rulebooks/nfr-index-rulebook.md +179 -0
  229. package/docs/ja/specdojo/rulebooks/nfr-integrity-rulebook.md +184 -0
  230. package/docs/ja/specdojo/rulebooks/nfr-maintainability-rulebook.md +183 -0
  231. package/docs/ja/specdojo/rulebooks/nfr-operations-rulebook.md +185 -0
  232. package/docs/ja/specdojo/rulebooks/nfr-performance-rulebook.md +185 -0
  233. package/docs/ja/specdojo/rulebooks/nfr-reliability-rulebook.md +186 -0
  234. package/docs/ja/specdojo/rulebooks/nfr-security-safety-rulebook.md +186 -0
  235. package/docs/ja/specdojo/rulebooks/nfr-usability-rulebook.md +184 -0
  236. package/docs/ja/specdojo/rulebooks/ntp-rulebook.md +61 -0
  237. package/docs/ja/specdojo/rulebooks/opd-index-rulebook.md +84 -0
  238. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +357 -0
  239. package/docs/ja/specdojo/rulebooks/opr-index-rulebook.md +80 -0
  240. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +484 -0
  241. package/docs/ja/specdojo/rulebooks/otp-index-rulebook.md +120 -0
  242. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +293 -0
  243. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +211 -0
  244. package/docs/ja/specdojo/rulebooks/pm-change-request-log-rulebook.md +94 -0
  245. package/docs/ja/specdojo/rulebooks/pm-communication-plan-rulebook.md +116 -0
  246. package/docs/ja/specdojo/rulebooks/pm-issue-log-rulebook.md +93 -0
  247. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +190 -0
  248. package/docs/ja/specdojo/rulebooks/pm-organization-rulebook.md +108 -0
  249. package/docs/ja/specdojo/rulebooks/pm-plan-rulebook.md +122 -0
  250. package/docs/ja/specdojo/rulebooks/pm-quality-management-plan-rulebook.md +117 -0
  251. package/docs/ja/specdojo/rulebooks/pm-raci-rulebook.md +116 -0
  252. package/docs/ja/specdojo/rulebooks/pm-risk-register-rulebook.md +93 -0
  253. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +146 -0
  254. package/docs/ja/specdojo/rulebooks/pr-rulebook.md +65 -0
  255. package/docs/ja/specdojo/rulebooks/prj-assumptions-constraints-dependencies-rulebook.md +178 -0
  256. package/docs/ja/specdojo/rulebooks/prj-charter-rulebook.md +232 -0
  257. package/docs/ja/specdojo/rulebooks/prj-comparison-of-alternatives-rulebook.md +235 -0
  258. package/docs/ja/specdojo/rulebooks/prj-issues-and-approach-rulebook.md +242 -0
  259. package/docs/ja/specdojo/rulebooks/prj-overview-rulebook.md +187 -0
  260. package/docs/ja/specdojo/rulebooks/prj-scope-rulebook.md +201 -0
  261. package/docs/ja/specdojo/rulebooks/prj-stakeholder-register-rulebook.md +165 -0
  262. package/docs/ja/specdojo/rulebooks/prj-success-criteria-and-acceptance-criteria-rulebook.md +165 -0
  263. package/docs/ja/specdojo/rulebooks/sac-rulebook.md +202 -0
  264. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +139 -0
  265. package/docs/ja/specdojo/rulebooks/sf-index-rulebook.md +63 -0
  266. package/docs/ja/specdojo/rulebooks/sf-rulebook.md +93 -0
  267. package/docs/ja/specdojo/rulebooks/sld-rulebook.md +93 -0
  268. package/docs/ja/specdojo/rulebooks/stc-index-rulebook.md +329 -0
  269. package/docs/ja/specdojo/rulebooks/stc-rulebook.md +297 -0
  270. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +132 -0
  271. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +215 -0
  272. package/docs/ja/specdojo/rulebooks/sysd-critical-flows-rulebook.md +376 -0
  273. package/docs/ja/specdojo/rulebooks/sysd-cross-cutting-policy-rulebook.md +313 -0
  274. package/docs/ja/specdojo/rulebooks/sysd-index-rulebook.md +246 -0
  275. package/docs/ja/specdojo/rulebooks/sysd-rulebook.md +119 -0
  276. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +188 -0
  277. package/docs/ja/specdojo/rulebooks/trc-requirements-to-specs-rulebook.md +114 -0
  278. package/docs/ja/specdojo/rulebooks/trc-requirements-to-tests-rulebook.md +117 -0
  279. package/docs/ja/specdojo/rulebooks/tsd-index-rulebook.md +101 -0
  280. package/docs/ja/specdojo/rulebooks/tsd-rulebook.md +103 -0
  281. package/docs/ja/specdojo/rulebooks/tsp-index-rulebook.md +396 -0
  282. package/docs/ja/specdojo/rulebooks/uis-rulebook.md +207 -0
  283. package/docs/ja/specdojo/rulebooks/utc-index-rulebook.md +387 -0
  284. package/docs/ja/specdojo/rulebooks/utc-rulebook.md +303 -0
  285. package/docs/ja/specdojo/samples/atc-index-sample.md +38 -0
  286. package/docs/ja/specdojo/samples/atc-sample.md +41 -0
  287. package/docs/ja/specdojo/samples/bac-sample.md +38 -0
  288. package/docs/ja/specdojo/samples/bdd-sample.yaml +71 -0
  289. package/docs/ja/specdojo/samples/bds-sample.md +38 -0
  290. package/docs/ja/specdojo/samples/bes-index-sample.md +38 -0
  291. package/docs/ja/specdojo/samples/bes-sample.md +38 -0
  292. package/docs/ja/specdojo/samples/bps-sample.md +38 -0
  293. package/docs/ja/specdojo/samples/br-sample.md +40 -0
  294. package/docs/ja/specdojo/samples/ccd-sample.md +38 -0
  295. package/docs/ja/specdojo/samples/cdfd-overview-sample.md +284 -0
  296. package/docs/ja/specdojo/samples/cdfd-sample.md +229 -0
  297. package/docs/ja/specdojo/samples/cdfd-uc-sample.md +146 -0
  298. package/docs/ja/specdojo/samples/cdsd-sample.md +38 -0
  299. package/docs/ja/specdojo/samples/cld-sample.md +38 -0
  300. package/docs/ja/specdojo/samples/cnd-sample.md +38 -0
  301. package/docs/ja/specdojo/samples/cop-index-sample.md +38 -0
  302. package/docs/ja/specdojo/samples/cop-sample.md +38 -0
  303. package/docs/ja/specdojo/samples/cpd-sample.md +38 -0
  304. package/docs/ja/specdojo/samples/cstd-sample.md +11 -0
  305. package/docs/ja/specdojo/samples/cxd-sample.md +38 -0
  306. package/docs/ja/specdojo/samples/dct-index-sample.yaml +39 -0
  307. package/docs/ja/specdojo/samples/dct-sample.yaml +91 -0
  308. package/docs/ja/specdojo/samples/dec-sample.md +39 -0
  309. package/docs/ja/specdojo/samples/dmd-index-sample.md +50 -0
  310. package/docs/ja/specdojo/samples/dmd-sample.md +74 -0
  311. package/docs/ja/specdojo/samples/etc-index-sample.md +38 -0
  312. package/docs/ja/specdojo/samples/etc-sample.md +38 -0
  313. package/docs/ja/specdojo/samples/gl-sample.yaml +37 -0
  314. package/docs/ja/specdojo/samples/ifd-sample.md +38 -0
  315. package/docs/ja/specdojo/samples/ifx-api-sample.yaml +102 -0
  316. package/docs/ja/specdojo/samples/ifx-cmd-sample.yaml +107 -0
  317. package/docs/ja/specdojo/samples/ifx-file-sample.md +38 -0
  318. package/docs/ja/specdojo/samples/ifx-msg-sample.yaml +89 -0
  319. package/docs/ja/specdojo/samples/imp-business-sample.md +66 -0
  320. package/docs/ja/specdojo/samples/imp-data-sample.md +60 -0
  321. package/docs/ja/specdojo/samples/imp-interface-sample.md +60 -0
  322. package/docs/ja/specdojo/samples/imp-operations-sample.md +60 -0
  323. package/docs/ja/specdojo/samples/imp-test-sample.md +60 -0
  324. package/docs/ja/specdojo/samples/itc-index-sample.md +38 -0
  325. package/docs/ja/specdojo/samples/itc-sample.md +38 -0
  326. package/docs/ja/specdojo/samples/mip-index-sample.md +38 -0
  327. package/docs/ja/specdojo/samples/mm-sample.md +35 -0
  328. package/docs/ja/specdojo/samples/mtp-sample.md +38 -0
  329. package/docs/ja/specdojo/samples/nfr-availability-sample.md +38 -0
  330. package/docs/ja/specdojo/samples/nfr-index-sample.md +38 -0
  331. package/docs/ja/specdojo/samples/nfr-integrity-sample.md +38 -0
  332. package/docs/ja/specdojo/samples/nfr-maintainability-sample.md +38 -0
  333. package/docs/ja/specdojo/samples/nfr-operations-sample.md +38 -0
  334. package/docs/ja/specdojo/samples/nfr-performance-sample.md +38 -0
  335. package/docs/ja/specdojo/samples/nfr-reliability-sample.md +38 -0
  336. package/docs/ja/specdojo/samples/nfr-security-safety-sample.md +38 -0
  337. package/docs/ja/specdojo/samples/nfr-usability-sample.md +38 -0
  338. package/docs/ja/specdojo/samples/ntp-sample.md +38 -0
  339. package/docs/ja/specdojo/samples/opd-access-control-sample.md +29 -0
  340. package/docs/ja/specdojo/samples/opd-incident-management-sample.md +31 -0
  341. package/docs/ja/specdojo/samples/opd-index-sample.md +41 -0
  342. package/docs/ja/specdojo/samples/opd-monitoring-sample.md +32 -0
  343. package/docs/ja/specdojo/samples/opd-sample.md +38 -0
  344. package/docs/ja/specdojo/samples/opr-access-control-sample.md +24 -0
  345. package/docs/ja/specdojo/samples/opr-backup-restore-sample.md +27 -0
  346. package/docs/ja/specdojo/samples/opr-batch-sample.md +23 -0
  347. package/docs/ja/specdojo/samples/opr-change-sample.md +24 -0
  348. package/docs/ja/specdojo/samples/opr-incident-sample.md +38 -0
  349. package/docs/ja/specdojo/samples/opr-index-sample.md +43 -0
  350. package/docs/ja/specdojo/samples/opr-monitoring-sample.md +27 -0
  351. package/docs/ja/specdojo/samples/opr-sample.md +38 -0
  352. package/docs/ja/specdojo/samples/opr-support-sample.md +23 -0
  353. package/docs/ja/specdojo/samples/otp-index-sample.md +66 -0
  354. package/docs/ja/specdojo/samples/otp-sample.md +68 -0
  355. package/docs/ja/specdojo/samples/pm-change-request-log-sample.md +47 -0
  356. package/docs/ja/specdojo/samples/pm-communication-plan-sample.md +46 -0
  357. package/docs/ja/specdojo/samples/pm-issue-log-sample.md +45 -0
  358. package/docs/ja/specdojo/samples/pm-members-sample.yaml +103 -0
  359. package/docs/ja/specdojo/samples/pm-organization-sample.md +46 -0
  360. package/docs/ja/specdojo/samples/pm-plan-sample.md +57 -0
  361. package/docs/ja/specdojo/samples/pm-quality-management-plan-sample.md +52 -0
  362. package/docs/ja/specdojo/samples/pm-raci-sample.md +57 -0
  363. package/docs/ja/specdojo/samples/pm-risk-register-sample.md +43 -0
  364. package/docs/ja/specdojo/samples/pm-roles-sample.yaml +41 -0
  365. package/docs/ja/specdojo/samples/pr-sample.md +39 -0
  366. package/docs/ja/specdojo/samples/prj-assumptions-constraints-dependencies-sample.md +57 -0
  367. package/docs/ja/specdojo/samples/prj-charter-sample.md +121 -0
  368. package/docs/ja/specdojo/samples/prj-comparison-of-alternatives-sample.md +105 -0
  369. package/docs/ja/specdojo/samples/prj-issues-and-approach-sample.md +78 -0
  370. package/docs/ja/specdojo/samples/prj-overview-sample.md +95 -0
  371. package/docs/ja/specdojo/samples/prj-scope-sample.md +71 -0
  372. package/docs/ja/specdojo/samples/prj-stakeholder-register-sample.md +60 -0
  373. package/docs/ja/specdojo/samples/prj-success-criteria-and-acceptance-criteria-sample.md +62 -0
  374. package/docs/ja/specdojo/samples/sac-sample.md +38 -0
  375. package/docs/ja/specdojo/samples/sf-index-sample.md +38 -0
  376. package/docs/ja/specdojo/samples/sf-sample.md +38 -0
  377. package/docs/ja/specdojo/samples/sld-sample.md +38 -0
  378. package/docs/ja/specdojo/samples/stc-index-sample.md +38 -0
  379. package/docs/ja/specdojo/samples/stc-sample.md +38 -0
  380. package/docs/ja/specdojo/samples/stsd-sample.md +58 -0
  381. package/docs/ja/specdojo/samples/sysd-critical-flows-sample.md +38 -0
  382. package/docs/ja/specdojo/samples/sysd-cross-cutting-policy-sample.md +38 -0
  383. package/docs/ja/specdojo/samples/sysd-index-sample.md +38 -0
  384. package/docs/ja/specdojo/samples/trc-requirements-to-specs-sample.md +56 -0
  385. package/docs/ja/specdojo/samples/trc-requirements-to-tests-sample.md +56 -0
  386. package/docs/ja/specdojo/samples/tsd-index-sample.md +29 -0
  387. package/docs/ja/specdojo/samples/tsd-sample.md +38 -0
  388. package/docs/ja/specdojo/samples/tsp-index-sample.md +38 -0
  389. package/docs/ja/specdojo/samples/uis-sample.md +38 -0
  390. package/docs/ja/specdojo/samples/utc-index-sample.md +38 -0
  391. package/docs/ja/specdojo/samples/utc-sample.md +38 -0
  392. package/docs/ja/specdojo/schemas/v1/guide-content.schema.yaml +20 -0
  393. package/docs/ja/specdojo/schemas/v1/philosophy-content.schema.yaml +21 -0
  394. package/docs/ja/specdojo/schemas/v1/reference-content.schema.yaml +21 -0
  395. package/docs/ja/specdojo/standards/document-metadata-standard.md +323 -0
  396. package/docs/ja/specdojo/standards/exec-human-finalize-standard.md +75 -0
  397. package/docs/ja/specdojo/standards/git-branching-standard.md +227 -0
  398. package/docs/ja/specdojo/standards/guide-authoring-standard.md +124 -0
  399. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +929 -0
  400. package/docs/ja/specdojo/standards/job-definition-standard.md +148 -0
  401. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +431 -0
  402. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +113 -0
  403. package/docs/ja/specdojo/standards/recipe-authoring-standard.md +143 -0
  404. package/docs/ja/specdojo/standards/reference-authoring-standard.md +99 -0
  405. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +140 -0
  406. package/docs/ja/specdojo/standards/sample-authoring-standard.md +151 -0
  407. package/docs/ja/specdojo/standards/standard-authoring-standard.md +108 -0
  408. package/docs/ja/specdojo/standards/template-authoring-standard.md +101 -0
  409. package/docs/ja/specdojo/standards/test-document-scope-standard.md +176 -0
  410. package/docs/ja/specdojo/templates/cdfd-overview-template.md +199 -0
  411. package/docs/ja/specdojo/templates/cdfd-template.md +173 -0
  412. package/docs/ja/specdojo/templates/cdfd-uc-template.md +148 -0
  413. package/docs/ja/specdojo/templates/dct-architecture-template.yaml +136 -0
  414. package/docs/ja/specdojo/templates/dct-business-acceptance-criteria-template.yaml +34 -0
  415. package/docs/ja/specdojo/templates/dct-business-model-bes-template.yaml +75 -0
  416. package/docs/ja/specdojo/templates/dct-business-model-bps-template.yaml +49 -0
  417. package/docs/ja/specdojo/templates/dct-business-model-br-template.yaml +50 -0
  418. package/docs/ja/specdojo/templates/dct-data-flow-template.yaml +40 -0
  419. package/docs/ja/specdojo/templates/dct-data-model-bdd-template.yaml +46 -0
  420. package/docs/ja/specdojo/templates/dct-data-model-ccd-template.yaml +46 -0
  421. package/docs/ja/specdojo/templates/dct-data-model-cdsd-template.yaml +41 -0
  422. package/docs/ja/specdojo/templates/dct-data-model-cld-template.yaml +38 -0
  423. package/docs/ja/specdojo/templates/dct-data-model-sld-template.yaml +38 -0
  424. package/docs/ja/specdojo/templates/dct-data-model-stsd-template.yaml +46 -0
  425. package/docs/ja/specdojo/templates/dct-external-interface-specs-template.yaml +114 -0
  426. package/docs/ja/specdojo/templates/dct-glossary-template.yaml +35 -0
  427. package/docs/ja/specdojo/templates/dct-impact-analysis-template.yaml +138 -0
  428. package/docs/ja/specdojo/templates/dct-index-template.md +40 -0
  429. package/docs/ja/specdojo/templates/dct-migration-planning-template.yaml +148 -0
  430. package/docs/ja/specdojo/templates/dct-non-functional-requirements-template.yaml +222 -0
  431. package/docs/ja/specdojo/templates/dct-operations-template.yaml +108 -0
  432. package/docs/ja/specdojo/templates/dct-project-definition-template.yaml +210 -0
  433. package/docs/ja/specdojo/templates/dct-project-management-template.yaml +423 -0
  434. package/docs/ja/specdojo/templates/dct-system-acceptance-criteria-template.yaml +37 -0
  435. package/docs/ja/specdojo/templates/dct-system-design-template.yaml +82 -0
  436. package/docs/ja/specdojo/templates/dct-system-functions-template.yaml +58 -0
  437. package/docs/ja/specdojo/templates/dct-test-specs-template.yaml +261 -0
  438. package/docs/ja/specdojo/templates/dct-user-interface-model-template.yaml +60 -0
  439. package/docs/ja/specdojo/templates/ifx-cmd-template.yaml +88 -0
  440. package/docs/ja/specdojo/templates/opr-template.md +85 -0
  441. package/docs/ja/specdojo/templates/pjr-change-request-template.md +60 -0
  442. package/docs/ja/specdojo/templates/pjr-decision-template.md +61 -0
  443. package/docs/ja/specdojo/templates/pjr-index-template.md +49 -0
  444. package/docs/ja/specdojo/templates/pjr-issue-template.md +50 -0
  445. package/docs/ja/specdojo/templates/pjr-note-template.md +35 -0
  446. package/docs/ja/specdojo/templates/pjr-question-template.md +53 -0
  447. package/docs/ja/specdojo/templates/pjr-risk-template.md +49 -0
  448. package/docs/ja/specdojo/templates/pjr-todo-template.md +41 -0
  449. package/docs/ja/specdojo/templates/pjr-views-by-owner-template.md +22 -0
  450. package/docs/ja/specdojo/templates/pjr-views-by-priority-template.md +22 -0
  451. package/docs/ja/specdojo/templates/pjr-views-by-status-template.md +22 -0
  452. package/docs/ja/specdojo/templates/pm-change-request-log-template.md +20 -0
  453. package/docs/ja/specdojo/templates/pm-communication-plan-template.md +46 -0
  454. package/docs/ja/specdojo/templates/pm-decision-log-template.md +20 -0
  455. package/docs/ja/specdojo/templates/pm-issue-log-template.md +20 -0
  456. package/docs/ja/specdojo/templates/pm-members-template.yaml +105 -0
  457. package/docs/ja/specdojo/templates/pm-organization-template.md +44 -0
  458. package/docs/ja/specdojo/templates/pm-plan-template.md +52 -0
  459. package/docs/ja/specdojo/templates/pm-quality-management-plan-template.md +46 -0
  460. package/docs/ja/specdojo/templates/pm-raci-template.md +51 -0
  461. package/docs/ja/specdojo/templates/pm-risk-register-template.md +20 -0
  462. package/docs/ja/specdojo/templates/pm-roles-template.yaml +53 -0
  463. package/docs/ja/specdojo/templates/prj-assumptions-constraints-dependencies-template.md +59 -0
  464. package/docs/ja/specdojo/templates/prj-charter-template.md +116 -0
  465. package/docs/ja/specdojo/templates/prj-comparison-of-alternatives-template.md +116 -0
  466. package/docs/ja/specdojo/templates/prj-issues-and-approach-template.md +89 -0
  467. package/docs/ja/specdojo/templates/prj-overview-template.md +85 -0
  468. package/docs/ja/specdojo/templates/prj-scope-template.md +75 -0
  469. package/docs/ja/specdojo/templates/prj-stakeholder-register-template.md +64 -0
  470. package/docs/ja/specdojo/templates/prj-success-criteria-and-acceptance-criteria-template.md +60 -0
  471. package/docs/ja/specdojo/templates/stsd-template.md +57 -0
  472. package/docs/specdojo/schemas/v1/bdd.schema.yaml +230 -0
  473. package/docs/specdojo/schemas/v1/common-frontmatter.schema.yaml +77 -0
  474. package/docs/specdojo/schemas/v1/dct-index.schema.yaml +85 -0
  475. package/docs/specdojo/schemas/v1/dct-plan.schema.yaml +324 -0
  476. package/docs/specdojo/schemas/v1/dct.schema.yaml +368 -0
  477. package/docs/specdojo/schemas/v1/deliverable-frontmatter.schema.yaml +91 -0
  478. package/docs/specdojo/schemas/v1/esil.schema.yaml +142 -0
  479. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +101 -0
  480. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +272 -0
  481. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +162 -0
  482. package/docs/specdojo/schemas/v1/exec-plan-frontmatter.schema.yaml +126 -0
  483. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +151 -0
  484. package/docs/specdojo/schemas/v1/exec-result-frontmatter.schema.yaml +144 -0
  485. package/docs/specdojo/schemas/v1/grade-done-criteria.schema.yaml +79 -0
  486. package/docs/specdojo/schemas/v1/grade-pipeline-state.schema.yaml +60 -0
  487. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +118 -0
  488. package/docs/specdojo/schemas/v1/guide-frontmatter.schema.yaml +19 -0
  489. package/docs/specdojo/schemas/v1/ifx-cmd.schema.yaml +293 -0
  490. package/docs/specdojo/schemas/v1/job-run.schema.yaml +90 -0
  491. package/docs/specdojo/schemas/v1/job.schema.yaml +198 -0
  492. package/docs/specdojo/schemas/v1/philosophy-frontmatter.schema.yaml +19 -0
  493. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +56 -0
  494. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +252 -0
  495. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +387 -0
  496. package/docs/specdojo/schemas/v1/pm-roles.schema.yaml +106 -0
  497. package/docs/specdojo/schemas/v1/recipe-frontmatter.schema.yaml +27 -0
  498. package/docs/specdojo/schemas/v1/reference-frontmatter.schema.yaml +18 -0
  499. package/docs/specdojo/schemas/v1/register-events.schema.yaml +106 -0
  500. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +204 -0
  501. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +36 -0
  502. package/docs/specdojo/schemas/v1/routine.schema.yaml +87 -0
  503. package/docs/specdojo/schemas/v1/rulebook-frontmatter.schema.yaml +61 -0
  504. package/docs/specdojo/schemas/v1/sch-common.schema.yaml +258 -0
  505. package/docs/specdojo/schemas/v1/sch-defaults.schema.yaml +48 -0
  506. package/docs/specdojo/schemas/v1/sch-milestones.schema.yaml +64 -0
  507. package/docs/specdojo/schemas/v1/sch-strategy.schema.yaml +772 -0
  508. package/docs/specdojo/schemas/v1/sch-track.schema.yaml +66 -0
  509. package/docs/specdojo/schemas/v1/standard-frontmatter.schema.yaml +18 -0
  510. package/docs/specdojo/schemas/v1/tml-index.schema.yaml +103 -0
  511. package/package.json +120 -24
  512. package/templates/claude/README.md +46 -0
  513. package/templates/claude/agents/claude-expert-review-executor.md +14 -0
  514. package/templates/claude/agents/claude-review-executor.md +14 -0
  515. package/templates/claude/settings.edit.json +6 -0
  516. package/templates/claude/settings.report.json +6 -0
  517. package/templates/claude/settings.review.json +7 -0
  518. package/templates/codex/README.md +61 -0
  519. package/templates/codex/agents/codex-executor.toml +12 -0
  520. package/templates/codex/agents/codex-expert-executor.toml +12 -0
  521. package/templates/codex/agents/codex-expert-review-executor.toml +10 -0
  522. package/templates/codex/agents/codex-review-executor.toml +10 -0
  523. package/templates/copilot/README.md +41 -0
  524. package/templates/copilot/exec-defaults-snippet.yaml +28 -0
  525. package/templates/copilot/pm-members-snippet.yaml +44 -0
  526. package/templates/opencode/README.md +41 -0
  527. package/templates/opencode/agents/opencode-executor.md +59 -0
  528. package/templates/opencode/agents/opencode-reporter.md +26 -0
  529. package/templates/opencode/agents/opencode-review-executor.md +48 -0
  530. package/dist/exec-schedule-timeline-render.js +0 -201
  531. package/dist/exec-schedule-timeline.js +0 -2
package/dist/grade.js ADDED
@@ -0,0 +1,2456 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import yaml from "js-yaml";
5
+ import remarkParse from "remark-parse";
6
+ import { unified } from "unified";
7
+ import { extractJsonText } from "./agent-response.js";
8
+ import { collectResolvedDeliverables, loadCatalogDocs } from "./catalog-build.js";
9
+ import { isTrashedPath, resolveBasePath } from "./catalog-paths.js";
10
+ import { resolveViewpointsDoc } from "./review-plan.js";
11
+ import { assertValidActor, getProjectCatalogPath, getProjectExecutionPath, getProjectViewpointsPath, loadConfig, loadMemberRoster, specdojoRootDir, } from "./specdojo-config.js";
12
+ import { listFilesRecursive } from "./exec-shared.js";
13
+ import { resolveSpecdojoPath } from "./template-resolution.js";
14
+ import { gradeContentHash, gradeFindingCount, gradeResultPath, markdownDocumentId, readGradeResult, readGradeResultForDocument, resolveGradeResultsDirectory, validateGradeResult, writeGradeResult, } from "./grade-result.js";
15
+ const FINDING_RE = /^[ \t]*<!--[ \t]*specdojo:finding[ \t]+id=([^ \t]+)[ \t]+severity=(blocker|major|minor|note)[ \t]+rule=([^ \t]+)(?:[ \t]+line=([1-9][0-9]*))?[ \t]+(.*?)[ \t]*-->[ \t]*(?:\r?\n|$)/gm;
16
+ const KATA_DIRS = ["rulebooks", "recipes", "samples", "templates"];
17
+ const KATA_REFERENCE_EXTENSIONS = new Set([".md", ".yaml", ".yml", ".json"]);
18
+ const KATA_REFERENCE_FIELDS = ["rulebook", "recipe", "sample", "template"];
19
+ const CRITERION_ID_RE = /^DC-[0-9]{3,}$/;
20
+ const CRITERION_STATUSES = ["satisfied", "unsatisfied"];
21
+ const DONE_CRITERIA_SCHEMA = "docs/specdojo/schemas/v1/grade-done-criteria.schema.yaml";
22
+ const GRADE_PLACEHOLDER = "__SPECDOJO_GRADE_FLOW_PLACEHOLDER__";
23
+ const GRADE_FINDINGS_PLACEHOLDER = "__SPECDOJO_GRADE_FINDINGS_FLOW_PLACEHOLDER__";
24
+ const GRADE_UNSATISFIED_PLACEHOLDER = "__SPECDOJO_GRADE_UNSATISFIED_BLOCK_PLACEHOLDER__";
25
+ const SEVERITY_LEVEL_CAP = {
26
+ blocker: 0,
27
+ major: 2,
28
+ minor: 3,
29
+ note: 4,
30
+ };
31
+ function preservePreviousFindingSeverities(body, viewpoints) {
32
+ const previousByMessage = new Map();
33
+ for (const finding of previousGradeFindings(body)) {
34
+ const message = sanitizeCommentText(finding.message);
35
+ const previous = previousByMessage.get(message);
36
+ if (previous === undefined ||
37
+ SEVERITY_LEVEL_CAP[finding.severity] < SEVERITY_LEVEL_CAP[previous]) {
38
+ previousByMessage.set(message, finding.severity);
39
+ }
40
+ }
41
+ return viewpoints.map((viewpoint) => {
42
+ const findings = (viewpoint.findings ?? []).map((finding) => {
43
+ const previous = previousByMessage.get(sanitizeCommentText(finding.message));
44
+ return previous !== undefined &&
45
+ SEVERITY_LEVEL_CAP[previous] < SEVERITY_LEVEL_CAP[finding.severity]
46
+ ? { ...finding, severity: previous }
47
+ : { ...finding };
48
+ });
49
+ return {
50
+ ...viewpoint,
51
+ findings,
52
+ level: Math.min(viewpoint.level, levelCapForFindings(findings)),
53
+ };
54
+ });
55
+ }
56
+ function preserveStoredFindingSeverities(previous, viewpoints) {
57
+ const previousByMessage = new Map();
58
+ for (const finding of previous?.findings ?? []) {
59
+ const message = sanitizeCommentText(finding.message);
60
+ const stored = previousByMessage.get(message);
61
+ if (stored === undefined || SEVERITY_LEVEL_CAP[finding.severity] < SEVERITY_LEVEL_CAP[stored]) {
62
+ previousByMessage.set(message, finding.severity);
63
+ }
64
+ }
65
+ return viewpoints.map((viewpoint) => {
66
+ const findings = (viewpoint.findings ?? []).map((finding) => {
67
+ const stored = previousByMessage.get(sanitizeCommentText(finding.message));
68
+ return stored !== undefined &&
69
+ SEVERITY_LEVEL_CAP[stored] < SEVERITY_LEVEL_CAP[finding.severity]
70
+ ? { ...finding, severity: stored }
71
+ : { ...finding };
72
+ });
73
+ return {
74
+ ...viewpoint,
75
+ findings,
76
+ level: Math.min(viewpoint.level, levelCapForFindings(findings)),
77
+ };
78
+ });
79
+ }
80
+ function levelCapForFindings(findings) {
81
+ const majorCount = findings.filter((finding) => finding.severity === "major").length;
82
+ const severityCap = findings.reduce((current, finding) => Math.min(current, SEVERITY_LEVEL_CAP[finding.severity]), 4);
83
+ return majorCount >= 2 ? Math.min(severityCap, 1) : severityCap;
84
+ }
85
+ function isRecord(value) {
86
+ return typeof value === "object" && value !== null && !Array.isArray(value);
87
+ }
88
+ function parseMarkdown(content, path) {
89
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
90
+ if (!match)
91
+ throw new Error(`${path}: Markdown frontmatter is required`);
92
+ const parsed = yaml.load(match[1]);
93
+ if (!isRecord(parsed) || !isRecord(parsed.specdojo)) {
94
+ throw new Error(`${path}: frontmatter must contain a specdojo mapping`);
95
+ }
96
+ return { data: parsed, body: (match[2] ?? "").replace(/^(?:\r?\n)+/, "") };
97
+ }
98
+ function serializeGrade(grade) {
99
+ const gradeForDump = structuredClone(grade);
100
+ const findings = isRecord(gradeForDump.findings) ? gradeForDump.findings : undefined;
101
+ if (findings)
102
+ gradeForDump.findings = GRADE_FINDINGS_PLACEHOLDER;
103
+ const doneCriteria = isRecord(gradeForDump.done_criteria)
104
+ ? gradeForDump.done_criteria
105
+ : undefined;
106
+ const unsatisfied = doneCriteria && isRecord(doneCriteria.unsatisfied) ? doneCriteria.unsatisfied : undefined;
107
+ if (doneCriteria && unsatisfied)
108
+ doneCriteria.unsatisfied = GRADE_UNSATISFIED_PLACEHOLDER;
109
+ let dumped = yaml
110
+ .dump({ grade: gradeForDump },
111
+ // categories / viewpoints の各値だけをフロー化する。grade 全体や各 collection
112
+ // までフロー化すると一行が長くなり、差分も読みづらくなる。
113
+ { lineWidth: 120, noRefs: true, flowLevel: 3, quotingType: '"' })
114
+ .trimEnd();
115
+ if (findings) {
116
+ const inlineFindings = yaml
117
+ .dump(findings, { lineWidth: -1, noRefs: true, flowLevel: 0 })
118
+ .trimEnd();
119
+ dumped = dumped.replace(GRADE_FINDINGS_PLACEHOLDER, inlineFindings);
120
+ }
121
+ if (unsatisfied) {
122
+ // 未充足条件は viewpoints と同じく「条件ごとに1行、値はフロー」で記録する。
123
+ // 条件数が増えても1行が伸びず、Prettier の整形後も同じ形を保つ。
124
+ const blockUnsatisfied = yaml
125
+ .dump(unsatisfied, { lineWidth: -1, noRefs: true, flowLevel: 1 })
126
+ .trimEnd()
127
+ .split("\n")
128
+ .map((line) => ` ${line}`)
129
+ .join("\n");
130
+ dumped = dumped.replace(` unsatisfied: ${GRADE_UNSATISFIED_PLACEHOLDER}`, ` unsatisfied:\n${blockUnsatisfied}`);
131
+ }
132
+ // js-yaml は `{score: 100}`、Prettier は `{ score: 100 }` と出力する。
133
+ // 最初から Prettier の形へ合わせ、整形と再評価の往復で差分が出ないようにする。
134
+ return dumped.replace(/^(\s+[^:\n]+: )\{([^{}\n]*)\}$/gm, "$1{ $2 }");
135
+ }
136
+ function serializeMarkdown(document) {
137
+ const dataForDump = structuredClone(document.data);
138
+ const specdojo = isRecord(dataForDump.specdojo) ? dataForDump.specdojo : undefined;
139
+ const grade = specdojo && isRecord(specdojo.grade) ? specdojo.grade : undefined;
140
+ if (!specdojo || !grade) {
141
+ return `---\n${yaml.dump(dataForDump, { lineWidth: 120, noRefs: true }).trimEnd()}\n---\n\n${document.body.replace(/^\n+/, "")}`;
142
+ }
143
+ specdojo.grade = GRADE_PLACEHOLDER;
144
+ const gradeBlock = serializeGrade(grade)
145
+ .split("\n")
146
+ .map((line) => ` ${line}`)
147
+ .join("\n");
148
+ const frontmatter = yaml
149
+ .dump(dataForDump, { lineWidth: 120, noRefs: true })
150
+ .trimEnd()
151
+ .replace(` grade: ${GRADE_PLACEHOLDER}`, gradeBlock);
152
+ return `---\n${frontmatter}\n---\n\n${document.body.replace(/^\n+/, "")}`;
153
+ }
154
+ function withoutFindingComments(body) {
155
+ return body.replace(FINDING_RE, "");
156
+ }
157
+ function normalizeContentForHash(body) {
158
+ return body
159
+ .replace(/\r\n?/g, "\n")
160
+ .replace(/[ \t]+$/gm, "")
161
+ .replace(/\n{3,}/g, "\n\n");
162
+ }
163
+ function previousGradeFindings(body) {
164
+ return [...body.matchAll(FINDING_RE)].map((match) => ({
165
+ severity: match[2],
166
+ rule: match[3],
167
+ ...(match[4] ? { line: Number(match[4]) } : {}),
168
+ message: match[5].trim(),
169
+ }));
170
+ }
171
+ // 移行前のインライン grade を読み取る互換 API だけが使用する旧ハッシュ。
172
+ function legacyInlineContentHash(document) {
173
+ const cloned = structuredClone(document.data);
174
+ const specdojo = isRecord(cloned.specdojo) ? cloned.specdojo : {};
175
+ delete specdojo.grade;
176
+ return createHash("sha256")
177
+ .update(yaml.dump(cloned, { sortKeys: true, noRefs: true, lineWidth: -1 }))
178
+ .update("\n")
179
+ .update(normalizeContentForHash(withoutFindingComments(document.body)))
180
+ .digest("hex");
181
+ }
182
+ function stableContentHash(document) {
183
+ return gradeContentHash(serializeMarkdown(document));
184
+ }
185
+ // pipeline 状態は成果物そのもののハッシュで識別する。grade apply は成果物を変更しないため、
186
+ // grade / finding や空行を除外する正規化は不要である。
187
+ export function pipelineContentHash(document) {
188
+ return stableContentHash(document);
189
+ }
190
+ function sanitizeCommentText(value) {
191
+ return (value
192
+ .replace(/--+/g, "—")
193
+ .replace(/[\r\n]+/g, " ")
194
+ // 山括弧プレースホルダは HTML コメント内でもプロジェクトの lint が検知する。
195
+ // コメント内ではインラインコードが機能しないため、全角へ置き換えて退避する。
196
+ .replace(/</g, "<")
197
+ .replace(/>/g, ">")
198
+ .trim());
199
+ }
200
+ function findingComment(finding, rule) {
201
+ return `<!-- specdojo:finding id=${finding.id} severity=${finding.severity} rule=${rule} line=${finding.line ?? 1} ${sanitizeCommentText(finding.message)} -->`;
202
+ }
203
+ function markdownBlockRanges(body) {
204
+ const root = unified().use(remarkParse).parse(body);
205
+ return root.children.flatMap((node) => {
206
+ const startLine = node.position?.start.line;
207
+ const endLine = node.position?.end.line;
208
+ return startLine === undefined || endLine === undefined
209
+ ? []
210
+ : [
211
+ {
212
+ startLine,
213
+ endLine,
214
+ isHtmlComment: node.type === "html" &&
215
+ "value" in node &&
216
+ typeof node.value === "string" &&
217
+ /^\s*<!--[\s\S]*-->\s*$/.test(node.value),
218
+ },
219
+ ];
220
+ });
221
+ }
222
+ function safeFindingInsertionIndex(blocks, lines, requestedIndex) {
223
+ const requestedLine = requestedIndex + 1;
224
+ const containingIndex = blocks.findIndex((block) => block.startLine <= requestedLine && requestedLine <= block.endLine);
225
+ if (containingIndex === -1)
226
+ return requestedIndex;
227
+ let insertionStartLine = blocks[containingIndex].startLine;
228
+ for (let index = containingIndex - 1; index >= 0; index -= 1) {
229
+ const candidate = blocks[index];
230
+ if (!candidate.isHtmlComment)
231
+ break;
232
+ const linesBetween = lines.slice(candidate.endLine, insertionStartLine - 1);
233
+ if (linesBetween.some((line) => line.trim() !== ""))
234
+ break;
235
+ insertionStartLine = candidate.startLine;
236
+ }
237
+ return insertionStartLine - 1;
238
+ }
239
+ function insertFindings(body, viewpoints) {
240
+ const bodyWithoutFindings = withoutFindingComments(body);
241
+ const lines = bodyWithoutFindings.split("\n");
242
+ const blocks = markdownBlockRanges(bodyWithoutFindings);
243
+ const insertions = new Map();
244
+ const usedIds = new Set(viewpoints.flatMap((viewpoint) => (viewpoint.findings ?? []).flatMap((finding) => (finding.id ? [finding.id] : []))));
245
+ let sequence = 0;
246
+ for (const viewpoint of viewpoints) {
247
+ for (const finding of viewpoint.findings ?? []) {
248
+ let id = finding.id?.trim();
249
+ if (!id) {
250
+ do {
251
+ sequence += 1;
252
+ id = `F${String(sequence).padStart(3, "0")}`;
253
+ } while (usedIds.has(id));
254
+ usedIds.add(id);
255
+ }
256
+ const requestedIndex = Math.max(0, Math.min(lines.length, (finding.line ?? 1) - 1));
257
+ // finding は対象行を含む最上位 Markdown ブロックの直前へ置く。これにより、
258
+ // 入れ子リスト、表、引用、コードフェンス、複数行段落の内部を分断しない。
259
+ // 対象行そのものはコメントの line 属性に残す。
260
+ const index = safeFindingInsertionIndex(blocks, lines, requestedIndex);
261
+ const existing = insertions.get(index) ?? [];
262
+ existing.push(findingComment({ ...finding, id }, viewpoint.id));
263
+ insertions.set(index, existing);
264
+ }
265
+ }
266
+ const output = [];
267
+ for (let index = 0; index <= lines.length; index += 1) {
268
+ const comments = insertions.get(index) ?? [];
269
+ // 直前が空行の場合は連続空行になるため詰める。agent が本文末尾を超える行番号を
270
+ // 指定すると、末尾の空行の後ろへコメントが並び markdownlint の MD012 に触れる。
271
+ if (comments.length > 0) {
272
+ while (output.length > 0 && output[output.length - 1].trim() === "")
273
+ output.pop();
274
+ if (output.length > 0)
275
+ output.push("");
276
+ }
277
+ output.push(...comments);
278
+ if (index < lines.length)
279
+ output.push(lines[index]);
280
+ }
281
+ return (output
282
+ .join("\n")
283
+ .replace(/^\n+/, "")
284
+ .replace(/\n{3,}/g, "\n\n")
285
+ // grade apply の出力だけで lint 可能な状態にする。走査は文書ごとの apply 間に
286
+ // Prettier を実行しないため、入力由来の末尾空行をここで1改行へ正規化する。
287
+ .replace(/(?:\n[ \t]*)*$/, "\n"));
288
+ }
289
+ function resolveProject(projectOption) {
290
+ const { config } = loadConfig();
291
+ if (!config)
292
+ throw new Error("grade commands require .specdojo/specdojo.config.json");
293
+ const id = projectOption?.trim() || config.current_project || Object.keys(config.projects)[0] || "";
294
+ const project = config.projects[id];
295
+ if (!project)
296
+ throw new Error(`Unknown project: ${id}`);
297
+ return { id, project };
298
+ }
299
+ function loadViewpoints(projectOption) {
300
+ const { project } = resolveProject(projectOption);
301
+ const path = getProjectViewpointsPath(project);
302
+ if (!path)
303
+ throw new Error("viewpoints_path is required for grade");
304
+ return resolveViewpointsDoc(resolve(specdojoRootDir(), path));
305
+ }
306
+ export function resolveGradeActor(actor, roster) {
307
+ const normalized = actor.trim();
308
+ if (!normalized)
309
+ throw new Error("--by must be a non-empty pm-members.yaml nickname");
310
+ if (!roster)
311
+ throw new Error("members_path is required for grade apply --by");
312
+ assertValidActor(normalized, roster);
313
+ if (roster.members.filter((member) => member.nickname === normalized).length !== 1) {
314
+ throw new Error(`Duplicate actor nickname in members_path: ${normalized}`);
315
+ }
316
+ return normalized;
317
+ }
318
+ function assertRubric(doc) {
319
+ const rubric = doc.grade_rubric;
320
+ if (!rubric)
321
+ throw new Error("Resolved viewpoints do not define grade_rubric");
322
+ return rubric;
323
+ }
324
+ function relativePathFromRoot(path, rootDir) {
325
+ return relative(rootDir, path).replace(/\\/g, "/");
326
+ }
327
+ function repoRelativePath(path) {
328
+ return relativePathFromRoot(path, specdojoRootDir());
329
+ }
330
+ function referenceIds(metadata) {
331
+ return KATA_REFERENCE_FIELDS.flatMap((field) => {
332
+ const value = metadata[field];
333
+ if (typeof value === "string")
334
+ return [value];
335
+ if (Array.isArray(value))
336
+ return value.filter((item) => typeof item === "string");
337
+ return [];
338
+ }).filter((id) => id !== "none" && id !== "undecided");
339
+ }
340
+ function parseKataReference(path, kind) {
341
+ try {
342
+ const extension = extname(path).toLowerCase();
343
+ let metadata;
344
+ if (extension === ".md") {
345
+ metadata = parseMarkdown(readFileSync(path, "utf8"), repoRelativePath(path)).data
346
+ .specdojo;
347
+ }
348
+ else {
349
+ const parsed = yaml.load(readFileSync(path, "utf8"));
350
+ if (!isRecord(parsed))
351
+ return null;
352
+ metadata = isRecord(parsed.specdojo) ? parsed.specdojo : parsed;
353
+ }
354
+ const id = typeof metadata.id === "string" ? metadata.id.trim() : "";
355
+ if (!id)
356
+ return null;
357
+ return { id, path, kind, references: referenceIds(metadata) };
358
+ }
359
+ catch {
360
+ // Some reusable snippets in Kata directories are Markdown fragments rather than documents.
361
+ return null;
362
+ }
363
+ }
364
+ // grade の評価対象は利用リポジトリが所有する kata に限る。package 側の kata は SpecDojo が
365
+ // 管理する成果物であり、利用プロジェクトが評価・改善する対象ではない。フォールバックは
366
+ // 個別ファイルの解決にのみ用い、対象の列挙には用いない(解決と列挙を区別する)。
367
+ function loadKataReferences() {
368
+ const references = new Map();
369
+ const root = specdojoRootDir();
370
+ for (const kind of KATA_DIRS) {
371
+ const paths = listFilesRecursive(join(root, "docs/ja/specdojo", kind))
372
+ .filter((path) => KATA_REFERENCE_EXTENSIONS.has(extname(path).toLowerCase()))
373
+ .flatMap((path) => {
374
+ const reference = parseKataReference(path, kind);
375
+ return reference ? [reference] : [];
376
+ });
377
+ for (const reference of paths) {
378
+ if (!references.has(reference.id))
379
+ references.set(reference.id, reference);
380
+ }
381
+ }
382
+ return [...references.values()];
383
+ }
384
+ function resolveGradeReferencePathsFromCatalog(path, catalog) {
385
+ const target = resolveSafeMarkdownPath(path);
386
+ const targetDocument = parseMarkdown(readFileSync(target, "utf8"), repoRelativePath(target));
387
+ const targetMetadata = targetDocument.data.specdojo;
388
+ const targetId = typeof targetMetadata.id === "string" ? targetMetadata.id.trim() : "";
389
+ if (!targetId)
390
+ return [];
391
+ const byId = new Map(catalog.map((item) => [item.id, item]));
392
+ const selected = new Map();
393
+ const add = (item) => {
394
+ if (item && item.path !== target)
395
+ selected.set(item.id, item);
396
+ };
397
+ for (const id of referenceIds(targetMetadata))
398
+ add(byId.get(id));
399
+ for (const item of catalog)
400
+ if (item.references.includes(targetId))
401
+ add(item);
402
+ // A document and the directly linked rulebook/recipe form the anchor of a Kata set.
403
+ // Follow their declared links, but do not recursively traverse sibling back-links.
404
+ for (let depth = 0; depth < 2; depth += 1) {
405
+ for (const item of [...selected.values()]) {
406
+ if (item.kind !== "rulebooks" && item.kind !== "recipes")
407
+ continue;
408
+ for (const id of item.references)
409
+ add(byId.get(id));
410
+ }
411
+ }
412
+ return [...selected.values()].map((item) => item.path).sort();
413
+ }
414
+ export function resolveGradeReferencePaths(path) {
415
+ return resolveGradeReferencePathsFromCatalog(path, loadKataReferences());
416
+ }
417
+ function gradeReferenceExampleFamily(target, path, metadata) {
418
+ if (target === "kata") {
419
+ const rel = repoRelativePath(path);
420
+ const kind = KATA_DIRS.find((candidate) => {
421
+ const marker = `docs/ja/specdojo/${candidate}/`;
422
+ return rel.startsWith(marker) || rel.includes(`/${marker}`);
423
+ });
424
+ if (kind)
425
+ return kind;
426
+ }
427
+ const type = typeof metadata.type === "string" ? metadata.type.trim() : "";
428
+ return type || null;
429
+ }
430
+ function parseGradeReferenceExample(path, target) {
431
+ try {
432
+ const absolute = resolveSafeMarkdownPath(path);
433
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), repoRelativePath(absolute));
434
+ const metadata = document.data.specdojo;
435
+ return {
436
+ path: absolute,
437
+ family: gradeReferenceExampleFamily(target, absolute, metadata),
438
+ status: typeof metadata.status === "string" ? metadata.status.trim() : "",
439
+ };
440
+ }
441
+ catch {
442
+ return null;
443
+ }
444
+ }
445
+ function selectGradeReferenceExampleFromCatalog(opts) {
446
+ const target = resolveSafeMarkdownPath(opts.path);
447
+ const targetDocument = parseMarkdown(readFileSync(target, "utf8"), repoRelativePath(target));
448
+ const targetMetadata = targetDocument.data.specdojo;
449
+ const family = gradeReferenceExampleFamily(opts.target, target, targetMetadata);
450
+ if (!family)
451
+ return undefined;
452
+ // 同種別だけを候補にする。種別が違うと構造も目的も異なり、記載水準の基準として
453
+ // 誤りを招く。template はプレースホルダを正解と誤解させ、rulebook は recipe の
454
+ // 基準にならない。該当がなければリファレンスなしで評価する。
455
+ const candidates = opts.candidates
456
+ .filter((candidate) => candidate.path !== target && candidate.family === family && candidate.status === "ready")
457
+ .map((candidate) => candidate.path)
458
+ .sort();
459
+ if (candidates.length === 0)
460
+ return undefined;
461
+ const random = opts.random ?? Math.random;
462
+ const sample = random();
463
+ const normalizedSample = Number.isFinite(sample) ? Math.max(0, sample) : 0;
464
+ const index = Math.min(Math.floor(normalizedSample * candidates.length), candidates.length - 1);
465
+ return candidates[index];
466
+ }
467
+ export function selectGradeReferenceExample(opts) {
468
+ return selectGradeReferenceExampleFromCatalog({
469
+ ...opts,
470
+ candidates: opts.candidates.flatMap((candidate) => {
471
+ const parsed = parseGradeReferenceExample(candidate, opts.target);
472
+ return parsed ? [parsed] : [];
473
+ }),
474
+ });
475
+ }
476
+ function resolveSafeMarkdownPath(input, root = specdojoRootDir()) {
477
+ const absolute = resolve(root, input);
478
+ const rel = relativePathFromRoot(absolute, root);
479
+ if (rel.startsWith("../") || isAbsolute(rel))
480
+ throw new Error(`Path is outside repository: ${input}`);
481
+ if (extname(absolute).toLowerCase() !== ".md") {
482
+ throw new Error(`${input}: grade currently writes inline findings only for Markdown`);
483
+ }
484
+ if (!existsSync(absolute))
485
+ throw new Error(`Document not found: ${input}`);
486
+ return absolute;
487
+ }
488
+ function resolveSafeRepositoryPath(input, option) {
489
+ const root = specdojoRootDir();
490
+ const absolute = resolve(root, input);
491
+ const rel = relative(root, absolute);
492
+ if (rel.startsWith("../") || isAbsolute(rel)) {
493
+ throw new Error(`${option} must be inside the repository`);
494
+ }
495
+ return absolute;
496
+ }
497
+ function isGeneratedGradeTarget(path, rootDir = specdojoRootDir()) {
498
+ return relativePathFromRoot(path, rootDir).split("/").includes("generated");
499
+ }
500
+ function isTrashedGradeTarget(path, rootDir = specdojoRootDir()) {
501
+ return isTrashedPath(relativePathFromRoot(path, rootDir));
502
+ }
503
+ function criterionId(index) {
504
+ return `DC-${String(index + 1).padStart(3, "0")}`;
505
+ }
506
+ // カタログの Markdown 成果物を絶対パスで引ける形にする。grade の対象探索と
507
+ // done_criteria の解決が同じ集合を見るよう、両者はこの関数を共有する。
508
+ function loadDeliverableCatalog(projectOption, root = specdojoRootDir()) {
509
+ const { project } = resolveProject(projectOption);
510
+ const catalog = getProjectCatalogPath(project);
511
+ if (!catalog)
512
+ throw new Error("catalog_path is required for deliverable grading");
513
+ const entries = new Map();
514
+ for (const loaded of loadCatalogDocs(resolve(root, catalog))) {
515
+ const resolved = [];
516
+ collectResolvedDeliverables(loaded.doc.groups, resolveBasePath("", loaded.doc.base_path), resolved);
517
+ for (const item of resolved) {
518
+ if (item.item.kind === "generated" || !item.item.path)
519
+ continue;
520
+ if (!item.resolvedPath.endsWith(".md"))
521
+ continue;
522
+ if (isTrashedPath(item.resolvedPath))
523
+ continue;
524
+ const path = resolve(root, item.resolvedPath);
525
+ if (!existsSync(path) || entries.has(path))
526
+ continue;
527
+ entries.set(path, {
528
+ path,
529
+ localId: item.item.local_id,
530
+ doneCriteria: (item.item.done_criteria ?? []).map((criterion, index) => ({
531
+ id: criterionId(index),
532
+ text: criterion.text,
533
+ roles: [...criterion.roles],
534
+ viewpoint: criterion.viewpoint,
535
+ })),
536
+ });
537
+ }
538
+ }
539
+ return entries;
540
+ }
541
+ // 成果物ごとの done_criteria 定義を、submission が使うリポジトリ相対パスで引ける形にする。
542
+ // カタログに無い文書(--path で明示した非カタログ文書)は含めず、plan と apply は
543
+ // 定義が無い文書を「完了条件なし」として扱う。
544
+ export function resolveDeliverableDoneCriteria(paths, projectOption) {
545
+ const catalog = loadDeliverableCatalog(projectOption);
546
+ const result = new Map();
547
+ for (const path of paths) {
548
+ const entry = catalog.get(resolveSafeMarkdownPath(path));
549
+ if (entry && entry.doneCriteria.length > 0) {
550
+ result.set(repoRelativePath(entry.path), entry.doneCriteria);
551
+ }
552
+ }
553
+ return result;
554
+ }
555
+ function gradePipelineStateDirectory(projectOption, rootDir = specdojoRootDir()) {
556
+ const { project } = resolveProject(projectOption);
557
+ return resolve(rootDir, getProjectExecutionPath(project), "grade", "pipeline");
558
+ }
559
+ function gradePipelineStatePath(documentPath, projectOption, rootDir = specdojoRootDir()) {
560
+ const relativeDocument = relativePathFromRoot(resolve(rootDir, documentPath), rootDir);
561
+ const stem = basename(relativeDocument, extname(relativeDocument)).replace(/[^A-Za-z0-9._-]/g, "-");
562
+ const digest = createHash("sha256").update(relativeDocument).digest("hex").slice(0, 12);
563
+ return join(gradePipelineStateDirectory(projectOption, rootDir), `${stem}-${digest}.json`);
564
+ }
565
+ function parseGradePipelineState(value, path) {
566
+ if (!isRecord(value))
567
+ throw new Error(`${path}: grade pipeline state must be an object`);
568
+ const integer = (key, minimum) => {
569
+ const candidate = value[key];
570
+ if (!Number.isSafeInteger(candidate) || candidate < minimum) {
571
+ throw new Error(`${path}: ${key} must be an integer >= ${minimum}`);
572
+ }
573
+ return candidate;
574
+ };
575
+ const text = (key) => {
576
+ const candidate = value[key];
577
+ if (typeof candidate !== "string" || !candidate.trim()) {
578
+ throw new Error(`${path}: ${key} must be a non-empty string`);
579
+ }
580
+ return candidate;
581
+ };
582
+ const target = value.target;
583
+ if (target !== "kata" && target !== "deliverable") {
584
+ throw new Error(`${path}: target must be kata or deliverable`);
585
+ }
586
+ const stageFailed = value.stage_failed;
587
+ if (stageFailed !== null && (!Number.isSafeInteger(stageFailed) || stageFailed < 1)) {
588
+ throw new Error(`${path}: stage_failed must be null or a positive integer`);
589
+ }
590
+ const state = {
591
+ version: integer("version", 1),
592
+ project_id: text("project_id"),
593
+ target,
594
+ document: text("document"),
595
+ content_hash: text("content_hash"),
596
+ stage_completed: integer("stage_completed", 0),
597
+ stage_failed: stageFailed,
598
+ stage_total: integer("stage_total", 1),
599
+ consecutive_failures: integer("consecutive_failures", 0),
600
+ max_failures: integer("max_failures", 1),
601
+ last_run_id: text("last_run_id"),
602
+ updated_at: text("updated_at"),
603
+ };
604
+ if (state.version !== 1)
605
+ throw new Error(`${path}: unsupported grade pipeline state version`);
606
+ if (!/^[a-f0-9]{64}$/.test(state.content_hash)) {
607
+ throw new Error(`${path}: content_hash must be a SHA-256 hex digest`);
608
+ }
609
+ if (isAbsolute(state.document) ||
610
+ !state.document.startsWith("docs/") ||
611
+ state.document.split("/").includes("..")) {
612
+ throw new Error(`${path}: document must be a repository-relative path below docs/`);
613
+ }
614
+ if (state.stage_completed >= state.stage_total) {
615
+ throw new Error(`${path}: completed pipeline state must be removed`);
616
+ }
617
+ if (state.stage_failed !== null && state.stage_failed !== state.stage_completed + 1) {
618
+ throw new Error(`${path}: stage_failed must immediately follow stage_completed`);
619
+ }
620
+ if ((state.stage_failed === null && state.consecutive_failures !== 0) ||
621
+ (state.stage_failed !== null && state.consecutive_failures < 1)) {
622
+ throw new Error(`${path}: consecutive_failures does not match stage_failed`);
623
+ }
624
+ return state;
625
+ }
626
+ function loadGradePipelineStates(projectOption, rootDir = specdojoRootDir()) {
627
+ const states = new Map();
628
+ const projectId = resolveProject(projectOption).id;
629
+ for (const path of listFilesRecursive(gradePipelineStateDirectory(projectOption, rootDir))) {
630
+ if (!path.endsWith(".json"))
631
+ continue;
632
+ const state = parseGradePipelineState(JSON.parse(readFileSync(path, "utf8")), relativePathFromRoot(path, rootDir));
633
+ if (state.project_id !== projectId) {
634
+ throw new Error(`${relativePathFromRoot(path, rootDir)}: project_id must be ${projectId}`);
635
+ }
636
+ states.set(state.document, state);
637
+ }
638
+ return states;
639
+ }
640
+ function currentGradePipelineState(document, path, state, target) {
641
+ if (!state || state.document !== path || (target !== undefined && state.target !== target)) {
642
+ return undefined;
643
+ }
644
+ return state.content_hash === pipelineContentHash(document) ? state : undefined;
645
+ }
646
+ function isIncompleteGradePipelineState(state) {
647
+ return state !== undefined && state.consecutive_failures < state.max_failures;
648
+ }
649
+ export function readGradePipelineState(opts) {
650
+ const absolute = resolveSafeMarkdownPath(opts.path);
651
+ const relativeDocument = repoRelativePath(absolute);
652
+ const statePath = gradePipelineStatePath(relativeDocument, opts.project);
653
+ if (!existsSync(statePath))
654
+ return undefined;
655
+ const state = parseGradePipelineState(JSON.parse(readFileSync(statePath, "utf8")), repoRelativePath(statePath));
656
+ const projectId = resolveProject(opts.project).id;
657
+ if (state.project_id !== projectId) {
658
+ throw new Error(`${repoRelativePath(statePath)}: project_id must be ${projectId}`);
659
+ }
660
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), relativeDocument);
661
+ return currentGradePipelineState(document, relativeDocument, state, opts.target);
662
+ }
663
+ export function listExhaustedGradePipelineStates(opts) {
664
+ const states = loadGradePipelineStates(opts.project);
665
+ return [...states.values()]
666
+ .filter((state) => {
667
+ if (state.target !== opts.target || state.consecutive_failures < state.max_failures)
668
+ return false;
669
+ const absolute = resolve(specdojoRootDir(), state.document);
670
+ if (!existsSync(absolute))
671
+ return false;
672
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), state.document);
673
+ return currentGradePipelineState(document, state.document, state, opts.target) !== undefined;
674
+ })
675
+ .sort((left, right) => left.document.localeCompare(right.document));
676
+ }
677
+ export function recordGradePipelineStage(opts) {
678
+ const absolute = resolveSafeMarkdownPath(opts.path);
679
+ const relativeDocument = repoRelativePath(absolute);
680
+ const statePath = gradePipelineStatePath(relativeDocument, opts.project);
681
+ if (opts.status === "complete") {
682
+ if (existsSync(statePath))
683
+ unlinkSync(statePath);
684
+ return undefined;
685
+ }
686
+ if (!Number.isSafeInteger(opts.stage) ||
687
+ opts.stage < 1 ||
688
+ !Number.isSafeInteger(opts.stageTotal) ||
689
+ opts.stageTotal < opts.stage ||
690
+ !Number.isSafeInteger(opts.maxFailures) ||
691
+ opts.maxFailures < 1) {
692
+ throw new Error("grade pipeline stage, total, and failure limit are invalid");
693
+ }
694
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), relativeDocument);
695
+ const previous = readGradePipelineState({
696
+ target: opts.target,
697
+ project: opts.project,
698
+ path: relativeDocument,
699
+ });
700
+ const previousCompleted = previous?.stage_completed ?? 0;
701
+ if (opts.stage !== previousCompleted + 1) {
702
+ throw new Error(`grade pipeline stage ${opts.stage} must immediately follow completed stage ${previousCompleted}`);
703
+ }
704
+ const stageCompleted = opts.status === "passed" ? opts.stage : Math.min(previousCompleted, opts.stage - 1);
705
+ if (stageCompleted >= opts.stageTotal) {
706
+ if (existsSync(statePath))
707
+ unlinkSync(statePath);
708
+ return undefined;
709
+ }
710
+ const state = {
711
+ version: 1,
712
+ project_id: resolveProject(opts.project).id,
713
+ target: opts.target,
714
+ document: relativeDocument,
715
+ content_hash: pipelineContentHash(document),
716
+ stage_completed: stageCompleted,
717
+ stage_failed: opts.status === "failed" ? opts.stage : null,
718
+ stage_total: opts.stageTotal,
719
+ consecutive_failures: opts.status === "failed"
720
+ ? previous?.stage_failed === opts.stage
721
+ ? previous.consecutive_failures + 1
722
+ : 1
723
+ : 0,
724
+ max_failures: opts.maxFailures,
725
+ last_run_id: opts.runId,
726
+ updated_at: (opts.now ?? new Date()).toISOString(),
727
+ };
728
+ mkdirSync(dirname(statePath), { recursive: true });
729
+ writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
730
+ return state;
731
+ }
732
+ export function discoverGradeTargets(opts, rootDir = specdojoRootDir()) {
733
+ validateGradeTargetFilters(opts);
734
+ let candidates;
735
+ if (opts.paths && opts.paths.length > 0) {
736
+ candidates = opts.paths.map((path) => resolveSafeMarkdownPath(path, rootDir));
737
+ const generated = candidates.find((path) => isGeneratedGradeTarget(path, rootDir));
738
+ if (generated) {
739
+ throw new Error(`${relativePathFromRoot(generated, rootDir)}: generated documents cannot be graded`);
740
+ }
741
+ const trashed = candidates.find((path) => isTrashedGradeTarget(path, rootDir));
742
+ if (trashed) {
743
+ throw new Error(`${relativePathFromRoot(trashed, rootDir)}: trashed documents cannot be graded`);
744
+ }
745
+ }
746
+ else if (opts.target === "kata") {
747
+ // 対象の列挙は利用リポジトリ限定。eject されていない kata は評価対象にしない。
748
+ candidates = KATA_DIRS.flatMap((dir) => listFilesRecursive(join(rootDir, "docs/ja/specdojo", dir)).filter((entry) => entry.endsWith(".md")));
749
+ }
750
+ else {
751
+ candidates = [...loadDeliverableCatalog(opts.project, rootDir).keys()];
752
+ }
753
+ const unique = [...new Set(candidates)]
754
+ .filter((path) => !isGeneratedGradeTarget(path, rootDir))
755
+ .filter((path) => !isTrashedGradeTarget(path, rootDir))
756
+ .sort();
757
+ if (!opts.changedOnly &&
758
+ opts.verdict === undefined &&
759
+ opts.minScore === undefined &&
760
+ opts.maxFindings === undefined &&
761
+ !opts.ungraded &&
762
+ !opts.incomplete) {
763
+ return unique;
764
+ }
765
+ const pipelineStates = opts.incomplete
766
+ ? loadGradePipelineStates(opts.project, rootDir)
767
+ : new Map();
768
+ return unique.filter((path) => {
769
+ const rel = relativePathFromRoot(path, rootDir);
770
+ const content = readFileSync(path, "utf8");
771
+ const document = parseMarkdown(content, rel);
772
+ const pipelineState = currentGradePipelineState(document, rel, pipelineStates.get(rel), opts.target);
773
+ const result = readGradeResultForDocument({
774
+ documentPath: rel,
775
+ project: opts.project,
776
+ rootDir,
777
+ });
778
+ if (opts.incomplete && !isIncompleteGradePipelineState(pipelineState))
779
+ return false;
780
+ if (opts.ungraded && result !== undefined)
781
+ return false;
782
+ if (opts.verdict !== undefined && result?.verdict !== opts.verdict)
783
+ return false;
784
+ if (opts.minScore !== undefined && (result === undefined || result.score < opts.minScore)) {
785
+ return false;
786
+ }
787
+ if (opts.maxFindings !== undefined &&
788
+ (result === undefined || gradeFindingCount(result) > opts.maxFindings)) {
789
+ return false;
790
+ }
791
+ return !opts.changedOnly || result?.content_hash !== gradeContentHash(content);
792
+ });
793
+ }
794
+ function validateGradeTargetFilters(filters) {
795
+ if (filters.verdict !== undefined &&
796
+ filters.verdict !== "pass" &&
797
+ filters.verdict !== "needs-work" &&
798
+ filters.verdict !== "fail") {
799
+ throw new Error("--verdict must be pass, needs-work, or fail");
800
+ }
801
+ if (filters.minScore !== undefined &&
802
+ (!Number.isSafeInteger(filters.minScore) || filters.minScore < 0 || filters.minScore > 100)) {
803
+ throw new Error("--min-score must be an integer between 0 and 100");
804
+ }
805
+ if (filters.maxFindings !== undefined &&
806
+ (!Number.isSafeInteger(filters.maxFindings) || filters.maxFindings < 0)) {
807
+ throw new Error("--max-findings must be a non-negative integer");
808
+ }
809
+ if (filters.ungraded &&
810
+ (filters.verdict !== undefined ||
811
+ filters.minScore !== undefined ||
812
+ filters.maxFindings !== undefined)) {
813
+ throw new Error("--ungraded cannot be combined with --verdict, --min-score, or --max-findings");
814
+ }
815
+ }
816
+ function storedGradeScore(grade, path) {
817
+ const score = grade.score;
818
+ if (!Number.isSafeInteger(score) || score < 0 || score > 100) {
819
+ throw new Error(`${path}: specdojo.grade.score must be an integer between 0 and 100`);
820
+ }
821
+ return score;
822
+ }
823
+ function storedFindingCount(grade, path) {
824
+ const findings = grade.findings;
825
+ if (!isRecord(findings))
826
+ throw new Error(`${path}: specdojo.grade.findings is missing`);
827
+ return ["blocker", "major", "minor", "note"].reduce((total, severity) => {
828
+ const count = findings[severity];
829
+ if (!Number.isSafeInteger(count) || count < 0) {
830
+ throw new Error(`${path}: specdojo.grade.findings.${severity} must be a non-negative integer`);
831
+ }
832
+ return total + count;
833
+ }, 0);
834
+ }
835
+ function matchesParsedGradeTargetFilters(document, path, filters, incomplete = false) {
836
+ const specdojo = document.data.specdojo;
837
+ const grade = isRecord(specdojo.grade) ? specdojo.grade : undefined;
838
+ if (filters.incomplete && !incomplete)
839
+ return false;
840
+ if (filters.ungraded && grade !== undefined)
841
+ return false;
842
+ if (filters.verdict !== undefined && grade?.verdict !== filters.verdict)
843
+ return false;
844
+ if (filters.minScore !== undefined &&
845
+ (grade === undefined || storedGradeScore(grade, path) < filters.minScore)) {
846
+ return false;
847
+ }
848
+ if (filters.maxFindings !== undefined &&
849
+ (grade === undefined || storedFindingCount(grade, path) > filters.maxFindings)) {
850
+ return false;
851
+ }
852
+ return !filters.changedOnly || grade?.content_hash !== legacyInlineContentHash(document);
853
+ }
854
+ export function matchesGradeTargetFilters(content, path, filters, pipelineState) {
855
+ validateGradeTargetFilters(filters);
856
+ const document = parseMarkdown(content, path);
857
+ const currentState = currentGradePipelineState(document, path, pipelineState);
858
+ return matchesParsedGradeTargetFilters(document, path, filters, isIncompleteGradePipelineState(currentState));
859
+ }
860
+ function continuousViewpoints(doc, target) {
861
+ return (doc.viewpoints ?? []).filter((viewpoint) => viewpoint.continuous === true &&
862
+ viewpoint.evaluation !== "human" &&
863
+ (viewpoint.grade_targets === undefined || viewpoint.grade_targets.includes(target)));
864
+ }
865
+ function agentViewpoints(doc, target) {
866
+ return continuousViewpoints(doc, target).filter((viewpoint) => viewpoint.evaluation === "agent");
867
+ }
868
+ function deterministicResults(document, definitions, target) {
869
+ const results = [];
870
+ for (const viewpoint of continuousViewpoints(definitions, target).filter((item) => item.evaluation === "deterministic")) {
871
+ const findings = [];
872
+ const specdojo = document.data.specdojo;
873
+ if (viewpoint.id === "vp-arc-document-structure") {
874
+ for (const key of ["id", "type", "status"]) {
875
+ if (typeof specdojo[key] !== "string" || !String(specdojo[key]).trim()) {
876
+ findings.push({
877
+ severity: "major",
878
+ message: `Frontmatter の specdojo.${key} が未設定です。`,
879
+ line: 1,
880
+ });
881
+ }
882
+ }
883
+ if (!/^#\s+\S/m.test(document.body)) {
884
+ findings.push({ severity: "major", message: "本文に H1 見出しがありません。", line: 1 });
885
+ }
886
+ }
887
+ if (viewpoint.id === "vp-qe-config-validity") {
888
+ const placeholderLine = document.body
889
+ .split("\n")
890
+ .findIndex((line) => /(?:_TODO_|_ASSUMPTION_)/.test(line));
891
+ if (placeholderLine >= 0) {
892
+ findings.push({
893
+ severity: "major",
894
+ message: "未解決の _TODO_ / _ASSUMPTION_ が残っています。",
895
+ line: placeholderLine + 1,
896
+ });
897
+ }
898
+ }
899
+ const cap = levelCapForFindings(findings);
900
+ results.push({ id: viewpoint.id, level: cap, findings });
901
+ }
902
+ return results;
903
+ }
904
+ function doneCriteriaPlanLines(doneCriteria, definitions) {
905
+ const titles = new Map((definitions.viewpoints ?? []).map((viewpoint) => [viewpoint.id, viewpoint.title]));
906
+ return [
907
+ "### 3.4. 完了条件(done_criteria)",
908
+ "",
909
+ "成果物カタログが対象へ宣言する完了条件である。viewpoint と rubric による level 判定とは別の軸として、各条件を現在の本文の根拠だけで `satisfied` / `unsatisfied` のどちらかに判定する。score や level の高低から充足を推論せず、条件文が要求する内容を本文で確認できるかだけで判定する。`roles` は条件の確認責任を持つ Role code、`viewpoint` は条件を見る観点であり、`evaluation: human` の観点に紐づく条件も本文の根拠で一次判定する。",
910
+ "",
911
+ ...doneCriteria.map((criterion) => {
912
+ const title = titles.get(criterion.viewpoint);
913
+ const viewpoint = title ? `${criterion.viewpoint}(${title})` : criterion.viewpoint;
914
+ return `- ${criterion.id} [roles=${criterion.roles.join(",")}; viewpoint=${viewpoint}]: ${criterion.text}`;
915
+ }),
916
+ "",
917
+ ];
918
+ }
919
+ export function renderGradePlan(opts) {
920
+ const rubric = assertRubric(opts.viewpoints);
921
+ const viewpoints = agentViewpoints(opts.viewpoints, opts.target);
922
+ const absolute = resolveSafeMarkdownPath(opts.path);
923
+ const rel = repoRelativePath(absolute);
924
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), rel);
925
+ const metadata = document.data.specdojo;
926
+ const documentId = typeof metadata.id === "string" ? metadata.id : rel;
927
+ const priorFindings = (opts.resultsDirectory
928
+ ? readGradeResult(gradeResultPath(opts.resultsDirectory, documentId))
929
+ : readGradeResultForDocument({ documentPath: rel, project: opts.projectId }))?.findings ?? [];
930
+ const taskHash = createHash("sha256").update(rel).digest("hex").slice(0, 12).toUpperCase();
931
+ const taskId = `GRADE-${opts.target.toUpperCase()}-${taskHash}`;
932
+ const references = (opts.references ?? []).map((reference) => repoRelativePath(resolveSafeRepositoryPath(reference, "reference")));
933
+ const referenceExample = opts.referenceExample
934
+ ? repoRelativePath(resolveSafeMarkdownPath(opts.referenceExample))
935
+ : undefined;
936
+ const doneCriteria = opts.target === "deliverable" ? (opts.doneCriteria ?? []) : [];
937
+ const lines = [
938
+ "---",
939
+ yaml
940
+ .dump({
941
+ specdojo: {
942
+ id: `${opts.projectId}:grade-${opts.target}-${taskHash.toLowerCase()}-plan`,
943
+ type: "exec-plan",
944
+ rulebook: "none",
945
+ task_id: taskId,
946
+ name: `grade: ${rel}`,
947
+ mode: "review",
948
+ status: "ready",
949
+ project_id: opts.projectId,
950
+ targets: [documentId],
951
+ },
952
+ }, { lineWidth: 120, noRefs: true })
953
+ .trimEnd(),
954
+ "---",
955
+ "",
956
+ `# Review Plan: ${taskId} grade: ${rel}`,
957
+ "",
958
+ "この plan は grade pipeline の executor stage 用である。評価と根拠の記述だけを行い、GradeSubmission JSON は作成しない。後続の reporter が判定内容を変更せず JSON へ構造化する。",
959
+ "",
960
+ "## 1. このタスクで行うこと",
961
+ "",
962
+ `評価対象 \`${rel}\` を共通 viewpoint と category rubric で 0-4 判定する。deterministic viewpoint は CLI が判定するため、agent の出力には含めない。`,
963
+ "",
964
+ "## 2. 対象項目",
965
+ "",
966
+ `- \`target\`: ${opts.target}`,
967
+ `- \`rubric\`: ${rubric.id}`,
968
+ `- \`document_id\`: ${documentId}`,
969
+ `- \`評価対象\`: \`${rel}\``,
970
+ "",
971
+ "### 参考資料",
972
+ "",
973
+ "参考資料は評価対象ではなく、成果物間整合を判定するための材料である。参考資料自体を評価しない。",
974
+ "",
975
+ ...(references.length > 0 ? references.map((reference) => `- \`${reference}\``) : ["- なし"]),
976
+ "",
977
+ // 比較リファレンスは任意である。指定がない場合は節ごと省略する。空の節を残すと
978
+ // 候補が存在しないのか指定していないのかを読み手が区別できない。
979
+ ...(referenceExample
980
+ ? [
981
+ "### 良い実例(比較リファレンス)",
982
+ "",
983
+ "`status: ready` の文書から選んだ比較材料である。記載水準を具体化するために使い、評価対象へ含めず、内容を正解として機械的に模倣しない。`ready` は品質保証ではないため、実例自体の問題を評価対象へ転用しない。",
984
+ "",
985
+ `- \`${referenceExample}\``,
986
+ "",
987
+ ]
988
+ : []),
989
+ "## 3. 進め方",
990
+ "",
991
+ "1. 評価対象をファイル読み取りツールで全文読み、実行ログに読み取り操作を残す。plan に対象本文は埋め込まれていないため、この手順を省略しない。",
992
+ "2. 参考資料と良い実例がある場合は列挙された全ファイルを全文読み、実行ログに各パスの読み取り操作を残す。参考資料や良い実例を評価対象と混同しない。",
993
+ "3. 良い実例がある場合は、章ごとの具体性、根拠の密度、過不足を評価対象と比較して記載水準を判定する。表現の類似や実例自体の欠点を評価理由にせず、rubric と viewpoint を最終的な判定基準にする。",
994
+ "4. 評価対象を次の rubric と viewpoint に照らし、各 viewpoint を 0-4 で判定する。ある viewpoint の finding の有無から、ほかの viewpoint の判定を推論しない。",
995
+ "5. level 3 以下には finding を付ける。finding には severity(blocker / major / minor / note)、対象直前の本文行番号、具体的な修正理由を含める。line は Frontmatter を除く本文の1始まり(通常は H1 が1行目)とする。level 4 は finding なしとする。",
996
+ "6. 前回の指摘を対象の現在内容と照合し、解消済みか確認する。未解消なら前回の message を変更せず今回の finding に含め、severity は前回と同等以上を指定する。前回の rule は前回評価時の分類として扱い、各 viewpoint は現在の根拠から独立に評価する。前回の問題が解消され、別の軽微な問題だけが残るため severity を引き下げる場合は、その根拠を新しい finding の message に含める。",
997
+ "7. 前回の指摘の確認だけで終了せず、前回の指摘にない問題もすべての viewpoint で独立して検出する。",
998
+ ...(doneCriteria.length > 0
999
+ ? [
1000
+ "8. 完了条件(done_criteria)を1件ずつ本文の根拠と照合し、`satisfied` / `unsatisfied` を判定する。viewpoint の level や総合 score とは独立した判定であり、level が高いことを理由に条件を満たしたとみなさない。`unsatisfied` には不足している内容を1行で記す。",
1001
+ ]
1002
+ : []),
1003
+ "",
1004
+ "### 3.1. 前回の指摘",
1005
+ "",
1006
+ "grade result サイドカーに記録された前回の finding を示す。対象本文には評価コメントを書き込まない。",
1007
+ "",
1008
+ // 前回の id は今回の採番と混同させないため渡さない。事実(severity / rule / 位置 / message)だけを示す。
1009
+ ...(priorFindings.length > 0
1010
+ ? [
1011
+ "```json",
1012
+ JSON.stringify(priorFindings.map(({ severity, rule, line, anchor, message }) => ({
1013
+ severity,
1014
+ rule,
1015
+ line,
1016
+ anchor,
1017
+ message,
1018
+ })), null, 2),
1019
+ "```",
1020
+ ]
1021
+ : ["- なし"]),
1022
+ "",
1023
+ "### 3.2. Rubric",
1024
+ "",
1025
+ ...rubric.levels.map((level) => `- ${level.level} (${level.name}, review=${level.review_verdict}): ${level.description}`),
1026
+ "",
1027
+ "### 3.3. Viewpoints",
1028
+ "",
1029
+ ...viewpoints.map((viewpoint) => `- ${viewpoint.id} [${viewpoint.category}/${viewpoint.evaluation}]: ${viewpoint.check} Evidence: ${viewpoint.evidence}`),
1030
+ "",
1031
+ ...(doneCriteria.length > 0 ? doneCriteriaPlanLines(doneCriteria, opts.viewpoints) : []),
1032
+ "## 4. 完了手順",
1033
+ "",
1034
+ "1. すべての agent viewpoint の判定と、必要な finding が揃っていることを確認する。",
1035
+ "2. 最終応答では各 viewpoint を次のマーカーで1回ずつ宣言する。マーカー間には根拠や検討過程を自由形式で詳しく記述してよい。JSON、Markdown コードフェンス、GradeSubmission は出力しない。",
1036
+ "3. `LEVEL` と各 `FINDING` は reporter が忠実性を機械検証する申告値である。message は1行で具体的に記し、reporter が一字一句コピーできるようにする。finding がない場合は `FINDING` 行を記さない。",
1037
+ "4. すべての viewpoint marker、0-4 の level、level 3 以下の finding、severity と非空 message が揃っていることを確認する。",
1038
+ ...(doneCriteria.length > 0
1039
+ ? [
1040
+ "5. 完了条件は `[DONE_CRITERIA]` と `[END DONE_CRITERIA]` で囲んだブロックを1回だけ置き、列挙されたすべての条件 ID を1行ずつ `<ID>: satisfied` または `<ID>: unsatisfied: <不足内容>` の形で申告する。列挙にない ID を追加せず、ID を省略しない。",
1041
+ ]
1042
+ : []),
1043
+ "",
1044
+ "```text",
1045
+ ...viewpoints.flatMap((viewpoint) => [
1046
+ `[VIEWPOINT ${viewpoint.id}]`,
1047
+ "LEVEL: <0-4>",
1048
+ "根拠を自由形式で記述する。",
1049
+ "FINDING <severity> line=<line>: level 3 以下の場合だけ、具体的な修正理由を1行で記述する。",
1050
+ "[END VIEWPOINT]",
1051
+ "",
1052
+ ]),
1053
+ ...(doneCriteria.length > 0
1054
+ ? [
1055
+ "[DONE_CRITERIA]",
1056
+ ...doneCriteria.map((criterion) => `${criterion.id}: <satisfied|unsatisfied>: 不足内容を1行で記述する。`),
1057
+ "[END DONE_CRITERIA]",
1058
+ "",
1059
+ ]
1060
+ : []),
1061
+ "```",
1062
+ "",
1063
+ "## 5. 異常終了の条件",
1064
+ "",
1065
+ "- 評価対象、参考資料、または良い実例を読み取れない場合は、内容を推測せず異常終了する。",
1066
+ "- rubric または viewpoint に不足があり、全項目を判定できない場合は異常終了する。",
1067
+ "- すべての viewpoint の level と finding を申告できない場合は異常終了する。",
1068
+ ...(doneCriteria.length > 0
1069
+ ? ["- 列挙された完了条件のいずれかを判定できない場合は異常終了する。"]
1070
+ : []),
1071
+ ];
1072
+ return `${lines.join("\n")}\n`;
1073
+ }
1074
+ export function renderGradeReporterPlan(opts) {
1075
+ const rubric = assertRubric(opts.viewpoints);
1076
+ const viewpoints = agentViewpoints(opts.viewpoints, opts.target);
1077
+ const absolute = resolveSafeMarkdownPath(opts.path);
1078
+ const rel = repoRelativePath(absolute);
1079
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), rel);
1080
+ const metadata = document.data.specdojo;
1081
+ const documentId = typeof metadata.id === "string" ? metadata.id : rel;
1082
+ const taskHash = createHash("sha256").update(rel).digest("hex").slice(0, 12).toUpperCase();
1083
+ const taskId = `GRADE-${opts.target.toUpperCase()}-${taskHash}-REPORTER`;
1084
+ const doneCriteria = opts.target === "deliverable" ? (opts.doneCriteria ?? []) : [];
1085
+ const lines = [
1086
+ "---",
1087
+ yaml
1088
+ .dump({
1089
+ specdojo: {
1090
+ id: `${opts.projectId}:grade-${opts.target}-${taskHash.toLowerCase()}-reporter-plan`,
1091
+ type: "exec-plan",
1092
+ rulebook: "none",
1093
+ task_id: taskId,
1094
+ name: `grade reporter: ${rel}`,
1095
+ mode: "review",
1096
+ status: "ready",
1097
+ project_id: opts.projectId,
1098
+ targets: [documentId],
1099
+ },
1100
+ }, { lineWidth: 120, noRefs: true })
1101
+ .trimEnd(),
1102
+ "---",
1103
+ "",
1104
+ `# Reporter Plan: ${taskId} grade: ${rel}`,
1105
+ "",
1106
+ "この plan は grade pipeline の reporter stage 用である。executor の最終応答が `<grade_executor_output>` としてこの plan と一緒に渡される。評価やファイル読み取りは行わず、申告済みの判定を GradeSubmission JSON へ忠実に構造化する。",
1107
+ "",
1108
+ "## 1. このタスクで行うこと",
1109
+ "",
1110
+ "executor が申告した全 viewpoint の level と finding を、追加・省略・変更せず GradeSubmission JSON へ写す。",
1111
+ "",
1112
+ "## 2. 対象項目",
1113
+ "",
1114
+ `- \`target\`: ${opts.target}`,
1115
+ `- \`rubric\`: ${rubric.id}`,
1116
+ `- \`document_id\`: ${documentId}`,
1117
+ `- \`評価対象\`: \`${rel}\``,
1118
+ "",
1119
+ "## 3. 進め方",
1120
+ "",
1121
+ "1. `<grade_executor_output>` の `[VIEWPOINT <id>]` ごとに `LEVEL` とすべての `FINDING` を読み取る。対象文書や参考資料は読まない。",
1122
+ "2. level、severity、line、message を executor の申告どおりにコピーする。message の要約、言い換え、校正を行わない。",
1123
+ "3. executor が述べていない finding を追加せず、述べた finding を省略しない。finding の `id` は出力しない。",
1124
+ "4. marker が欠けている、値が曖昧、または GradeSubmission の検証規則と矛盾する場合は推測せず異常終了する。",
1125
+ ...(doneCriteria.length > 0
1126
+ ? [
1127
+ "5. `[DONE_CRITERIA]` ブロックの各行を `done_criteria` へ写す。`id` と `status`(`satisfied` / `unsatisfied`)は申告どおりにコピーし、`unsatisfied` に続く不足内容は `reason` へ一字一句コピーする。条件の追加・省略・判定変更を行わない。",
1128
+ ]
1129
+ : []),
1130
+ "",
1131
+ "## 4. 完了手順",
1132
+ "",
1133
+ "1. facts である `rubric` と `path` を次のテンプレートから変更しない。",
1134
+ "2. すべての agent viewpoint が1回ずつあり、level と finding が executor の申告と一致することを確認する。",
1135
+ ...(doneCriteria.length > 0
1136
+ ? [
1137
+ "3. `done_criteria` の各要素が executor の申告した ID と status に一致することを確認する。",
1138
+ "4. 正常終了時の最終応答は GradeSubmission JSON オブジェクト1個だけとする。前置き、要約、Markdown コードフェンスを含めない。",
1139
+ ]
1140
+ : [
1141
+ "3. 正常終了時の最終応答は GradeSubmission JSON オブジェクト1個だけとする。前置き、要約、Markdown コードフェンスを含めない。",
1142
+ ]),
1143
+ "",
1144
+ "```json",
1145
+ JSON.stringify({
1146
+ rubric: rubric.id,
1147
+ documents: [
1148
+ {
1149
+ path: rel,
1150
+ viewpoints: viewpoints.map((viewpoint) => ({
1151
+ id: viewpoint.id,
1152
+ level: 4,
1153
+ findings: [],
1154
+ })),
1155
+ ...(doneCriteria.length > 0
1156
+ ? {
1157
+ done_criteria: doneCriteria.map((criterion) => ({
1158
+ id: criterion.id,
1159
+ status: "satisfied",
1160
+ })),
1161
+ }
1162
+ : {}),
1163
+ },
1164
+ ],
1165
+ }, null, 2),
1166
+ "```",
1167
+ "",
1168
+ "## 5. 異常終了の条件",
1169
+ "",
1170
+ "- `<grade_executor_output>` が渡されていない、または marker 契約を解析できない場合は異常終了する。",
1171
+ "- executor の申告を変更しなければ GradeSubmission の契約を満たせない場合は異常終了する。",
1172
+ ];
1173
+ return `${lines.join("\n")}\n`;
1174
+ }
1175
+ function gradePlanFilename(path) {
1176
+ const rel = repoRelativePath(path);
1177
+ const stem = basename(path, extname(path))
1178
+ .toLowerCase()
1179
+ .replace(/[^a-z0-9-]+/g, "-")
1180
+ .replace(/^-+|-+$/g, "");
1181
+ const hash = createHash("sha256").update(rel).digest("hex").slice(0, 10);
1182
+ return `${stem || "document"}-${hash}-grade-plan.md`;
1183
+ }
1184
+ function gradeReporterPlanFilename(path) {
1185
+ return gradePlanFilename(path).replace(/-grade-plan\.md$/, "-grade-reporter-plan.md");
1186
+ }
1187
+ export function writeGradePlans(opts) {
1188
+ const outputDirectory = resolveSafeRepositoryPath(opts.outputDirectory, "--out");
1189
+ if (opts.paths.length === 0)
1190
+ return [];
1191
+ mkdirSync(outputDirectory, { recursive: true });
1192
+ const kataReferences = loadKataReferences();
1193
+ const referenceExamples = opts.referenceExampleCandidates.flatMap((candidate) => {
1194
+ const parsed = parseGradeReferenceExample(candidate, opts.target);
1195
+ return parsed ? [parsed] : [];
1196
+ });
1197
+ return opts.paths.map((path) => {
1198
+ const absolute = resolveSafeMarkdownPath(path);
1199
+ const output = join(outputDirectory, gradePlanFilename(absolute));
1200
+ const reporterOutput = join(outputDirectory, gradeReporterPlanFilename(absolute));
1201
+ const referenceExample = opts.referenceExampleOverride ??
1202
+ selectGradeReferenceExampleFromCatalog({
1203
+ target: opts.target,
1204
+ path: absolute,
1205
+ candidates: referenceExamples,
1206
+ random: opts.random,
1207
+ });
1208
+ const doneCriteria = opts.doneCriteriaByPath?.get(repoRelativePath(absolute));
1209
+ const content = renderGradePlan({
1210
+ target: opts.target,
1211
+ path: absolute,
1212
+ references: resolveGradeReferencePathsFromCatalog(absolute, kataReferences),
1213
+ referenceExample,
1214
+ viewpoints: opts.viewpoints,
1215
+ projectId: opts.projectId,
1216
+ doneCriteria,
1217
+ });
1218
+ const reporterContent = renderGradeReporterPlan({
1219
+ target: opts.target,
1220
+ path: absolute,
1221
+ viewpoints: opts.viewpoints,
1222
+ projectId: opts.projectId,
1223
+ doneCriteria,
1224
+ });
1225
+ const changed = !existsSync(output) || readFileSync(output, "utf8") !== content;
1226
+ const reporterChanged = !existsSync(reporterOutput) || readFileSync(reporterOutput, "utf8") !== reporterContent;
1227
+ if (changed)
1228
+ writeFileSync(output, content, "utf8");
1229
+ if (reporterChanged)
1230
+ writeFileSync(reporterOutput, reporterContent, "utf8");
1231
+ return {
1232
+ path: repoRelativePath(output),
1233
+ changed,
1234
+ reporterPath: repoRelativePath(reporterOutput),
1235
+ reporterChanged,
1236
+ target: repoRelativePath(absolute),
1237
+ referenceExample,
1238
+ };
1239
+ });
1240
+ }
1241
+ export function parseGradeExecutorAnalysis(raw) {
1242
+ const viewpoints = [];
1243
+ let doneCriteria;
1244
+ let inDoneCriteria = false;
1245
+ let current;
1246
+ for (const [lineIndex, line] of raw.split(/\r?\n/).entries()) {
1247
+ if (/^\[DONE_CRITERIA\]\s*$/.test(line)) {
1248
+ if (current)
1249
+ throw new Error(`line ${lineIndex + 1}: DONE_CRITERIA inside VIEWPOINT`);
1250
+ if (doneCriteria !== undefined) {
1251
+ throw new Error(`line ${lineIndex + 1}: duplicate DONE_CRITERIA block`);
1252
+ }
1253
+ doneCriteria = [];
1254
+ inDoneCriteria = true;
1255
+ continue;
1256
+ }
1257
+ if (/^\[END DONE_CRITERIA\]\s*$/.test(line)) {
1258
+ if (!inDoneCriteria) {
1259
+ throw new Error(`line ${lineIndex + 1}: unexpected END DONE_CRITERIA marker`);
1260
+ }
1261
+ inDoneCriteria = false;
1262
+ continue;
1263
+ }
1264
+ if (inDoneCriteria) {
1265
+ if (line.trim() === "")
1266
+ continue;
1267
+ const criterion = line.match(/^(DC-[0-9]{3,}):\s*(satisfied|unsatisfied)(?:\s*[::]\s*(\S.*?))?\s*$/);
1268
+ if (!criterion) {
1269
+ throw new Error(`line ${lineIndex + 1}: malformed DONE_CRITERIA entry`);
1270
+ }
1271
+ doneCriteria.push({
1272
+ id: criterion[1],
1273
+ status: criterion[2],
1274
+ ...(criterion[3] ? { reason: criterion[3].trim() } : {}),
1275
+ });
1276
+ continue;
1277
+ }
1278
+ const start = line.match(/^\[VIEWPOINT ([A-Za-z0-9][A-Za-z0-9._-]*)\]\s*$/);
1279
+ if (start) {
1280
+ if (current) {
1281
+ throw new Error(`line ${lineIndex + 1}: nested VIEWPOINT marker`);
1282
+ }
1283
+ current = { id: start[1], findings: [] };
1284
+ continue;
1285
+ }
1286
+ if (/^\[END VIEWPOINT\]\s*$/.test(line)) {
1287
+ if (!current)
1288
+ throw new Error(`line ${lineIndex + 1}: unexpected END VIEWPOINT marker`);
1289
+ if (current.level === undefined) {
1290
+ throw new Error(`viewpoint ${current.id}: LEVEL is required`);
1291
+ }
1292
+ viewpoints.push({ id: current.id, level: current.level, findings: current.findings });
1293
+ current = undefined;
1294
+ continue;
1295
+ }
1296
+ if (!current)
1297
+ continue;
1298
+ const level = line.match(/^LEVEL:\s*([0-4])\s*$/);
1299
+ if (level) {
1300
+ if (current.level !== undefined) {
1301
+ throw new Error(`line ${lineIndex + 1}: duplicate LEVEL for ${current.id}`);
1302
+ }
1303
+ current.level = Number(level[1]);
1304
+ continue;
1305
+ }
1306
+ if (/^LEVEL\s*:/.test(line)) {
1307
+ throw new Error(`line ${lineIndex + 1}: malformed LEVEL for ${current.id}`);
1308
+ }
1309
+ const finding = line.match(/^FINDING\s+(blocker|major|minor|note)(?:\s+line=([1-9][0-9]*))?:\s*(\S.*)\s*$/);
1310
+ if (finding) {
1311
+ current.findings.push({
1312
+ severity: finding[1],
1313
+ ...(finding[2] ? { line: Number(finding[2]) } : {}),
1314
+ message: finding[3].trim(),
1315
+ });
1316
+ continue;
1317
+ }
1318
+ if (/^FINDING(?:\s|:)/.test(line)) {
1319
+ throw new Error(`line ${lineIndex + 1}: malformed FINDING for ${current.id}`);
1320
+ }
1321
+ }
1322
+ if (current)
1323
+ throw new Error(`viewpoint ${current.id}: END VIEWPOINT marker is required`);
1324
+ if (inDoneCriteria)
1325
+ throw new Error("END DONE_CRITERIA marker is required");
1326
+ if (viewpoints.length === 0)
1327
+ throw new Error("No VIEWPOINT markers found in executor analysis");
1328
+ return { viewpoints, ...(doneCriteria !== undefined ? { doneCriteria } : {}) };
1329
+ }
1330
+ function normalizeFindingMessageForFidelity(message) {
1331
+ return message
1332
+ .normalize("NFC")
1333
+ .replace(/[、,]/gu, ",")
1334
+ .replace(/[。.]/gu, ".")
1335
+ .replace(/!/gu, "!")
1336
+ .replace(/?/gu, "?")
1337
+ .replace(/:/gu, ":")
1338
+ .replace(/;/gu, ";")
1339
+ .replace(/\s+/gu, " ")
1340
+ .trim()
1341
+ .replace(/\s*([,.;:!?])\s*/gu, "$1");
1342
+ }
1343
+ function findingFidelityKey(finding) {
1344
+ return JSON.stringify({
1345
+ severity: finding.severity,
1346
+ line: finding.line ?? null,
1347
+ message: normalizeFindingMessageForFidelity(finding.message),
1348
+ });
1349
+ }
1350
+ function unmatchedFindings(declared, reported) {
1351
+ const remainingReported = reported.map((finding) => ({
1352
+ finding,
1353
+ matched: false,
1354
+ }));
1355
+ const unmatchedDeclared = [];
1356
+ for (const finding of declared) {
1357
+ const key = findingFidelityKey(finding);
1358
+ const match = remainingReported.find((candidate) => !candidate.matched && findingFidelityKey(candidate.finding) === key);
1359
+ if (match)
1360
+ match.matched = true;
1361
+ else
1362
+ unmatchedDeclared.push(finding);
1363
+ }
1364
+ return {
1365
+ declared: unmatchedDeclared,
1366
+ reported: remainingReported
1367
+ .filter((candidate) => !candidate.matched)
1368
+ .map((candidate) => candidate.finding),
1369
+ };
1370
+ }
1371
+ function findingDifferenceMessage(declared, reported) {
1372
+ const differences = [];
1373
+ if (declared.severity !== reported.severity) {
1374
+ differences.push(`severity executor=${declared.severity} reporter=${reported.severity}`);
1375
+ }
1376
+ if (declared.line !== reported.line) {
1377
+ differences.push(`line executor=${declared.line ?? "none"} reporter=${reported.line ?? "none"}`);
1378
+ }
1379
+ if (normalizeFindingMessageForFidelity(declared.message) !==
1380
+ normalizeFindingMessageForFidelity(reported.message)) {
1381
+ differences.push(`message executor=${JSON.stringify(declared.message)} reporter=${JSON.stringify(reported.message)}`);
1382
+ }
1383
+ return differences.join("; ");
1384
+ }
1385
+ function findingSimilarity(declared, reported) {
1386
+ return (Number(declared.severity === reported.severity) +
1387
+ Number(declared.line === reported.line) +
1388
+ Number(normalizeFindingMessageForFidelity(declared.message) ===
1389
+ normalizeFindingMessageForFidelity(reported.message)));
1390
+ }
1391
+ function doneCriteriaFidelityIssues(declared, reported) {
1392
+ const issues = [];
1393
+ const where = "documents[0].done_criteria";
1394
+ if (declared === undefined && reported === undefined)
1395
+ return issues;
1396
+ if (declared === undefined) {
1397
+ issues.push({ path: where, message: "reporter added done_criteria not declared by executor" });
1398
+ return issues;
1399
+ }
1400
+ const reportedById = new Map((reported ?? []).map((criterion) => [criterion.id, criterion]));
1401
+ for (const criterion of declared) {
1402
+ const match = reportedById.get(criterion.id);
1403
+ if (!match) {
1404
+ issues.push({ path: where, message: `reporter omitted executor criterion: ${criterion.id}` });
1405
+ continue;
1406
+ }
1407
+ reportedById.delete(criterion.id);
1408
+ if (match.status !== criterion.status) {
1409
+ issues.push({
1410
+ path: `${where}.${criterion.id}`,
1411
+ message: `reporter status ${match.status} differs from executor status ${criterion.status}`,
1412
+ });
1413
+ }
1414
+ if (normalizeFindingMessageForFidelity(criterion.reason ?? "") !==
1415
+ normalizeFindingMessageForFidelity(match.reason ?? "")) {
1416
+ issues.push({
1417
+ path: `${where}.${criterion.id}`,
1418
+ message: `reporter changed executor reason: executor=${JSON.stringify(criterion.reason ?? "")} reporter=${JSON.stringify(match.reason ?? "")}`,
1419
+ });
1420
+ }
1421
+ }
1422
+ for (const id of reportedById.keys()) {
1423
+ issues.push({
1424
+ path: where,
1425
+ message: `reporter added criterion not declared by executor: ${id}`,
1426
+ });
1427
+ }
1428
+ return issues;
1429
+ }
1430
+ export function validateGradeReporterFidelity(opts) {
1431
+ let analysis;
1432
+ try {
1433
+ analysis = parseGradeExecutorAnalysis(opts.executorOutput);
1434
+ }
1435
+ catch (error) {
1436
+ return [
1437
+ {
1438
+ path: "$analysis",
1439
+ message: error instanceof Error ? error.message : String(error),
1440
+ },
1441
+ ];
1442
+ }
1443
+ const rubric = assertRubric(opts.viewpoints);
1444
+ const analysisIssues = validateGradeSubmission({
1445
+ rubric: rubric.id,
1446
+ documents: [
1447
+ {
1448
+ path: opts.expectedPath,
1449
+ viewpoints: analysis.viewpoints,
1450
+ ...(analysis.doneCriteria ? { done_criteria: analysis.doneCriteria } : {}),
1451
+ },
1452
+ ],
1453
+ }, opts.viewpoints, opts.target, opts.doneCriteria
1454
+ ? { doneCriteriaByPath: new Map([[opts.expectedPath, opts.doneCriteria]]) }
1455
+ : {}).map((issue) => ({ path: `$analysis.${issue.path}`, message: issue.message }));
1456
+ if (analysisIssues.length > 0)
1457
+ return analysisIssues;
1458
+ if (opts.submission.documents.length !== 1) {
1459
+ return [
1460
+ { path: "documents", message: "reporter submission must contain exactly one document" },
1461
+ ];
1462
+ }
1463
+ const document = opts.submission.documents[0];
1464
+ if (document.path !== opts.expectedPath) {
1465
+ return [
1466
+ {
1467
+ path: "documents[0].path",
1468
+ message: `reporter path must remain ${opts.expectedPath}`,
1469
+ },
1470
+ ];
1471
+ }
1472
+ const issues = [];
1473
+ const reportedById = new Map(document.viewpoints.map((viewpoint) => [viewpoint.id, viewpoint]));
1474
+ for (const declared of analysis.viewpoints) {
1475
+ const reported = reportedById.get(declared.id);
1476
+ if (!reported) {
1477
+ issues.push({
1478
+ path: `documents[0].viewpoints`,
1479
+ message: `reporter omitted executor viewpoint: ${declared.id}`,
1480
+ });
1481
+ continue;
1482
+ }
1483
+ if (reported.level !== declared.level) {
1484
+ issues.push({
1485
+ path: `documents[0].viewpoints.${declared.id}.level`,
1486
+ message: `reporter level ${reported.level} differs from executor level ${declared.level}`,
1487
+ });
1488
+ }
1489
+ const unmatched = unmatchedFindings(declared.findings ?? [], reported.findings ?? []);
1490
+ while (unmatched.declared.length > 0 && unmatched.reported.length > 0) {
1491
+ const executorFinding = unmatched.declared.shift();
1492
+ let bestIndex = 0;
1493
+ for (let index = 1; index < unmatched.reported.length; index += 1) {
1494
+ if (findingSimilarity(executorFinding, unmatched.reported[index]) >
1495
+ findingSimilarity(executorFinding, unmatched.reported[bestIndex])) {
1496
+ bestIndex = index;
1497
+ }
1498
+ }
1499
+ const reporterFinding = unmatched.reported.splice(bestIndex, 1)[0];
1500
+ issues.push({
1501
+ path: `documents[0].viewpoints.${declared.id}.findings`,
1502
+ message: `reporter changed executor finding: ${findingDifferenceMessage(executorFinding, reporterFinding)}`,
1503
+ });
1504
+ }
1505
+ for (const finding of unmatched.declared) {
1506
+ issues.push({
1507
+ path: `documents[0].viewpoints.${declared.id}.findings`,
1508
+ message: `reporter omitted executor finding: ${JSON.stringify(finding)}`,
1509
+ });
1510
+ }
1511
+ for (const finding of unmatched.reported) {
1512
+ issues.push({
1513
+ path: `documents[0].viewpoints.${declared.id}.findings`,
1514
+ message: `reporter added finding not declared by executor: ${JSON.stringify(finding)}`,
1515
+ });
1516
+ }
1517
+ }
1518
+ issues.push(...doneCriteriaFidelityIssues(analysis.doneCriteria, document.done_criteria));
1519
+ return issues;
1520
+ }
1521
+ export function parseGradeSubmission(raw) {
1522
+ let value;
1523
+ try {
1524
+ value = JSON.parse(extractJsonText(raw));
1525
+ }
1526
+ catch (error) {
1527
+ throw new Error(`Grade submission must be JSON: ${error instanceof Error ? error.message : String(error)}`);
1528
+ }
1529
+ if (!isRecord(value) ||
1530
+ typeof value.rubric !== "string" ||
1531
+ (value.graded_by !== undefined && typeof value.graded_by !== "string") ||
1532
+ !Array.isArray(value.documents)) {
1533
+ throw new Error("Grade submission requires rubric and documents[]");
1534
+ }
1535
+ return value;
1536
+ }
1537
+ function validateDoneCriteriaInput(opts) {
1538
+ const issues = [];
1539
+ const { where, value, expected } = opts;
1540
+ if (value === undefined) {
1541
+ if (expected && expected.length > 0) {
1542
+ issues.push({ path: where, message: "done_criteria[] is required for this deliverable" });
1543
+ }
1544
+ return issues;
1545
+ }
1546
+ if (!Array.isArray(value)) {
1547
+ issues.push({ path: `${where}.done_criteria`, message: "done_criteria must be an array" });
1548
+ return issues;
1549
+ }
1550
+ if (opts.target !== "deliverable") {
1551
+ issues.push({
1552
+ path: `${where}.done_criteria`,
1553
+ message: "done_criteria is accepted only for deliverable targets",
1554
+ });
1555
+ return issues;
1556
+ }
1557
+ const expectedIds = expected ? new Set(expected.map((criterion) => criterion.id)) : undefined;
1558
+ const seen = new Set();
1559
+ for (const [index, entry] of value.entries()) {
1560
+ const entryPath = `${where}.done_criteria[${index}]`;
1561
+ if (!isRecord(entry) ||
1562
+ typeof entry.id !== "string" ||
1563
+ !CRITERION_ID_RE.test(entry.id) ||
1564
+ typeof entry.status !== "string" ||
1565
+ !CRITERION_STATUSES.includes(entry.status)) {
1566
+ issues.push({ path: entryPath, message: "id (DC-NNN) and status are required" });
1567
+ continue;
1568
+ }
1569
+ if (entry.reason !== undefined && typeof entry.reason !== "string") {
1570
+ issues.push({ path: `${entryPath}.reason`, message: "reason must be a string" });
1571
+ }
1572
+ if (entry.status === "unsatisfied" &&
1573
+ !(typeof entry.reason === "string" && entry.reason.trim())) {
1574
+ issues.push({ path: entryPath, message: "unsatisfied requires a non-empty reason" });
1575
+ }
1576
+ if (seen.has(entry.id)) {
1577
+ issues.push({ path: entryPath, message: `duplicate criterion: ${entry.id}` });
1578
+ }
1579
+ seen.add(entry.id);
1580
+ if (expectedIds && !expectedIds.has(entry.id)) {
1581
+ issues.push({ path: entryPath, message: `unknown criterion: ${entry.id}` });
1582
+ }
1583
+ }
1584
+ for (const id of expectedIds ?? []) {
1585
+ if (!seen.has(id))
1586
+ issues.push({ path: where, message: `missing criterion: ${id}` });
1587
+ }
1588
+ return issues;
1589
+ }
1590
+ export function validateGradeSubmission(submission, doc, target, options = {}) {
1591
+ const issues = [];
1592
+ const rubric = assertRubric(doc);
1593
+ if (submission.rubric !== rubric.id)
1594
+ issues.push({ path: "$", message: `rubric must be ${rubric.id}` });
1595
+ const required = agentViewpoints(doc, target);
1596
+ const allowed = new Map(required.map((viewpoint) => [viewpoint.id, viewpoint]));
1597
+ const paths = new Set();
1598
+ for (const [documentIndex, document] of submission.documents.entries()) {
1599
+ const where = `documents[${documentIndex}]`;
1600
+ if (!document || typeof document.path !== "string" || !Array.isArray(document.viewpoints)) {
1601
+ issues.push({ path: where, message: "path and viewpoints[] are required" });
1602
+ continue;
1603
+ }
1604
+ if (paths.has(document.path))
1605
+ issues.push({ path: where, message: `duplicate path: ${document.path}` });
1606
+ paths.add(document.path);
1607
+ const normalizedDocumentPath = repoRelativePath(resolve(specdojoRootDir(), document.path));
1608
+ issues.push(...validateDoneCriteriaInput({
1609
+ where,
1610
+ target,
1611
+ value: document.done_criteria,
1612
+ expected: options.doneCriteriaByPath?.get(document.path) ??
1613
+ options.doneCriteriaByPath?.get(normalizedDocumentPath),
1614
+ }));
1615
+ const ids = new Set();
1616
+ const findingIds = new Set();
1617
+ for (const [viewpointIndex, result] of document.viewpoints.entries()) {
1618
+ const resultPath = `${where}.viewpoints[${viewpointIndex}]`;
1619
+ if (!result || !allowed.has(result.id)) {
1620
+ issues.push({
1621
+ path: resultPath,
1622
+ message: `unknown or non-continuous viewpoint: ${result?.id ?? ""}`,
1623
+ });
1624
+ continue;
1625
+ }
1626
+ if (ids.has(result.id))
1627
+ issues.push({ path: resultPath, message: `duplicate viewpoint: ${result.id}` });
1628
+ ids.add(result.id);
1629
+ if (!Number.isInteger(result.level) || result.level < 0 || result.level > 4) {
1630
+ issues.push({ path: resultPath, message: "level must be an integer from 0 to 4" });
1631
+ }
1632
+ const findings = result.findings ?? [];
1633
+ if (!Array.isArray(findings)) {
1634
+ issues.push({ path: resultPath, message: "findings must be an array" });
1635
+ continue;
1636
+ }
1637
+ if (result.level < 4 && findings.length === 0) {
1638
+ issues.push({ path: resultPath, message: "level 0-3 requires at least one finding" });
1639
+ }
1640
+ for (const [findingIndex, finding] of findings.entries()) {
1641
+ if (!finding ||
1642
+ !Object.hasOwn(SEVERITY_LEVEL_CAP, finding.severity) ||
1643
+ typeof finding.message !== "string" ||
1644
+ !finding.message.trim()) {
1645
+ issues.push({
1646
+ path: `${resultPath}.findings[${findingIndex}]`,
1647
+ message: "severity and non-empty message are required",
1648
+ });
1649
+ continue;
1650
+ }
1651
+ if (finding.id !== undefined) {
1652
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(finding.id)) {
1653
+ issues.push({
1654
+ path: `${resultPath}.findings[${findingIndex}].id`,
1655
+ message: "id must contain only letters, digits, dot, underscore, or hyphen",
1656
+ });
1657
+ }
1658
+ else if (findingIds.has(finding.id)) {
1659
+ issues.push({
1660
+ path: `${resultPath}.findings[${findingIndex}].id`,
1661
+ message: `duplicate finding id: ${finding.id}`,
1662
+ });
1663
+ }
1664
+ findingIds.add(finding.id);
1665
+ }
1666
+ if (finding.line !== undefined && (!Number.isInteger(finding.line) || finding.line < 1)) {
1667
+ issues.push({
1668
+ path: `${resultPath}.findings[${findingIndex}].line`,
1669
+ message: "line must be a positive integer",
1670
+ });
1671
+ }
1672
+ }
1673
+ const cap = levelCapForFindings(findings);
1674
+ if (result.level > cap)
1675
+ issues.push({ path: resultPath, message: `finding severity caps level at ${cap}` });
1676
+ }
1677
+ for (const viewpoint of required) {
1678
+ if (!ids.has(viewpoint.id)) {
1679
+ issues.push({ path: where, message: `missing agent viewpoint: ${viewpoint.id}` });
1680
+ }
1681
+ }
1682
+ }
1683
+ return issues;
1684
+ }
1685
+ function scoreDocument(input, rubric, doc, target) {
1686
+ const definitions = new Map((doc.viewpoints ?? []).map((viewpoint) => [viewpoint.id, viewpoint]));
1687
+ const categoryLevels = new Map();
1688
+ const counts = { blocker: 0, major: 0, minor: 0, note: 0 };
1689
+ const viewpointOutput = {};
1690
+ for (const result of input.viewpoints) {
1691
+ const definition = definitions.get(result.id);
1692
+ const values = categoryLevels.get(definition.category) ?? [];
1693
+ values.push(result.level);
1694
+ categoryLevels.set(definition.category, values);
1695
+ viewpointOutput[result.id] = { level: result.level, score: result.level * 25 };
1696
+ for (const finding of result.findings ?? [])
1697
+ counts[finding.severity] += 1;
1698
+ }
1699
+ const categories = {};
1700
+ let weighted = 0;
1701
+ let totalWeight = 0;
1702
+ for (const [category, levels] of categoryLevels) {
1703
+ const score = Math.round((levels.reduce((sum, level) => sum + level, 0) / levels.length) * 25);
1704
+ categories[category] = { score };
1705
+ const weight = rubric.weights[target][category] ?? 0;
1706
+ weighted += score * weight;
1707
+ totalWeight += weight;
1708
+ }
1709
+ const score = totalWeight > 0 ? Math.round(weighted / totalWeight) : 0;
1710
+ const verdict = counts.blocker > 0
1711
+ ? "fail"
1712
+ : counts.major > 0 || score < rubric.pass_score
1713
+ ? "needs-work"
1714
+ : "pass";
1715
+ return { score, verdict, categories, viewpoints: viewpointOutput, findings: counts };
1716
+ }
1717
+ // 詳細ファイルは成果物ごとに1件で、再評価のたびに上書きする。時点の記録は git 履歴が担う。
1718
+ // grade 本体と同じ方式であり、実行ごとにファイルを増やすと最新の評価を判別できなくなる。
1719
+ export function doneCriteriaDetailPath(criteriaDirectory, documentPath) {
1720
+ const absolute = resolveSafeMarkdownPath(documentPath);
1721
+ const directory = resolveSafeRepositoryPath(criteriaDirectory, "criteria directory");
1722
+ return join(directory, gradePlanFilename(absolute).replace(/-grade-plan\.md$/, "-done-criteria.yaml"));
1723
+ }
1724
+ function doneCriteriaDetailId(documentId, documentPath) {
1725
+ if (documentId)
1726
+ return `${documentId}-grade-criteria`;
1727
+ const hash = createHash("sha256")
1728
+ .update(repoRelativePath(documentPath))
1729
+ .digest("hex")
1730
+ .slice(0, 10);
1731
+ return `grade-criteria-${hash}`;
1732
+ }
1733
+ export function renderDoneCriteriaDetail(detail, detailPath) {
1734
+ const schemaRef = relative(dirname(detailPath), resolveSpecdojoPath(DONE_CRITERIA_SCHEMA))
1735
+ .split(sep)
1736
+ .join("/");
1737
+ return `# yaml-language-server: $schema=${schemaRef}\n${yaml.dump(detail, { lineWidth: 120, noRefs: true, quotingType: '"' })}`;
1738
+ }
1739
+ export function applyGradeSubmission(opts) {
1740
+ const issues = validateGradeSubmission(opts.submission, opts.viewpoints, opts.target, {
1741
+ doneCriteriaByPath: opts.doneCriteriaByPath,
1742
+ });
1743
+ if (issues.length > 0)
1744
+ throw new Error(issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n"));
1745
+ const changed = [];
1746
+ for (const input of opts.submission.documents) {
1747
+ const absolute = resolveSafeMarkdownPath(input.path);
1748
+ const rel = repoRelativePath(absolute);
1749
+ const current = readFileSync(absolute, "utf8");
1750
+ const definitions = opts.doneCriteriaByPath?.get(rel);
1751
+ const detailPath = definitions && input.done_criteria && opts.criteriaDirectory
1752
+ ? doneCriteriaDetailPath(opts.criteriaDirectory, absolute)
1753
+ : undefined;
1754
+ if (definitions && input.done_criteria && !detailPath) {
1755
+ throw new Error(`${rel}: criteriaDirectory is required to record done_criteria`);
1756
+ }
1757
+ if (opts.resultsDirectory) {
1758
+ const documentId = markdownDocumentId(current, rel);
1759
+ const resultPath = gradeResultPath(opts.resultsDirectory, documentId);
1760
+ const previous = readGradeResult(resultPath);
1761
+ const document = parseMarkdown(current, rel);
1762
+ const agentResults = preserveStoredFindingSeverities(previous, input.viewpoints);
1763
+ const evaluated = {
1764
+ ...input,
1765
+ viewpoints: [
1766
+ ...agentResults,
1767
+ ...deterministicResults(document, opts.viewpoints, opts.target),
1768
+ ],
1769
+ };
1770
+ const rubric = assertRubric(opts.viewpoints);
1771
+ const summary = scoreDocument(evaluated, rubric, opts.viewpoints, opts.target);
1772
+ const gradedAt = (opts.now ?? new Date()).toISOString();
1773
+ const usedIds = new Set();
1774
+ let sequence = 0;
1775
+ const bodyLines = document.body.split(/\r?\n/);
1776
+ const findings = evaluated.viewpoints.flatMap((viewpoint) => (viewpoint.findings ?? []).map((finding) => {
1777
+ let id = finding.id?.trim();
1778
+ if (!id || usedIds.has(id)) {
1779
+ do {
1780
+ sequence += 1;
1781
+ id = `F${String(sequence).padStart(3, "0")}`;
1782
+ } while (usedIds.has(id));
1783
+ }
1784
+ usedIds.add(id);
1785
+ const line = Math.max(1, finding.line ?? 1);
1786
+ return {
1787
+ id,
1788
+ severity: finding.severity,
1789
+ rule: viewpoint.id,
1790
+ line,
1791
+ anchor: bodyLines[Math.min(bodyLines.length, line) - 1]?.trim() ?? "",
1792
+ message: sanitizeCommentText(finding.message),
1793
+ };
1794
+ }));
1795
+ const criteriaResults = opts.target === "deliverable" && definitions && input.done_criteria && detailPath
1796
+ ? input.done_criteria
1797
+ : undefined;
1798
+ const detailRef = criteriaResults ? doneCriteriaDetailId(documentId, absolute) : undefined;
1799
+ const result = {
1800
+ version: 1,
1801
+ document: documentId,
1802
+ path: rel,
1803
+ target: opts.target,
1804
+ rubric: rubric.id,
1805
+ ...(opts.reference ? { reference: resolveGradeReferenceId(opts.reference) } : {}),
1806
+ verdict: summary.verdict,
1807
+ score: summary.score,
1808
+ graded_at: gradedAt,
1809
+ graded_by: opts.gradedBy,
1810
+ content_hash: gradeContentHash(current),
1811
+ categories: summary.categories,
1812
+ viewpoints: summary.viewpoints,
1813
+ finding_counts: summary.findings,
1814
+ findings,
1815
+ ...(criteriaResults && definitions && detailRef
1816
+ ? { done_criteria: summarizeDoneCriteria(definitions, criteriaResults, detailRef) }
1817
+ : {}),
1818
+ };
1819
+ if (criteriaResults && definitions && detailPath && detailRef) {
1820
+ const resultById = new Map(criteriaResults.map((criterion) => [criterion.id, criterion]));
1821
+ const criteria = definitions.map((definition) => {
1822
+ const criterion = resultById.get(definition.id);
1823
+ return {
1824
+ ...definition,
1825
+ status: criterion?.status ?? "unsatisfied",
1826
+ ...(criterion?.reason ? { reason: criterion.reason } : {}),
1827
+ };
1828
+ });
1829
+ const satisfied = criteria.filter((criterion) => criterion.status === "satisfied").length;
1830
+ const detail = {
1831
+ id: detailRef,
1832
+ document: documentId,
1833
+ path: rel,
1834
+ graded_at: gradedAt,
1835
+ graded_by: opts.gradedBy,
1836
+ content_hash: result.content_hash,
1837
+ summary: { satisfied, unsatisfied: criteria.length - satisfied, total: criteria.length },
1838
+ criteria,
1839
+ };
1840
+ const rendered = renderDoneCriteriaDetail(detail, detailPath);
1841
+ if (!existsSync(detailPath) || readFileSync(detailPath, "utf8") !== rendered) {
1842
+ changed.push(repoRelativePath(detailPath));
1843
+ if (!opts.dryRun) {
1844
+ mkdirSync(dirname(detailPath), { recursive: true });
1845
+ writeFileSync(detailPath, rendered, "utf8");
1846
+ }
1847
+ }
1848
+ }
1849
+ if (writeGradeResult(resultPath, result, opts.dryRun)) {
1850
+ changed.push(repoRelativePath(resultPath));
1851
+ }
1852
+ continue;
1853
+ }
1854
+ const documentId = parseMarkdown(current, rel).data.specdojo;
1855
+ const graded = gradeMarkdownDocument({
1856
+ content: current,
1857
+ path: rel,
1858
+ input,
1859
+ viewpoints: opts.viewpoints,
1860
+ target: opts.target,
1861
+ gradedBy: opts.gradedBy,
1862
+ reference: opts.reference,
1863
+ now: opts.now,
1864
+ doneCriteria: definitions && detailPath
1865
+ ? {
1866
+ definitions,
1867
+ detailRef: doneCriteriaDetailId(typeof documentId.id === "string" ? documentId.id : undefined, absolute),
1868
+ }
1869
+ : undefined,
1870
+ });
1871
+ // 詳細を先に永続化してから成果物へ detail_ref を書く。途中で詳細の書き込みに失敗しても、
1872
+ // 存在しない参照だけが成果物へ残る状態を避ける。
1873
+ if (graded.detail && detailPath) {
1874
+ const rendered = renderDoneCriteriaDetail(graded.detail, detailPath);
1875
+ const detailRel = repoRelativePath(detailPath);
1876
+ if (!existsSync(detailPath) || readFileSync(detailPath, "utf8") !== rendered) {
1877
+ changed.push(detailRel);
1878
+ if (!opts.dryRun) {
1879
+ mkdirSync(dirname(detailPath), { recursive: true });
1880
+ writeFileSync(detailPath, rendered, "utf8");
1881
+ }
1882
+ }
1883
+ }
1884
+ if (graded.content !== current) {
1885
+ changed.push(rel);
1886
+ if (!opts.dryRun)
1887
+ writeFileSync(absolute, graded.content, "utf8");
1888
+ }
1889
+ }
1890
+ return changed;
1891
+ }
1892
+ // 比較リファレンスは ID で保存する。パスで保存すると文書を移動したときに参照が壊れる。
1893
+ // 引数にはパスと ID のどちらも渡せる。パスの場合は Frontmatter の id を読み取る。
1894
+ export function resolveGradeReferenceId(pathOrId) {
1895
+ const trimmed = pathOrId.trim();
1896
+ if (!trimmed.endsWith(".md"))
1897
+ return trimmed;
1898
+ const absolute = resolveSafeMarkdownPath(trimmed);
1899
+ const document = parseMarkdown(readFileSync(absolute, "utf8"), repoRelativePath(absolute));
1900
+ const metadata = document.data.specdojo;
1901
+ if (!isRecord(metadata) || typeof metadata.id !== "string" || metadata.id.length === 0) {
1902
+ throw new Error(`${repoRelativePath(absolute)}: reference document has no specdojo.id`);
1903
+ }
1904
+ return metadata.id;
1905
+ }
1906
+ // score と done_criteria の充足は別の軸として扱う。verdict は score と finding だけで決め、
1907
+ // 充足状況は要約として並記する。score の閾値が充足判定を上書きせず、その逆も行わない。
1908
+ function summarizeDoneCriteria(definitions, results, detailRef) {
1909
+ const resultById = new Map(results.map((result) => [result.id, result]));
1910
+ const unsatisfied = {};
1911
+ let satisfied = 0;
1912
+ for (const criterion of definitions) {
1913
+ const result = resultById.get(criterion.id);
1914
+ if (result?.status === "satisfied")
1915
+ satisfied += 1;
1916
+ else
1917
+ unsatisfied[criterion.id] = [...criterion.roles];
1918
+ }
1919
+ return {
1920
+ satisfied,
1921
+ total: definitions.length,
1922
+ ...(Object.keys(unsatisfied).length > 0 ? { unsatisfied } : {}),
1923
+ detail_ref: detailRef,
1924
+ };
1925
+ }
1926
+ export function gradeMarkdownDocument(opts) {
1927
+ const document = parseMarkdown(opts.content, opts.path);
1928
+ const specdojo = document.data.specdojo;
1929
+ const agentResults = preservePreviousFindingSeverities(document.body, opts.input.viewpoints);
1930
+ const evaluated = {
1931
+ ...opts.input,
1932
+ viewpoints: [...agentResults, ...deterministicResults(document, opts.viewpoints, opts.target)],
1933
+ };
1934
+ const rubric = assertRubric(opts.viewpoints);
1935
+ const summary = scoreDocument(evaluated, rubric, opts.viewpoints, opts.target);
1936
+ const body = insertFindings(document.body, evaluated.viewpoints);
1937
+ const gradedAt = (opts.now ?? new Date()).toISOString();
1938
+ const contentHash = legacyInlineContentHash({ data: document.data, body });
1939
+ const criteriaResults = opts.target === "deliverable" && opts.doneCriteria && opts.input.done_criteria
1940
+ ? opts.input.done_criteria
1941
+ : undefined;
1942
+ specdojo.grade = {
1943
+ rubric: rubric.id,
1944
+ ...(opts.reference ? { reference: resolveGradeReferenceId(opts.reference) } : {}),
1945
+ target: opts.target,
1946
+ verdict: summary.verdict,
1947
+ score: summary.score,
1948
+ graded_at: gradedAt,
1949
+ graded_by: opts.gradedBy,
1950
+ content_hash: contentHash,
1951
+ categories: summary.categories,
1952
+ viewpoints: summary.viewpoints,
1953
+ findings: summary.findings,
1954
+ ...(criteriaResults && opts.doneCriteria
1955
+ ? {
1956
+ done_criteria: summarizeDoneCriteria(opts.doneCriteria.definitions, criteriaResults, opts.doneCriteria.detailRef),
1957
+ }
1958
+ : {}),
1959
+ };
1960
+ const content = serializeMarkdown({ data: document.data, body });
1961
+ if (!criteriaResults || !opts.doneCriteria)
1962
+ return { content };
1963
+ const resultById = new Map(criteriaResults.map((result) => [result.id, result]));
1964
+ const criteria = opts.doneCriteria.definitions.map((criterion) => {
1965
+ const result = resultById.get(criterion.id);
1966
+ return {
1967
+ ...criterion,
1968
+ status: result?.status ?? "unsatisfied",
1969
+ ...(result?.reason ? { reason: result.reason } : {}),
1970
+ };
1971
+ });
1972
+ const satisfied = criteria.filter((criterion) => criterion.status === "satisfied").length;
1973
+ return {
1974
+ content,
1975
+ detail: {
1976
+ id: opts.doneCriteria.detailRef,
1977
+ document: typeof specdojo.id === "string" ? specdojo.id : opts.path,
1978
+ path: opts.path,
1979
+ graded_at: gradedAt,
1980
+ graded_by: opts.gradedBy,
1981
+ content_hash: contentHash,
1982
+ summary: { satisfied, unsatisfied: criteria.length - satisfied, total: criteria.length },
1983
+ criteria,
1984
+ },
1985
+ };
1986
+ }
1987
+ export function gradeMarkdownContent(opts) {
1988
+ return gradeMarkdownDocument(opts).content;
1989
+ }
1990
+ export function validateGradedDocument(path) {
1991
+ const absolute = resolveSafeMarkdownPath(path);
1992
+ const rel = repoRelativePath(absolute);
1993
+ return validateGradedMarkdown(readFileSync(absolute, "utf8"), rel);
1994
+ }
1995
+ export function validateGradeResultForDocument(opts) {
1996
+ const absolute = resolveSafeMarkdownPath(opts.path);
1997
+ const rel = repoRelativePath(absolute);
1998
+ const content = readFileSync(absolute, "utf8");
1999
+ const result = readGradeResultForDocument({ documentPath: rel, project: opts.project });
2000
+ if (!result)
2001
+ return [];
2002
+ return validateGradeResult(result, content, rel, opts.target);
2003
+ }
2004
+ export function validateGradedMarkdown(content, path) {
2005
+ const document = parseMarkdown(content, path);
2006
+ const specdojo = document.data.specdojo;
2007
+ const grade = isRecord(specdojo.grade) ? specdojo.grade : null;
2008
+ if (!grade)
2009
+ return [`${path}: specdojo.grade is missing`];
2010
+ const findings = isRecord(grade.findings) ? grade.findings : {};
2011
+ const actual = { blocker: 0, major: 0, minor: 0, note: 0 };
2012
+ for (const match of document.body.matchAll(FINDING_RE))
2013
+ actual[match[2]] += 1;
2014
+ const errors = [];
2015
+ for (const severity of Object.keys(actual)) {
2016
+ if (findings[severity] !== actual[severity])
2017
+ errors.push(`${path}: findings.${severity}=${String(findings[severity])}, comments=${actual[severity]}`);
2018
+ }
2019
+ if (grade.content_hash !== legacyInlineContentHash(document))
2020
+ errors.push(`${path}: content changed after the last grade`);
2021
+ return errors;
2022
+ }
2023
+ export function migrateInlineGrades(opts) {
2024
+ const rootDir = specdojoRootDir();
2025
+ const candidates = opts.paths && opts.paths.length > 0
2026
+ ? opts.paths.map((path) => resolveSafeMarkdownPath(path, rootDir))
2027
+ : [
2028
+ ...(opts.target !== "deliverable"
2029
+ ? discoverGradeTargets({ target: "kata", project: opts.project }, rootDir)
2030
+ : []),
2031
+ ...(opts.target !== "kata"
2032
+ ? discoverGradeTargets({ target: "deliverable", project: opts.project }, rootDir)
2033
+ : []),
2034
+ ];
2035
+ const resultsDirectory = resolveGradeResultsDirectory(opts.project, rootDir);
2036
+ const changed = [];
2037
+ for (const absolute of candidates) {
2038
+ const rel = relativePathFromRoot(absolute, rootDir);
2039
+ const current = readFileSync(absolute, "utf8");
2040
+ if (!current.includes("specdojo:finding") && !/^ grade:\s*$/m.test(current))
2041
+ continue;
2042
+ let document;
2043
+ try {
2044
+ document = parseMarkdown(current, rel);
2045
+ }
2046
+ catch {
2047
+ continue;
2048
+ }
2049
+ const specdojo = document.data.specdojo;
2050
+ const legacyGrade = isRecord(specdojo.grade) ? structuredClone(specdojo.grade) : undefined;
2051
+ const legacyTarget = legacyGrade?.target;
2052
+ const target = legacyTarget === "kata" || legacyTarget === "deliverable"
2053
+ ? legacyTarget
2054
+ : rel.startsWith("docs/ja/specdojo/")
2055
+ ? "kata"
2056
+ : "deliverable";
2057
+ if (opts.target && target !== opts.target)
2058
+ continue;
2059
+ const legacyFindings = [...document.body.matchAll(FINDING_RE)].map((match) => ({
2060
+ id: match[1],
2061
+ severity: match[2],
2062
+ rule: match[3],
2063
+ line: match[4] ? Number(match[4]) : 1,
2064
+ message: match[5].trim(),
2065
+ }));
2066
+ delete specdojo.grade;
2067
+ document.body = withoutFindingComments(document.body)
2068
+ .replace(/\n{3,}/g, "\n\n")
2069
+ .replace(/(?:\n[ \t]*)*$/, "\n");
2070
+ const cleaned = serializeMarkdown(document);
2071
+ if (cleaned !== current) {
2072
+ changed.push(rel);
2073
+ if (!opts.dryRun)
2074
+ writeFileSync(absolute, cleaned, "utf8");
2075
+ }
2076
+ if (!legacyGrade)
2077
+ continue;
2078
+ const documentId = markdownDocumentId(cleaned, rel);
2079
+ const bodyLines = document.body.split(/\r?\n/);
2080
+ const findings = legacyFindings.map((finding) => ({
2081
+ ...finding,
2082
+ anchor: bodyLines[Math.min(bodyLines.length, finding.line) - 1]?.trim() ?? "",
2083
+ }));
2084
+ const counts = { blocker: 0, major: 0, minor: 0, note: 0 };
2085
+ for (const finding of findings)
2086
+ counts[finding.severity] += 1;
2087
+ if (typeof legacyGrade.rubric !== "string" ||
2088
+ (legacyGrade.verdict !== "pass" &&
2089
+ legacyGrade.verdict !== "needs-work" &&
2090
+ legacyGrade.verdict !== "fail") ||
2091
+ !Number.isSafeInteger(legacyGrade.score) ||
2092
+ typeof legacyGrade.graded_at !== "string" ||
2093
+ typeof legacyGrade.graded_by !== "string" ||
2094
+ !isRecord(legacyGrade.categories) ||
2095
+ !isRecord(legacyGrade.viewpoints)) {
2096
+ throw new Error(`${rel}: legacy specdojo.grade is invalid`);
2097
+ }
2098
+ const result = {
2099
+ version: 1,
2100
+ document: documentId,
2101
+ path: rel,
2102
+ target,
2103
+ rubric: legacyGrade.rubric,
2104
+ ...(typeof legacyGrade.reference === "string" ? { reference: legacyGrade.reference } : {}),
2105
+ verdict: legacyGrade.verdict,
2106
+ score: legacyGrade.score,
2107
+ graded_at: legacyGrade.graded_at,
2108
+ graded_by: legacyGrade.graded_by,
2109
+ content_hash: gradeContentHash(cleaned),
2110
+ categories: legacyGrade.categories,
2111
+ viewpoints: legacyGrade.viewpoints,
2112
+ finding_counts: counts,
2113
+ findings,
2114
+ ...(isRecord(legacyGrade.done_criteria) ? { done_criteria: legacyGrade.done_criteria } : {}),
2115
+ };
2116
+ const resultPath = gradeResultPath(resultsDirectory, documentId);
2117
+ if (writeGradeResult(resultPath, result, opts.dryRun)) {
2118
+ changed.push(repoRelativePath(resultPath));
2119
+ }
2120
+ }
2121
+ return changed;
2122
+ }
2123
+ function collectPathOption(value, previous) {
2124
+ return [...previous, value];
2125
+ }
2126
+ function requireTarget(value) {
2127
+ if (value !== "kata" && value !== "deliverable")
2128
+ throw new Error("--target must be kata or deliverable");
2129
+ return value;
2130
+ }
2131
+ function requireGradeVerdict(value) {
2132
+ if (value !== "pass" && value !== "needs-work" && value !== "fail") {
2133
+ throw new Error("--verdict must be pass, needs-work, or fail");
2134
+ }
2135
+ return value;
2136
+ }
2137
+ function requireMaxFindings(value) {
2138
+ const parsed = Number(value);
2139
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
2140
+ throw new Error("--max-findings must be a non-negative integer");
2141
+ }
2142
+ return parsed;
2143
+ }
2144
+ function requireMinScore(value) {
2145
+ const parsed = Number(value);
2146
+ if (!Number.isSafeInteger(parsed) || parsed < 0 || parsed > 100) {
2147
+ throw new Error("--min-score must be an integer between 0 and 100");
2148
+ }
2149
+ return parsed;
2150
+ }
2151
+ function requirePositiveInteger(value) {
2152
+ const parsed = Number(value);
2153
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
2154
+ throw new Error("value must be a positive integer");
2155
+ }
2156
+ return parsed;
2157
+ }
2158
+ function requirePipelineStatus(value) {
2159
+ if (value !== "passed" && value !== "failed" && value !== "complete") {
2160
+ throw new Error("--status must be passed, failed, or complete");
2161
+ }
2162
+ return value;
2163
+ }
2164
+ function commandError(error) {
2165
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
2166
+ process.exitCode = 1;
2167
+ }
2168
+ export function registerGradeCommand(program) {
2169
+ const grade = program
2170
+ .command("grade")
2171
+ .description("Continuously assess Kata and deliverable content quality");
2172
+ const addSelection = (command) => command
2173
+ .requiredOption("--target <target>", "kata or deliverable")
2174
+ .option("--project <projectId>", "Project id in specdojo.config.json")
2175
+ .option("--path <path>", "Grade only this Markdown document (repeatable)", collectPathOption, [])
2176
+ .option("--changed-only", "Select documents changed since their latest grade", false)
2177
+ .option("--verdict <verdict>", "Select documents with this latest verdict: pass, needs-work, or fail", requireGradeVerdict)
2178
+ .option("--min-score <score>", "Select graded documents with at least this score (0-100)", requireMinScore)
2179
+ .option("--max-findings <count>", "Select graded documents with at most this many findings", requireMaxFindings)
2180
+ .option("--ungraded", "Select documents without a stored grade", false)
2181
+ .option("--incomplete", "Select documents with a retryable incomplete pipeline", false);
2182
+ addSelection(grade.command("list").description("Print selected document paths without writing grade plans")).action((options) => {
2183
+ try {
2184
+ const paths = discoverGradeTargets({
2185
+ target: requireTarget(options.target),
2186
+ project: options.project,
2187
+ paths: options.path,
2188
+ changedOnly: options.changedOnly,
2189
+ verdict: options.verdict,
2190
+ minScore: options.minScore,
2191
+ maxFindings: options.maxFindings,
2192
+ ungraded: options.ungraded,
2193
+ incomplete: options.incomplete,
2194
+ });
2195
+ for (const path of paths)
2196
+ process.stdout.write(`${repoRelativePath(path)}\n`);
2197
+ }
2198
+ catch (error) {
2199
+ commandError(error);
2200
+ }
2201
+ });
2202
+ addSelection(grade
2203
+ .command("plan")
2204
+ .description("Write reusable executor and reporter plans per selected document"))
2205
+ .option("--out <directory>", "Write plans below this repository-relative directory")
2206
+ .option("--reference <path>", "Use this document as the comparison reference")
2207
+ .option("--random-reference", "Select a comparison reference at random from ready documents", false)
2208
+ .action((options) => {
2209
+ try {
2210
+ const target = requireTarget(options.target);
2211
+ const viewpoints = loadViewpoints(options.project);
2212
+ const { id: projectId, project } = resolveProject(options.project);
2213
+ const paths = discoverGradeTargets({
2214
+ target,
2215
+ project: options.project,
2216
+ paths: options.path,
2217
+ changedOnly: options.changedOnly,
2218
+ verdict: options.verdict,
2219
+ minScore: options.minScore,
2220
+ maxFindings: options.maxFindings,
2221
+ ungraded: options.ungraded,
2222
+ incomplete: options.incomplete,
2223
+ });
2224
+ if (options.reference && options.randomReference) {
2225
+ throw new Error("--reference and --random-reference cannot be combined");
2226
+ }
2227
+ // 比較リファレンスは既定で付けない。効果が未実証であり、付けると executor の
2228
+ // 読み込み対象が増えるためである。利用する場合は明示的に指定する。
2229
+ const referenceExampleCandidates = options.randomReference
2230
+ ? discoverGradeTargets({ target, project: options.project, changedOnly: false })
2231
+ : [];
2232
+ const outputDirectory = options.out ??
2233
+ join(getProjectExecutionPath(project), "grade", "generated", "plans", target);
2234
+ const plans = writeGradePlans({
2235
+ target,
2236
+ paths,
2237
+ referenceExampleCandidates,
2238
+ referenceExampleOverride: options.reference,
2239
+ viewpoints,
2240
+ projectId,
2241
+ outputDirectory,
2242
+ doneCriteriaByPath: target === "deliverable"
2243
+ ? resolveDeliverableDoneCriteria(paths, options.project)
2244
+ : undefined,
2245
+ });
2246
+ for (const plan of plans) {
2247
+ // 無作為選定を求めたのに同種別の ready が無い場合は、種別を跨いで代用せず
2248
+ // リファレンスなしで続行する。種別が違うと記載水準の基準として誤りを招く。
2249
+ // 気づかないまま基準なしで評価し続けることを避けるため警告する。
2250
+ if (options.randomReference && !plan.referenceExample) {
2251
+ process.stderr.write(`warning: no ready reference of the same kind for ${plan.target}; grading without a reference\n`);
2252
+ }
2253
+ process.stdout.write(`${plan.changed ? "written" : "unchanged"}: ${plan.path}\n`);
2254
+ process.stdout.write(`${plan.reporterChanged ? "written" : "unchanged"}: ${plan.reporterPath}\n`);
2255
+ }
2256
+ process.stdout.write(`Planned: ${plans.length} document(s)\n`);
2257
+ }
2258
+ catch (error) {
2259
+ commandError(error);
2260
+ }
2261
+ });
2262
+ addSelection(grade
2263
+ .command("apply")
2264
+ .description("Validate reporter fidelity and JSON, calculate scores, and update documents"))
2265
+ .requiredOption("--from <path>", "GradeSubmission JSON produced by the assessment agent")
2266
+ .requiredOption("--by <nickname>", "Grading agent nickname from pm-members.yaml")
2267
+ .option("--analysis-from <path>", "Executor analysis used to verify reporter fidelity (omit only for legacy one-stage output)")
2268
+ .option("--reference <pathOrId>", "Comparison reference used during grading; recorded as a document id")
2269
+ .option("--dry-run", "Validate and list updates without writing", false)
2270
+ .action((options) => {
2271
+ try {
2272
+ const target = requireTarget(options.target);
2273
+ const viewpoints = loadViewpoints(options.project);
2274
+ const { project } = resolveProject(options.project);
2275
+ const gradedBy = resolveGradeActor(options.by, loadMemberRoster(specdojoRootDir(), project));
2276
+ const submission = parseGradeSubmission(readFileSync(resolveSafeRepositoryPath(options.from, "--from"), "utf8"));
2277
+ const selected = new Set(discoverGradeTargets({
2278
+ target,
2279
+ project: options.project,
2280
+ paths: options.path,
2281
+ changedOnly: options.changedOnly,
2282
+ verdict: options.verdict,
2283
+ minScore: options.minScore,
2284
+ maxFindings: options.maxFindings,
2285
+ ungraded: options.ungraded,
2286
+ incomplete: options.incomplete,
2287
+ }).map(repoRelativePath));
2288
+ const doneCriteriaByPath = target === "deliverable"
2289
+ ? resolveDeliverableDoneCriteria([...selected], options.project)
2290
+ : undefined;
2291
+ if (options.analysisFrom) {
2292
+ if (selected.size !== 1) {
2293
+ throw new Error("--analysis-from requires exactly one selected --path");
2294
+ }
2295
+ const expectedPath = [...selected][0];
2296
+ const fidelityIssues = validateGradeReporterFidelity({
2297
+ executorOutput: readFileSync(resolveSafeRepositoryPath(options.analysisFrom, "--analysis-from"), "utf8"),
2298
+ submission,
2299
+ viewpoints,
2300
+ target,
2301
+ expectedPath,
2302
+ doneCriteria: doneCriteriaByPath?.get(expectedPath),
2303
+ });
2304
+ if (fidelityIssues.length > 0) {
2305
+ throw new Error(fidelityIssues.map((issue) => `${issue.path}: ${issue.message}`).join("\n"));
2306
+ }
2307
+ }
2308
+ for (const document of submission.documents)
2309
+ if (!selected.has(repoRelativePath(resolve(specdojoRootDir(), document.path))))
2310
+ throw new Error(`${document.path}: not selected by the current grade filters`);
2311
+ const changed = applyGradeSubmission({
2312
+ submission,
2313
+ viewpoints,
2314
+ target,
2315
+ gradedBy,
2316
+ reference: options.reference,
2317
+ dryRun: options.dryRun,
2318
+ doneCriteriaByPath,
2319
+ criteriaDirectory: join(getProjectExecutionPath(project), "grade", "criteria"),
2320
+ resultsDirectory: join(getProjectExecutionPath(project), "grade", "results"),
2321
+ });
2322
+ for (const path of changed)
2323
+ process.stdout.write(`${options.dryRun ? "would update" : "updated"}: ${path}\n`);
2324
+ process.stdout.write(`Graded: ${submission.documents.length}, updated: ${changed.length}\n`);
2325
+ }
2326
+ catch (error) {
2327
+ commandError(error);
2328
+ }
2329
+ });
2330
+ addSelection(grade.command("validate").description("Validate stored grade hashes and finding counts")).action((options) => {
2331
+ try {
2332
+ const target = requireTarget(options.target);
2333
+ const paths = discoverGradeTargets({
2334
+ target,
2335
+ project: options.project,
2336
+ paths: options.path,
2337
+ changedOnly: options.changedOnly,
2338
+ verdict: options.verdict,
2339
+ minScore: options.minScore,
2340
+ maxFindings: options.maxFindings,
2341
+ ungraded: options.ungraded,
2342
+ incomplete: options.incomplete,
2343
+ });
2344
+ const errors = paths.flatMap((path) => validateGradeResultForDocument({ path, target, project: options.project }));
2345
+ for (const error of errors)
2346
+ process.stderr.write(`ERROR: ${error}\n`);
2347
+ process.stdout.write(`Validated: ${paths.length} document(s), ${errors.length} error(s)\n`);
2348
+ if (errors.length > 0)
2349
+ process.exitCode = 1;
2350
+ }
2351
+ catch (error) {
2352
+ commandError(error);
2353
+ }
2354
+ });
2355
+ grade
2356
+ .command("result")
2357
+ .description("Print the stored grade result sidecar for one document as JSON")
2358
+ .requiredOption("--path <path>", "Markdown document whose grade result is read")
2359
+ .option("--project <projectId>", "Project id in specdojo.config.json")
2360
+ .action((options) => {
2361
+ try {
2362
+ const absolute = resolveSafeMarkdownPath(options.path);
2363
+ const rel = repoRelativePath(absolute);
2364
+ const result = readGradeResultForDocument({ documentPath: rel, project: options.project });
2365
+ if (result)
2366
+ process.stdout.write(`${JSON.stringify(result)}\n`);
2367
+ }
2368
+ catch (error) {
2369
+ commandError(error);
2370
+ }
2371
+ });
2372
+ grade
2373
+ .command("state")
2374
+ .description("Read or update persistent per-document grade pipeline state")
2375
+ .requiredOption("--target <target>", "kata or deliverable")
2376
+ .option("--project <projectId>", "Project id in specdojo.config.json")
2377
+ .option("--path <path>", "Markdown document whose pipeline state is read or updated")
2378
+ .option("--status <status>", "Record passed, failed, or complete", requirePipelineStatus)
2379
+ .option("--stage <number>", "Current pipeline stage", requirePositiveInteger)
2380
+ .option("--stage-total <number>", "Total pipeline stages", requirePositiveInteger, 3)
2381
+ .option("--max-failures <number>", "Consecutive failures allowed before reporting only", requirePositiveInteger, 3)
2382
+ .option("--run-id <id>", "Job Run id that observed this state")
2383
+ .option("--exhausted", "List documents whose consecutive failure limit was reached", false)
2384
+ .action((options) => {
2385
+ try {
2386
+ const target = requireTarget(options.target);
2387
+ if (options.exhausted) {
2388
+ if (options.path || options.status) {
2389
+ throw new Error("--exhausted cannot be combined with --path or --status");
2390
+ }
2391
+ for (const state of listExhaustedGradePipelineStates({
2392
+ target,
2393
+ project: options.project,
2394
+ })) {
2395
+ process.stdout.write(`${state.document}\n`);
2396
+ }
2397
+ return;
2398
+ }
2399
+ if (!options.path)
2400
+ throw new Error("--path is required unless --exhausted is used");
2401
+ if (options.status) {
2402
+ if (!options.runId)
2403
+ throw new Error("--run-id is required with --status");
2404
+ if (!options.stage)
2405
+ throw new Error("--stage is required with --status");
2406
+ const state = recordGradePipelineStage({
2407
+ target,
2408
+ project: options.project,
2409
+ path: options.path,
2410
+ runId: options.runId,
2411
+ stage: options.stage,
2412
+ stageTotal: options.stageTotal,
2413
+ maxFailures: options.maxFailures,
2414
+ status: options.status,
2415
+ });
2416
+ if (state)
2417
+ process.stdout.write(`${JSON.stringify(state)}\n`);
2418
+ return;
2419
+ }
2420
+ const state = readGradePipelineState({
2421
+ target,
2422
+ project: options.project,
2423
+ path: options.path,
2424
+ });
2425
+ if (state)
2426
+ process.stdout.write(`${JSON.stringify(state)}\n`);
2427
+ }
2428
+ catch (error) {
2429
+ commandError(error);
2430
+ }
2431
+ });
2432
+ grade
2433
+ .command("migrate")
2434
+ .description("Move legacy inline grade snapshots and findings to result sidecars")
2435
+ .option("--target <target>", "Restrict migration to kata or deliverable", requireTarget)
2436
+ .option("--project <projectId>", "Project id in specdojo.config.json")
2437
+ .option("--path <path>", "Migrate only this Markdown document (repeatable)", collectPathOption, [])
2438
+ .option("--dry-run", "List updates without writing", false)
2439
+ .action((options) => {
2440
+ try {
2441
+ const changed = migrateInlineGrades({
2442
+ project: options.project,
2443
+ target: options.target,
2444
+ paths: options.path,
2445
+ dryRun: options.dryRun,
2446
+ });
2447
+ for (const path of changed) {
2448
+ process.stdout.write(`${options.dryRun ? "would update" : "updated"}: ${path}\n`);
2449
+ }
2450
+ process.stdout.write(`Migrated updates: ${changed.length}\n`);
2451
+ }
2452
+ catch (error) {
2453
+ commandError(error);
2454
+ }
2455
+ });
2456
+ }