specdojo 0.2.0 → 0.3.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 (170) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +280 -0
  3. package/README.md +143 -30
  4. package/dist/agent-response.js +20 -0
  5. package/dist/agent.js +4 -4
  6. package/dist/build-command.js +28 -8
  7. package/dist/dashboard.js +140 -9
  8. package/dist/devcontainer-command.js +43 -0
  9. package/dist/devcontainer-scaffold.js +165 -0
  10. package/dist/exec-agent-config.js +107 -9
  11. package/dist/exec-agent-git-state.js +18 -0
  12. package/dist/exec-agent-protected-config.js +46 -8
  13. package/dist/exec-evidence.js +254 -11
  14. package/dist/exec-format.js +13 -4
  15. package/dist/exec-handoff.js +336 -0
  16. package/dist/exec-parent-validation.js +317 -43
  17. package/dist/exec-pipeline-state.js +74 -9
  18. package/dist/exec-plans.js +115 -113
  19. package/dist/exec-protection-handoff.js +43 -2
  20. package/dist/exec-provider-scaffold.js +247 -15
  21. package/dist/exec-register-resume.js +65 -19
  22. package/dist/exec-register.js +9 -3
  23. package/dist/exec-repo-integration.js +811 -0
  24. package/dist/exec-repo-trace.js +182 -0
  25. package/dist/exec-reporter.js +613 -132
  26. package/dist/exec-results.js +81 -56
  27. package/dist/exec-run-lock.js +110 -107
  28. package/dist/exec-run.js +1585 -356
  29. package/dist/exec-shared.js +7 -0
  30. package/dist/exec-slot-lock.js +242 -0
  31. package/dist/exec-task-repos.js +415 -0
  32. package/dist/exec-trial.js +51 -25
  33. package/dist/exec-worktree-command.js +87 -43
  34. package/dist/exec-worktree-ops.js +502 -57
  35. package/dist/exec-worktree.js +114 -27
  36. package/dist/exec.js +13 -6
  37. package/dist/grade-result.js +128 -0
  38. package/dist/grade.js +809 -72
  39. package/dist/init-command.js +443 -0
  40. package/dist/job.js +160 -10
  41. package/dist/orchestrator.js +213 -0
  42. package/dist/package-paths.js +19 -1
  43. package/dist/register-event-merge.js +169 -0
  44. package/dist/register-item.js +7 -1
  45. package/dist/register.js +294 -86
  46. package/dist/review-grade.js +252 -0
  47. package/dist/review-plan.js +111 -1
  48. package/dist/review-types.js +40 -1
  49. package/dist/routine.js +72 -5
  50. package/dist/schedule-build.js +2 -2
  51. package/dist/schedule.js +17 -4
  52. package/dist/specdojo-config.js +466 -20
  53. package/dist/specdojo-gitignore.js +135 -0
  54. package/dist/specdojo.js +8 -1
  55. package/dist/viewpoint-document-kinds-check.js +128 -0
  56. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  57. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  58. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  59. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  60. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  61. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  62. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  63. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  64. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  65. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  66. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  67. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  68. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  69. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  70. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  71. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  72. package/docs/ja/specdojo/guides/exec-config-guide.md +91 -47
  73. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  74. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  75. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  76. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +25 -4
  77. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  78. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  79. package/docs/ja/specdojo/guides/quick-start-guide.md +261 -32
  80. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  81. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  82. package/docs/ja/specdojo/guides/remote-host-development-guide.md +184 -0
  83. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  84. package/docs/ja/specdojo/guides/routine-operation-guide.md +74 -9
  85. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  86. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  87. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  88. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  89. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  90. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  91. package/docs/ja/specdojo/index.md +2 -2
  92. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  93. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  94. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  95. package/docs/ja/specdojo/references/command-reference.md +336 -93
  96. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  97. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  98. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  99. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  100. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  101. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  102. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  103. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  104. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  105. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  106. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  107. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  108. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  109. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  110. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  111. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  112. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  113. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  114. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  115. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  116. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  117. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  118. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  119. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  120. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  121. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  122. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  123. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  124. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  125. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  126. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  127. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  128. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  129. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  130. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  131. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  132. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  133. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  134. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  135. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  136. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  137. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  138. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  139. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  140. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  141. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  142. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  143. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  144. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  145. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  146. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  147. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  148. package/package.json +16 -9
  149. package/templates/antigravity/README.md +60 -0
  150. package/templates/antigravity/agent-members-snippet.yaml +61 -0
  151. package/templates/antigravity/exec-defaults-snippet.yaml +39 -0
  152. package/templates/antigravity/orchestrator.md +157 -0
  153. package/templates/antigravity/settings.global.json +55 -0
  154. package/templates/claude/agents/claude-executor.md +14 -0
  155. package/templates/claude/agents/claude-reporter.md +16 -0
  156. package/templates/claude/agents/specdojo-orchestrator.md +164 -0
  157. package/templates/claude/settings.edit.json +27 -1
  158. package/templates/codex/README.md +5 -4
  159. package/templates/codex/agents/specdojo-orchestrator.toml +165 -0
  160. package/templates/codex/orchestrator.md +157 -0
  161. package/templates/copilot/README.md +7 -5
  162. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  163. package/templates/devcontainer/devcontainer.json +27 -0
  164. package/templates/devcontainer/emacs/init.el +88 -0
  165. package/templates/devcontainer/post-create.sh +62 -0
  166. package/templates/init-agent-members.yaml +200 -0
  167. package/templates/init-exec-defaults.yaml +72 -0
  168. package/templates/opencode/agents/specdojo-orchestrator.md +204 -0
  169. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  170. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -0,0 +1,252 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { gitEnvironment } from "./git-environment.js";
5
+ import { gradeContentHash, gradeFindingDisplayMessage, gradeResultPathForDocument, parseGradeResult, } from "./grade-result.js";
6
+ export const REVIEW_GRADE_SCRIPT = join("tools", "grade", "run-per-document.sh");
7
+ function errorMessage(error) {
8
+ return error instanceof Error ? error.message : String(error);
9
+ }
10
+ /**
11
+ * Classify a stored grade against the current content of its subject. Only content_hash decides
12
+ * freshness here; comparison-source changes are left to `grade list --dependency-changed`.
13
+ */
14
+ export function classifyReviewGrade(opts) {
15
+ const { content, sidecarPath, sidecarContent } = opts;
16
+ if (sidecarContent === undefined)
17
+ return { state: "missing", sidecarPath };
18
+ let result;
19
+ try {
20
+ result = parseGradeResult(sidecarContent, sidecarPath);
21
+ }
22
+ catch (error) {
23
+ return { state: "unreadable", sidecarPath, reason: errorMessage(error) };
24
+ }
25
+ return result.content_hash === gradeContentHash(content)
26
+ ? { state: "fresh", sidecarPath, result }
27
+ : { state: "stale", sidecarPath, result };
28
+ }
29
+ /** Read the subject and its sidecar from disk and classify the stored grade. */
30
+ export function reviewGradeFreshness(opts) {
31
+ const { subjectPath, projectId, rootDir } = opts;
32
+ if (!subjectPath)
33
+ return { state: "unresolved", reason: "評価対象のパスを解決できない" };
34
+ const absolute = join(rootDir, subjectPath);
35
+ if (!existsSync(absolute)) {
36
+ return { state: "unresolved", reason: `評価対象が存在しない: ${subjectPath}` };
37
+ }
38
+ let sidecarPath;
39
+ let content;
40
+ try {
41
+ content = readFileSync(absolute, "utf8");
42
+ sidecarPath = gradeResultPathForDocument({
43
+ documentPath: subjectPath,
44
+ project: projectId,
45
+ rootDir,
46
+ });
47
+ }
48
+ catch (error) {
49
+ return { state: "unresolved", reason: errorMessage(error) };
50
+ }
51
+ let sidecarContent;
52
+ try {
53
+ sidecarContent = existsSync(sidecarPath) ? readFileSync(sidecarPath, "utf8") : undefined;
54
+ }
55
+ catch (error) {
56
+ return { state: "unreadable", sidecarPath, reason: errorMessage(error) };
57
+ }
58
+ return classifyReviewGrade({ content, sidecarPath, sidecarContent });
59
+ }
60
+ /**
61
+ * Decide whether the runner grades the subject before the review plan is written. A fresh grade is
62
+ * reused; an unresolved subject or a repository without the grade pipeline cannot be graded.
63
+ */
64
+ export function decideReviewGradeAction(opts) {
65
+ const { freshness, scriptAvailable, dryRun } = opts;
66
+ if (freshness.state === "fresh")
67
+ return { run: false, outcome: { action: "skipped" } };
68
+ if (freshness.state === "unresolved") {
69
+ return { run: false, outcome: { action: "not-run", detail: freshness.reason } };
70
+ }
71
+ if (dryRun)
72
+ return { run: false, outcome: { action: "not-run", detail: "dry-run のため実行しない" } };
73
+ if (!scriptAvailable) {
74
+ return {
75
+ run: false,
76
+ outcome: {
77
+ action: "not-run",
78
+ detail: `grade の実行スクリプトがリポジトリにない: ${REVIEW_GRADE_SCRIPT.split("\\").join("/")}`,
79
+ },
80
+ };
81
+ }
82
+ return { run: true };
83
+ }
84
+ export function reviewGradeRunId(taskId, now) {
85
+ const safeTaskId = taskId.replace(/[^A-Za-z0-9-]+/g, "-").replace(/^-+|-+$/g, "") || "task";
86
+ const stamp = now
87
+ .toISOString()
88
+ .replace(/[-:]/g, "")
89
+ .replace(/\.\d+Z$/, "Z");
90
+ return `review-${safeTaskId}-${stamp}`;
91
+ }
92
+ export function reviewGradeArgs(opts) {
93
+ const args = [
94
+ REVIEW_GRADE_SCRIPT.split("\\").join("/"),
95
+ "--run-id",
96
+ opts.runId,
97
+ "--project",
98
+ opts.projectId,
99
+ "--target",
100
+ opts.target,
101
+ ];
102
+ // kata の対象範囲は --kind で決まる。評価対象の種類を問わず受け付けるよう all を渡す。
103
+ if (opts.target === "kata")
104
+ args.push("--kind", "all");
105
+ args.push("--path", opts.subjectPath);
106
+ return args;
107
+ }
108
+ const defaultInvoke = (command, args, cwd) => new Promise((resolvePromise) => {
109
+ const child = spawn(command, [...args], {
110
+ cwd,
111
+ env: gitEnvironment(),
112
+ stdio: ["ignore", "inherit", "pipe"],
113
+ });
114
+ let stderr = "";
115
+ child.stderr?.on("data", (chunk) => {
116
+ const text = chunk.toString("utf8");
117
+ stderr += text;
118
+ process.stderr.write(text);
119
+ });
120
+ child.on("error", (error) => resolvePromise({ exitCode: 1, stderr: errorMessage(error) }));
121
+ child.on("close", (code) => resolvePromise({ exitCode: code ?? 1, stderr }));
122
+ });
123
+ function lastLine(text) {
124
+ const lines = text
125
+ .split(/\r?\n/)
126
+ .map((line) => line.trim())
127
+ .filter(Boolean);
128
+ return lines.at(-1) ?? "";
129
+ }
130
+ /**
131
+ * Runner-side grade before a review plan is generated. The executor never grades (PJR-2ZVS 3.6).
132
+ * Failures are reported in the outcome instead of thrown so the review can still record
133
+ * grade-stale / grade-unavailable as its verdict.
134
+ */
135
+ export async function ensureReviewGrade(opts) {
136
+ const freshness = reviewGradeFreshness({
137
+ subjectPath: opts.subjectPath,
138
+ projectId: opts.projectId,
139
+ rootDir: opts.repoRoot,
140
+ });
141
+ const decision = decideReviewGradeAction({
142
+ freshness,
143
+ scriptAvailable: existsSync(join(opts.repoRoot, REVIEW_GRADE_SCRIPT)),
144
+ dryRun: opts.dryRun,
145
+ });
146
+ if (!decision.run)
147
+ return decision.outcome;
148
+ const runId = reviewGradeRunId(opts.taskId, opts.now ?? new Date());
149
+ const args = reviewGradeArgs({
150
+ runId,
151
+ projectId: opts.projectId,
152
+ target: opts.target,
153
+ subjectPath: opts.subjectPath,
154
+ });
155
+ const invoke = opts.invoke ?? defaultInvoke;
156
+ try {
157
+ const { exitCode, stderr } = await invoke("bash", args, opts.repoRoot);
158
+ if (exitCode === 0)
159
+ return { action: "executed", runId };
160
+ const reason = lastLine(stderr);
161
+ return {
162
+ action: "failed",
163
+ runId,
164
+ detail: `exit ${exitCode}${reason ? `: ${reason}` : ""}`,
165
+ };
166
+ }
167
+ catch (error) {
168
+ return { action: "failed", runId, detail: errorMessage(error) };
169
+ }
170
+ }
171
+ function outcomeLine(outcome) {
172
+ if (!outcome)
173
+ return undefined;
174
+ switch (outcome.action) {
175
+ case "skipped":
176
+ return "- runner の grade 実行: 省略した(評価対象の `content_hash` が評価結果と一致したため、既存の評価結果を使う)";
177
+ case "executed":
178
+ return `- runner の grade 実行: 実行した(run id: \`${outcome.runId}\`)`;
179
+ case "failed":
180
+ return `- runner の grade 実行: 失敗した(run id: \`${outcome.runId}\`; ${outcome.detail})`;
181
+ case "not-run":
182
+ return `- runner の grade 実行: 実行していない(${outcome.detail})`;
183
+ }
184
+ }
185
+ function freshnessLine(freshness) {
186
+ switch (freshness.state) {
187
+ case "fresh":
188
+ return "- 鮮度: 最新(評価対象の `content_hash` が評価結果の `content_hash` と一致する)";
189
+ case "stale":
190
+ return "- 鮮度: 最新でない(評価対象の `content_hash` が評価結果の `content_hash` と一致しない)。以下は変更前の内容に対する評価結果であり、現在の内容の評価ではない";
191
+ case "missing":
192
+ return "- 鮮度: 評価結果がない(評価結果サイドカーが存在しない)";
193
+ case "unresolved":
194
+ return `- 鮮度: 確認できない(${freshness.reason})`;
195
+ case "unreadable":
196
+ return `- 鮮度: 確認できない(評価結果サイドカーを読み取れない: ${freshness.reason})`;
197
+ }
198
+ }
199
+ function inlineText(value) {
200
+ return value.replace(/\s+/g, " ").trim();
201
+ }
202
+ function gradeResultLines(result) {
203
+ const counts = result.finding_counts;
204
+ const lines = [
205
+ `- \`verdict\`: \`${result.verdict}\``,
206
+ `- \`score\`: ${result.score}`,
207
+ `- \`graded_at\`: ${result.graded_at}(\`graded_by\`: ${result.graded_by})`,
208
+ `- finding 件数: blocker ${counts.blocker ?? 0} / major ${counts.major ?? 0} / minor ${counts.minor ?? 0} / note ${counts.note ?? 0}`,
209
+ "",
210
+ "grade が判定した観点(全観点):",
211
+ "",
212
+ ];
213
+ const viewpoints = Object.entries(result.viewpoints).sort(([a], [b]) => a.localeCompare(b));
214
+ if (viewpoints.length === 0) {
215
+ lines.push("- なし");
216
+ }
217
+ else {
218
+ lines.push("| 観点 | level | score |", "| --- | --- | --- |");
219
+ for (const [id, value] of viewpoints) {
220
+ lines.push(`| \`${id}\` | ${value.level} | ${value.score} |`);
221
+ }
222
+ }
223
+ lines.push("", "finding:", "");
224
+ if (result.findings.length === 0) {
225
+ lines.push("- なし");
226
+ }
227
+ else {
228
+ for (const finding of result.findings) {
229
+ lines.push(`- \`${finding.id}\` [${finding.severity}/\`${finding.rule}\`; line=${finding.line}]: ${inlineText(gradeFindingDisplayMessage(finding))}`);
230
+ }
231
+ }
232
+ return lines;
233
+ }
234
+ /**
235
+ * Render the grade result presented in a review plan. The wording states facts that grade has
236
+ * already settled; it does not ask the reviewer to re-evaluate viewpoints or to raise findings
237
+ * again. Every viewpoint in the result is listed regardless of its evaluation class.
238
+ */
239
+ export function renderReviewGradeSummary(freshness, outcome) {
240
+ const lines = [
241
+ "runner が review の前に確認した評価結果を次に示す。これは grade が確定済みの事実であり、review で観点を評価し直したり、同じ finding を改めて指摘したりしない。",
242
+ "",
243
+ ];
244
+ const runLine = outcomeLine(outcome);
245
+ if (runLine)
246
+ lines.push(runLine);
247
+ lines.push(freshnessLine(freshness));
248
+ if (freshness.state === "fresh" || freshness.state === "stale") {
249
+ lines.push(...gradeResultLines(freshness.result));
250
+ }
251
+ return lines.join("\n");
252
+ }
@@ -1,7 +1,51 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import yaml from "js-yaml";
3
3
  import { resolveSpecdojoPath } from "./template-resolution.js";
4
+ import { GRADE_LEVEL_REVIEW_VERDICTS, REVIEW_VERDICTS, describeInvalidReviewVerdict, } from "./review-types.js";
4
5
  export const COMMON_VIEWPOINTS_ID = "specdojo:pm-review-viewpoints";
6
+ function nestedRecord(value) {
7
+ return isRecord(value) ? value : undefined;
8
+ }
9
+ /**
10
+ * Resolve the rulebook ID that represents a document kind. Rulebooks identify themselves,
11
+ * recipes/samples/deliverables refer to their rulebook directly, and templates carry the
12
+ * generated document's rulebook in frontmatter_template.
13
+ */
14
+ export function documentKind(metadata) {
15
+ const direct = metadata["rulebook"];
16
+ if (typeof direct === "string" &&
17
+ !["none", "undecided", "not-needed"].includes(direct) &&
18
+ direct.trim()) {
19
+ return direct;
20
+ }
21
+ const id = metadata["id"];
22
+ if (metadata["type"] === "rulebook" && typeof id === "string" && id.trim())
23
+ return id;
24
+ const frontmatterTemplate = nestedRecord(metadata["frontmatter_template"]);
25
+ const generatedMetadata = nestedRecord(frontmatterTemplate?.["specdojo"]);
26
+ const generatedRulebook = generatedMetadata?.["rulebook"];
27
+ if (typeof generatedRulebook === "string" &&
28
+ !["none", "undecided", "not-needed"].includes(generatedRulebook) &&
29
+ generatedRulebook.trim()) {
30
+ return generatedRulebook;
31
+ }
32
+ return undefined;
33
+ }
34
+ /**
35
+ * Apply a viewpoint's document-kind declaration. Omitted declarations and unclassified
36
+ * documents remain applicable for backward compatibility unless explicitly excluded.
37
+ */
38
+ export function viewpointAppliesToDocument(viewpoint, metadata) {
39
+ const declaration = viewpoint.document_kinds;
40
+ if (!declaration)
41
+ return true;
42
+ const kind = documentKind(metadata);
43
+ if (!kind)
44
+ return declaration.unclassified !== "exclude";
45
+ if (declaration.exclude?.includes(kind))
46
+ return false;
47
+ return declaration.include === undefined || declaration.include.includes(kind);
48
+ }
5
49
  const COLLECTIONS = [
6
50
  ["categories", "id"],
7
51
  ["coverage_types", "id"],
@@ -83,6 +127,65 @@ function mergeCollection(opts) {
83
127
  .filter((itemKey) => !disabledSet.has(itemKey))
84
128
  .map((itemKey) => values.get(itemKey));
85
129
  }
130
+ const VIEWPOINT_EVALUATIONS = [
131
+ "deterministic",
132
+ "referential",
133
+ "discretionary",
134
+ ];
135
+ // Values removed when evaluation was redefined by where the judging criterion lives (PJR-WPWB).
136
+ // Old values are rejected with guidance instead of being ignored.
137
+ const LEGACY_VIEWPOINT_EVALUATIONS = {
138
+ agent: "referential or discretionary",
139
+ human: "referential or discretionary",
140
+ };
141
+ function validateViewpointFields(doc, path) {
142
+ for (const viewpoint of recordArray(doc, "viewpoints", path)) {
143
+ const id = String(viewpoint["id"] ?? "(unknown)");
144
+ // continuous was removed when every viewpoint became a grade target (PJR-K351).
145
+ // Reject it instead of ignoring it so that an overlay cannot silently expect a narrower scope.
146
+ if (Object.hasOwn(viewpoint, "continuous")) {
147
+ throw new Error(`Viewpoint '${id}' uses removed field 'continuous'; every viewpoint is graded, ` +
148
+ `so delete it and narrow scope with grade_targets or document_kinds: ${path}`);
149
+ }
150
+ const value = viewpoint["evaluation"];
151
+ if (value === undefined)
152
+ continue;
153
+ if (typeof value === "string" && value in LEGACY_VIEWPOINT_EVALUATIONS) {
154
+ throw new Error(`Viewpoint '${id}' uses removed evaluation '${value}'; use ${LEGACY_VIEWPOINT_EVALUATIONS[value]} ` +
155
+ `(allowed: ${VIEWPOINT_EVALUATIONS.join(", ")}): ${path}`);
156
+ }
157
+ if (!VIEWPOINT_EVALUATIONS.includes(value)) {
158
+ throw new Error(`Viewpoint '${id}' has unknown evaluation '${String(value)}'; allowed: ${VIEWPOINT_EVALUATIONS.join(", ")}: ${path}`);
159
+ }
160
+ }
161
+ }
162
+ // verdict_definitions は review の verdict と同じ語彙に限る(PJR-XTAN)。grade_rubric の review_verdict は
163
+ // grade の level を review の入力にする写像であり、level から決まる 3 値だけを許す。
164
+ function validateVerdictVocabulary(doc, path) {
165
+ for (const definition of recordArray(doc, "verdict_definitions", path)) {
166
+ const value = definition["id"];
167
+ if (!REVIEW_VERDICTS.includes(value)) {
168
+ throw new Error(`verdict_definitions has ${describeInvalidReviewVerdict(value)}: ${path}`);
169
+ }
170
+ }
171
+ const rubric = doc["grade_rubric"];
172
+ if (rubric === undefined)
173
+ return;
174
+ if (!isRecord(rubric))
175
+ throw new Error(`Review viewpoints 'grade_rubric' must be a mapping: ${path}`);
176
+ const levels = rubric["levels"];
177
+ if (!Array.isArray(levels))
178
+ return;
179
+ for (const level of levels) {
180
+ if (!isRecord(level))
181
+ continue;
182
+ const value = level["review_verdict"];
183
+ if (!GRADE_LEVEL_REVIEW_VERDICTS.includes(value)) {
184
+ throw new Error(`grade_rubric level ${String(level["level"])} review_verdict has ` +
185
+ `${describeInvalidReviewVerdict(value, GRADE_LEVEL_REVIEW_VERDICTS)}: ${path}`);
186
+ }
187
+ }
188
+ }
86
189
  function validateResolvedInheritance(doc, projectPath) {
87
190
  const categories = new Set(recordArray(doc, "categories", projectPath).map((item) => String(item.id)));
88
191
  const coverageTypes = new Set(recordArray(doc, "coverage_types", projectPath).map((item) => String(item.id)));
@@ -142,8 +245,11 @@ export function commonViewpointsPath() {
142
245
  */
143
246
  export function resolveViewpointsDoc(projectPath, commonPath = commonViewpointsPath()) {
144
247
  const project = loadYamlMapping(projectPath);
145
- if (project["extends"] === undefined)
248
+ if (project["extends"] === undefined) {
249
+ validateViewpointFields(project, projectPath);
250
+ validateVerdictVocabulary(project, projectPath);
146
251
  return project;
252
+ }
147
253
  if (project["extends"] !== COMMON_VIEWPOINTS_ID) {
148
254
  throw new Error(`Unsupported review viewpoints inheritance '${String(project["extends"])}'; expected '${COMMON_VIEWPOINTS_ID}': ${projectPath}`);
149
255
  }
@@ -164,6 +270,10 @@ export function resolveViewpointsDoc(projectPath, commonPath = commonViewpointsP
164
270
  }
165
271
  delete resolved["extends"];
166
272
  delete resolved["disabled"];
273
+ validateViewpointFields(common, commonPath);
274
+ validateViewpointFields(project, projectPath);
275
+ validateVerdictVocabulary(common, commonPath);
276
+ validateVerdictVocabulary(project, projectPath);
167
277
  validateResolvedInheritance(resolved, projectPath);
168
278
  return resolved;
169
279
  }
@@ -1 +1,40 @@
1
- export {};
1
+ // review の verdict。タスクの完了可否を表す唯一の語彙であり、bps-task-completion の検証・受入観点
2
+ // 6 区分と一対一に対応する。pm-review-viewpoints.yaml の verdict_definitions と review result の
3
+ // verdict はこの値を共有する(PJR-XTAN)。grade の文書 verdict(pass / needs-work / fail)は成果物の
4
+ // 品質という別の対象を判定するため、この語彙へ統一しない。
5
+ export const REVIEW_VERDICTS = [
6
+ "complete",
7
+ "complete-with-findings",
8
+ "incomplete",
9
+ "grade-stale",
10
+ "grade-unavailable",
11
+ "changed-during-review",
12
+ ];
13
+ // grade の level から写像できる verdict。鮮度や評価不能は grade の level から決まらないため含めない。
14
+ export const GRADE_LEVEL_REVIEW_VERDICTS = [
15
+ "complete",
16
+ "complete-with-findings",
17
+ "incomplete",
18
+ ];
19
+ // タスクの完了可否を表していた旧語彙と、その移行先。旧値は無視せず、移行先を示して拒否する。
20
+ // verdict_definitions の旧値と、xrr-template.md の decision.recommendation の旧値を含む。
21
+ export const LEGACY_REVIEW_VERDICTS = {
22
+ pass: "complete",
23
+ conditional_pass: "complete-with-findings",
24
+ changes_requested: "incomplete",
25
+ blocked: "grade-stale, grade-unavailable, or changed-during-review",
26
+ approve: "complete or complete-with-findings",
27
+ revise: "incomplete",
28
+ reject: "incomplete",
29
+ };
30
+ export function isReviewVerdict(value) {
31
+ return typeof value === "string" && REVIEW_VERDICTS.includes(value);
32
+ }
33
+ /** Explain why a value is not a review verdict, naming the replacement for a legacy value. */
34
+ export function describeInvalidReviewVerdict(value, allowed = REVIEW_VERDICTS) {
35
+ const shown = typeof value === "string" ? `'${value}'` : String(value);
36
+ if (typeof value === "string" && Object.hasOwn(LEGACY_REVIEW_VERDICTS, value)) {
37
+ return `removed verdict ${shown}; use ${LEGACY_REVIEW_VERDICTS[value]} (allowed: ${allowed.join(", ")})`;
38
+ }
39
+ return `unknown verdict ${shown}; allowed: ${allowed.join(", ")}`;
40
+ }
package/dist/routine.js CHANGED
@@ -7,7 +7,7 @@ import { selfRunArgs } from "./spawn-self.js";
7
7
  import { getProjectRoutinesPath, loadConfig, loadEnv, specdojoRootDir } from "./specdojo-config.js";
8
8
  import { ensureDir, listFilesRecursive, nowUtcIsoSeconds, padEndDisplay, readJson, readYaml, writeJson, } from "./exec-shared.js";
9
9
  import { ROUTINE_BUSY_SKIP_EXIT_CODE, ROUTINE_EXEC_ENV } from "./exec-run-lock.js";
10
- import { resolveJobPaths } from "./job.js";
10
+ import { jobDeclaresReview, jobRunUsesReviewedIntegration, loadJobDefinition, resolveJobPaths, resolveJobReviewAgentNominations, } from "./job.js";
11
11
  export function routineActionKindLabel(action) {
12
12
  const actions = Array.isArray(action) ? action : [action];
13
13
  return actions.length > 0 ? actions.map((item) => item.kind).join(" -> ") : "-";
@@ -197,7 +197,7 @@ function parseRoutineAction(value, fieldName, errors) {
197
197
  }
198
198
  return { kind: "specdojo", args: args };
199
199
  }
200
- const unknownKeys = Object.keys(value).filter((key) => key !== "kind" && key !== "job" && key !== "inputs");
200
+ const unknownKeys = Object.keys(value).filter((key) => key !== "kind" && key !== "job" && key !== "inputs" && key !== "commit");
201
201
  if (unknownKeys.length > 0) {
202
202
  errors.push(`${fieldName} has unknown key(s): ${unknownKeys.sort().join(", ")}`);
203
203
  }
@@ -212,10 +212,14 @@ function parseRoutineAction(value, fieldName, errors) {
212
212
  Object.values(value.inputs).some((item) => typeof item !== "string"))) {
213
213
  errors.push(`${fieldName}.inputs must be a mapping of string values`);
214
214
  }
215
+ if (value.commit !== undefined && typeof value.commit !== "boolean") {
216
+ errors.push(`${fieldName}.commit must be a boolean`);
217
+ }
215
218
  return {
216
219
  kind: "job",
217
220
  job: typeof value.job === "string" ? value.job : "",
218
221
  ...(isRecord(value.inputs) ? { inputs: value.inputs } : {}),
222
+ ...(typeof value.commit === "boolean" ? { commit: value.commit } : {}),
219
223
  };
220
224
  }
221
225
  // rtn-*.yaml 1 ファイルぶんを検証し、妥当なら RoutineDoc として返す。
@@ -473,13 +477,36 @@ function ensureFreshDistForRoutineRun() {
473
477
  }
474
478
  return result.outcome !== "rebuild-failed";
475
479
  }
480
+ let lastRoutineSpawnReason;
481
+ let lastRoutineSpawnRunId;
476
482
  function spawnSelf(args) {
483
+ lastRoutineSpawnReason = undefined;
484
+ lastRoutineSpawnRunId = undefined;
477
485
  const [exe, fullArgs] = selfRunArgs(args);
478
486
  const result = spawnSync(exe, fullArgs, {
479
- stdio: "inherit",
487
+ encoding: "utf8",
488
+ stdio: ["inherit", "pipe", "pipe"],
489
+ maxBuffer: 128 * 1024 * 1024,
480
490
  cwd: specdojoRootDir(),
481
491
  env: { ...process.env, [ROUTINE_EXEC_ENV]: "1" },
482
492
  });
493
+ if (result.stdout)
494
+ process.stdout.write(result.stdout);
495
+ if (result.stderr)
496
+ process.stderr.write(result.stderr);
497
+ const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`;
498
+ const marker = [...output.matchAll(/^\[routine-job\]\s+([^\n]+)$/gm)].at(-1)?.[1];
499
+ if (marker) {
500
+ lastRoutineSpawnRunId = marker.match(/\brun_id=([^\s]+)/)?.[1];
501
+ lastRoutineSpawnReason = marker.match(/\breason=(.+)$/)?.[1]?.trim();
502
+ }
503
+ if (!lastRoutineSpawnReason && result.status !== 0) {
504
+ lastRoutineSpawnReason = String(result.stderr ?? "")
505
+ .split(/\r?\n/)
506
+ .map((line) => line.trim())
507
+ .filter(Boolean)
508
+ .at(-1);
509
+ }
483
510
  if (result.status === ROUTINE_BUSY_SKIP_EXIT_CODE)
484
511
  return "skipped";
485
512
  return result.status === 0 ? "success" : "failure";
@@ -504,11 +531,30 @@ export function buildJobRunArgs(action, projectId, scheduledAt, timezone = "UTC"
504
531
  "--if-busy",
505
532
  "skip",
506
533
  ];
534
+ // action.commit is kept for compatibility. A Job that declares task.review is reviewed by
535
+ // exec run regardless of this flag, so the Job's declaration takes precedence.
536
+ if (action.commit)
537
+ args.push("--worktree");
507
538
  for (const [key, value] of Object.entries(action.inputs ?? {}).sort(([a], [b]) => a.localeCompare(b))) {
508
539
  args.push("--input", `${key}=${renderRoutineInput(value, scheduledAt, timezone)}`);
509
540
  }
510
541
  return args;
511
542
  }
543
+ /**
544
+ * Describes how a job action's Run is integrated and which review agents the Job nominates.
545
+ * The Job's task.review declaration wins over the legacy routine `commit`; routine never
546
+ * passes --review-by / --reporter-by, so an agent without a Job nomination is auto selected.
547
+ */
548
+ export function describeJobActionReview(action, definition) {
549
+ if (!jobRunUsesReviewedIntegration(definition, { worktree: action.commit === true })) {
550
+ return "review: none (in-place)";
551
+ }
552
+ const source = jobDeclaresReview(definition)
553
+ ? "job task.review"
554
+ : "routine action.commit (compat)";
555
+ const nominations = resolveJobReviewAgentNominations({}, definition);
556
+ return `review: ${source} (executor=${nominations.executor?.nickname ?? "auto"}, reporter=${nominations.reporter?.nickname ?? "auto"})`;
557
+ }
512
558
  export function aggregateRoutineActionResults(results) {
513
559
  if (results.includes("failure"))
514
560
  return "failure";
@@ -528,7 +574,18 @@ function executeRoutineAction(doc, action, projectId, dryRun, scheduledAt = new
528
574
  ? buildSpecdojoActionArgs(action, projectId)
529
575
  : buildJobRunArgs(action, projectId, scheduledAt, doc.trigger?.timezone ?? "UTC");
530
576
  if (dryRun) {
577
+ lastRoutineSpawnReason = undefined;
578
+ lastRoutineSpawnRunId = undefined;
531
579
  process.stdout.write(` [dry-run] specdojo ${args.join(" ")}\n`);
580
+ if (action.kind === "job") {
581
+ try {
582
+ const definition = loadJobDefinition(resolveJobPaths(projectId), action.job);
583
+ process.stdout.write(` [dry-run] ${describeJobActionReview(action, definition)}\n`);
584
+ }
585
+ catch (error) {
586
+ process.stdout.write(` [dry-run] review: unknown (${error instanceof Error ? error.message : String(error)})\n`);
587
+ }
588
+ }
532
589
  return "success";
533
590
  }
534
591
  return spawnSelf(args);
@@ -573,7 +630,8 @@ function executeRoutine(routine, projectId, dryRun, scheduledAt = new Date()) {
573
630
  const jobRunId = dryRun ? undefined : findJobRunId(doc.action, projectId, scheduledAt);
574
631
  return {
575
632
  result,
576
- jobRunIds: jobRunId ? [jobRunId] : [],
633
+ jobRunIds: lastRoutineSpawnRunId ? [lastRoutineSpawnRunId] : jobRunId ? [jobRunId] : [],
634
+ ...(lastRoutineSpawnReason ? { reason: lastRoutineSpawnReason } : {}),
577
635
  };
578
636
  }
579
637
  const actionResults = executeRoutineActions(actions, (action, index) => {
@@ -590,7 +648,14 @@ function executeRoutine(routine, projectId, dryRun, scheduledAt = new Date()) {
590
648
  const runId = findJobRunId(action, projectId, scheduledAt);
591
649
  return runId ? [runId] : [];
592
650
  });
593
- return { result, actionResults, jobRunIds };
651
+ return {
652
+ result,
653
+ actionResults,
654
+ jobRunIds: [
655
+ ...new Set([...(lastRoutineSpawnRunId ? [lastRoutineSpawnRunId] : []), ...jobRunIds]),
656
+ ],
657
+ ...(lastRoutineSpawnReason ? { reason: lastRoutineSpawnReason } : {}),
658
+ };
594
659
  }
595
660
  // ================================
596
661
  // Command registration
@@ -785,6 +850,7 @@ export function registerRoutineCommands(program) {
785
850
  state.routines[entry.doc.id] = {
786
851
  ...state.routines[entry.doc.id],
787
852
  last_result: result,
853
+ ...(execution.reason ? { last_reason: execution.reason } : { last_reason: undefined }),
788
854
  last_action_results: execution.actionResults,
789
855
  };
790
856
  writeRoutineState(paths, state);
@@ -796,6 +862,7 @@ export function registerRoutineCommands(program) {
796
862
  completed_at: nowUtcIsoSeconds(),
797
863
  result,
798
864
  job_run_ids: execution.jobRunIds,
865
+ ...(execution.reason ? { reason: execution.reason } : {}),
799
866
  });
800
867
  }
801
868
  }
@@ -124,7 +124,7 @@ function topoSort(deliverables, crossDeps) {
124
124
  // --- Main export ---
125
125
  function validateAgentAssignment(label, assignment, roster, errors) {
126
126
  if (!roster) {
127
- errors.push(`${label}: agent assignment requires a configured pm-members.yaml`);
127
+ errors.push(`${label}: agent assignment requires configured member registries`);
128
128
  return;
129
129
  }
130
130
  for (const [stageRole, nickname] of [
@@ -135,7 +135,7 @@ function validateAgentAssignment(label, assignment, roster, errors) {
135
135
  continue;
136
136
  const members = roster.members.filter((member) => member.type === "agent" && member.nickname === nickname);
137
137
  if (members.length !== 1) {
138
- errors.push(`${label}.agent.${stageRole}: nickname '${nickname}' was not found uniquely in pm-members.yaml`);
138
+ errors.push(`${label}.agent.${stageRole}: nickname '${nickname}' was not found uniquely in agent-members.yaml`);
139
139
  continue;
140
140
  }
141
141
  if (members[0].stage_role !== stageRole) {
package/dist/schedule.js CHANGED
@@ -1,9 +1,10 @@
1
- import { join, resolve } from "node:path";
1
+ import { dirname, join, relative, resolve, sep } from "node:path";
2
2
  import { existsSync, readdirSync, writeFileSync } from "node:fs";
3
3
  import yaml from "js-yaml";
4
4
  import { getProjectCatalogPath, getProjectRolesPath, getProjectSchedulePath, getProjectTimelinePath, loadConfig, loadEnv, loadMemberRoster, specdojoRootDir, } from "./specdojo-config.js";
5
5
  import { buildScheduleTrack, } from "./schedule-build.js";
6
6
  import { readYaml } from "./exec-shared.js";
7
+ import { resolveSpecdojoPath } from "./template-resolution.js";
7
8
  import { generateStrategy, writeStrategyFile } from "./schedule-strategy-generate.js";
8
9
  function resolveSchedulePath(opts) {
9
10
  loadEnv();
@@ -79,6 +80,18 @@ export function collectProjectMilestones(schedulePath, baseDir, projectId, prebu
79
80
  }
80
81
  return { milestones, errors, warnings };
81
82
  }
83
+ const TRACK_SCHEMA = "docs/specdojo/schemas/v1/sch-track.schema.yaml";
84
+ const MILESTONES_SCHEMA = "docs/specdojo/schemas/v1/sch-milestones.schema.yaml";
85
+ /**
86
+ * 生成した YAML の先頭へ schema modeline を付ける。validate:schema は modeline から schema を
87
+ * 解決するため、yaml.dump の結果だけを書き出すと再生成のたびに検証対象から外れる。
88
+ */
89
+ export function withSchemaModeline(outFile, schemaPath, body) {
90
+ const schemaRef = relative(dirname(outFile), resolveSpecdojoPath(schemaPath))
91
+ .split(sep)
92
+ .join("/");
93
+ return `# yaml-language-server: $schema=${schemaRef}\n${body}`;
94
+ }
82
95
  export function updateMilestonesFile(schedulePath, projectId, newMilestones, dryRun) {
83
96
  const filePath = join(schedulePath, "sch-milestones.yaml");
84
97
  if (newMilestones.length === 0 && !existsSync(filePath))
@@ -145,7 +158,7 @@ export function updateMilestonesFile(schedulePath, projectId, newMilestones, dry
145
158
  generatedById.delete(milestone.id);
146
159
  }
147
160
  doc.milestones = orderedMilestones.map((milestone) => ({ ...milestone }));
148
- const outYaml = yaml.dump(doc, { lineWidth: 120, noRefs: true });
161
+ const outYaml = withSchemaModeline(filePath, MILESTONES_SCHEMA, yaml.dump(doc, { lineWidth: 120, noRefs: true }));
149
162
  if (dryRun) {
150
163
  const label = fileCreated ? "created" : "updated";
151
164
  process.stdout.write(`\n# --- (dry-run) sch-milestones.yaml (${label}) ---\n`);
@@ -386,12 +399,12 @@ export function registerScheduleCommands(program) {
386
399
  startDate,
387
400
  tasks,
388
401
  });
389
- const outYaml = yaml.dump(outDoc, {
402
+ const outYaml = withSchemaModeline(outFile, TRACK_SCHEMA, yaml.dump(outDoc, {
390
403
  lineWidth: 120,
391
404
  quotingType: '"',
392
405
  forceQuotes: false,
393
406
  noRefs: true,
394
- });
407
+ }));
395
408
  if (opts.dryRun) {
396
409
  process.stdout.write(outYaml);
397
410
  process.stdout.write(`\n# dry-run: ${tasks.length} tasks — not written to disk\n`);