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
@@ -0,0 +1,531 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { basename, relative, resolve, sep } from "node:path";
4
+ import { resolveMemberCommand, resolveRateLimitDetection, resolveRateLimitPolicy, } from "./exec-agent-config.js";
5
+ import { normalizeAgentLimit } from "./exec-limit.js";
6
+ import { replaceDocIndexRefs } from "./doc-index.js";
7
+ import { loadPlan, parsePlanTaskIdentity } from "./exec-plans.js";
8
+ import { recordParentValidationFailureOutput, validateResumedTargetCoverage, writeExecutorEvidence, } from "./exec-evidence.js";
9
+ import { parentValidationDisplayCommands, parentValidationGateFor, parentValidationLabels, parentValidationRoots, recordedParentValidationLabel, replaceParentValidationResults, runParentValidationBatch, } from "./exec-parent-validation.js";
10
+ import { getProjectExecutionPath, loadConfig, loadMemberRoster, specdojoRootDir, } from "./specdojo-config.js";
11
+ import { agentProtectedConfigViolation, captureAgentProtectedConfigAcrossRepos, changedAgentProtectedConfigAcrossRepos, qualifiedRepoPaths, } from "./exec-agent-protected-config.js";
12
+ import { agentGitStateViolation, captureAgentGitStateAcrossRepos, changedAgentGitStateAcrossRepos, qualifiedGitStateFields, } from "./exec-agent-git-state.js";
13
+ import { recordGitStateBlockAcrossRepos, recordProtectedConfigBlockAcrossRepos, } from "./exec-protection-handoff.js";
14
+ import { productRepoEnvironment, productRootsFromEnvironment, withAgentExtraRoots, withoutInheritedRepoEnvironment, } from "./exec-task-repos.js";
15
+ import { gitEnvironment } from "./exec-worktree.js";
16
+ import { isRateLimitError, resolveAgentOverride, selectCandidates, } from "./exec-run-shared.js";
17
+ function delay(ms) {
18
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
19
+ }
20
+ export function expandPromptRefs(prompt, indexPath = resolve(specdojoRootDir(), ".specdojo/doc-index.json")) {
21
+ if (!existsSync(indexPath))
22
+ return prompt;
23
+ // Agents open the referenced files directly, so resolve [[id]] refs to canonical
24
+ // repo-relative paths (no leading slash) rather than markdown links. This keeps every
25
+ // path in the agent-consumed plan in one form that resolves from the run CWD.
26
+ const result = replaceDocIndexRefs(prompt, indexPath, {
27
+ format: "path",
28
+ missing: "keep",
29
+ });
30
+ if (result.missingIds.length > 0) {
31
+ process.stderr.write(`Unresolved ID reference(s): ${result.missingIds.join(", ")}\n`);
32
+ }
33
+ return result.content;
34
+ }
35
+ export function loadPrompt(executionPath, taskId) {
36
+ const plan = loadPlan(executionPath, taskId);
37
+ return plan ? expandPromptRefs(plan) : null;
38
+ }
39
+ export function resolveResumedCoverageTargets(plan, initialChangeTargets = []) {
40
+ const declared = [
41
+ ...new Set((parsePlanTaskIdentity(plan)?.targets ?? []).map((target) => target.trim())),
42
+ ].filter(Boolean);
43
+ if (declared.length > 0)
44
+ return { source: "declared", targets: declared };
45
+ const initial = [...new Set(initialChangeTargets.map((target) => target.trim()))].filter(Boolean);
46
+ return initial.length > 0
47
+ ? { source: "initial-changes", targets: initial }
48
+ : { source: "none", targets: [] };
49
+ }
50
+ function executorEvidenceContract(parentValidations, options = {}) {
51
+ const parentValidationLabelList = parentValidationLabels(parentValidations);
52
+ const parentValidationCommands = parentValidationDisplayCommands(parentValidations);
53
+ const parentValidationInstruction = parentValidationLabelList.length > 0
54
+ ? `\nThe SpecDojo parent runner will execute these allowlisted validations after you exit: ${parentValidationLabelList.join(", ")} (${parentValidationCommands.join(", ")}). Do not run those commands inside the agent sandbox or report duplicate executor results for them. Run only the remaining sandbox-safe validations required by the plan. Parent-run results will be appended to evidence with source=runner and are authoritative.\n`
55
+ : "";
56
+ const coverage = {
57
+ source: options.coverageSource ?? "none",
58
+ targets: [...(options.initialChangeTargets ?? [])],
59
+ };
60
+ const coverageInstruction = coverage.source === "initial-changes"
61
+ ? `The plan declares no \`targets\`. The paths below were materially changed by the first
62
+ executor attempt and are an incomplete lower bound, not an upper bound on the work required.
63
+ Inspect the entire plan and any additional artifacts it requires. For each lower-bound path,
64
+ include one \`target_coverage\` entry and use the path exactly as the entry's \`target\` value:
65
+ ${coverage.targets.map((target) => `- \`${target}\``).join("\n")}`
66
+ : coverage.source === "declared"
67
+ ? `For each entry in plan frontmatter \`targets\`, include one \`target_coverage\` entry in
68
+ the evidence envelope. Use the target ID exactly as written in the plan. Declared targets take
69
+ priority over any files recorded by an earlier attempt.`
70
+ : `The plan declares no \`targets\` and no first-attempt change lower bound was recorded.
71
+ Omit \`target_coverage\` and state in \`final_message\` which artifacts you verified and which
72
+ remain unverified.`;
73
+ const resumeInstruction = options.resumed
74
+ ? `
75
+ This executor invocation resumes an interrupted attempt. Existing worktree changes may represent
76
+ only a partial implementation; they are not proof that the plan is complete. Re-read the entire
77
+ plan before reporting success. ${coverageInstruction}
78
+
79
+ ${options.resumeHandoff?.length
80
+ ? `The previous attempt left these failure details. Address them before reporting success:\n${options.resumeHandoff.map((detail) => `- ${detail}`).join("\n")}\n`
81
+ : ""}
82
+
83
+ A changed target must use status \`changed\`, provide its
84
+ repository-relative \`path\`, and actually be present in the cumulative worktree diff. A target
85
+ that legitimately needs no change must use status \`unchanged\` and provide a concrete \`reason\`;
86
+ the runner will preserve that reason in the result. If you cannot account for every target, exit
87
+ non-zero instead of claiming completion.${options.existingChanges?.length
88
+ ? `\n\nChanges already present when this resumed invocation started:\n${options.existingChanges.map((path) => `- \`${path}\``).join("\n")}`
89
+ : ""}
90
+ `
91
+ : "";
92
+ const targetCoverageExample = options.resumed
93
+ ? ',"target_coverage":[{"target":"exact declared target id or lower-bound path","status":"changed|unchanged","path":"repo-relative path for changed targets","reason":"required when unchanged"}]'
94
+ : "";
95
+ const reviewValidationInstruction = options.mode === "review"
96
+ ? `
97
+ For a review task, report only checks you actually ran in \`validations\`. Do not add optional
98
+ checks you chose not to run as \`not_run\` or \`not_applicable\`. Describe them instead in
99
+ \`final_message\` under "確認できなかった範囲" so the reporter can record that scope in the
100
+ review result and reflect it in the verdict.
101
+ `
102
+ : "";
103
+ return `
104
+
105
+ ---
106
+
107
+ # Pipeline executor stage instructions
108
+
109
+ This invocation is the executor stage of an executor/reporter pipeline. Edit and validate the
110
+ artifacts required by the plan, but do not create or update the result file. Any plan instruction
111
+ that assigns result writing or lifecycle transitions to the agent belongs to the later reporter or
112
+ runner stage and does not apply here.
113
+
114
+ The parent runner owns Git commits and repository configuration. Do not run git commit or change
115
+ local, global, or system Git configuration, including user.name and user.email. A Git state change
116
+ will stop the pipeline before validation, reporting, commit, or merge.
117
+
118
+ Do not create disposable or scratch files at the repository root; place them in \`tmp/\` within
119
+ the worktree or outside the repository. Files under \`tmp/\` are excluded from commits.
120
+
121
+ When writing Markdown in the final evidence, wrap identifiers or field names containing an
122
+ underscore in inline code (for example, \`depends_on\`).
123
+ ${parentValidationInstruction}
124
+ ${resumeInstruction}
125
+ ${reviewValidationInstruction}
126
+
127
+ Use validation status \`requires_human\` only for a check that cannot run from the agent sandbox,
128
+ such as launching a real agent CLI, consuming a usage quota or incurring a charge, or requiring
129
+ credentials or a host-side operation. Do not use it for a check that could run but was skipped;
130
+ report that as \`not_run\`. A \`requires_human\` check is carried into the result as a human handoff
131
+ and does not block pipeline completion.
132
+
133
+ Use validation status \`not_applicable\` when the repository does not meet a check's applicability
134
+ conditions, and include a non-empty \`reason\`. The runner carries it into the result without
135
+ blocking completion, but rejects the claim when it can confirm the check applies:
136
+ - \`npm run <script>\` / \`npm test\`: the script exists in package.json.
137
+ - \`npx <package>\`: the package is in package.json dependencies or devDependencies.
138
+ - A command that targets a declared product repository (a \`<repo>:<path>\` argument or
139
+ \`--prefix <repo>\`) is judged by that repository's package.json, not the project repository's.
140
+ - \`specdojo catalog validate\`: the run's target project (or \`--project <id>\`) sets \`catalog_path\`
141
+ and your changes reach \`docs/ja/projects/\`. A project without \`catalog_path\`, or changes
142
+ outside \`docs/ja/projects/\`, is a valid reason; state it in \`reason\`.
143
+
144
+ Do not run or report \`specdojo index build\`. It writes \`.specdojo/doc-index.json\`, which the
145
+ agent may not write, and the runner regenerates the index while preparing the worktree and before
146
+ integration.
147
+
148
+ End the final response with exactly one machine-readable report using this envelope. Do not place
149
+ Markdown fences around the JSON.
150
+
151
+ <specdojo_executor_evidence>
152
+ {"final_message":"concise outcome","validations":[{"command":"exact command","status":"passed|failed|not_run|not_applicable|requires_human","summary":"concise result or required human check","reason":"required when status is not_applicable"}]${targetCoverageExample}}
153
+ </specdojo_executor_evidence>
154
+ `;
155
+ }
156
+ export function buildExecutorPrompt(plan, parentValidations = [], options = {}) {
157
+ const coverage = resolveResumedCoverageTargets(plan, options.initialChangeTargets);
158
+ return `${plan.trimEnd()}${executorEvidenceContract(parentValidations, {
159
+ ...options,
160
+ mode: options.mode ?? parsePlanTaskIdentity(plan)?.mode ?? "edit",
161
+ initialChangeTargets: coverage.targets,
162
+ coverageSource: coverage.source,
163
+ })}`;
164
+ }
165
+ export function resumedTargetCoverageFailure(params) {
166
+ if (!params.resumed)
167
+ return undefined;
168
+ const targets = resolveResumedCoverageTargets(params.plan, params.initialChangeTargets).targets;
169
+ const coverage = validateResumedTargetCoverage(targets, params.evidence);
170
+ if (coverage.ok)
171
+ return undefined;
172
+ params.evidence.stage.status = "failed";
173
+ writeExecutorEvidence(params.evidencePath, params.evidence);
174
+ return coverage.reason;
175
+ }
176
+ // 同じ exec run 内の親検証は run 全体の gate(既定 1 本)で直列化する。executor と reporter は
177
+ // gate の外で並列に動き、検証だけが順番待ちになる。`cwd` に文字列を渡すとプロジェクト worktree
178
+ // だけを持つ run として扱い、プロダクトリポジトリへ割り当てた検証は failed になる(PJR-V96B)。
179
+ export async function runConfiguredParentValidationBatch(execDefaults, cwd, options = {}) {
180
+ const entries = execDefaults.pipeline?.parent_validations;
181
+ if (!entries?.length)
182
+ return { validations: [], failureOutputs: [] };
183
+ const labels = parentValidationLabels(entries);
184
+ const label = options.label ?? basename(typeof cwd === "string" ? cwd : cwd.project);
185
+ const batch = await parentValidationGateFor(execDefaults).run(label, labels, async () => {
186
+ process.stdout.write(` Running parent validations (${label}): ${labels.join(", ")}\n`);
187
+ return await runParentValidationBatch(entries, cwd, options.invoke);
188
+ });
189
+ for (const validation of batch.validations) {
190
+ process.stdout.write(` Parent validation ${recordedParentValidationLabel(validation)}: ${validation.status}\n`);
191
+ }
192
+ return batch;
193
+ }
194
+ export async function runConfiguredParentValidations(execDefaults, cwd, options = {}) {
195
+ return (await runConfiguredParentValidationBatch(execDefaults, cwd, options)).validations;
196
+ }
197
+ // executor のプロセス結果は親検証より先に checkpoint する。親検証は長時間かかり得るため、
198
+ // その途中で runner が終了しても agent 出力と変更一覧を失わないよう、ここでは保存済み evidence
199
+ // へ runner-owned validation だけを追記する。
200
+ export async function appendParentValidationsToExecutorEvidence(params) {
201
+ const parentValidationBatch = await runConfiguredParentValidationBatch(params.execDefaults, parentValidationRoots(params.cwd, params.productWorktrees), { label: params.evidence.task_id });
202
+ const evidenceWithValidations = replaceParentValidationResults(params.evidence, parentValidationBatch.validations);
203
+ const evidence = recordParentValidationFailureOutput({
204
+ worktreePath: params.cwd,
205
+ evidencePath: params.evidencePath,
206
+ evidence: evidenceWithValidations,
207
+ failureOutputs: parentValidationBatch.failureOutputs,
208
+ });
209
+ if (parentValidationBatch.failureOutputs.length === 0) {
210
+ writeExecutorEvidence(params.evidencePath, evidence);
211
+ }
212
+ return evidence;
213
+ }
214
+ export function executorRequirements(task) {
215
+ const executor = task.agent_pipeline?.stages[0];
216
+ if (!executor || executor.stage_role !== "executor")
217
+ return undefined;
218
+ return {
219
+ capabilities: executor.capabilities ?? [],
220
+ proficiency: executor.proficiency,
221
+ stage_role: "executor",
222
+ };
223
+ }
224
+ export function reporterRequirements(task) {
225
+ const reporter = task.agent_pipeline?.stages[1];
226
+ if (!reporter || reporter.stage_role !== "reporter")
227
+ return undefined;
228
+ return {
229
+ capabilities: reporter.capabilities ?? [],
230
+ proficiency: reporter.proficiency,
231
+ stage_role: "reporter",
232
+ };
233
+ }
234
+ export function resolveReporterAgentCandidates(task, roster, execDefaults, busyActors, nicknameOverride) {
235
+ const requirements = reporterRequirements(task);
236
+ if (!requirements)
237
+ return [];
238
+ if (nicknameOverride) {
239
+ const resolution = resolveAgentOverride(task.mode ?? "edit", nicknameOverride, {}, roster, execDefaults, "reporter");
240
+ if (resolution.kind === "error") {
241
+ throw new Error(resolution.message.replace(/^--by/, "--reporter-by"));
242
+ }
243
+ if (resolution.kind === "command") {
244
+ return [
245
+ {
246
+ command: resolution.command,
247
+ actor: resolution.actor,
248
+ provider: resolution.provider,
249
+ },
250
+ ];
251
+ }
252
+ }
253
+ // Reporter behavior (turn captured evidence into a structured result; write nothing
254
+ // else) does not vary between edit and review tasks, unlike the executor stage. Do not
255
+ // filter reporter candidates by task.mode: a reporter member's own `mode` (if it has
256
+ // one, e.g. to resolve a provider command_template placeholder) only affects command
257
+ // construction, not eligibility.
258
+ const candidates = [];
259
+ for (const member of selectCandidates(requirements, roster, undefined, busyActors, execDefaults)) {
260
+ try {
261
+ const command = resolveMemberCommand(execDefaults, member);
262
+ if (command)
263
+ candidates.push({ command, actor: member.nickname, provider: member.provider });
264
+ }
265
+ catch (error) {
266
+ process.stdout.write(` Skipping reporter ${member.nickname}: ${error instanceof Error ? error.message : String(error)}\n`);
267
+ }
268
+ }
269
+ return candidates;
270
+ }
271
+ export function loadRosterForExecutionPath(executionPath) {
272
+ const { config } = loadConfig();
273
+ if (!config)
274
+ return null;
275
+ const rootDir = specdojoRootDir();
276
+ for (const project of Object.values(config.projects)) {
277
+ const projExecPath = resolve(rootDir, getProjectExecutionPath(project));
278
+ if (projExecPath === executionPath) {
279
+ return loadMemberRoster(rootDir, project);
280
+ }
281
+ }
282
+ return null;
283
+ }
284
+ export async function executeAgent(agentCommand, prompt, detection, provider, cooldownSeconds, cwd, env, quiet = false) {
285
+ if (!agentCommand.trim()) {
286
+ return { result: "failure", exitCode: null, stdout: "", stderr: "Empty agent command" };
287
+ }
288
+ // stdout is piped (not inherited) so it can be scanned for rate-limit signals: some CLIs print
289
+ // the limit notice to stdout, not stderr (e.g. claude's "session limit"). Unless quiet, each
290
+ // chunk is teed to the parent's stdout so live output/logging is preserved.
291
+ const child = spawn(agentCommand, {
292
+ cwd,
293
+ env,
294
+ shell: true,
295
+ stdio: ["pipe", "pipe", "pipe"],
296
+ });
297
+ // stdin を読まずに即終了するコマンドへの書き込みは EPIPE になる。未処理だと
298
+ // プロセスごと落ちて失敗時の後処理(block 遷移・result 更新)が走らないため無視する。
299
+ // 実行結果は終了コードで判定する。
300
+ child.stdin.on("error", () => undefined);
301
+ let stdout = "";
302
+ let stderr = "";
303
+ child.stdout.setEncoding("utf8");
304
+ child.stdout.on("data", (chunk) => {
305
+ stdout += chunk;
306
+ if (!quiet)
307
+ process.stdout.write(chunk);
308
+ });
309
+ child.stderr.setEncoding("utf8");
310
+ child.stderr.on("data", (chunk) => {
311
+ stderr += chunk;
312
+ process.stderr.write(chunk);
313
+ });
314
+ child.stdin.end(prompt);
315
+ const exitCode = await new Promise((resolveExit) => {
316
+ child.once("error", (error) => {
317
+ stderr += `${error.message}\n`;
318
+ resolveExit(null);
319
+ });
320
+ child.once("close", (code) => resolveExit(code));
321
+ });
322
+ const combinedOutput = `${stdout}\n${stderr}`;
323
+ if (isRateLimitError(exitCode, combinedOutput, detection)) {
324
+ return {
325
+ result: "rate_limit",
326
+ exitCode,
327
+ stdout,
328
+ stderr,
329
+ limit: normalizeAgentLimit({
330
+ output: combinedOutput,
331
+ provider,
332
+ cooldownSeconds,
333
+ }),
334
+ };
335
+ }
336
+ if (exitCode !== 0) {
337
+ return { result: "failure", exitCode, stdout, stderr };
338
+ }
339
+ return { result: "success", exitCode: 0, stdout, stderr: "" };
340
+ }
341
+ // Run the task's agent command, falling back through the remaining candidates on rate limit.
342
+ // The next-priority candidate is assumed to be a different account/provider, so we switch to it
343
+ // immediately (no wait). Only after every candidate is rate-limited do we wait+backoff and run
344
+ // another full pass, bounded by rate_limit_policy.on_critical.retry.max_attempts. Applies to all
345
+ // tasks (critical and non-critical) so a rate limit no longer stops the run outright.
346
+ //
347
+ // Detection is resolved per candidate from its provider (e.g. claude's "session limit" vs
348
+ // opencode's "timeout"/"out of memory"); the run-level retry/backoff policy is governed by the
349
+ // primary (highest-priority) candidate's provider.
350
+ // 保護機構が block したとき、result へ自動記録できたかを実行ログにも残す。記録できない場合
351
+ // (result 未 scaffold など)は、申し送りが result に無いことが分かるよう理由を出力する。
352
+ export function reportProtectionHandoffRecord(recorded, resultPath) {
353
+ process.stdout.write(recorded
354
+ ? ` Handoff recorded in result: ${resultPath}\n`
355
+ : " Handoff not recorded: no writable result for this run\n");
356
+ }
357
+ //
358
+ // resultPath は保護機構が block したときの申し送り記録先(agent が動く cwd 側の result)。
359
+ // 未指定でも block と終了コードの扱いは変わらない。
360
+ function rateLimitPrefix(result) {
361
+ return result === "rate_limit" ? "rate limit reached; " : "";
362
+ }
363
+ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, resultPath) {
364
+ const policy = resolveRateLimitPolicy(execDefaults, candidates[0]?.provider);
365
+ let attempts = 0;
366
+ // PJR-98G4: agentEnvironment が渡したプロダクト worktree を、provider の追加ディレクトリと
367
+ // 保護設定・Git 状態の検査対象に加える。宣言の無い project では cwd だけになる。
368
+ const productRoots = productRootsFromEnvironment(env);
369
+ const agentRepos = [
370
+ { root: cwd },
371
+ ...productRoots.map((root) => ({ name: root.name, root: root.path })),
372
+ ];
373
+ // One pass tries every candidate in priority order with no wait between switches.
374
+ const runPass = async () => {
375
+ let lastStderr = "";
376
+ let lastStdout = "";
377
+ let lastExitCode = null;
378
+ let lastLimit;
379
+ for (let idx = 0; idx < candidates.length; idx++) {
380
+ if (idx > 0) {
381
+ process.stdout.write(`Rate limit detected. Switching to next agent (${idx + 1}/${candidates.length})...\n`);
382
+ }
383
+ const detection = resolveRateLimitDetection(execDefaults, candidates[idx].provider);
384
+ attempts++;
385
+ const protectedConfigBefore = captureAgentProtectedConfigAcrossRepos(agentRepos);
386
+ const gitStateBefore = captureAgentGitStateAcrossRepos(agentRepos);
387
+ const attempt = await executeAgent(withAgentExtraRoots(candidates[idx].command, candidates[idx].provider, productRoots.map((root) => root.path)), prompt, detection, candidates[idx].provider, policy?.cooldown_seconds, cwd, env);
388
+ const protectedConfigChanges = changedAgentProtectedConfigAcrossRepos(protectedConfigBefore);
389
+ if (protectedConfigChanges.length > 0) {
390
+ // 利用上限で止まった場合も保護の検査は飛ばさない。止まった理由として利用上限を先に記録する。
391
+ const reason = rateLimitPrefix(attempt.result) +
392
+ agentProtectedConfigViolation(qualifiedRepoPaths(protectedConfigChanges));
393
+ process.stderr.write(`blocked: ${reason}\n`);
394
+ reportProtectionHandoffRecord(recordProtectedConfigBlockAcrossRepos({
395
+ resultPath,
396
+ changes: protectedConfigChanges,
397
+ reason,
398
+ }), resultPath);
399
+ return {
400
+ result: "failure",
401
+ exitCode: 1,
402
+ stdout: attempt.stdout,
403
+ stderr: `${attempt.stderr}${attempt.stderr.endsWith("\n") || !attempt.stderr ? "" : "\n"}${reason}\n`,
404
+ protectionBlock: true,
405
+ };
406
+ }
407
+ const gitStateChanges = changedAgentGitStateAcrossRepos(gitStateBefore);
408
+ if (gitStateChanges.length > 0) {
409
+ // 利用上限で止まった場合も保護の検査は飛ばさない。止まった理由として利用上限を先に記録する。
410
+ const reason = rateLimitPrefix(attempt.result) +
411
+ agentGitStateViolation(qualifiedGitStateFields(gitStateChanges));
412
+ process.stderr.write(`blocked: ${reason}\n`);
413
+ reportProtectionHandoffRecord(recordGitStateBlockAcrossRepos({
414
+ resultPath,
415
+ changes: gitStateChanges,
416
+ reason,
417
+ }), resultPath);
418
+ return {
419
+ result: "failure",
420
+ exitCode: 1,
421
+ stdout: attempt.stdout,
422
+ stderr: `${attempt.stderr}${attempt.stderr.endsWith("\n") || !attempt.stderr ? "" : "\n"}${reason}\n`,
423
+ protectionBlock: true,
424
+ };
425
+ }
426
+ lastStderr = attempt.stderr;
427
+ lastStdout = attempt.stdout;
428
+ lastExitCode = attempt.exitCode;
429
+ lastLimit = attempt.limit;
430
+ if (attempt.result !== "rate_limit")
431
+ return {
432
+ result: attempt.result,
433
+ exitCode: attempt.exitCode,
434
+ stdout: attempt.stdout,
435
+ stderr: attempt.stderr,
436
+ };
437
+ }
438
+ return {
439
+ result: "rate_limit",
440
+ exitCode: lastExitCode,
441
+ stdout: lastStdout,
442
+ stderr: lastStderr,
443
+ limit: lastLimit,
444
+ };
445
+ };
446
+ const firstPass = await runPass();
447
+ if (firstPass.result !== "rate_limit")
448
+ return { ...firstPass, attempts };
449
+ // Every candidate is rate-limited. Without a policy we cannot bound further retries, so stop.
450
+ if (!policy) {
451
+ process.stdout.write(`Rate limit: all ${candidates.length} agent(s) exhausted.\n`);
452
+ return { ...firstPass, attempts };
453
+ }
454
+ // Session and quota limits do not recover within the short in-process backoff loop. Keep their
455
+ // explicit reset/cooldown for a later routine invocation instead of sleeping and retrying now.
456
+ if (firstPass.limit?.kind === "session_limit" || firstPass.limit?.kind === "quota_exhausted") {
457
+ return { ...firstPass, attempts };
458
+ }
459
+ const { retry } = policy.on_critical;
460
+ let waitSeconds = retry.initial_wait_seconds;
461
+ let lastStderr = firstPass.stderr;
462
+ let lastStdout = firstPass.stdout;
463
+ let lastExitCode = firstPass.exitCode;
464
+ let lastLimit = firstPass.limit;
465
+ // First pass counts as attempt 1; remaining passes wait+backoff before retrying all candidates.
466
+ for (let pass = 2; pass <= retry.max_attempts; pass++) {
467
+ const actualWait = Math.min(waitSeconds, retry.max_wait_seconds);
468
+ process.stdout.write(`Rate limit: all agents exhausted (attempt ${pass}/${retry.max_attempts}). Waiting ${actualWait}s before retry...\n`);
469
+ await delay(actualWait * 1000);
470
+ const result = await runPass();
471
+ lastStderr = result.stderr;
472
+ lastStdout = result.stdout;
473
+ lastExitCode = result.exitCode;
474
+ lastLimit = result.limit;
475
+ if (result.result !== "rate_limit")
476
+ return { ...result, attempts };
477
+ waitSeconds = Math.min(waitSeconds * retry.backoff_multiplier, retry.max_wait_seconds);
478
+ }
479
+ process.stdout.write(`Rate limit: all ${candidates.length} agent(s) exhausted after ${retry.max_attempts} attempt(s).\n`);
480
+ return {
481
+ result: "rate_limit",
482
+ exitCode: lastExitCode,
483
+ stdout: lastStdout,
484
+ stderr: lastStderr,
485
+ attempts,
486
+ limit: lastLimit,
487
+ };
488
+ }
489
+ export function pathInsideWorktree(repoRoot, worktreePath, sourcePath) {
490
+ const repoRelative = relative(repoRoot, sourcePath);
491
+ if (repoRelative === ".." || repoRelative.startsWith(`..${sep}`)) {
492
+ throw new Error(`Project path is outside repository root: ${sourcePath}`);
493
+ }
494
+ return resolve(worktreePath, repoRelative);
495
+ }
496
+ export function reportProductWorktrees(worktree) {
497
+ for (const product of worktree.repos ?? []) {
498
+ process.stdout.write(` [run] ${product.created ? "setup" : "reuse"}: worktree ${product.path} ` +
499
+ `(${product.branch} in ${product.name})\n`);
500
+ }
501
+ }
502
+ // productWorktrees(PJR-98G4)は、cwd(プロジェクト worktree)以外に agent が書き込むプロダクト
503
+ // worktree。SPECDOJO_REPO_<NAME> で絶対パスを渡し、runWithRetry はここから provider の追加
504
+ // ディレクトリと保護検査の対象を導く。
505
+ export function agentEnvironment(repoRoot, worktreePath, schedulePath, executionPath, productWorktrees) {
506
+ return {
507
+ ...withoutInheritedRepoEnvironment(gitEnvironment()),
508
+ SPECDOJO_SCHEDULE_PATH: pathInsideWorktree(repoRoot, worktreePath, schedulePath),
509
+ SPECDOJO_EXECUTION_PATH: pathInsideWorktree(repoRoot, worktreePath, executionPath),
510
+ ...productRepoEnvironment(worktreePath, productWorktrees),
511
+ };
512
+ }
513
+ const MAX_BLOCK_REASON_LENGTH = 500;
514
+ // agent の stderr から block イベント用の簡潔な理由を取り出す。テンプレートは異常終了時に
515
+ // `blocked: <reason>; need=...; ref=...`(review は `review-blocked: ...`)を出力させるため、
516
+ // その行を優先する。無ければ最後の非空行、それも無ければ汎用メッセージにフォールバックする。
517
+ export function extractBlockReason(stderr) {
518
+ const fallback = "agent exited with non-zero code";
519
+ const lines = stderr
520
+ .split("\n")
521
+ .map((line) => line.trim())
522
+ .filter((line) => line.length > 0);
523
+ const tagged = lines.find((line) => /^(blocked|review-blocked):/i.test(line));
524
+ const reason = tagged ?? lines.at(-1);
525
+ if (!reason)
526
+ return fallback;
527
+ const trimmed = reason.length > MAX_BLOCK_REASON_LENGTH
528
+ ? `${reason.slice(0, MAX_BLOCK_REASON_LENGTH)}…`
529
+ : reason;
530
+ return `${fallback}: ${trimmed}`;
531
+ }