specdojo 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +298 -0
  3. package/README.md +92 -42
  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/catalog-build-references.js +144 -0
  8. package/dist/catalog-build-render.js +144 -0
  9. package/dist/catalog-build.js +13 -290
  10. package/dist/catalog-generate.js +6 -9
  11. package/dist/catalog-plan-generate.js +2 -2
  12. package/dist/catalog-plan.js +6 -6
  13. package/dist/catalog-scaffold.js +4 -4
  14. package/dist/catalog.js +2 -2
  15. package/dist/dashboard-exec-records.js +105 -0
  16. package/dist/dashboard-routines.js +255 -0
  17. package/dist/dashboard-shared.js +14 -0
  18. package/dist/dashboard-timeline.js +175 -0
  19. package/dist/dashboard.js +31 -444
  20. package/dist/deliverable-trash.js +3 -3
  21. package/dist/devcontainer-command.js +43 -0
  22. package/dist/devcontainer-scaffold.js +165 -0
  23. package/dist/doc-index.js +3 -3
  24. package/dist/exec-agent-config.js +107 -9
  25. package/dist/exec-agent-git-state.js +18 -0
  26. package/dist/exec-agent-protected-config.js +46 -8
  27. package/dist/exec-commands.js +557 -0
  28. package/dist/exec-core.js +457 -0
  29. package/dist/exec-evidence.js +254 -11
  30. package/dist/exec-handoff.js +336 -0
  31. package/dist/exec-parent-validation.js +317 -43
  32. package/dist/exec-pipeline-state.js +74 -9
  33. package/dist/exec-plans-core.js +693 -0
  34. package/dist/exec-plans-generation.js +206 -0
  35. package/dist/exec-plans-storage.js +131 -0
  36. package/dist/exec-plans.js +3 -1016
  37. package/dist/exec-protection-handoff.js +43 -2
  38. package/dist/exec-provider-scaffold.js +247 -15
  39. package/dist/exec-register-resume.js +65 -19
  40. package/dist/exec-register.js +9 -3
  41. package/dist/exec-repo-integration-git.js +23 -0
  42. package/dist/exec-repo-integration-sync.js +264 -0
  43. package/dist/exec-repo-integration.js +534 -0
  44. package/dist/exec-repo-trace.js +182 -0
  45. package/dist/exec-reporter-output.js +206 -0
  46. package/dist/exec-reporter.js +525 -248
  47. package/dist/exec-results.js +103 -71
  48. package/dist/exec-run-agent-pipeline.js +256 -0
  49. package/dist/exec-run-agent.js +531 -0
  50. package/dist/exec-run-in-place.js +541 -0
  51. package/dist/exec-run-job.js +717 -0
  52. package/dist/exec-run-lifecycle-commands.js +522 -0
  53. package/dist/exec-run-lock.js +110 -107
  54. package/dist/exec-run-mode-shared.js +140 -0
  55. package/dist/exec-run-register-command.js +244 -0
  56. package/dist/exec-run-register-core.js +386 -0
  57. package/dist/exec-run-register-mode.js +206 -0
  58. package/dist/exec-run-register-resume.js +393 -0
  59. package/dist/exec-run-register-state.js +322 -0
  60. package/dist/exec-run-register-worktree.js +509 -0
  61. package/dist/exec-run-schedule-mode.js +294 -0
  62. package/dist/exec-run-schedule-prepare.js +353 -0
  63. package/dist/exec-run-schedule-task.js +572 -0
  64. package/dist/exec-run-shared.js +399 -0
  65. package/dist/exec-run.js +11 -4953
  66. package/dist/exec-shared.js +9 -2
  67. package/dist/exec-slot-lock.js +242 -0
  68. package/dist/exec-task-repos.js +415 -0
  69. package/dist/exec-trial-commands.js +558 -0
  70. package/dist/exec-trial-core.js +371 -0
  71. package/dist/exec-trial.js +2 -895
  72. package/dist/exec-worktree-command.js +87 -43
  73. package/dist/exec-worktree-ops-commit.js +707 -0
  74. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  75. package/dist/exec-worktree-ops-merge.js +303 -0
  76. package/dist/exec-worktree-ops.js +3 -847
  77. package/dist/exec-worktree.js +146 -31
  78. package/dist/exec.js +2 -999
  79. package/dist/frontmatter-namespace.js +2 -2
  80. package/dist/grade-apply.js +734 -0
  81. package/dist/grade-command-apply.js +250 -0
  82. package/dist/grade-command-inspect.js +138 -0
  83. package/dist/grade-command-plan.js +101 -0
  84. package/dist/grade-command-shared.js +68 -0
  85. package/dist/grade-core.js +307 -0
  86. package/dist/grade-markdown.js +274 -0
  87. package/dist/grade-pipeline-state.js +184 -0
  88. package/dist/grade-plan.js +507 -0
  89. package/dist/grade-result.js +133 -5
  90. package/dist/grade-target-discovery.js +265 -0
  91. package/dist/grade-targets.js +432 -0
  92. package/dist/grade.js +14 -2451
  93. package/dist/init-command.js +443 -0
  94. package/dist/job-definition.js +670 -0
  95. package/dist/job.js +64 -578
  96. package/dist/kata-command.js +2 -2
  97. package/dist/orchestrator.js +213 -0
  98. package/dist/register-command-types.js +1 -0
  99. package/dist/register-core.js +363 -0
  100. package/dist/register-create-commands.js +245 -0
  101. package/dist/register-event-merge.js +169 -0
  102. package/dist/register-events.js +4 -4
  103. package/dist/register-item.js +13 -7
  104. package/dist/register-maintenance-commands.js +187 -0
  105. package/dist/register-migration.js +268 -0
  106. package/dist/register-renumber.js +314 -0
  107. package/dist/register-transition-commands.js +248 -0
  108. package/dist/register-update.js +230 -0
  109. package/dist/register-views.js +256 -0
  110. package/dist/register.js +175 -1975
  111. package/dist/review-grade.js +252 -0
  112. package/dist/review-plan.js +114 -4
  113. package/dist/review-types.js +40 -1
  114. package/dist/routine-definition.js +401 -0
  115. package/dist/routine.js +73 -402
  116. package/dist/schedule-approach.js +2 -2
  117. package/dist/schedule-build.js +2 -2
  118. package/dist/schedule-strategy-generate-document.js +273 -0
  119. package/dist/schedule-strategy-generate-scope.js +199 -0
  120. package/dist/schedule-strategy-generate.js +9 -473
  121. package/dist/schedule.js +19 -6
  122. package/dist/specdojo-config.js +465 -20
  123. package/dist/specdojo-gitignore.js +135 -0
  124. package/dist/specdojo.js +6 -0
  125. package/dist/viewpoint-document-kinds-check.js +128 -0
  126. package/dist/yaml-pages.js +4 -4
  127. package/dist/yaml.js +28 -0
  128. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  129. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  130. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  131. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  132. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  133. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  134. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  135. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  136. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  137. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  138. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  139. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  140. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  141. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  142. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  143. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  144. package/docs/ja/specdojo/guides/exec-config-guide.md +93 -49
  145. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  146. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  147. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  148. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +45 -22
  149. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  150. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  151. package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
  152. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  153. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  154. package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
  155. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  156. package/docs/ja/specdojo/guides/routine-operation-guide.md +75 -10
  157. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  158. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  159. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  160. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  161. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  162. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  163. package/docs/ja/specdojo/index.md +2 -2
  164. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  165. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  166. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  167. package/docs/ja/specdojo/references/command-reference.md +335 -92
  168. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  169. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  170. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  171. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  172. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  173. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  174. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  175. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  176. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  177. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  178. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  179. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  180. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  181. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  182. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  183. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  184. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  185. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  186. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  187. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  188. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  189. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  190. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  191. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  192. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  193. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  194. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  195. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  196. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  197. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  198. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  199. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  200. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  201. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  202. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  203. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  204. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  205. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  206. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  207. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  208. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  209. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  210. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  211. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  212. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  213. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  214. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  215. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  216. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  217. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  218. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  219. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  220. package/package.json +17 -12
  221. package/templates/antigravity/README.md +29 -4
  222. package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
  223. package/templates/antigravity/exec-defaults-snippet.yaml +10 -7
  224. package/templates/antigravity/orchestrator.md +18 -7
  225. package/templates/antigravity/settings.global.json +55 -0
  226. package/templates/claude/agents/claude-executor.md +14 -0
  227. package/templates/claude/agents/claude-reporter.md +16 -0
  228. package/templates/claude/agents/specdojo-orchestrator.md +18 -7
  229. package/templates/claude/settings.edit.json +27 -1
  230. package/templates/codex/README.md +5 -4
  231. package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
  232. package/templates/codex/orchestrator.md +18 -7
  233. package/templates/copilot/README.md +7 -5
  234. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  235. package/templates/devcontainer/devcontainer.json +27 -0
  236. package/templates/devcontainer/emacs/init.el +88 -0
  237. package/templates/devcontainer/post-create.sh +62 -0
  238. package/templates/init-agent-members.yaml +200 -0
  239. package/templates/init-exec-defaults.yaml +74 -0
  240. package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
  241. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  242. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -1,269 +1,544 @@
1
- import Ajv2020Module from "ajv/dist/2020.js";
2
- import { extractJsonText } from "./agent-response.js";
3
- const MAX_TEXT_LENGTH = 4_000;
4
- const MAX_ITEMS = 1_000;
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join, relative, resolve, sep } from "node:path";
3
+ import { PARENT_VALIDATION_PROJECT_REPO, failedParentValidationReason, } from "./exec-parent-validation.js";
4
+ import { getProjectExecutionPath, resolveRepoRoot, specdojoRootDir, } from "./specdojo-config.js";
5
+ import { MAX_TEXT_LENGTH, parseReporterOutput, reporterOutputSchemaForMode, } from "./exec-reporter-output.js";
6
+ export { REPORTER_OUTPUT_SCHEMA, REVIEW_VERDICTS, parseReporterOutput, reporterOutputSchemaForMode, } from "./exec-reporter-output.js";
5
7
  const REPORTER_FORMAT_ATTEMPTS = 3;
6
- export const REPORTER_OUTPUT_SCHEMA = {
7
- $schema: "https://json-schema.org/draft/2020-12/schema",
8
- oneOf: [
9
- {
10
- type: "object",
11
- additionalProperties: false,
12
- required: [
13
- "schema_version",
14
- "mode",
15
- "outcome",
16
- "summary",
17
- "changed_files",
18
- "handoff",
19
- "approach",
20
- "block_reason",
21
- ],
22
- properties: {
23
- schema_version: { const: 1 },
24
- mode: { const: "edit" },
25
- outcome: { enum: ["complete", "blocked"] },
26
- summary: { type: "array", minItems: 1, maxItems: 100, items: { $ref: "#/$defs/text" } },
27
- changed_files: {
28
- type: "array",
29
- maxItems: MAX_ITEMS,
30
- items: {
31
- type: "object",
32
- additionalProperties: false,
33
- required: ["path", "summary"],
34
- properties: {
35
- path: { type: "string", minLength: 1, maxLength: 1_000 },
36
- summary: { $ref: "#/$defs/text" },
37
- },
38
- },
39
- },
40
- handoff: { type: "array", maxItems: 100, items: { $ref: "#/$defs/text" } },
41
- approach: { $ref: "#/$defs/text" },
42
- block_reason: { type: "string", maxLength: MAX_TEXT_LENGTH },
43
- },
44
- allOf: [
45
- {
46
- if: { properties: { outcome: { const: "blocked" } } },
47
- then: { properties: { block_reason: { type: "string", pattern: "\\S" } } },
48
- else: { properties: { block_reason: { type: "string", maxLength: 0 } } },
49
- },
50
- ],
51
- },
52
- {
53
- type: "object",
54
- additionalProperties: false,
55
- required: [
56
- "schema_version",
57
- "mode",
58
- "outcome",
59
- "viewpoint_results",
60
- "findings",
61
- "approach",
62
- "recommendation",
63
- "block_reason",
64
- ],
65
- properties: {
66
- schema_version: { const: 1 },
67
- mode: { const: "review" },
68
- outcome: { enum: ["complete", "blocked"] },
69
- viewpoint_results: {
70
- type: "array",
71
- maxItems: 100,
72
- items: {
73
- type: "object",
74
- additionalProperties: false,
75
- required: ["id", "result", "evidence", "notes"],
76
- properties: {
77
- id: { type: "string", pattern: "^RVP-[0-9]{3}$" },
78
- result: { enum: ["pass", "fail", "unclear"] },
79
- evidence: {
80
- type: "array",
81
- minItems: 1,
82
- maxItems: 100,
83
- items: { $ref: "#/$defs/text" },
84
- },
85
- notes: { type: "string", maxLength: MAX_TEXT_LENGTH },
86
- },
87
- },
88
- },
89
- findings: { type: "array", maxItems: 100, items: { $ref: "#/$defs/text" } },
90
- approach: { $ref: "#/$defs/text" },
91
- recommendation: { enum: ["approve", "revise", "reject"] },
92
- block_reason: { type: "string", maxLength: MAX_TEXT_LENGTH },
8
+ function isProjectConfig(value) {
9
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10
+ }
11
+ /**
12
+ * Finds the single configured project whose execution directory is `executionPath`. Returns
13
+ * undefined when no project or more than one project matches, so ambiguity never picks a project.
14
+ */
15
+ function projectIdForExecutionPath(config, repoRoot, executionPath) {
16
+ if (!config)
17
+ return undefined;
18
+ const target = resolve(executionPath);
19
+ const matches = Object.keys(config.projects)
20
+ .sort()
21
+ .filter((projectId) => {
22
+ const project = config.projects[projectId];
23
+ if (!isProjectConfig(project))
24
+ return false;
25
+ return resolve(repoRoot, getProjectExecutionPath(project)) === target;
26
+ });
27
+ return matches.length === 1 ? matches[0] : undefined;
28
+ }
29
+ function repoRelativePath(root, path) {
30
+ return relative(root, path).split(sep).join("/").replace(/^\.\//u, "");
31
+ }
32
+ function pathIsWithin(path, root) {
33
+ return path === root || path.startsWith(`${root}/`);
34
+ }
35
+ function isRunnerManagedChangePath(path, scope) {
36
+ const normalized = path.replaceAll("\\", "/").replace(/^\.\//u, "");
37
+ // exec/ 配下(evidence・plans・results・events・.locks など)はすべて runner の記録であり、
38
+ // executor の成果物ではない。
39
+ const execRoot = repoRelativePath(scope.repoRoot, join(scope.executionPath, "exec"));
40
+ const managedRoots = [
41
+ execRoot,
42
+ ...(scope.registerPaths ?? []).map((path) => repoRelativePath(scope.repoRoot, path)),
43
+ ];
44
+ const resultPath = scope.resultPath
45
+ ? repoRelativePath(scope.worktreePath, scope.resultPath)
46
+ : undefined;
47
+ return managedRoots.some((root) => pathIsWithin(normalized, root)) || normalized === resultPath;
48
+ }
49
+ function isRunnerManagedChange(change, scope) {
50
+ // A rename can contain two repository-relative paths. Exclude the entry only when every side
51
+ // is runner-managed so a move between a managed location and a deliverable remains visible.
52
+ return change.path.split(" -> ").every((path) => isRunnerManagedChangePath(path, scope));
53
+ }
54
+ /**
55
+ * Builds the bounded evidence view used by the reporter and result renderer. Runner-owned
56
+ * bookkeeping remains in the persisted evidence, but it is not presented as executor output.
57
+ */
58
+ export function evidenceForReporter(evidence, scope) {
59
+ const changes = evidence.changes.filter((change) => !isRunnerManagedChange(change, scope));
60
+ const attemptChanges = evidence.attempt_changes?.filter((change) => !isRunnerManagedChange(change, scope));
61
+ // `attempt_changes` excludes lifecycle changes that existed before the executor started. Its
62
+ // removed entries therefore tell the reporter that the executor really touched runner-owned
63
+ // bookkeeping, without putting those paths back into the authoritative deliverable list.
64
+ const runnerManagedAttemptChanges = (evidence.attempt_changes ?? []).filter((change) => isRunnerManagedChange(change, scope));
65
+ const factOptions = scope.factOptions ?? {};
66
+ const config = factOptions.specdojoConfig === undefined ? defaultSpecdojoConfig() : factOptions.specdojoConfig;
67
+ const projectId = scope.projectId ??
68
+ factOptions.projectId ??
69
+ projectIdForExecutionPath(config, scope.repoRoot, scope.executionPath);
70
+ const scopedFactOptions = {
71
+ ...factOptions,
72
+ ...(projectId ? { projectId } : {}),
73
+ changedPaths: changes.map((change) => change.path),
74
+ };
75
+ const mechanicallyNotApplicable = evidence.validations.flatMap((validation) => {
76
+ if (validation.source === "runner" || validation.status !== "not_run")
77
+ return [];
78
+ const reason = mechanicallyNotApplicableReason(validation.command, scopedFactOptions);
79
+ return reason === undefined ? [] : [{ command: validation.command, reason }];
80
+ });
81
+ const filtered = changes.length !== evidence.changes.length ||
82
+ attemptChanges?.length !== evidence.attempt_changes?.length;
83
+ const scoped = projectId
84
+ ? { ...evidence, runner_scope: { project_id: projectId } }
85
+ : evidence;
86
+ const selected = filtered
87
+ ? {
88
+ ...scoped,
89
+ changes,
90
+ ...(attemptChanges ? { attempt_changes: attemptChanges } : {}),
91
+ diff_summary: {
92
+ files_changed: changes.length,
93
+ summary: changes
94
+ .map((change) => `${change.status} ${change.path}`)
95
+ .join("\n")
96
+ .slice(0, MAX_TEXT_LENGTH),
93
97
  },
94
- allOf: [
95
- {
96
- if: { properties: { outcome: { const: "blocked" } } },
97
- then: { properties: { block_reason: { type: "string", pattern: "\\S" } } },
98
- else: { properties: { block_reason: { type: "string", maxLength: 0 } } },
99
- },
100
- ],
101
- },
102
- ],
103
- $defs: {
104
- text: { type: "string", minLength: 1, maxLength: MAX_TEXT_LENGTH },
105
- },
106
- };
107
- const Ajv2020 = Ajv2020Module.default;
108
- const validateReporterSchema = new Ajv2020({ allErrors: true, strict: true }).compile(REPORTER_OUTPUT_SCHEMA);
109
- function isRecord(value) {
110
- return value !== null && typeof value === "object" && !Array.isArray(value);
111
- }
112
- function exactKeys(value, keys) {
113
- const actual = Object.keys(value).sort();
114
- const expected = [...keys].sort();
115
- return actual.length === expected.length && actual.every((key, index) => key === expected[index]);
116
- }
117
- function isText(value, allowEmpty = false) {
118
- return (typeof value === "string" &&
119
- value.length <= MAX_TEXT_LENGTH &&
120
- (allowEmpty || value.trim().length > 0));
121
- }
122
- function isTextArray(value, maxItems = 100, minItems = 0) {
123
- return (Array.isArray(value) &&
124
- value.length >= minItems &&
125
- value.length <= maxItems &&
126
- value.every((item) => isText(item)));
127
- }
128
- function validateCommon(value, mode) {
129
- if (value.schema_version !== 1)
130
- return "schema_version must equal 1";
131
- if (value.mode !== mode)
132
- return `mode must equal ${mode}`;
133
- if (value.outcome !== "complete" && value.outcome !== "blocked") {
134
- return "outcome must be complete or blocked";
98
+ }
99
+ : scoped;
100
+ if (mechanicallyNotApplicable.length === 0 && runnerManagedAttemptChanges.length === 0) {
101
+ return selected;
135
102
  }
136
- if (!isText(value.block_reason, true))
137
- return "block_reason must be a bounded string";
138
- if (value.outcome === "blocked" && !String(value.block_reason).trim()) {
139
- return "block_reason is required when outcome is blocked";
103
+ return {
104
+ ...selected,
105
+ runner_context: {
106
+ mechanically_not_applicable: mechanicallyNotApplicable,
107
+ runner_managed_attempt_changes: runnerManagedAttemptChanges,
108
+ },
109
+ };
110
+ }
111
+ /**
112
+ * Derives result facts only from runner-owned evidence. Reporter prose is deliberately absent
113
+ * from this decision so an LLM cannot change paths or turn a failed run into a completed one.
114
+ */
115
+ export function deriveReporterFacts(evidence, options = {}) {
116
+ const changedFiles = evidence.changes.map(({ path, status }) => ({ path, status }));
117
+ if (evidence.stage.status !== "succeeded" || evidence.stage.exit_code !== 0) {
118
+ const blockReason = evidence.block_reason ||
119
+ (evidence.stage.status === "rate_limited"
120
+ ? "executor rate limit reached"
121
+ : evidence.stage.exit_code === null
122
+ ? "executor failed without an exit code"
123
+ : evidence.stage.exit_code !== 0
124
+ ? `executor exited with code ${evidence.stage.exit_code}`
125
+ : "executor stage failed");
126
+ return { outcome: "blocked", changed_files: changedFiles, block_reason: blockReason };
140
127
  }
141
- if (value.outcome === "complete" && String(value.block_reason).length > 0) {
142
- return "block_reason must be empty when outcome is complete";
128
+ const validationFailure = failedParentValidationReason(evidence.validations);
129
+ if (validationFailure) {
130
+ return {
131
+ outcome: "blocked",
132
+ changed_files: changedFiles,
133
+ block_reason: validationFailure,
134
+ };
143
135
  }
144
- if (!isText(value.approach))
145
- return "approach must be a non-empty bounded string";
146
- return undefined;
147
- }
148
- function validateEdit(value) {
149
- const keys = [
150
- "schema_version",
151
- "mode",
152
- "outcome",
153
- "summary",
154
- "changed_files",
155
- "handoff",
156
- "approach",
157
- "block_reason",
158
- ];
159
- if (!exactKeys(value, keys))
160
- return "edit output has missing or additional properties";
161
- const common = validateCommon(value, "edit");
162
- if (common)
163
- return common;
164
- if (!isTextArray(value.summary, 100, 1))
165
- return "summary must contain 1-100 bounded strings";
166
- if (!isTextArray(value.handoff, 100))
167
- return "handoff must contain at most 100 bounded strings";
168
- if (!Array.isArray(value.changed_files) || value.changed_files.length > MAX_ITEMS) {
169
- return "changed_files must be an array with at most 1000 items";
136
+ const packageScripts = options.packageScripts ?? defaultPackageScripts();
137
+ const packageDependencies = options.packageDependencies ?? defaultPackageDependencies();
138
+ const specdojoConfig = options.specdojoConfig === undefined ? defaultSpecdojoConfig() : options.specdojoConfig;
139
+ const projectId = options.projectId ?? evidence.runner_scope?.project_id;
140
+ const applicabilityOptions = {
141
+ packageScripts,
142
+ packageDependencies,
143
+ specdojoConfig,
144
+ ...(projectId ? { projectId } : {}),
145
+ ...(options.productPackageManifests
146
+ ? { productPackageManifests: options.productPackageManifests }
147
+ : {}),
148
+ changedPaths: options.changedPaths ?? evidence.changes.map((change) => change.path),
149
+ };
150
+ const passedCommandsByRepo = new Map();
151
+ const runnerPassedCommandsByRepo = new Map();
152
+ const addPassedCommand = (target, repo, command) => {
153
+ const commands = target.get(repo) ?? new Set();
154
+ commands.add(command);
155
+ target.set(repo, commands);
156
+ };
157
+ // sandbox で実行できない検証を executor が not_run(親 runner へ委譲)と記録し、runner が
158
+ // 同じリポジトリで同じコマンドを実行して通した場合は満たされたものとして扱う。executor の
159
+ // failed は runner の結果で打ち消さない(PJR-2GZE)。
160
+ for (const validation of evidence.validations) {
161
+ if (validation.status !== "passed")
162
+ continue;
163
+ if (validation.source === "runner") {
164
+ const repo = validation.repo ?? PARENT_VALIDATION_PROJECT_REPO;
165
+ const command = normalizeValidationCommand(validation.command);
166
+ addPassedCommand(runnerPassedCommandsByRepo, repo, command);
167
+ addPassedCommand(passedCommandsByRepo, repo, command);
168
+ continue;
169
+ }
170
+ const manifest = commandManifest(normalizeValidationCommand(validation.command), applicabilityOptions, specdojoConfig);
171
+ addPassedCommand(passedCommandsByRepo, manifest.repoName ?? PARENT_VALIDATION_PROJECT_REPO, manifest.command);
170
172
  }
171
- for (const file of value.changed_files) {
172
- if (!isRecord(file) || !exactKeys(file, ["path", "summary"])) {
173
- return "changed_files entries have missing or additional properties";
173
+ // `npm run check` のような合成コマンドを executor が not_run(親 runner へ委譲)とした場合は、
174
+ // 対象リポジトリの package.json の script を展開し、構成する各コマンドが同じリポジトリの
175
+ // 親検証か executor 自身の検証で通っていれば満たされたものとして扱う(PJR-SDWF)。
176
+ const isDelegatedValidationSatisfied = (command) => {
177
+ const manifest = commandManifest(normalizeValidationCommand(command), applicabilityOptions, specdojoConfig);
178
+ const repo = manifest.repoName ?? PARENT_VALIDATION_PROJECT_REPO;
179
+ const runnerPassedCommands = runnerPassedCommandsByRepo.get(repo) ?? new Set();
180
+ if (runnerPassedCommands.has(manifest.command))
181
+ return true;
182
+ const passedCommands = passedCommandsByRepo.get(repo) ?? new Set();
183
+ const components = compositeComponents(manifest.command, manifest.scripts);
184
+ return (components !== undefined &&
185
+ components.every((component) => isComponentSatisfied(component, passedCommands, manifest.scripts)));
186
+ };
187
+ // runner が担う検証(index build)の executor 側の not_run / not_applicable は満たしたものとする。
188
+ // runner の再生成が失敗した場合は worktree の準備で run が止まり、runner の記録に失敗が残れば
189
+ // 上の failedParentValidationReason で block するため、ここまで到達しない。
190
+ const executorValidationFailures = evidence.validations.filter((validation) => {
191
+ if (validation.source === "runner")
192
+ return false;
193
+ if (validation.status === "passed" || validation.status === "requires_human")
194
+ return false;
195
+ // review executor の任意確認は verdict の判断材料であり、未実施・適用外そのものを
196
+ // pipeline の失敗にしない。実行して失敗した確認だけは mode にかかわらず block する。
197
+ if (options.mode === "review" &&
198
+ (validation.status === "not_run" || validation.status === "not_applicable")) {
199
+ return false;
200
+ }
201
+ if ((validation.status === "not_run" || validation.status === "not_applicable") &&
202
+ runnerOwnedValidationReason(validation.command) !== undefined) {
203
+ return false;
174
204
  }
175
- if (typeof file.path !== "string" || !file.path.trim() || file.path.length > 1_000) {
176
- return "changed_files path must be a non-empty bounded string";
205
+ if (validation.status === "not_applicable") {
206
+ return !isValidNotApplicableValidation(validation.command, validation.reason, applicabilityOptions);
177
207
  }
178
- if (!isText(file.summary))
179
- return "changed_files summary must be a non-empty bounded string";
208
+ return !(validation.status === "not_run" &&
209
+ (isDelegatedValidationSatisfied(validation.command) ||
210
+ mechanicallyNotApplicableReason(validation.command, applicabilityOptions) !== undefined));
211
+ });
212
+ if (executorValidationFailures.length > 0) {
213
+ return {
214
+ outcome: "blocked",
215
+ changed_files: changedFiles,
216
+ block_reason: `executor validation failed or not run: ${executorValidationFailures
217
+ .map((validation) => validation.command)
218
+ .join(", ")}`,
219
+ };
180
220
  }
181
- return undefined;
221
+ return { outcome: "complete", changed_files: changedFiles, block_reason: "" };
182
222
  }
183
- function validateReview(value) {
184
- const keys = [
185
- "schema_version",
186
- "mode",
187
- "outcome",
188
- "viewpoint_results",
189
- "findings",
190
- "approach",
191
- "recommendation",
192
- "block_reason",
193
- ];
194
- if (!exactKeys(value, keys))
195
- return "review output has missing or additional properties";
196
- const common = validateCommon(value, "review");
197
- if (common)
198
- return common;
199
- if (!isTextArray(value.findings, 100))
200
- return "findings must contain at most 100 bounded strings";
201
- if (!Array.isArray(value.viewpoint_results) || value.viewpoint_results.length > 100) {
202
- return "viewpoint_results must be an array with at most 100 items";
223
+ // `npm test` は単体テストと統合テストの全件ゲートであり、親 runner は同じ範囲を
224
+ // `npm run test:unit` と `npm run test:integration` に分けて実行する。
225
+ const COMMAND_EQUIVALENTS = {
226
+ "npm test": ["npm run test:unit", "npm run test:integration"],
227
+ };
228
+ const MAX_COMPOSITE_DEPTH = 5;
229
+ function normalizeValidationCommand(command) {
230
+ const collapsed = command.trim().replace(/\s+/g, " ");
231
+ if (collapsed === "npm t" || collapsed === "npm run test")
232
+ return "npm test";
233
+ return collapsed.replace(/^npm run-script /, "npm run ");
234
+ }
235
+ function scriptNameOf(command) {
236
+ if (command === "npm test")
237
+ return "test";
238
+ return /^npm run ([A-Za-z0-9:_.-]+)$/.exec(command)?.[1];
239
+ }
240
+ // 適用条件の反証では npm が解決する script 名だけを取り出す。後続引数の有無は script の
241
+ // 存在を変えない。一方、委譲・合成コマンドの同一性判定は scriptNameOf の完全一致を保つ。
242
+ function invokedScriptNameOf(command) {
243
+ if (command === "npm test")
244
+ return "test";
245
+ return /^npm run ([A-Za-z0-9:_.-]+)(?:\s|$)/u.exec(command)?.[1];
246
+ }
247
+ function npxPackageNameOf(command) {
248
+ return /^npx\s+((?:@[A-Za-z0-9_.-]+\/)?[A-Za-z0-9_.-]+)(?:\s|$)/u.exec(command)?.[1];
249
+ }
250
+ function specdojoCommandArgs(command) {
251
+ const normalized = normalizeValidationCommand(command);
252
+ return (/^(?:npx\s+)?specdojo\s+(.+)$/u.exec(normalized)?.[1] ??
253
+ /^(?:(?:node --import tsx|npx tsx|tsx)\s+(?:\.\/)?src\/specdojo\.ts|node\s+(?:\.\/)?dist\/specdojo\.js)\s+(.+)$/u.exec(normalized)?.[1]);
254
+ }
255
+ /**
256
+ * Returns why a validation is owned by the runner rather than the executor. `specdojo index build`
257
+ * writes `.specdojo/doc-index.json`, which agents may not write; the runner regenerates the index
258
+ * while preparing the worktree and before integration, so the executor cannot and need not run it.
259
+ * Other SpecDojo subcommands return undefined and keep their usual `not_run` handling.
260
+ */
261
+ export function runnerOwnedValidationReason(command) {
262
+ const args = specdojoCommandArgs(command);
263
+ if (args === undefined || !/^index\s+build(?:\s|$)/u.test(args))
264
+ return undefined;
265
+ return "index は runner が worktree の準備と統合の前に再生成する";
266
+ }
267
+ const PROJECT_DOCUMENTS_ROOT = "docs/ja/projects/";
268
+ function changesReachProjectDocuments(changedPaths) {
269
+ return changedPaths
270
+ .flatMap((path) => path.split(" -> "))
271
+ .some((path) => path.replaceAll("\\", "/").replace(/^\.\//u, "").startsWith(PROJECT_DOCUMENTS_ROOT));
272
+ }
273
+ function projectOptionOf(args) {
274
+ return /(?:^|\s)--project(?:=|\s+)([A-Za-z0-9_-]+)(?=\s|$)/u.exec(args)?.[1];
275
+ }
276
+ function specdojoCommandApplicability(command, config, runProjectId, changedPaths) {
277
+ const args = specdojoCommandArgs(command);
278
+ if (args === undefined)
279
+ return { recognized: false };
280
+ if (!/^catalog\s+validate(?:\s|$)/u.test(args)) {
281
+ return { recognized: true, applicable: undefined };
203
282
  }
204
- const ids = new Set();
205
- for (const viewpoint of value.viewpoint_results) {
206
- if (!isRecord(viewpoint) || !exactKeys(viewpoint, ["id", "result", "evidence", "notes"])) {
207
- return "viewpoint_results entries have missing or additional properties";
208
- }
209
- if (typeof viewpoint.id !== "string" || !/^RVP-[0-9]{3}$/.test(viewpoint.id)) {
210
- return "viewpoint id must match RVP-NNN";
211
- }
212
- if (ids.has(viewpoint.id))
213
- return `duplicate viewpoint id: ${viewpoint.id}`;
214
- ids.add(viewpoint.id);
215
- if (viewpoint.result !== "pass" &&
216
- viewpoint.result !== "fail" &&
217
- viewpoint.result !== "unclear") {
218
- return "viewpoint result must be pass, fail, or unclear";
219
- }
220
- if (!isTextArray(viewpoint.evidence, 100, 1)) {
221
- return "viewpoint evidence must contain 1-100 bounded strings";
283
+ const configuredProjectId = config?.current_project;
284
+ // 明示の --project を優先し、次に run の対象 project を使う。current_project は run の対象を
285
+ // 特定できない場合の最後の手段にとどめる(別 project の catalog_path で判定しないため)。
286
+ const projectId = projectOptionOf(args) ??
287
+ runProjectId ??
288
+ (typeof configuredProjectId === "string" ? configuredProjectId : undefined);
289
+ const project = projectId ? config?.projects[projectId] : undefined;
290
+ if (!project || typeof project !== "object" || Array.isArray(project)) {
291
+ return { recognized: true, applicable: undefined };
292
+ }
293
+ if (typeof project.catalog_path === "string" && project.catalog_path.trim()) {
294
+ // plan の共通規約は catalog validate を docs/ja/projects/ 配下の変更に限って求める。
295
+ if (changedPaths !== undefined && !changesReachProjectDocuments(changedPaths)) {
296
+ return {
297
+ recognized: true,
298
+ applicable: false,
299
+ reason: `変更が ${PROJECT_DOCUMENTS_ROOT} 配下に及ばない`,
300
+ };
222
301
  }
223
- if (!isText(viewpoint.notes, true))
224
- return "viewpoint notes must be a bounded string";
302
+ return { recognized: true, applicable: true };
225
303
  }
226
- if (value.recommendation !== "approve" &&
227
- value.recommendation !== "revise" &&
228
- value.recommendation !== "reject") {
229
- return "recommendation must be approve, revise, or reject";
304
+ if (project.catalog_path !== undefined) {
305
+ return { recognized: true, applicable: undefined };
306
+ }
307
+ return {
308
+ recognized: true,
309
+ applicable: false,
310
+ reason: `project '${projectId}' に catalog_path が設定されていない`,
311
+ };
312
+ }
313
+ /**
314
+ * Returns the runner-owned reason when a command is mechanically known not to apply. Unknown
315
+ * applicability deliberately returns undefined so an ordinary `not_run` continues to block.
316
+ */
317
+ export function mechanicallyNotApplicableReason(command, options = {}) {
318
+ const normalized = normalizeValidationCommand(command);
319
+ const config = options.specdojoConfig === undefined ? defaultSpecdojoConfig() : options.specdojoConfig;
320
+ const specdojo = specdojoCommandApplicability(normalized, config, options.projectId, options.changedPaths);
321
+ if (specdojo.recognized) {
322
+ return specdojo.applicable === false ? specdojo.reason : undefined;
323
+ }
324
+ const manifest = commandManifest(normalized, options, config);
325
+ const packageJson = manifest.repoName === undefined ? "package.json" : `${manifest.repoName} の package.json`;
326
+ const scriptName = invokedScriptNameOf(manifest.command);
327
+ if (scriptName !== undefined && manifest.scripts[scriptName] === undefined) {
328
+ return `${packageJson} に npm script '${scriptName}' がない`;
329
+ }
330
+ const packageName = npxPackageNameOf(manifest.command);
331
+ if (packageName !== undefined && !manifest.dependencies.has(packageName)) {
332
+ return `${packageJson} の dependencies / devDependencies に '${packageName}' がない`;
230
333
  }
231
334
  return undefined;
232
335
  }
233
- export function parseReporterOutput(raw, mode) {
234
- let value;
235
- try {
236
- value = JSON.parse(extractJsonText(raw));
336
+ function isValidNotApplicableValidation(command, reason, options) {
337
+ if (!reason?.trim())
338
+ return false;
339
+ const normalized = normalizeValidationCommand(command);
340
+ const config = options.specdojoConfig === undefined ? defaultSpecdojoConfig() : options.specdojoConfig;
341
+ const specdojo = specdojoCommandApplicability(normalized, config, options.projectId, options.changedPaths);
342
+ if (specdojo.recognized)
343
+ return specdojo.applicable !== true;
344
+ const manifest = commandManifest(normalized, options, config);
345
+ const scriptName = invokedScriptNameOf(manifest.command);
346
+ if (scriptName !== undefined && manifest.scripts[scriptName] !== undefined)
347
+ return false;
348
+ const packageName = npxPackageNameOf(manifest.command);
349
+ return packageName === undefined || !manifest.dependencies.has(packageName);
350
+ }
351
+ const PREFIX_OPTION_PATTERN = /(?:^|\s)--prefix(?:=|\s+)(\S+)(?=\s|$)/u;
352
+ function normalizeRepoPathText(path) {
353
+ return path.replaceAll("\\", "/").replace(/^\.\//u, "").replace(/\/+$/u, "");
354
+ }
355
+ function declaredRepos(config, projectId) {
356
+ const targetProjectId = projectId ?? config?.current_project;
357
+ const project = targetProjectId ? config?.projects[targetProjectId] : undefined;
358
+ if (!isProjectConfig(project) || !Array.isArray(project.repos))
359
+ return [];
360
+ // 設定ファイル由来の値なので、型の宣言に頼らず name と path が文字列の要素だけを使う。
361
+ return project.repos.filter((repo) => typeof repo === "object" &&
362
+ repo !== null &&
363
+ typeof repo.name === "string" &&
364
+ typeof repo.path === "string");
365
+ }
366
+ /**
367
+ * Identifies a command that targets a declared product repository, either through
368
+ * `--prefix <repo>` (the repository name or its configured path) or a `<repo>:<path>` argument.
369
+ */
370
+ function productRepoCommand(command, repos) {
371
+ const prefix = PREFIX_OPTION_PATTERN.exec(command)?.[1];
372
+ if (prefix !== undefined) {
373
+ const value = normalizeRepoPathText(prefix);
374
+ const repo = repos.find((candidate) => candidate.name === value || normalizeRepoPathText(candidate.path) === value);
375
+ if (!repo)
376
+ return undefined;
377
+ return {
378
+ repo,
379
+ command: normalizeValidationCommand(command.replace(PREFIX_OPTION_PATTERN, " ")),
380
+ };
237
381
  }
238
- catch (error) {
382
+ const tokens = command.split(" ");
383
+ const repo = repos.find((candidate) => tokens.some((token) => token.startsWith(`${candidate.name}:`)));
384
+ return repo ? { repo, command } : undefined;
385
+ }
386
+ const productManifestCache = new Map();
387
+ function productPackageManifest(repo, options) {
388
+ const injected = options.productPackageManifests?.[repo.name];
389
+ if (injected)
390
+ return injected;
391
+ const packageJsonPath = join(resolveRepoRoot(specdojoRootDir(), repo), "package.json");
392
+ const cached = productManifestCache.get(packageJsonPath);
393
+ if (cached)
394
+ return cached;
395
+ const manifest = readPackageManifest(packageJsonPath);
396
+ productManifestCache.set(packageJsonPath, manifest);
397
+ return manifest;
398
+ }
399
+ /**
400
+ * Selects the package.json that decides a command's applicability: the product repository's
401
+ * when the command targets one declared by the run's project, otherwise the project repository's.
402
+ */
403
+ function commandManifest(command, options, config) {
404
+ const product = productRepoCommand(command, declaredRepos(config, options.projectId));
405
+ if (product) {
239
406
  return {
240
- error: `response is not a single JSON value: ${error instanceof Error ? error.message : String(error)}`,
407
+ ...productPackageManifest(product.repo, options),
408
+ command: product.command,
409
+ repoName: product.repo.name,
241
410
  };
242
411
  }
243
- if (!isRecord(value))
244
- return { error: "response root must be an object" };
245
- if (!validateReporterSchema(value)) {
246
- const details = (validateReporterSchema.errors ?? [])
247
- .slice(0, 5)
248
- .map((error) => `${error.instancePath || "/"} ${error.keyword}: ${error.message ?? "invalid value"}`)
249
- .join("; ");
250
- return { error: `response does not match reporter JSON Schema: ${details}` };
412
+ return {
413
+ scripts: options.packageScripts ?? defaultPackageScripts(),
414
+ dependencies: options.packageDependencies ?? defaultPackageDependencies(),
415
+ command,
416
+ };
417
+ }
418
+ // package.json の script が npm script の呼び出しを `&&` でつないだだけの合成なら、直下の構成
419
+ // コマンドを返す。それ以外(任意のシェル、引数付きなど)は合成として扱わない。
420
+ function compositeComponents(command, scripts) {
421
+ const name = scriptNameOf(command);
422
+ const body = name === undefined ? undefined : scripts[name];
423
+ if (body === undefined)
424
+ return undefined;
425
+ const parts = body.split("&&").map((part) => normalizeValidationCommand(part));
426
+ if (parts.length < 2 || parts.some((part) => scriptNameOf(part) === undefined))
427
+ return undefined;
428
+ return parts;
429
+ }
430
+ // executor は `npm run <name>` の代わりに script の中身(例: `node --import tsx src/specdojo.ts
431
+ // catalog validate`)を直接実行して記録することがある。tsx の起動の書き方の違いだけをそろえて比べる。
432
+ // 対象のプロジェクトを指定する `--project <id>` は検証の範囲を変えないため、比較では取り除く。
433
+ function normalizeScriptBody(command) {
434
+ return normalizeValidationCommand(command)
435
+ .replace(/^(?:node --import tsx|npx tsx) /, "tsx ")
436
+ .replace(/ --project(?:=| )[A-Za-z0-9_-]+(?= |$)/g, "");
437
+ }
438
+ // 構成コマンドは、それ自体が通っていれば満たす。通っていなければ、同等のコマンドの組、script の
439
+ // 中身の直接実行、さらに合成ならその構成コマンドの順に確かめる(runner が合成の script を丸ごと
440
+ // 実行して通した場合に、中身を分解して探さないため)。
441
+ function isComponentSatisfied(command, passed, scripts, depth = 0) {
442
+ if (passed.has(command))
443
+ return true;
444
+ if (depth < MAX_COMPOSITE_DEPTH) {
445
+ const components = compositeComponents(command, scripts);
446
+ if (components?.every((component) => isComponentSatisfied(component, passed, scripts, depth + 1))) {
447
+ return true;
448
+ }
449
+ }
450
+ const equivalents = COMMAND_EQUIVALENTS[command];
451
+ if (equivalents !== undefined && equivalents.every((equivalent) => passed.has(equivalent))) {
452
+ return true;
453
+ }
454
+ const name = scriptNameOf(command);
455
+ const body = name === undefined ? undefined : scripts[name];
456
+ if (body === undefined)
457
+ return false;
458
+ const normalizedBody = normalizeScriptBody(body);
459
+ return [...passed].some((candidate) => normalizeScriptBody(candidate) === normalizedBody);
460
+ }
461
+ let cachedPackageManifest;
462
+ let cachedSpecdojoConfig;
463
+ function defaultPackageManifest() {
464
+ if (cachedPackageManifest)
465
+ return cachedPackageManifest;
466
+ cachedPackageManifest = readPackageManifest(join(specdojoRootDir(), "package.json"));
467
+ return cachedPackageManifest;
468
+ }
469
+ function defaultPackageScripts() {
470
+ return defaultPackageManifest().scripts;
471
+ }
472
+ function defaultPackageDependencies() {
473
+ return defaultPackageManifest().dependencies;
474
+ }
475
+ function defaultSpecdojoConfig() {
476
+ if (cachedSpecdojoConfig !== undefined)
477
+ return cachedSpecdojoConfig;
478
+ const configPath = join(specdojoRootDir(), ".specdojo", "specdojo.config.json");
479
+ if (!existsSync(configPath)) {
480
+ cachedSpecdojoConfig = null;
481
+ return cachedSpecdojoConfig;
251
482
  }
252
- const validationError = mode === "edit" ? validateEdit(value) : validateReview(value);
253
- return validationError
254
- ? { error: validationError }
255
- : { output: value };
483
+ try {
484
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
485
+ cachedSpecdojoConfig =
486
+ parsed.version === 1 &&
487
+ typeof parsed.projects === "object" &&
488
+ parsed.projects !== null &&
489
+ !Array.isArray(parsed.projects)
490
+ ? parsed
491
+ : null;
492
+ }
493
+ catch {
494
+ cachedSpecdojoConfig = null;
495
+ }
496
+ return cachedSpecdojoConfig;
497
+ }
498
+ export function readPackageScripts(packageJsonPath) {
499
+ return readPackageManifest(packageJsonPath).scripts;
500
+ }
501
+ function readPackageManifest(packageJsonPath) {
502
+ const empty = { scripts: {}, dependencies: new Set() };
503
+ if (!existsSync(packageJsonPath))
504
+ return empty;
505
+ let parsed;
506
+ try {
507
+ parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
508
+ }
509
+ catch (error) {
510
+ process.stderr.write(`warning: cannot read package scripts from ${packageJsonPath}: ${String(error)}\n`);
511
+ return empty;
512
+ }
513
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
514
+ return empty;
515
+ const manifest = parsed;
516
+ const scripts = typeof manifest.scripts === "object" &&
517
+ manifest.scripts !== null &&
518
+ !Array.isArray(manifest.scripts)
519
+ ? Object.fromEntries(Object.entries(manifest.scripts).filter((entry) => typeof entry[1] === "string"))
520
+ : {};
521
+ const dependencyEntries = [manifest.dependencies, manifest.devDependencies].flatMap((section) => typeof section === "object" && section !== null && !Array.isArray(section)
522
+ ? Object.entries(section).filter((entry) => typeof entry[1] === "string")
523
+ : []);
524
+ return { scripts, dependencies: new Set(dependencyEntries.map(([name]) => name)) };
256
525
  }
257
526
  export function buildReporterPrompt(opts) {
258
527
  const correction = opts.validationError
259
528
  ? `\nThe previous response failed validation: ${opts.validationError}\nReturn a corrected JSON value.\n`
260
529
  : "";
530
+ const reviewGuidance = opts.mode === "review"
531
+ ? `\n\nFor review mode, the executor did not re-grade the deliverable; it judged task completion
532
+ from the stored grade result. Record that judgement in verdict and put unmet items and improvement
533
+ instructions in improvements. If evidence.final_message identifies "確認できなかった範囲",
534
+ record that scope in rationale or improvements and reflect it in the verdict.`
535
+ : "";
261
536
  return `You are the reporter stage of a SpecDojo executor/reporter pipeline.
262
537
  Use only the supplied plan and bounded executor evidence. Do not edit or inspect files. Do not
263
538
  invent facts that are absent from evidence. Return exactly one JSON object matching the supplied
264
- JSON Schema, without Markdown fences or commentary. Use outcome=blocked when the evidence cannot
265
- support a complete result. The runner owns frontmatter and Markdown rendering: it writes your JSON
266
- response, verbatim, into the plan's result file.
539
+ JSON Schema, without Markdown fences or commentary. The runner owns frontmatter, outcome,
540
+ block_reason, the authoritative changed-file list, and Markdown rendering. It derives those facts
541
+ mechanically from evidence; your response supplies prose associated with evidence paths.
267
542
 
268
543
  The runner renders your free-text JSON fields as Markdown. Wrap every identifier or field name
269
544
  containing an underscore in inline code (for example, \`depends_on\`) so Markdown parsers do not
@@ -272,16 +547,18 @@ misread it as emphasis.
272
547
  The plan below was written as generic instructions for a single agent that both edits the
273
548
  deliverable and records its own result. In this pipeline, those two responsibilities are split:
274
549
  the executor already completed the deliverable edit and intentionally left the result file
275
- untouched (its evidence may say so explicitly) because writing the result is your job, not its.
276
- Your JSON response IS the act of recording the result — returning a well-formed response with
277
- outcome="complete" satisfies the plan's "record to result" and "result must not remain unfilled"
278
- instructions; you do not need file access to fulfill them. Do not treat the executor's evidence
279
- noting an untouched result file as a reason to block. Reserve outcome=blocked for cases where the
280
- evidence itself shows the deliverable work is incomplete, incorrect, unverifiable, or otherwise
281
- falls short of the plan's completion criteria for the edit itself. Validation entries with
282
- source="runner" were executed by the SpecDojo parent process from a fixed allowlist and are
283
- authoritative. If any runner validation is failed or not_run, return outcome="blocked" and cite
284
- that validation; never replace or contradict its status.${correction}
550
+ untouched because the runner writes it from your prose and machine facts. For edit mode, identify
551
+ each changed_files summary with the exact path from its evidence.changes entry. The runner matches
552
+ descriptions by path: order does not matter, missing descriptions use a default message, and paths
553
+ absent from evidence are discarded. Do not include statuses. An empty changes list requires an
554
+ empty changed_files list. Validation entries with source="runner" were executed by the parent
555
+ process and remain authoritative machine facts. Do not turn them into outcome or block_reason
556
+ fields. When runner_context is present, it contains additional authoritative facts: do not ask for
557
+ a command in mechanically_not_applicable to be run, because the runner already determined that it
558
+ does not apply and will preserve that handoff itself. Paths in runner_managed_attempt_changes were
559
+ materially changed during the executor attempt but are intentionally absent from changed_files;
560
+ do not request confirmation solely because the executor mentions one of those changes while the
561
+ path is absent from changed_files.${reviewGuidance}${correction}
285
562
  <specdojo_plan>
286
563
  ${opts.plan.trimEnd()}
287
564
  </specdojo_plan>
@@ -291,7 +568,7 @@ ${JSON.stringify(opts.evidence, null, 2)}
291
568
  </specdojo_executor_evidence>
292
569
 
293
570
  <specdojo_reporter_output_schema mode="${opts.mode}">
294
- ${JSON.stringify(REPORTER_OUTPUT_SCHEMA, null, 2)}
571
+ ${JSON.stringify(reporterOutputSchemaForMode(opts.mode), null, 2)}
295
572
  </specdojo_reporter_output_schema>
296
573
  `;
297
574
  }