specdojo 0.3.0 → 0.4.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 (245) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +77 -18
  3. package/dist/catalog/build-references.js +144 -0
  4. package/dist/catalog/build-render.js +32 -0
  5. package/dist/{catalog-build.js → catalog/build.js} +18 -295
  6. package/dist/{catalog.js → catalog/catalog.js} +11 -11
  7. package/dist/{catalog-generate.js → catalog/generate.js} +13 -16
  8. package/dist/catalog/paths.js +1 -0
  9. package/dist/{catalog-plan-generate.js → catalog/plan-generate.js} +5 -5
  10. package/dist/{catalog-plan.js → catalog/plan.js} +9 -9
  11. package/dist/{catalog-scaffold.js → catalog/scaffold.js} +6 -6
  12. package/dist/{agent.js → commands/agent.js} +11 -11
  13. package/dist/{build-command.js → commands/build.js} +2 -2
  14. package/dist/{init-command.js → commands/init.js} +103 -37
  15. package/dist/{orchestrator.js → commands/orchestrator.js} +2 -2
  16. package/dist/{watch.js → commands/watch.js} +3 -3
  17. package/dist/dashboard/dashboard-timeline.js +175 -0
  18. package/dist/{dashboard.js → dashboard/dashboard.js} +16 -549
  19. package/dist/dashboard/exec-records.js +105 -0
  20. package/dist/dashboard/routines.js +256 -0
  21. package/dist/dashboard/shared.js +14 -0
  22. package/dist/{timeline-build.js → dashboard/timeline-build.js} +2 -1
  23. package/dist/{timeline.js → dashboard/timeline.js} +1 -1
  24. package/dist/{deliverable.js → deliverable/deliverable.js} +5 -5
  25. package/dist/{deliverable-trash.js → deliverable/trash.js} +7 -7
  26. package/dist/{devcontainer-command.js → devcontainer/command.js} +5 -3
  27. package/dist/{devcontainer-scaffold.js → devcontainer/scaffold.js} +94 -2
  28. package/dist/{doc-index.js → docs/doc-index.js} +3 -3
  29. package/dist/{frontmatter-namespace.js → docs/frontmatter-namespace.js} +2 -2
  30. package/dist/{index-command.js → docs/index-command.js} +1 -1
  31. package/dist/docs/template-resolution.js +1 -0
  32. package/dist/{viewpoint-document-kinds-check.js → docs/viewpoint-document-kinds-check.js} +3 -3
  33. package/dist/{yaml-pages-command.js → docs/yaml-pages-command.js} +1 -1
  34. package/dist/{yaml-pages.js → docs/yaml-pages.js} +5 -5
  35. package/dist/{exec-agent-config.js → exec/agent-config.js} +33 -4
  36. package/dist/{exec-agent-git-state.js → exec/agent-git-state.js} +1 -1
  37. package/dist/{exec-agent-protected-config.js → exec/agent-protected-config.js} +1 -1
  38. package/dist/{exec.js → exec/commands.js} +22 -467
  39. package/dist/exec/core.js +457 -0
  40. package/dist/{exec-events.js → exec/events.js} +2 -2
  41. package/dist/{exec-evidence.js → exec/evidence.js} +11 -6
  42. package/dist/exec/exec.js +2 -0
  43. package/dist/exec/format.js +1 -0
  44. package/dist/{exec-handoff.js → exec/handoff.js} +13 -12
  45. package/dist/{exec-limit.js → exec/limit.js} +93 -12
  46. package/dist/{exec-parent-validation.js → exec/parent-validation.js} +4 -4
  47. package/dist/{exec-pipeline-state.js → exec/pipeline-state.js} +16 -2
  48. package/dist/{exec-plans.js → exec/plans-core.js} +97 -468
  49. package/dist/exec/plans-generation.js +249 -0
  50. package/dist/exec/plans-storage.js +131 -0
  51. package/dist/exec/plans.js +3 -0
  52. package/dist/{exec-project.js → exec/project.js} +1 -1
  53. package/dist/{exec-protection-handoff.js → exec/protection-handoff.js} +3 -3
  54. package/dist/{exec-register-resume.js → exec/register-resume.js} +2 -2
  55. package/dist/{exec-register.js → exec/register.js} +92 -9
  56. package/dist/exec/repo-integration-git.js +23 -0
  57. package/dist/exec/repo-integration-sync.js +264 -0
  58. package/dist/{exec-repo-integration.js → exec/repo-integration.js} +13 -287
  59. package/dist/{exec-repo-trace.js → exec/repo-trace.js} +3 -3
  60. package/dist/exec/reporter-output.js +206 -0
  61. package/dist/{exec-reporter.js → exec/reporter.js} +29 -216
  62. package/dist/{exec-results.js → exec/results.js} +277 -36
  63. package/dist/exec/run/agent-pipeline.js +276 -0
  64. package/dist/exec/run/agent.js +583 -0
  65. package/dist/exec/run/in-place.js +570 -0
  66. package/dist/exec/run/job.js +746 -0
  67. package/dist/exec/run/lifecycle-commands.js +530 -0
  68. package/dist/{exec-run-lock.js → exec/run/lock.js} +4 -3
  69. package/dist/exec/run/mode-shared.js +140 -0
  70. package/dist/exec/run/register-command.js +252 -0
  71. package/dist/exec/run/register-core.js +411 -0
  72. package/dist/exec/run/register-mode.js +210 -0
  73. package/dist/exec/run/register-resume.js +398 -0
  74. package/dist/exec/run/register-state.js +325 -0
  75. package/dist/exec/run/register-worktree.js +540 -0
  76. package/dist/exec/run/run.js +11 -0
  77. package/dist/exec/run/schedule-mode.js +294 -0
  78. package/dist/exec/run/schedule-prepare.js +366 -0
  79. package/dist/exec/run/schedule-task.js +599 -0
  80. package/dist/exec/run/shared.js +449 -0
  81. package/dist/{exec-schedule-calendar.js → exec/schedule/calendar.js} +1 -1
  82. package/dist/{exec-schedule-cpm.js → exec/schedule/cpm.js} +2 -2
  83. package/dist/{exec-schedule-gantt-chart-render.js → exec/schedule/gantt-chart-render.js} +2 -2
  84. package/dist/exec/schedule/gantt-chart.js +2 -0
  85. package/dist/{exec-schedule-hash.js → exec/schedule/hash.js} +2 -2
  86. package/dist/exec/schedule/index.js +1 -0
  87. package/dist/{exec-schedule-initial.js → exec/schedule/initial.js} +2 -2
  88. package/dist/{exec-schedule-progress.js → exec/schedule/progress.js} +2 -2
  89. package/dist/{exec-schedule-ready.js → exec/schedule/ready.js} +2 -2
  90. package/dist/{exec-schedule.js → exec/schedule/schedule.js} +11 -11
  91. package/dist/exec/shared.js +63 -0
  92. package/dist/exec/slot-lock.js +1 -0
  93. package/dist/{exec-strategy.js → exec/strategy.js} +2 -2
  94. package/dist/{exec-task-repos.js → exec/task-repos.js} +2 -2
  95. package/dist/{exec-task-view.js → exec/task-view.js} +4 -4
  96. package/dist/{exec-trial.js → exec/trial-commands.js} +23 -388
  97. package/dist/exec/trial-core.js +371 -0
  98. package/dist/exec/trial.js +2 -0
  99. package/dist/{exec-worktree-command.js → exec/worktree-command.js} +25 -23
  100. package/dist/exec/worktree-ops-commit.js +672 -0
  101. package/dist/exec/worktree-ops-lifecycle.js +297 -0
  102. package/dist/exec/worktree-ops-merge.js +344 -0
  103. package/dist/exec/worktree-ops.js +3 -0
  104. package/dist/exec/worktree.js +305 -0
  105. package/dist/grade/apply.js +734 -0
  106. package/dist/grade/command-apply.js +250 -0
  107. package/dist/grade/command-inspect.js +138 -0
  108. package/dist/grade/command-plan.js +101 -0
  109. package/dist/grade/command-shared.js +68 -0
  110. package/dist/grade/core.js +307 -0
  111. package/dist/grade/grade.js +19 -0
  112. package/dist/grade/markdown.js +274 -0
  113. package/dist/grade/pipeline-state.js +184 -0
  114. package/dist/grade/plan.js +507 -0
  115. package/dist/{grade-result.js → grade/result.js} +7 -96
  116. package/dist/grade/target-discovery.js +265 -0
  117. package/dist/grade/targets.js +435 -0
  118. package/dist/{job.js → job/definition.js} +32 -574
  119. package/dist/job/job.js +568 -0
  120. package/dist/{kata-command.js → kata/command.js} +4 -4
  121. package/dist/{kata.js → kata/kata.js} +5 -5
  122. package/dist/register/approach.js +134 -0
  123. package/dist/register/command-types.js +1 -0
  124. package/dist/register/core.js +369 -0
  125. package/dist/register/create-commands.js +352 -0
  126. package/dist/{register-date.js → register/date.js} +1 -1
  127. package/dist/register/derivation.js +163 -0
  128. package/dist/{register-event-merge.js → register/event-merge.js} +32 -3
  129. package/dist/{register-events.js → register/events.js} +12 -6
  130. package/dist/{register-history.js → register/history.js} +7 -6
  131. package/dist/{register-item.js → register/item.js} +28 -10
  132. package/dist/register/lifecycle-lock.js +5 -0
  133. package/dist/register/maintenance-commands.js +193 -0
  134. package/dist/{register-migrate-timestamps.js → register/migrate-timestamps.js} +3 -3
  135. package/dist/register/migration.js +268 -0
  136. package/dist/register/register.js +404 -0
  137. package/dist/register/renumber.js +341 -0
  138. package/dist/register/transition-commands.js +248 -0
  139. package/dist/register/update.js +230 -0
  140. package/dist/register/views.js +296 -0
  141. package/dist/{review-grade.js → review/grade.js} +2 -2
  142. package/dist/{review-plan.js → review/plan.js} +5 -5
  143. package/dist/routine/definition.js +401 -0
  144. package/dist/{routine.js → routine/routine.js} +50 -419
  145. package/dist/{schedule-approach.js → schedule/approach.js} +9 -9
  146. package/dist/{schedule-build.js → schedule/build.js} +7 -4
  147. package/dist/{schedule.js → schedule/schedule.js} +9 -9
  148. package/dist/schedule/strategy-generate-document.js +273 -0
  149. package/dist/schedule/strategy-generate-scope.js +199 -0
  150. package/dist/schedule/strategy-generate.js +348 -0
  151. package/dist/shared/agent-types.js +23 -0
  152. package/dist/shared/artifact-path.js +9 -0
  153. package/dist/{build-if-stale.js → shared/build-if-stale.js} +1 -1
  154. package/dist/shared/catalog-render.js +115 -0
  155. package/dist/{exec-slot-lock.js → shared/cross-process-lock.js} +3 -1
  156. package/dist/shared/fs.js +30 -0
  157. package/dist/shared/git.js +316 -0
  158. package/dist/shared/grade-result.js +94 -0
  159. package/dist/{package-paths.js → shared/package-paths.js} +3 -3
  160. package/dist/shared/plan-templates.js +114 -0
  161. package/dist/{exec-provider-scaffold.js → shared/provider-scaffold.js} +3 -1
  162. package/dist/shared/random.js +4 -0
  163. package/dist/{exec-schedule-index.js → shared/schedule-index.js} +3 -1
  164. package/dist/shared/schedule-paths.js +9 -0
  165. package/dist/{specdojo-config.js → shared/specdojo-config.js} +96 -9
  166. package/dist/{exec-shared.js → shared/text.js} +0 -134
  167. package/dist/shared/time.js +28 -0
  168. package/dist/shared/yaml.js +28 -0
  169. package/dist/specdojo.js +22 -22
  170. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +29 -17
  171. package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +1 -2
  172. package/docs/ja/specdojo/exec-templates/xep-register-template.md +1 -2
  173. package/docs/ja/specdojo/exec-templates/xer-template.md +1 -3
  174. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +6 -4
  175. package/docs/ja/specdojo/guides/exec-config-guide.md +97 -22
  176. package/docs/ja/specdojo/guides/exec-operation-guide.md +145 -12
  177. package/docs/ja/specdojo/guides/exec-worktree-guide.md +2 -0
  178. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +51 -18
  179. package/docs/ja/specdojo/guides/quick-start-guide.md +81 -16
  180. package/docs/ja/specdojo/guides/register-operation-guide.md +2 -1
  181. package/docs/ja/specdojo/guides/remote-host-development-guide.md +10 -1
  182. package/docs/ja/specdojo/guides/review-guide.md +1 -1
  183. package/docs/ja/specdojo/guides/routine-operation-guide.md +6 -6
  184. package/docs/ja/specdojo/guides/use-case-guide.md +1 -1
  185. package/docs/ja/specdojo/references/command-reference.md +52 -28
  186. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +17 -11
  187. package/docs/ja/specdojo/standards/job-definition-standard.md +20 -18
  188. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -2
  189. package/docs/ja/specdojo/templates/pjr-derived-items-template.md +22 -0
  190. package/docs/ja/specdojo/templates/pjr-index-template.md +1 -0
  191. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +29 -2
  192. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +20 -0
  193. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +23 -0
  194. package/docs/specdojo/schemas/v1/job-run.schema.yaml +2 -2
  195. package/docs/specdojo/schemas/v1/job.schema.yaml +7 -0
  196. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +26 -0
  197. package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
  198. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +70 -7
  199. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +1 -1
  200. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +1 -1
  201. package/package.json +4 -5
  202. package/templates/antigravity/README.md +7 -3
  203. package/templates/antigravity/agent-members-snippet.yaml +108 -12
  204. package/templates/antigravity/exec-defaults-snippet.yaml +10 -13
  205. package/templates/claude/README.md +27 -3
  206. package/templates/claude/agents/claude-executor.md +0 -1
  207. package/templates/claude/agents/claude-reporter.md +2 -1
  208. package/templates/claude/agents/claude-review-executor.md +0 -1
  209. package/templates/codex/README.md +23 -4
  210. package/templates/devcontainer/devcontainer.json +2 -2
  211. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +69 -0
  212. package/templates/devcontainer/remote-host/ssh-config.sample +16 -0
  213. package/templates/init-agent-members.yaml +75 -25
  214. package/templates/init-exec-defaults.yaml +26 -8
  215. package/templates/opencode/README.md +17 -3
  216. package/templates/opencode/agents/opencode-executor.md +0 -1
  217. package/templates/opencode/agents/opencode-reporter.md +2 -1
  218. package/templates/opencode/agents/opencode-review-executor.md +0 -1
  219. package/dist/exec-run.js +0 -6182
  220. package/dist/exec-schedule-gantt-chart.js +0 -2
  221. package/dist/exec-worktree-ops.js +0 -1292
  222. package/dist/exec-worktree.js +0 -446
  223. package/dist/grade.js +0 -3193
  224. package/dist/register.js +0 -2407
  225. package/dist/schedule-strategy-generate.js +0 -812
  226. package/templates/claude/agents/claude-expert-review-executor.md +0 -14
  227. /package/dist/{catalog-plan-prompt.js → catalog/plan-prompt.js} +0 -0
  228. /package/dist/{catalog-types.js → catalog/types.js} +0 -0
  229. /package/dist/{template-frontmatter.js → docs/template-frontmatter.js} +0 -0
  230. /package/dist/{role-types.js → exec/role-types.js} +0 -0
  231. /package/dist/{exec-schedule-gantt-chart-scope.js → exec/schedule/gantt-chart-scope.js} +0 -0
  232. /package/dist/{exec-types.js → exec/types.js} +0 -0
  233. /package/dist/{review-types.js → review/types.js} +0 -0
  234. /package/dist/{schedule-phase-sets.js → schedule/phase-sets.js} +0 -0
  235. /package/dist/{schedule-strategy-profiles.js → schedule/strategy-profiles.js} +0 -0
  236. /package/dist/{agent-response.js → shared/agent-response.js} +0 -0
  237. /package/dist/{catalog-paths.js → shared/catalog-paths.js} +0 -0
  238. /package/dist/{dist-freshness.js → shared/dist-freshness.js} +0 -0
  239. /package/dist/{git-environment.js → shared/git-environment.js} +0 -0
  240. /package/dist/{exec-format.js → shared/markdown-format.js} +0 -0
  241. /package/dist/{practice-id.js → shared/practice-id.js} +0 -0
  242. /package/dist/{spawn-self.js → shared/spawn-self.js} +0 -0
  243. /package/dist/{specdojo-gitignore.js → shared/specdojo-gitignore.js} +0 -0
  244. /package/dist/{template-resolution.js → shared/template-resolution.js} +0 -0
  245. /package/dist/{yaml-schema-modeline.js → shared/yaml-schema-modeline.js} +0 -0
@@ -0,0 +1,734 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative, resolve, sep } from "node:path";
4
+ import { dump } from "../shared/yaml.js";
5
+ import { extractJsonText } from "../shared/agent-response.js";
6
+ import { CRITERION_ID_RE, CRITERION_STATUSES, DONE_CRITERIA_SCHEMA, SEVERITY_LEVEL_CAP, agentViewpoints, correctViewpointLevels, isRecord, levelCapForFindings, parseMarkdown, preserveStoredFindingSeverities, sanitizeCommentText, } from "./core.js";
7
+ import { applicableDoneCriteria, deterministicResults, gradePlanFilename } from "./plan.js";
8
+ import { gradeContentHash, gradeResultPath, markdownDocumentId, readGradeResult, writeGradeResult, } from "./result.js";
9
+ import { gradeMarkdownDocument, resolveGradeReferenceId, scoreDocument, summarizeDoneCriteria, } from "./markdown.js";
10
+ import { assertRubric, createGradeSourceContext, gradeSourceHashes, repoRelativePath, resolveSafeMarkdownPath, resolveSafeRepositoryPath, } from "./targets.js";
11
+ import { specdojoRootDir } from "../shared/specdojo-config.js";
12
+ import { resolveSpecdojoPath } from "../docs/template-resolution.js";
13
+ export function normalizeGradeExecutorLine(line) {
14
+ let normalized = line.replace(/^\s*(?:>\s*)*(?:[-*+]\s+)?/, "");
15
+ const wrappedMarker = normalized.match(/^\*\*(\[(?:END )?(?:VIEWPOINT[^\]]*|DONE_CRITERIA)\])\*\*\s*$/);
16
+ if (wrappedMarker)
17
+ return wrappedMarker[1];
18
+ const wrappedLevel = normalized.match(/^\*\*(LEVEL:\s*[0-4])\*\*\s*$/);
19
+ if (wrappedLevel)
20
+ return wrappedLevel[1];
21
+ normalized = normalized.replace(/^\*\*(LEVEL|FINDING(?:\s+[a-z]+)?(?:\s+line=[0-9]+)?|DC-[0-9]{3,})(:?)\*\*(:?)/, (_match, head, innerColon, outerColon) => `${head}${innerColon}${outerColon}`);
22
+ return normalized;
23
+ }
24
+ export function parseGradeExecutorAnalysis(raw) {
25
+ const viewpoints = [];
26
+ let doneCriteria;
27
+ let inDoneCriteria = false;
28
+ let current;
29
+ for (const [lineIndex, rawLine] of raw.split(/\r?\n/).entries()) {
30
+ const line = normalizeGradeExecutorLine(rawLine);
31
+ if (/^\[DONE_CRITERIA\]\s*$/.test(line)) {
32
+ if (current)
33
+ throw new Error(`line ${lineIndex + 1}: DONE_CRITERIA inside VIEWPOINT`);
34
+ if (doneCriteria !== undefined) {
35
+ throw new Error(`line ${lineIndex + 1}: duplicate DONE_CRITERIA block`);
36
+ }
37
+ doneCriteria = [];
38
+ inDoneCriteria = true;
39
+ continue;
40
+ }
41
+ if (/^\[END DONE_CRITERIA\]\s*$/.test(line)) {
42
+ if (!inDoneCriteria) {
43
+ throw new Error(`line ${lineIndex + 1}: unexpected END DONE_CRITERIA marker`);
44
+ }
45
+ inDoneCriteria = false;
46
+ continue;
47
+ }
48
+ if (inDoneCriteria) {
49
+ if (line.trim() === "")
50
+ continue;
51
+ const criterion = line.match(/^(DC-[0-9]{3,}):\s*(satisfied|unsatisfied)(?:\s*[::]\s*(\S.*?))?\s*$/);
52
+ if (!criterion) {
53
+ throw new Error(`line ${lineIndex + 1}: malformed DONE_CRITERIA entry`);
54
+ }
55
+ doneCriteria.push({
56
+ id: criterion[1],
57
+ status: criterion[2],
58
+ ...(criterion[3] ? { reason: criterion[3].trim() } : {}),
59
+ });
60
+ continue;
61
+ }
62
+ const start = line.match(/^\[VIEWPOINT ([A-Za-z0-9][A-Za-z0-9._-]*)\]\s*$/);
63
+ if (start) {
64
+ if (current) {
65
+ throw new Error(`line ${lineIndex + 1}: nested VIEWPOINT marker`);
66
+ }
67
+ current = { id: start[1], findings: [] };
68
+ continue;
69
+ }
70
+ if (/^\[END VIEWPOINT\]\s*$/.test(line)) {
71
+ if (!current)
72
+ throw new Error(`line ${lineIndex + 1}: unexpected END VIEWPOINT marker`);
73
+ if (current.level === undefined) {
74
+ throw new Error(`viewpoint ${current.id}: LEVEL is required`);
75
+ }
76
+ viewpoints.push({ id: current.id, level: current.level, findings: current.findings });
77
+ current = undefined;
78
+ continue;
79
+ }
80
+ if (!current)
81
+ continue;
82
+ const level = line.match(/^LEVEL:\s*([0-4])\s*$/);
83
+ if (level) {
84
+ if (current.level !== undefined) {
85
+ throw new Error(`line ${lineIndex + 1}: duplicate LEVEL for ${current.id}`);
86
+ }
87
+ current.level = Number(level[1]);
88
+ continue;
89
+ }
90
+ if (/^LEVEL\s*:/.test(line)) {
91
+ throw new Error(`line ${lineIndex + 1}: malformed LEVEL for ${current.id}`);
92
+ }
93
+ const finding = line.match(/^FINDING\s+(blocker|major|minor|note)(?:\s+line=([1-9][0-9]*))?:\s*(\S.*)\s*$/);
94
+ if (finding) {
95
+ current.findings.push({
96
+ severity: finding[1],
97
+ ...(finding[2] ? { line: Number(finding[2]) } : {}),
98
+ message: finding[3].trim(),
99
+ });
100
+ continue;
101
+ }
102
+ if (/^FINDING(?:\s|:)/.test(line)) {
103
+ throw new Error(`line ${lineIndex + 1}: malformed FINDING for ${current.id}`);
104
+ }
105
+ }
106
+ if (current)
107
+ throw new Error(`viewpoint ${current.id}: END VIEWPOINT marker is required`);
108
+ if (inDoneCriteria)
109
+ throw new Error("END DONE_CRITERIA marker is required");
110
+ if (viewpoints.length === 0)
111
+ throw new Error("No VIEWPOINT markers found in executor analysis");
112
+ return { viewpoints, ...(doneCriteria !== undefined ? { doneCriteria } : {}) };
113
+ }
114
+ function normalizeFindingMessageForFidelity(message) {
115
+ return message
116
+ .normalize("NFC")
117
+ .replace(/[、,]/gu, ",")
118
+ .replace(/[。.]/gu, ".")
119
+ .replace(/!/gu, "!")
120
+ .replace(/?/gu, "?")
121
+ .replace(/:/gu, ":")
122
+ .replace(/;/gu, ";")
123
+ .replace(/\s+/gu, " ")
124
+ .trim()
125
+ .replace(/\s*([,.;:!?])\s*/gu, "$1");
126
+ }
127
+ function findingFidelityKey(finding) {
128
+ return JSON.stringify({
129
+ severity: finding.severity,
130
+ line: finding.line ?? null,
131
+ message: normalizeFindingMessageForFidelity(finding.message),
132
+ });
133
+ }
134
+ function unmatchedFindings(declared, reported) {
135
+ const remainingReported = reported.map((finding) => ({
136
+ finding,
137
+ matched: false,
138
+ }));
139
+ const unmatchedDeclared = [];
140
+ for (const finding of declared) {
141
+ const key = findingFidelityKey(finding);
142
+ const match = remainingReported.find((candidate) => !candidate.matched && findingFidelityKey(candidate.finding) === key);
143
+ if (match)
144
+ match.matched = true;
145
+ else
146
+ unmatchedDeclared.push(finding);
147
+ }
148
+ return {
149
+ declared: unmatchedDeclared,
150
+ reported: remainingReported
151
+ .filter((candidate) => !candidate.matched)
152
+ .map((candidate) => candidate.finding),
153
+ };
154
+ }
155
+ function findingDifferenceMessage(declared, reported) {
156
+ const differences = [];
157
+ if (declared.severity !== reported.severity) {
158
+ differences.push(`severity executor=${declared.severity} reporter=${reported.severity}`);
159
+ }
160
+ if (declared.line !== reported.line) {
161
+ differences.push(`line executor=${declared.line ?? "none"} reporter=${reported.line ?? "none"}`);
162
+ }
163
+ if (normalizeFindingMessageForFidelity(declared.message) !==
164
+ normalizeFindingMessageForFidelity(reported.message)) {
165
+ differences.push(`message executor=${JSON.stringify(declared.message)} reporter=${JSON.stringify(reported.message)}`);
166
+ }
167
+ return differences.join("; ");
168
+ }
169
+ function findingSimilarity(declared, reported) {
170
+ return (Number(declared.severity === reported.severity) +
171
+ Number(declared.line === reported.line) +
172
+ Number(normalizeFindingMessageForFidelity(declared.message) ===
173
+ normalizeFindingMessageForFidelity(reported.message)));
174
+ }
175
+ function doneCriteriaFidelityIssues(declared, reported) {
176
+ const issues = [];
177
+ const where = "documents[0].done_criteria";
178
+ if (declared === undefined && reported === undefined)
179
+ return issues;
180
+ if (declared === undefined) {
181
+ issues.push({ path: where, message: "reporter added done_criteria not declared by executor" });
182
+ return issues;
183
+ }
184
+ const reportedById = new Map((reported ?? []).map((criterion) => [criterion.id, criterion]));
185
+ for (const criterion of declared) {
186
+ const match = reportedById.get(criterion.id);
187
+ if (!match) {
188
+ issues.push({ path: where, message: `reporter omitted executor criterion: ${criterion.id}` });
189
+ continue;
190
+ }
191
+ reportedById.delete(criterion.id);
192
+ if (match.status !== criterion.status) {
193
+ issues.push({
194
+ path: `${where}.${criterion.id}`,
195
+ message: `reporter status ${match.status} differs from executor status ${criterion.status}`,
196
+ });
197
+ }
198
+ if (normalizeFindingMessageForFidelity(criterion.reason ?? "") !==
199
+ normalizeFindingMessageForFidelity(match.reason ?? "")) {
200
+ issues.push({
201
+ path: `${where}.${criterion.id}`,
202
+ message: `reporter changed executor reason: executor=${JSON.stringify(criterion.reason ?? "")} reporter=${JSON.stringify(match.reason ?? "")}`,
203
+ });
204
+ }
205
+ }
206
+ for (const id of reportedById.keys()) {
207
+ issues.push({
208
+ path: where,
209
+ message: `reporter added criterion not declared by executor: ${id}`,
210
+ });
211
+ }
212
+ return issues;
213
+ }
214
+ // executor の marker を parse し、GradeSubmission へ機械的に変換したうえで既存の
215
+ // GradeSubmission 検証にかける。severity が定める上限より level が高い場合は、判定を甘くしない
216
+ // 方向へ level だけを補正し、補正前後を submission に残す。それ以外の marker 契約違反と
217
+ // done_criteria の過不足は拒否する。
218
+ function convertGradeExecutorOutput(opts) {
219
+ let analysis;
220
+ try {
221
+ analysis = parseGradeExecutorAnalysis(opts.executorOutput);
222
+ }
223
+ catch (error) {
224
+ return {
225
+ issues: [
226
+ {
227
+ path: "$analysis",
228
+ message: error instanceof Error ? error.message : String(error),
229
+ },
230
+ ],
231
+ };
232
+ }
233
+ const rubric = assertRubric(opts.viewpoints);
234
+ const corrected = correctViewpointLevels(analysis.viewpoints);
235
+ const submission = {
236
+ rubric: rubric.id,
237
+ documents: [
238
+ {
239
+ path: opts.expectedPath,
240
+ viewpoints: corrected.viewpoints,
241
+ ...(corrected.corrections.length > 0 ? { level_corrections: corrected.corrections } : {}),
242
+ ...(analysis.doneCriteria ? { done_criteria: analysis.doneCriteria } : {}),
243
+ },
244
+ ],
245
+ };
246
+ const issues = validateGradeSubmission(submission, opts.viewpoints, opts.target, opts.doneCriteria
247
+ ? { doneCriteriaByPath: new Map([[opts.expectedPath, opts.doneCriteria]]) }
248
+ : {}).map((issue) => ({ path: `$analysis.${issue.path}`, message: issue.message }));
249
+ if (issues.length > 0)
250
+ return { issues };
251
+ return { analysis, submission, issues: [] };
252
+ }
253
+ // executor の分析から GradeSubmission を生成する。LLM の reporter を通さずに grade を記録する
254
+ // 既定の経路で使う。拒否時は issues を返し、呼び出し側は executor を再実行する。
255
+ export function buildGradeSubmissionFromAnalysis(opts) {
256
+ const conversion = convertGradeExecutorOutput(opts);
257
+ if (conversion.submission === undefined)
258
+ return { issues: conversion.issues };
259
+ return { submission: conversion.submission, issues: [] };
260
+ }
261
+ export function validateGradeReporterFidelity(opts) {
262
+ const conversion = convertGradeExecutorOutput(opts);
263
+ if (conversion.analysis === undefined)
264
+ return conversion.issues;
265
+ const analysis = conversion.analysis;
266
+ if (opts.submission.documents.length !== 1) {
267
+ return [
268
+ { path: "documents", message: "reporter submission must contain exactly one document" },
269
+ ];
270
+ }
271
+ const document = opts.submission.documents[0];
272
+ if (document.path !== opts.expectedPath) {
273
+ return [
274
+ {
275
+ path: "documents[0].path",
276
+ message: `reporter path must remain ${opts.expectedPath}`,
277
+ },
278
+ ];
279
+ }
280
+ const issues = [];
281
+ const reportedById = new Map(document.viewpoints.map((viewpoint) => [viewpoint.id, viewpoint]));
282
+ for (const declared of analysis.viewpoints) {
283
+ const reported = reportedById.get(declared.id);
284
+ if (!reported) {
285
+ issues.push({
286
+ path: `documents[0].viewpoints`,
287
+ message: `reporter omitted executor viewpoint: ${declared.id}`,
288
+ });
289
+ continue;
290
+ }
291
+ if (reported.level !== declared.level) {
292
+ issues.push({
293
+ path: `documents[0].viewpoints.${declared.id}.level`,
294
+ message: `reporter level ${reported.level} differs from executor level ${declared.level}`,
295
+ });
296
+ }
297
+ const unmatched = unmatchedFindings(declared.findings ?? [], reported.findings ?? []);
298
+ while (unmatched.declared.length > 0 && unmatched.reported.length > 0) {
299
+ const executorFinding = unmatched.declared.shift();
300
+ let bestIndex = 0;
301
+ for (let index = 1; index < unmatched.reported.length; index += 1) {
302
+ if (findingSimilarity(executorFinding, unmatched.reported[index]) >
303
+ findingSimilarity(executorFinding, unmatched.reported[bestIndex])) {
304
+ bestIndex = index;
305
+ }
306
+ }
307
+ const reporterFinding = unmatched.reported.splice(bestIndex, 1)[0];
308
+ issues.push({
309
+ path: `documents[0].viewpoints.${declared.id}.findings`,
310
+ message: `reporter changed executor finding: ${findingDifferenceMessage(executorFinding, reporterFinding)}`,
311
+ });
312
+ }
313
+ for (const finding of unmatched.declared) {
314
+ issues.push({
315
+ path: `documents[0].viewpoints.${declared.id}.findings`,
316
+ message: `reporter omitted executor finding: ${JSON.stringify(finding)}`,
317
+ });
318
+ }
319
+ for (const finding of unmatched.reported) {
320
+ issues.push({
321
+ path: `documents[0].viewpoints.${declared.id}.findings`,
322
+ message: `reporter added finding not declared by executor: ${JSON.stringify(finding)}`,
323
+ });
324
+ }
325
+ }
326
+ issues.push(...doneCriteriaFidelityIssues(analysis.doneCriteria, document.done_criteria));
327
+ return issues;
328
+ }
329
+ export function parseGradeSubmission(raw) {
330
+ let value;
331
+ try {
332
+ value = JSON.parse(extractJsonText(raw));
333
+ }
334
+ catch (error) {
335
+ throw new Error(`Grade submission must be JSON: ${error instanceof Error ? error.message : String(error)}`);
336
+ }
337
+ if (!isRecord(value) ||
338
+ typeof value.rubric !== "string" ||
339
+ (value.graded_by !== undefined && typeof value.graded_by !== "string") ||
340
+ !Array.isArray(value.documents)) {
341
+ throw new Error("Grade submission requires rubric and documents[]");
342
+ }
343
+ return value;
344
+ }
345
+ function validateDoneCriteriaInput(opts) {
346
+ const issues = [];
347
+ const { where, value, expected } = opts;
348
+ if (value === undefined) {
349
+ if (expected && expected.length > 0) {
350
+ issues.push({ path: where, message: "done_criteria[] is required for this deliverable" });
351
+ }
352
+ return issues;
353
+ }
354
+ if (!Array.isArray(value)) {
355
+ issues.push({ path: `${where}.done_criteria`, message: "done_criteria must be an array" });
356
+ return issues;
357
+ }
358
+ if (opts.target !== "deliverable") {
359
+ issues.push({
360
+ path: `${where}.done_criteria`,
361
+ message: "done_criteria is accepted only for deliverable targets",
362
+ });
363
+ return issues;
364
+ }
365
+ const expectedIds = expected ? new Set(expected.map((criterion) => criterion.id)) : undefined;
366
+ const seen = new Set();
367
+ for (const [index, entry] of value.entries()) {
368
+ const entryPath = `${where}.done_criteria[${index}]`;
369
+ if (!isRecord(entry) ||
370
+ typeof entry.id !== "string" ||
371
+ !CRITERION_ID_RE.test(entry.id) ||
372
+ typeof entry.status !== "string" ||
373
+ !CRITERION_STATUSES.includes(entry.status)) {
374
+ issues.push({ path: entryPath, message: "id (DC-NNN) and status are required" });
375
+ continue;
376
+ }
377
+ if (entry.reason !== undefined && typeof entry.reason !== "string") {
378
+ issues.push({ path: `${entryPath}.reason`, message: "reason must be a string" });
379
+ }
380
+ if (entry.status === "unsatisfied" &&
381
+ !(typeof entry.reason === "string" && entry.reason.trim())) {
382
+ issues.push({ path: entryPath, message: "unsatisfied requires a non-empty reason" });
383
+ }
384
+ if (seen.has(entry.id)) {
385
+ issues.push({ path: entryPath, message: `duplicate criterion: ${entry.id}` });
386
+ }
387
+ seen.add(entry.id);
388
+ if (expectedIds && !expectedIds.has(entry.id)) {
389
+ issues.push({ path: entryPath, message: `unknown criterion: ${entry.id}` });
390
+ }
391
+ }
392
+ for (const id of expectedIds ?? []) {
393
+ if (!seen.has(id))
394
+ issues.push({ path: where, message: `missing criterion: ${id}` });
395
+ }
396
+ return issues;
397
+ }
398
+ export function validateGradeSubmission(submission, doc, target, options = {}) {
399
+ const issues = [];
400
+ const rubric = assertRubric(doc);
401
+ if (submission.rubric !== rubric.id)
402
+ issues.push({ path: "$", message: `rubric must be ${rubric.id}` });
403
+ const paths = new Set();
404
+ for (const [documentIndex, document] of submission.documents.entries()) {
405
+ const where = `documents[${documentIndex}]`;
406
+ if (!document || typeof document.path !== "string" || !Array.isArray(document.viewpoints)) {
407
+ issues.push({ path: where, message: "path and viewpoints[] are required" });
408
+ continue;
409
+ }
410
+ if (paths.has(document.path))
411
+ issues.push({ path: where, message: `duplicate path: ${document.path}` });
412
+ paths.add(document.path);
413
+ const absoluteDocumentPath = resolve(specdojoRootDir(), document.path);
414
+ const normalizedDocumentPath = repoRelativePath(absoluteDocumentPath);
415
+ const metadata = existsSync(absoluteDocumentPath)
416
+ ? parseMarkdown(readFileSync(absoluteDocumentPath, "utf8"), normalizedDocumentPath).data
417
+ .specdojo
418
+ : {};
419
+ const required = agentViewpoints(doc, target, metadata);
420
+ const allowed = new Map(required.map((viewpoint) => [viewpoint.id, viewpoint]));
421
+ const expectedDoneCriteria = options.doneCriteriaByPath?.get(document.path) ??
422
+ options.doneCriteriaByPath?.get(normalizedDocumentPath);
423
+ issues.push(...validateDoneCriteriaInput({
424
+ where,
425
+ target,
426
+ value: document.done_criteria,
427
+ expected: expectedDoneCriteria
428
+ ? applicableDoneCriteria(expectedDoneCriteria, doc, metadata)
429
+ : undefined,
430
+ }));
431
+ const ids = new Set();
432
+ const findingIds = new Set();
433
+ for (const [viewpointIndex, result] of document.viewpoints.entries()) {
434
+ const resultPath = `${where}.viewpoints[${viewpointIndex}]`;
435
+ if (!result || !allowed.has(result.id)) {
436
+ issues.push({
437
+ path: resultPath,
438
+ message: `unknown or non-applicable viewpoint: ${result?.id ?? ""}`,
439
+ });
440
+ continue;
441
+ }
442
+ if (ids.has(result.id))
443
+ issues.push({ path: resultPath, message: `duplicate viewpoint: ${result.id}` });
444
+ ids.add(result.id);
445
+ if (!Number.isInteger(result.level) || result.level < 0 || result.level > 4) {
446
+ issues.push({ path: resultPath, message: "level must be an integer from 0 to 4" });
447
+ }
448
+ const findings = result.findings ?? [];
449
+ if (!Array.isArray(findings)) {
450
+ issues.push({ path: resultPath, message: "findings must be an array" });
451
+ continue;
452
+ }
453
+ if (result.level < 4 && findings.length === 0) {
454
+ issues.push({ path: resultPath, message: "level 0-3 requires at least one finding" });
455
+ }
456
+ for (const [findingIndex, finding] of findings.entries()) {
457
+ if (!finding ||
458
+ !Object.hasOwn(SEVERITY_LEVEL_CAP, finding.severity) ||
459
+ typeof finding.message !== "string" ||
460
+ !finding.message.trim()) {
461
+ issues.push({
462
+ path: `${resultPath}.findings[${findingIndex}]`,
463
+ message: "severity and non-empty message are required",
464
+ });
465
+ continue;
466
+ }
467
+ if (finding.message_ja !== undefined &&
468
+ (typeof finding.message_ja !== "string" || !finding.message_ja.trim())) {
469
+ issues.push({
470
+ path: `${resultPath}.findings[${findingIndex}].message_ja`,
471
+ message: "message_ja must be a non-empty string when present",
472
+ });
473
+ }
474
+ if (finding.id !== undefined) {
475
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(finding.id)) {
476
+ issues.push({
477
+ path: `${resultPath}.findings[${findingIndex}].id`,
478
+ message: "id must contain only letters, digits, dot, underscore, or hyphen",
479
+ });
480
+ }
481
+ else if (findingIds.has(finding.id)) {
482
+ issues.push({
483
+ path: `${resultPath}.findings[${findingIndex}].id`,
484
+ message: `duplicate finding id: ${finding.id}`,
485
+ });
486
+ }
487
+ findingIds.add(finding.id);
488
+ }
489
+ if (finding.line !== undefined && (!Number.isInteger(finding.line) || finding.line < 1)) {
490
+ issues.push({
491
+ path: `${resultPath}.findings[${findingIndex}].line`,
492
+ message: "line must be a positive integer",
493
+ });
494
+ }
495
+ }
496
+ const cap = levelCapForFindings(findings);
497
+ if (result.level > cap)
498
+ issues.push({ path: resultPath, message: `finding severity caps level at ${cap}` });
499
+ }
500
+ if (document.level_corrections !== undefined) {
501
+ if (!Array.isArray(document.level_corrections)) {
502
+ issues.push({ path: `${where}.level_corrections`, message: "must be an array" });
503
+ }
504
+ else {
505
+ for (const [index, correction] of document.level_corrections.entries()) {
506
+ const correctedViewpoint = document.viewpoints.find((viewpoint) => viewpoint.id === correction?.viewpoint);
507
+ if (!correction ||
508
+ typeof correction.viewpoint !== "string" ||
509
+ !correctedViewpoint ||
510
+ !Number.isInteger(correction.original_level) ||
511
+ !Number.isInteger(correction.corrected_level) ||
512
+ correction.original_level < 0 ||
513
+ correction.original_level > 4 ||
514
+ correction.corrected_level < 0 ||
515
+ correction.corrected_level >= correction.original_level ||
516
+ correctedViewpoint.level !== correction.corrected_level) {
517
+ issues.push({
518
+ path: `${where}.level_corrections[${index}]`,
519
+ message: "viewpoint and matching downward original/corrected levels from 0 to 4 are required",
520
+ });
521
+ }
522
+ }
523
+ }
524
+ }
525
+ for (const viewpoint of required) {
526
+ if (!ids.has(viewpoint.id)) {
527
+ issues.push({ path: where, message: `missing agent viewpoint: ${viewpoint.id}` });
528
+ }
529
+ }
530
+ }
531
+ return issues;
532
+ }
533
+ // 詳細ファイルは成果物ごとに1件で、再評価のたびに上書きする。時点の記録は git 履歴が担う。
534
+ // grade 本体と同じ方式であり、実行ごとにファイルを増やすと最新の評価を判別できなくなる。
535
+ export function doneCriteriaDetailPath(criteriaDirectory, documentPath) {
536
+ const absolute = resolveSafeMarkdownPath(documentPath);
537
+ const directory = resolveSafeRepositoryPath(criteriaDirectory, "criteria directory");
538
+ return join(directory, gradePlanFilename(absolute).replace(/-grade-plan\.md$/, "-done-criteria.yaml"));
539
+ }
540
+ function doneCriteriaDetailId(documentId, documentPath) {
541
+ if (documentId)
542
+ return `${documentId}-grade-criteria`;
543
+ const hash = createHash("sha256")
544
+ .update(repoRelativePath(documentPath))
545
+ .digest("hex")
546
+ .slice(0, 10);
547
+ return `grade-criteria-${hash}`;
548
+ }
549
+ export function renderDoneCriteriaDetail(detail, detailPath) {
550
+ const schemaRef = relative(dirname(detailPath), resolveSpecdojoPath(DONE_CRITERIA_SCHEMA))
551
+ .split(sep)
552
+ .join("/");
553
+ return `# yaml-language-server: $schema=${schemaRef}\n${dump(detail, { lineWidth: 120, noRefs: true, quoteStyle: "double" })}`;
554
+ }
555
+ export function applyGradeSubmission(opts) {
556
+ const issues = validateGradeSubmission(opts.submission, opts.viewpoints, opts.target, {
557
+ doneCriteriaByPath: opts.doneCriteriaByPath,
558
+ });
559
+ if (issues.length > 0)
560
+ throw new Error(issues.map((issue) => `${issue.path}: ${issue.message}`).join("\n"));
561
+ const changed = [];
562
+ const sourceContext = opts.resultsDirectory
563
+ ? createGradeSourceContext(opts.project, specdojoRootDir())
564
+ : undefined;
565
+ for (const input of opts.submission.documents) {
566
+ const absolute = resolveSafeMarkdownPath(input.path);
567
+ const rel = repoRelativePath(absolute);
568
+ const current = readFileSync(absolute, "utf8");
569
+ const definitions = opts.doneCriteriaByPath?.get(rel);
570
+ const detailPath = definitions && input.done_criteria && opts.criteriaDirectory
571
+ ? doneCriteriaDetailPath(opts.criteriaDirectory, absolute)
572
+ : undefined;
573
+ if (definitions && input.done_criteria && !detailPath) {
574
+ throw new Error(`${rel}: criteriaDirectory is required to record done_criteria`);
575
+ }
576
+ if (opts.resultsDirectory) {
577
+ const documentId = markdownDocumentId(current, rel);
578
+ const resultPath = gradeResultPath(opts.resultsDirectory, documentId);
579
+ const previous = readGradeResult(resultPath);
580
+ const document = parseMarkdown(current, rel);
581
+ const agentResults = preserveStoredFindingSeverities(previous, input.viewpoints);
582
+ const correctionByViewpoint = new Map((input.level_corrections ?? []).map((correction) => [
583
+ correction.viewpoint,
584
+ { ...correction },
585
+ ]));
586
+ for (const [index, result] of agentResults.entries()) {
587
+ const submitted = input.viewpoints[index];
588
+ if (submitted && result.level < submitted.level) {
589
+ const existing = correctionByViewpoint.get(result.id);
590
+ correctionByViewpoint.set(result.id, {
591
+ viewpoint: result.id,
592
+ original_level: existing?.original_level ?? submitted.level,
593
+ corrected_level: result.level,
594
+ });
595
+ }
596
+ }
597
+ const levelCorrections = [...correctionByViewpoint.values()];
598
+ const evaluated = {
599
+ ...input,
600
+ viewpoints: [
601
+ ...agentResults,
602
+ ...deterministicResults(document, opts.viewpoints, opts.target),
603
+ ],
604
+ };
605
+ const rubric = assertRubric(opts.viewpoints);
606
+ const summary = scoreDocument(evaluated, rubric, opts.viewpoints, opts.target);
607
+ const gradedAt = (opts.now ?? new Date()).toISOString();
608
+ const usedIds = new Set();
609
+ let sequence = 0;
610
+ const bodyLines = document.body.split(/\r?\n/);
611
+ const findings = evaluated.viewpoints.flatMap((viewpoint) => (viewpoint.findings ?? []).map((finding) => {
612
+ let id = finding.id?.trim();
613
+ if (!id || usedIds.has(id)) {
614
+ do {
615
+ sequence += 1;
616
+ id = `F${String(sequence).padStart(3, "0")}`;
617
+ } while (usedIds.has(id));
618
+ }
619
+ usedIds.add(id);
620
+ const line = Math.max(1, finding.line ?? 1);
621
+ return {
622
+ id,
623
+ severity: finding.severity,
624
+ rule: viewpoint.id,
625
+ line,
626
+ anchor: bodyLines[Math.min(bodyLines.length, line) - 1]?.trim() ?? "",
627
+ message: sanitizeCommentText(finding.message),
628
+ message_ja: sanitizeCommentText(finding.message_ja ?? finding.message),
629
+ };
630
+ }));
631
+ const criteriaResults = opts.target === "deliverable" && definitions && input.done_criteria && detailPath
632
+ ? input.done_criteria
633
+ : undefined;
634
+ const detailRef = criteriaResults ? doneCriteriaDetailId(documentId, absolute) : undefined;
635
+ const sourceHashes = sourceContext
636
+ ? gradeSourceHashes(absolute, document, opts.viewpoints, opts.target, sourceContext)
637
+ : undefined;
638
+ const result = {
639
+ version: 1,
640
+ document: documentId,
641
+ path: rel,
642
+ target: opts.target,
643
+ rubric: rubric.id,
644
+ ...(opts.reference ? { reference: resolveGradeReferenceId(opts.reference) } : {}),
645
+ verdict: summary.verdict,
646
+ score: summary.score,
647
+ graded_at: gradedAt,
648
+ graded_by: opts.gradedBy,
649
+ content_hash: gradeContentHash(current),
650
+ ...(sourceHashes && Object.keys(sourceHashes).length > 0
651
+ ? { source_hashes: sourceHashes }
652
+ : {}),
653
+ categories: summary.categories,
654
+ viewpoints: summary.viewpoints,
655
+ finding_counts: summary.findings,
656
+ findings,
657
+ ...(levelCorrections.length > 0 ? { level_corrections: levelCorrections } : {}),
658
+ ...(criteriaResults && definitions && detailRef
659
+ ? { done_criteria: summarizeDoneCriteria(definitions, criteriaResults, detailRef) }
660
+ : {}),
661
+ };
662
+ if (criteriaResults && definitions && detailPath && detailRef) {
663
+ const resultById = new Map(criteriaResults.map((criterion) => [criterion.id, criterion]));
664
+ const criteria = definitions.map((definition) => {
665
+ const criterion = resultById.get(definition.id);
666
+ return {
667
+ ...definition,
668
+ status: criterion?.status ?? "unsatisfied",
669
+ ...(criterion?.reason ? { reason: criterion.reason } : {}),
670
+ };
671
+ });
672
+ const satisfied = criteria.filter((criterion) => criterion.status === "satisfied").length;
673
+ const detail = {
674
+ id: detailRef,
675
+ document: documentId,
676
+ path: rel,
677
+ graded_at: gradedAt,
678
+ graded_by: opts.gradedBy,
679
+ content_hash: result.content_hash,
680
+ summary: { satisfied, unsatisfied: criteria.length - satisfied, total: criteria.length },
681
+ criteria,
682
+ };
683
+ const rendered = renderDoneCriteriaDetail(detail, detailPath);
684
+ if (!existsSync(detailPath) || readFileSync(detailPath, "utf8") !== rendered) {
685
+ changed.push(repoRelativePath(detailPath));
686
+ if (!opts.dryRun) {
687
+ mkdirSync(dirname(detailPath), { recursive: true });
688
+ writeFileSync(detailPath, rendered, "utf8");
689
+ }
690
+ }
691
+ }
692
+ if (writeGradeResult(resultPath, result, opts.dryRun)) {
693
+ changed.push(repoRelativePath(resultPath));
694
+ }
695
+ continue;
696
+ }
697
+ const documentId = parseMarkdown(current, rel).data.specdojo;
698
+ const graded = gradeMarkdownDocument({
699
+ content: current,
700
+ path: rel,
701
+ input,
702
+ viewpoints: opts.viewpoints,
703
+ target: opts.target,
704
+ gradedBy: opts.gradedBy,
705
+ reference: opts.reference,
706
+ now: opts.now,
707
+ doneCriteria: definitions && detailPath
708
+ ? {
709
+ definitions,
710
+ detailRef: doneCriteriaDetailId(typeof documentId.id === "string" ? documentId.id : undefined, absolute),
711
+ }
712
+ : undefined,
713
+ });
714
+ // 詳細を先に永続化してから成果物へ detail_ref を書く。途中で詳細の書き込みに失敗しても、
715
+ // 存在しない参照だけが成果物へ残る状態を避ける。
716
+ if (graded.detail && detailPath) {
717
+ const rendered = renderDoneCriteriaDetail(graded.detail, detailPath);
718
+ const detailRel = repoRelativePath(detailPath);
719
+ if (!existsSync(detailPath) || readFileSync(detailPath, "utf8") !== rendered) {
720
+ changed.push(detailRel);
721
+ if (!opts.dryRun) {
722
+ mkdirSync(dirname(detailPath), { recursive: true });
723
+ writeFileSync(detailPath, rendered, "utf8");
724
+ }
725
+ }
726
+ }
727
+ if (graded.content !== current) {
728
+ changed.push(rel);
729
+ if (!opts.dryRun)
730
+ writeFileSync(absolute, graded.content, "utf8");
731
+ }
732
+ }
733
+ return changed;
734
+ }