specdojo 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +77 -18
  3. package/dist/{catalog-build-references.js → catalog/build-references.js} +4 -4
  4. package/dist/catalog/build-render.js +32 -0
  5. package/dist/{catalog-build.js → catalog/build.js} +9 -9
  6. package/dist/{catalog.js → catalog/catalog.js} +10 -10
  7. package/dist/{catalog-generate.js → catalog/generate.js} +8 -8
  8. package/dist/catalog/paths.js +1 -0
  9. package/dist/{catalog-plan-generate.js → catalog/plan-generate.js} +4 -4
  10. package/dist/{catalog-plan.js → catalog/plan.js} +4 -4
  11. package/dist/{catalog-scaffold.js → catalog/scaffold.js} +3 -3
  12. package/dist/{agent.js → commands/agent.js} +11 -11
  13. package/dist/{build-command.js → commands/build.js} +2 -2
  14. package/dist/{init-command.js → commands/init.js} +98 -32
  15. package/dist/{orchestrator.js → commands/orchestrator.js} +2 -2
  16. package/dist/{watch.js → commands/watch.js} +3 -3
  17. package/dist/{dashboard-timeline.js → dashboard/dashboard-timeline.js} +2 -2
  18. package/dist/{dashboard.js → dashboard/dashboard.js} +11 -10
  19. package/dist/{dashboard-exec-records.js → dashboard/exec-records.js} +2 -2
  20. package/dist/{dashboard-routines.js → dashboard/routines.js} +6 -5
  21. package/dist/{dashboard-shared.js → dashboard/shared.js} +1 -1
  22. package/dist/{timeline-build.js → dashboard/timeline-build.js} +2 -1
  23. package/dist/{timeline.js → dashboard/timeline.js} +1 -1
  24. package/dist/{deliverable.js → deliverable/deliverable.js} +5 -5
  25. package/dist/{deliverable-trash.js → deliverable/trash.js} +5 -5
  26. package/dist/{devcontainer-command.js → devcontainer/command.js} +5 -3
  27. package/dist/{devcontainer-scaffold.js → devcontainer/scaffold.js} +94 -2
  28. package/dist/{doc-index.js → docs/doc-index.js} +1 -1
  29. package/dist/{frontmatter-namespace.js → docs/frontmatter-namespace.js} +1 -1
  30. package/dist/{index-command.js → docs/index-command.js} +1 -1
  31. package/dist/docs/template-resolution.js +1 -0
  32. package/dist/{viewpoint-document-kinds-check.js → docs/viewpoint-document-kinds-check.js} +1 -1
  33. package/dist/{yaml-pages-command.js → docs/yaml-pages-command.js} +1 -1
  34. package/dist/{yaml-pages.js → docs/yaml-pages.js} +2 -2
  35. package/dist/{exec-agent-config.js → exec/agent-config.js} +33 -4
  36. package/dist/{exec-agent-git-state.js → exec/agent-git-state.js} +1 -1
  37. package/dist/{exec-agent-protected-config.js → exec/agent-protected-config.js} +1 -1
  38. package/dist/{exec-commands.js → exec/commands.js} +22 -18
  39. package/dist/{exec-core.js → exec/core.js} +11 -11
  40. package/dist/{exec-events.js → exec/events.js} +2 -2
  41. package/dist/{exec-evidence.js → exec/evidence.js} +11 -6
  42. package/dist/exec/exec.js +2 -0
  43. package/dist/exec/format.js +1 -0
  44. package/dist/{exec-handoff.js → exec/handoff.js} +13 -12
  45. package/dist/{exec-limit.js → exec/limit.js} +93 -12
  46. package/dist/{exec-parent-validation.js → exec/parent-validation.js} +4 -4
  47. package/dist/{exec-pipeline-state.js → exec/pipeline-state.js} +16 -2
  48. package/dist/{exec-plans-core.js → exec/plans-core.js} +68 -114
  49. package/dist/{exec-plans-generation.js → exec/plans-generation.js} +53 -10
  50. package/dist/{exec-plans-storage.js → exec/plans-storage.js} +5 -5
  51. package/dist/{exec-plans.js → exec/plans.js} +3 -3
  52. package/dist/{exec-project.js → exec/project.js} +1 -1
  53. package/dist/{exec-protection-handoff.js → exec/protection-handoff.js} +3 -3
  54. package/dist/{exec-register-resume.js → exec/register-resume.js} +2 -2
  55. package/dist/{exec-register.js → exec/register.js} +92 -9
  56. package/dist/{exec-repo-integration-git.js → exec/repo-integration-git.js} +2 -2
  57. package/dist/{exec-repo-integration-sync.js → exec/repo-integration-sync.js} +4 -4
  58. package/dist/{exec-repo-integration.js → exec/repo-integration.js} +13 -10
  59. package/dist/{exec-repo-trace.js → exec/repo-trace.js} +3 -3
  60. package/dist/{exec-reporter-output.js → exec/reporter-output.js} +2 -2
  61. package/dist/{exec-reporter.js → exec/reporter.js} +29 -12
  62. package/dist/{exec-results.js → exec/results.js} +256 -22
  63. package/dist/{exec-run-agent-pipeline.js → exec/run/agent-pipeline.js} +32 -12
  64. package/dist/{exec-run-agent.js → exec/run/agent.js} +79 -27
  65. package/dist/{exec-run-in-place.js → exec/run/in-place.js} +56 -27
  66. package/dist/{exec-run-job.js → exec/run/job.js} +64 -35
  67. package/dist/{exec-run-lifecycle-commands.js → exec/run/lifecycle-commands.js} +30 -22
  68. package/dist/{exec-run-lock.js → exec/run/lock.js} +4 -3
  69. package/dist/{exec-run-mode-shared.js → exec/run/mode-shared.js} +3 -3
  70. package/dist/{exec-run-register-command.js → exec/run/register-command.js} +18 -10
  71. package/dist/{exec-run-register-core.js → exec/run/register-core.js} +46 -21
  72. package/dist/{exec-run-register-mode.js → exec/run/register-mode.js} +20 -16
  73. package/dist/{exec-run-register-resume.js → exec/run/register-resume.js} +22 -17
  74. package/dist/{exec-run-register-state.js → exec/run/register-state.js} +13 -10
  75. package/dist/{exec-run-register-worktree.js → exec/run/register-worktree.js} +54 -23
  76. package/dist/{exec-run.js → exec/run/run.js} +11 -11
  77. package/dist/{exec-run-schedule-mode.js → exec/run/schedule-mode.js} +17 -17
  78. package/dist/{exec-run-schedule-prepare.js → exec/run/schedule-prepare.js} +31 -18
  79. package/dist/{exec-run-schedule-task.js → exec/run/schedule-task.js} +45 -18
  80. package/dist/{exec-run-shared.js → exec/run/shared.js} +61 -11
  81. package/dist/{exec-schedule-calendar.js → exec/schedule/calendar.js} +1 -1
  82. package/dist/{exec-schedule-cpm.js → exec/schedule/cpm.js} +2 -2
  83. package/dist/{exec-schedule-gantt-chart-render.js → exec/schedule/gantt-chart-render.js} +2 -2
  84. package/dist/exec/schedule/gantt-chart.js +2 -0
  85. package/dist/{exec-schedule-hash.js → exec/schedule/hash.js} +2 -2
  86. package/dist/exec/schedule/index.js +1 -0
  87. package/dist/{exec-schedule-initial.js → exec/schedule/initial.js} +2 -2
  88. package/dist/{exec-schedule-progress.js → exec/schedule/progress.js} +2 -2
  89. package/dist/{exec-schedule-ready.js → exec/schedule/ready.js} +2 -2
  90. package/dist/{exec-schedule.js → exec/schedule/schedule.js} +11 -11
  91. package/dist/exec/shared.js +63 -0
  92. package/dist/exec/slot-lock.js +1 -0
  93. package/dist/{exec-strategy.js → exec/strategy.js} +2 -2
  94. package/dist/{exec-task-repos.js → exec/task-repos.js} +2 -2
  95. package/dist/{exec-task-view.js → exec/task-view.js} +4 -4
  96. package/dist/{exec-trial-commands.js → exec/trial-commands.js} +20 -22
  97. package/dist/{exec-trial-core.js → exec/trial-core.js} +6 -6
  98. package/dist/{exec-trial.js → exec/trial.js} +2 -2
  99. package/dist/{exec-worktree-command.js → exec/worktree-command.js} +25 -23
  100. package/dist/{exec-worktree-ops-commit.js → exec/worktree-ops-commit.js} +25 -60
  101. package/dist/{exec-worktree-ops-lifecycle.js → exec/worktree-ops-lifecycle.js} +13 -8
  102. package/dist/{exec-worktree-ops-merge.js → exec/worktree-ops-merge.js} +48 -7
  103. package/dist/{exec-worktree-ops.js → exec/worktree-ops.js} +3 -3
  104. package/dist/exec/worktree.js +305 -0
  105. package/dist/{grade-apply.js → grade/apply.js} +9 -9
  106. package/dist/{grade-command-apply.js → grade/command-apply.js} +7 -7
  107. package/dist/{grade-command-inspect.js → grade/command-inspect.js} +6 -6
  108. package/dist/{grade-command-plan.js → grade/command-plan.js} +5 -5
  109. package/dist/{grade-core.js → grade/core.js} +3 -3
  110. package/dist/grade/grade.js +19 -0
  111. package/dist/{grade-markdown.js → grade/markdown.js} +6 -6
  112. package/dist/{grade-pipeline-state.js → grade/pipeline-state.js} +4 -4
  113. package/dist/{grade-plan.js → grade/plan.js} +5 -5
  114. package/dist/{grade-result.js → grade/result.js} +5 -94
  115. package/dist/{grade-target-discovery.js → grade/target-discovery.js} +7 -7
  116. package/dist/{grade-targets.js → grade/targets.js} +11 -8
  117. package/dist/{job-definition.js → job/definition.js} +25 -6
  118. package/dist/{job.js → job/job.js} +12 -11
  119. package/dist/{kata-command.js → kata/command.js} +3 -3
  120. package/dist/{kata.js → kata/kata.js} +5 -5
  121. package/dist/register/approach.js +134 -0
  122. package/dist/{register-core.js → register/core.js} +13 -7
  123. package/dist/{register-create-commands.js → register/create-commands.js} +115 -8
  124. package/dist/{register-date.js → register/date.js} +1 -1
  125. package/dist/register/derivation.js +163 -0
  126. package/dist/{register-event-merge.js → register/event-merge.js} +32 -3
  127. package/dist/{register-events.js → register/events.js} +9 -3
  128. package/dist/{register-history.js → register/history.js} +7 -6
  129. package/dist/{register-item.js → register/item.js} +23 -5
  130. package/dist/register/lifecycle-lock.js +5 -0
  131. package/dist/{register-maintenance-commands.js → register/maintenance-commands.js} +13 -7
  132. package/dist/{register-migrate-timestamps.js → register/migrate-timestamps.js} +3 -3
  133. package/dist/{register-migration.js → register/migration.js} +4 -4
  134. package/dist/{register.js → register/register.js} +32 -27
  135. package/dist/{register-renumber.js → register/renumber.js} +38 -11
  136. package/dist/{register-transition-commands.js → register/transition-commands.js} +3 -3
  137. package/dist/{register-update.js → register/update.js} +5 -5
  138. package/dist/{register-views.js → register/views.js} +47 -7
  139. package/dist/{review-grade.js → review/grade.js} +2 -2
  140. package/dist/{review-plan.js → review/plan.js} +3 -3
  141. package/dist/{routine-definition.js → routine/definition.js} +2 -2
  142. package/dist/{routine.js → routine/routine.js} +49 -22
  143. package/dist/{schedule-approach.js → schedule/approach.js} +8 -8
  144. package/dist/{schedule-build.js → schedule/build.js} +7 -4
  145. package/dist/{schedule.js → schedule/schedule.js} +6 -6
  146. package/dist/{schedule-strategy-generate-document.js → schedule/strategy-generate-document.js} +2 -2
  147. package/dist/{schedule-strategy-generate-scope.js → schedule/strategy-generate-scope.js} +4 -4
  148. package/dist/{schedule-strategy-generate.js → schedule/strategy-generate.js} +10 -10
  149. package/dist/shared/agent-types.js +23 -0
  150. package/dist/shared/artifact-path.js +9 -0
  151. package/dist/{build-if-stale.js → shared/build-if-stale.js} +1 -1
  152. package/dist/{catalog-build-render.js → shared/catalog-render.js} +3 -32
  153. package/dist/{exec-slot-lock.js → shared/cross-process-lock.js} +3 -1
  154. package/dist/shared/fs.js +30 -0
  155. package/dist/{exec-worktree.js → shared/git.js} +83 -241
  156. package/dist/shared/grade-result.js +94 -0
  157. package/dist/{package-paths.js → shared/package-paths.js} +3 -3
  158. package/dist/shared/plan-templates.js +114 -0
  159. package/dist/{exec-provider-scaffold.js → shared/provider-scaffold.js} +3 -1
  160. package/dist/shared/random.js +4 -0
  161. package/dist/{exec-schedule-index.js → shared/schedule-index.js} +3 -1
  162. package/dist/shared/schedule-paths.js +9 -0
  163. package/dist/{specdojo-config.js → shared/specdojo-config.js} +93 -5
  164. package/dist/{exec-shared.js → shared/text.js} +0 -134
  165. package/dist/shared/time.js +28 -0
  166. package/dist/specdojo.js +22 -22
  167. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +29 -17
  168. package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +1 -2
  169. package/docs/ja/specdojo/exec-templates/xep-register-template.md +1 -2
  170. package/docs/ja/specdojo/exec-templates/xer-template.md +1 -3
  171. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +6 -4
  172. package/docs/ja/specdojo/guides/exec-config-guide.md +91 -16
  173. package/docs/ja/specdojo/guides/exec-operation-guide.md +145 -12
  174. package/docs/ja/specdojo/guides/exec-worktree-guide.md +2 -0
  175. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +31 -0
  176. package/docs/ja/specdojo/guides/quick-start-guide.md +81 -16
  177. package/docs/ja/specdojo/guides/register-operation-guide.md +2 -1
  178. package/docs/ja/specdojo/guides/remote-host-development-guide.md +10 -1
  179. package/docs/ja/specdojo/guides/review-guide.md +1 -1
  180. package/docs/ja/specdojo/guides/routine-operation-guide.md +5 -5
  181. package/docs/ja/specdojo/guides/use-case-guide.md +1 -1
  182. package/docs/ja/specdojo/references/command-reference.md +52 -28
  183. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +17 -11
  184. package/docs/ja/specdojo/standards/job-definition-standard.md +20 -18
  185. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -2
  186. package/docs/ja/specdojo/templates/pjr-derived-items-template.md +22 -0
  187. package/docs/ja/specdojo/templates/pjr-index-template.md +1 -0
  188. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +29 -2
  189. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +20 -0
  190. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +23 -0
  191. package/docs/specdojo/schemas/v1/job-run.schema.yaml +2 -2
  192. package/docs/specdojo/schemas/v1/job.schema.yaml +7 -0
  193. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +26 -0
  194. package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
  195. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +70 -7
  196. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +1 -1
  197. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +1 -1
  198. package/package.json +1 -1
  199. package/templates/antigravity/README.md +5 -1
  200. package/templates/antigravity/agent-members-snippet.yaml +108 -12
  201. package/templates/antigravity/exec-defaults-snippet.yaml +8 -13
  202. package/templates/claude/README.md +27 -3
  203. package/templates/claude/agents/claude-executor.md +0 -1
  204. package/templates/claude/agents/claude-reporter.md +2 -1
  205. package/templates/claude/agents/claude-review-executor.md +0 -1
  206. package/templates/codex/README.md +23 -4
  207. package/templates/devcontainer/devcontainer.json +2 -2
  208. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +69 -0
  209. package/templates/devcontainer/remote-host/ssh-config.sample +16 -0
  210. package/templates/init-agent-members.yaml +75 -25
  211. package/templates/init-exec-defaults.yaml +24 -8
  212. package/templates/opencode/README.md +17 -3
  213. package/templates/opencode/agents/opencode-executor.md +0 -1
  214. package/templates/opencode/agents/opencode-reporter.md +2 -1
  215. package/templates/opencode/agents/opencode-review-executor.md +0 -1
  216. package/dist/exec-schedule-gantt-chart.js +0 -2
  217. package/dist/exec.js +0 -2
  218. package/dist/grade.js +0 -19
  219. package/templates/claude/agents/claude-expert-review-executor.md +0 -14
  220. /package/dist/{catalog-plan-prompt.js → catalog/plan-prompt.js} +0 -0
  221. /package/dist/{catalog-types.js → catalog/types.js} +0 -0
  222. /package/dist/{template-frontmatter.js → docs/template-frontmatter.js} +0 -0
  223. /package/dist/{role-types.js → exec/role-types.js} +0 -0
  224. /package/dist/{exec-schedule-gantt-chart-scope.js → exec/schedule/gantt-chart-scope.js} +0 -0
  225. /package/dist/{exec-types.js → exec/types.js} +0 -0
  226. /package/dist/{grade-command-shared.js → grade/command-shared.js} +0 -0
  227. /package/dist/{register-command-types.js → register/command-types.js} +0 -0
  228. /package/dist/{review-types.js → review/types.js} +0 -0
  229. /package/dist/{schedule-phase-sets.js → schedule/phase-sets.js} +0 -0
  230. /package/dist/{schedule-strategy-profiles.js → schedule/strategy-profiles.js} +0 -0
  231. /package/dist/{agent-response.js → shared/agent-response.js} +0 -0
  232. /package/dist/{catalog-paths.js → shared/catalog-paths.js} +0 -0
  233. /package/dist/{dist-freshness.js → shared/dist-freshness.js} +0 -0
  234. /package/dist/{git-environment.js → shared/git-environment.js} +0 -0
  235. /package/dist/{exec-format.js → shared/markdown-format.js} +0 -0
  236. /package/dist/{practice-id.js → shared/practice-id.js} +0 -0
  237. /package/dist/{spawn-self.js → shared/spawn-self.js} +0 -0
  238. /package/dist/{specdojo-gitignore.js → shared/specdojo-gitignore.js} +0 -0
  239. /package/dist/{template-resolution.js → shared/template-resolution.js} +0 -0
  240. /package/dist/{yaml-schema-modeline.js → shared/yaml-schema-modeline.js} +0 -0
  241. /package/dist/{yaml.js → shared/yaml.js} +0 -0
@@ -1,19 +1,19 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
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";
4
+ import { resolveMemberCommand, resolveRateLimitDetection, resolveRateLimitPolicy, } from "../agent-config.js";
5
+ import { decidePinnedWait, normalizeAgentLimit, } from "../limit.js";
6
+ import { replaceDocIndexRefs } from "../../docs/doc-index.js";
7
+ import { loadPlan, parsePlanTaskIdentity } from "../plans.js";
8
+ import { recordParentValidationFailureOutput, validateResumedTargetCoverage, writeExecutorEvidence, } from "../evidence.js";
9
+ import { parentValidationDisplayCommands, parentValidationGateFor, parentValidationLabels, parentValidationRoots, recordedParentValidationLabel, replaceParentValidationResults, runParentValidationBatch, } from "../parent-validation.js";
10
+ import { getProjectExecutionPath, loadConfig, loadMemberRoster, specdojoRootDir, } from "../../shared/specdojo-config.js";
11
+ import { agentProtectedConfigViolation, captureAgentProtectedConfigAcrossRepos, changedAgentProtectedConfigAcrossRepos, qualifiedRepoPaths, } from "../agent-protected-config.js";
12
+ import { agentGitStateViolation, captureAgentGitStateAcrossRepos, changedAgentGitStateAcrossRepos, qualifiedGitStateFields, } from "../agent-git-state.js";
13
+ import { recordGitStateBlockAcrossRepos, recordProtectedConfigBlockAcrossRepos, } from "../protection-handoff.js";
14
+ import { productRepoEnvironment, productRootsFromEnvironment, withAgentExtraRoots, withoutInheritedRepoEnvironment, } from "../task-repos.js";
15
+ import { gitEnvironment } from "../worktree.js";
16
+ import { isRateLimitError, resolveAgentOverride, selectCandidates, } from "./shared.js";
17
17
  function delay(ms) {
18
18
  return new Promise((resolveDelay) => setTimeout(resolveDelay, ms));
19
19
  }
@@ -133,7 +133,8 @@ and does not block pipeline completion.
133
133
  Use validation status \`not_applicable\` when the repository does not meet a check's applicability
134
134
  conditions, and include a non-empty \`reason\`. The runner carries it into the result without
135
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.
136
+ - \`npm run <script>\` / \`npm test\`: the script exists in package.json. The placeholder \`test\`
137
+ script that \`npm init\` writes (\`echo "Error: no test specified" && exit 1\`) counts as absent.
137
138
  - \`npx <package>\`: the package is in package.json dependencies or devDependencies.
138
139
  - A command that targets a declared product repository (a \`<repo>:<path>\` argument or
139
140
  \`--prefix <repo>\`) is judged by that repository's package.json, not the project repository's.
@@ -360,7 +361,7 @@ export function reportProtectionHandoffRecord(recorded, resultPath) {
360
361
  function rateLimitPrefix(result) {
361
362
  return result === "rate_limit" ? "rate limit reached; " : "";
362
363
  }
363
- export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, resultPath) {
364
+ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, resultPath, pinned) {
364
365
  const policy = resolveRateLimitPolicy(execDefaults, candidates[0]?.provider);
365
366
  let attempts = 0;
366
367
  // PJR-98G4: agentEnvironment が渡したプロダクト worktree を、provider の追加ディレクトリと
@@ -371,20 +372,24 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
371
372
  ...productRoots.map((root) => ({ name: root.name, root: root.path })),
372
373
  ];
373
374
  // One pass tries every candidate in priority order with no wait between switches.
374
- const runPass = async () => {
375
+ const runPass = async (passCandidates = candidates) => {
375
376
  let lastStderr = "";
376
377
  let lastStdout = "";
377
378
  let lastExitCode = null;
378
379
  let lastLimit;
379
- for (let idx = 0; idx < candidates.length; idx++) {
380
+ let lastActor;
381
+ for (let idx = 0; idx < passCandidates.length; idx++) {
380
382
  if (idx > 0) {
381
- process.stdout.write(`Rate limit detected. Switching to next agent (${idx + 1}/${candidates.length})...\n`);
383
+ process.stdout.write(`Rate limit detected. Switching to next agent (${idx + 1}/${passCandidates.length})...\n`);
382
384
  }
383
- const detection = resolveRateLimitDetection(execDefaults, candidates[idx].provider);
385
+ const candidate = passCandidates[idx];
386
+ const detection = resolveRateLimitDetection(execDefaults, candidate.provider);
387
+ const candidatePolicy = resolveRateLimitPolicy(execDefaults, candidate.provider);
384
388
  attempts++;
389
+ lastActor = candidate.actor;
385
390
  const protectedConfigBefore = captureAgentProtectedConfigAcrossRepos(agentRepos);
386
391
  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);
392
+ const attempt = await executeAgent(withAgentExtraRoots(candidate.command, candidate.provider, productRoots.map((root) => root.path)), prompt, detection, candidate.provider, candidatePolicy?.cooldown_seconds, cwd, env);
388
393
  const protectedConfigChanges = changedAgentProtectedConfigAcrossRepos(protectedConfigBefore);
389
394
  if (protectedConfigChanges.length > 0) {
390
395
  // 利用上限で止まった場合も保護の検査は飛ばさない。止まった理由として利用上限を先に記録する。
@@ -402,6 +407,7 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
402
407
  stdout: attempt.stdout,
403
408
  stderr: `${attempt.stderr}${attempt.stderr.endsWith("\n") || !attempt.stderr ? "" : "\n"}${reason}\n`,
404
409
  protectionBlock: true,
410
+ actor: candidate.actor,
405
411
  };
406
412
  }
407
413
  const gitStateChanges = changedAgentGitStateAcrossRepos(gitStateBefore);
@@ -421,6 +427,7 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
421
427
  stdout: attempt.stdout,
422
428
  stderr: `${attempt.stderr}${attempt.stderr.endsWith("\n") || !attempt.stderr ? "" : "\n"}${reason}\n`,
423
429
  protectionBlock: true,
430
+ actor: candidate.actor,
424
431
  };
425
432
  }
426
433
  lastStderr = attempt.stderr;
@@ -433,6 +440,7 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
433
440
  exitCode: attempt.exitCode,
434
441
  stdout: attempt.stdout,
435
442
  stderr: attempt.stderr,
443
+ actor: candidate.actor,
436
444
  };
437
445
  }
438
446
  return {
@@ -441,20 +449,61 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
441
449
  stdout: lastStdout,
442
450
  stderr: lastStderr,
443
451
  limit: lastLimit,
452
+ actor: lastActor,
444
453
  };
445
454
  };
446
- const firstPass = await runPass();
447
- if (firstPass.result !== "rate_limit")
448
- return { ...firstPass, attempts };
455
+ const recoveryEvents = [];
456
+ const firstPass = await runPass(pinned ? candidates.slice(0, 1) : candidates);
457
+ if (firstPass.result !== "rate_limit") {
458
+ return { ...firstPass, attempts, rateLimitEvents: recoveryEvents };
459
+ }
460
+ if (pinned) {
461
+ const primary = candidates[0];
462
+ if (pinned.action === "fallback" && pinned.fallbackCandidate) {
463
+ const fallback = pinned.fallbackCandidate;
464
+ const resumedAt = (pinned.now?.() ?? new Date()).toISOString();
465
+ process.stdout.write(`Rate limit detected for pinned agent ${primary?.actor ?? "-"}. ` +
466
+ `Falling back to ${fallback.actor} at ${resumedAt}.\n`);
467
+ recoveryEvents.push({
468
+ action: "fallback",
469
+ from_actor: primary?.actor ?? "unknown",
470
+ to_actor: fallback.actor,
471
+ resumed_at: resumedAt,
472
+ });
473
+ const fallbackResult = await runPass([fallback]);
474
+ return { ...fallbackResult, attempts, rateLimitEvents: recoveryEvents };
475
+ }
476
+ if (pinned.action === "wait") {
477
+ const decision = decidePinnedWait(firstPass.limit, pinned.now?.() ?? new Date(), pinned.maxWaitSeconds);
478
+ if (decision.action === "wait") {
479
+ const { resumeAt, waitMilliseconds } = decision;
480
+ process.stdout.write(`Rate limit detected for pinned agent ${primary?.actor ?? "-"}. ` +
481
+ `Waiting until ${resumeAt.toISOString()} before resuming the same stage.\n`);
482
+ await (pinned.sleep ?? delay)(waitMilliseconds);
483
+ const resumedAt = (pinned.now?.() ?? new Date()).toISOString();
484
+ recoveryEvents.push({
485
+ action: "wait",
486
+ from_actor: primary?.actor ?? "unknown",
487
+ to_actor: primary?.actor ?? "unknown",
488
+ resume_at: resumeAt.toISOString(),
489
+ resumed_at: resumedAt,
490
+ });
491
+ const resumed = await runPass(candidates.slice(0, 1));
492
+ return { ...resumed, attempts, rateLimitEvents: recoveryEvents };
493
+ }
494
+ process.stdout.write(`${decision.message}\n`);
495
+ }
496
+ return { ...firstPass, attempts, rateLimitEvents: recoveryEvents };
497
+ }
449
498
  // Every candidate is rate-limited. Without a policy we cannot bound further retries, so stop.
450
499
  if (!policy) {
451
500
  process.stdout.write(`Rate limit: all ${candidates.length} agent(s) exhausted.\n`);
452
- return { ...firstPass, attempts };
501
+ return { ...firstPass, attempts, rateLimitEvents: recoveryEvents };
453
502
  }
454
503
  // Session and quota limits do not recover within the short in-process backoff loop. Keep their
455
504
  // explicit reset/cooldown for a later routine invocation instead of sleeping and retrying now.
456
505
  if (firstPass.limit?.kind === "session_limit" || firstPass.limit?.kind === "quota_exhausted") {
457
- return { ...firstPass, attempts };
506
+ return { ...firstPass, attempts, rateLimitEvents: recoveryEvents };
458
507
  }
459
508
  const { retry } = policy.on_critical;
460
509
  let waitSeconds = retry.initial_wait_seconds;
@@ -472,8 +521,9 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
472
521
  lastStdout = result.stdout;
473
522
  lastExitCode = result.exitCode;
474
523
  lastLimit = result.limit;
475
- if (result.result !== "rate_limit")
476
- return { ...result, attempts };
524
+ if (result.result !== "rate_limit") {
525
+ return { ...result, attempts, rateLimitEvents: recoveryEvents };
526
+ }
477
527
  waitSeconds = Math.min(waitSeconds * retry.backoff_multiplier, retry.max_wait_seconds);
478
528
  }
479
529
  process.stdout.write(`Rate limit: all ${candidates.length} agent(s) exhausted after ${retry.max_attempts} attempt(s).\n`);
@@ -484,6 +534,8 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
484
534
  stderr: lastStderr,
485
535
  attempts,
486
536
  limit: lastLimit,
537
+ actor: candidates.at(-1)?.actor,
538
+ rateLimitEvents: recoveryEvents,
487
539
  };
488
540
  }
489
541
  export function pathInsideWorktree(repoRoot, worktreePath, sourcePath) {
@@ -1,25 +1,25 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join, relative, resolve, sep } from "node:path";
4
- import { loadExecDefaultsConfig, resolveMemberCommand, } from "./exec-agent-config.js";
5
- import { activateResolvedProjectPaths, resolveProjectPaths } from "./exec-project.js";
6
- import { randomHex } from "./exec-shared.js";
7
- import { specdojoRootDir } from "./specdojo-config.js";
8
- import { extractLocalId } from "./schedule-phase-sets.js";
9
- import { archivePlan, buildInPlaceStem, generateDeliverablePlan, generateSinglePlan, parsePlanTaskIdentity, resolveDeliverableTarget, finalizeResultSectionsForDeliverable, targetDocIdsForScheduledTask, stemFromPlanPath, } from "./exec-plans.js";
10
- import { buildTaskView } from "./exec-task-view.js";
11
- import { isResultUnfilled, readResultFrontmatterSnapshot, renderReporterResult, scaffoldResult, updateResultStatus, } from "./exec-results.js";
12
- import { gitEnvironment } from "./exec-worktree.js";
13
- import { agentProtectedConfigViolation, captureAgentProtectedConfigSnapshot, changedAgentProtectedConfigPaths, } from "./exec-agent-protected-config.js";
14
- import { agentGitStateViolation, captureAgentGitStateSnapshot, changedAgentGitStateFields, } from "./exec-agent-git-state.js";
15
- import { recordGitStateBlock, recordProtectedConfigBlock } from "./exec-protection-handoff.js";
16
- import { recordExecutorEvidence, recordReporterFailureOutput } from "./exec-evidence.js";
17
- import { deriveReporterFacts, evidenceForReporter, runReporterWithFormatRetry, } from "./exec-reporter.js";
18
- import { createPipelineState, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "./exec-pipeline-state.js";
19
- import { pinnedExecutor, pinnedReporter, resolveExecDefaultsPath, selectCandidates, } from "./exec-run-shared.js";
20
- import { appendParentValidationsToExecutorEvidence, buildExecutorPrompt, executorRequirements, expandPromptRefs, extractBlockReason, loadRosterForExecutionPath, reportProtectionHandoffRecord, resolveReporterAgentCandidates, runWithRetry, } from "./exec-run-agent.js";
21
- import { gradeBeforeReviewPlan } from "./exec-run-schedule-prepare.js";
22
- import { pipelineRecoveryMeta, spawnBlock, spawnClaim, spawnComplete, } from "./exec-run-mode-shared.js";
4
+ import { loadExecDefaultsConfig, resolveMemberCommand, } from "../agent-config.js";
5
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "../project.js";
6
+ import { randomHex } from "../shared.js";
7
+ import { specdojoRootDir, resolveAgentMember, } from "../../shared/specdojo-config.js";
8
+ import { extractLocalId } from "../../schedule/phase-sets.js";
9
+ import { archivePlan, buildInPlaceStem, generateDeliverablePlan, generateSinglePlan, parsePlanTaskIdentity, resolveDeliverableTarget, finalizeResultSectionsForDeliverable, targetDocIdsForScheduledTask, stemFromPlanPath, } from "../plans.js";
10
+ import { buildTaskView } from "../task-view.js";
11
+ import { isResultUnfilled, readResultFrontmatterSnapshot, renderReporterResult, scaffoldResult, updateResultStatus, } from "../results.js";
12
+ import { gitEnvironment } from "../worktree.js";
13
+ import { agentProtectedConfigViolation, captureAgentProtectedConfigSnapshot, changedAgentProtectedConfigPaths, } from "../agent-protected-config.js";
14
+ import { agentGitStateViolation, captureAgentGitStateSnapshot, changedAgentGitStateFields, } from "../agent-git-state.js";
15
+ import { recordGitStateBlock, recordProtectedConfigBlock } from "../protection-handoff.js";
16
+ import { recordExecutorEvidence, recordReporterFailureOutput, writeExecutorEvidence, } from "../evidence.js";
17
+ import { deriveReporterFacts, evidenceForReporter, runReporterWithFormatRetry, } from "../reporter.js";
18
+ import { createPipelineState, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "../pipeline-state.js";
19
+ import { pinnedExecutor, pinnedReporter, resolvePinnedRateLimitRunOptions, resolveExecDefaultsPath, selectCandidates, } from "./shared.js";
20
+ import { appendParentValidationsToExecutorEvidence, buildExecutorPrompt, executorRequirements, expandPromptRefs, extractBlockReason, loadRosterForExecutionPath, reportProtectionHandoffRecord, resolveReporterAgentCandidates, runWithRetry, } from "./agent.js";
21
+ import { gradeBeforeReviewPlan } from "./schedule-prepare.js";
22
+ import { pipelineRecoveryMeta, spawnBlock, spawnClaim, spawnComplete } from "./mode-shared.js";
23
23
  // Resolve the agent command and the actor for an in-place run, ignoring task state. Unlike the
24
24
  // worktree flow, this never requires the task to be claimable. The actor is derived the same way
25
25
  // as the worktree path (`prepareTask`): explicit --by wins, otherwise the resolved member's
@@ -34,17 +34,17 @@ export function resolveInPlaceCommand(task, roster, opts, execDefaults = {}) {
34
34
  ? (opts.executorBy ?? opts.by ?? pinnedExecutor(task))
35
35
  : (opts.by ?? pinnedExecutor(task)))?.trim();
36
36
  if (by) {
37
- const member = roster?.members.find((m) => m.nickname === by && m.type === "agent");
37
+ const member = resolveAgentMember(roster, by);
38
38
  if (task?.agent_pipeline && member?.stage_role !== "executor") {
39
39
  throw new Error(`Agent must have stage_role: executor for this pipeline stage: ${by}`);
40
40
  }
41
41
  const command = member ? resolveMemberCommand(execDefaults, member) : undefined;
42
- if (!command)
42
+ if (!member || !command)
43
43
  throw new Error(`Agent command not found for actor: ${by}`);
44
44
  return {
45
45
  command,
46
- actor: by,
47
- ...(member?.provider ? { provider: member.provider } : {}),
46
+ actor: member.nickname,
47
+ ...(member.provider ? { provider: member.provider } : {}),
48
48
  };
49
49
  }
50
50
  if (task && (task.execution ?? "agent") === "human") {
@@ -91,7 +91,7 @@ export function resolveInPlaceAgentPipeline(task, roster, opts, source) {
91
91
  const by = opts.by?.trim();
92
92
  if (!by)
93
93
  return undefined;
94
- const member = roster?.members.find((m) => m.type === "agent" && m.nickname === by);
94
+ const member = resolveAgentMember(roster, by);
95
95
  if (member?.stage_role === "executor") {
96
96
  throw new Error(`--by ${by} is a pipeline executor agent (stage_role: executor) and does not write the result. ` +
97
97
  `Run ${flag} with --executor-by ${by} --reporter-by <reporter> instead.`);
@@ -356,14 +356,20 @@ export async function runInPlaceMode(opts) {
356
356
  ...gitEnvironment(),
357
357
  SPECDOJO_SCHEDULE_PATH: schedulePath,
358
358
  SPECDOJO_EXECUTION_PATH: executionPath,
359
- }, resultPath);
359
+ }, resultPath, (opts.executorBy ?? opts.by ?? pinnedExecutor(task))
360
+ ? resolvePinnedRateLimitRunOptions(opts, execDefaults, roster, "executor", {
361
+ command,
362
+ actor,
363
+ provider,
364
+ })
365
+ : undefined);
360
366
  const recorded = recordExecutorEvidence({
361
367
  repoRoot,
362
368
  worktreePath: repoRoot,
363
369
  executionPath,
364
370
  taskId: task.id,
365
371
  runId: pipelineRunId,
366
- actor,
372
+ actor: outcome.actor ?? actor,
367
373
  status: outcome.result === "success"
368
374
  ? "succeeded"
369
375
  : outcome.result === "rate_limit"
@@ -375,6 +381,7 @@ export async function runInPlaceMode(opts) {
375
381
  attempts: outcome.attempts,
376
382
  stdout: outcome.stdout,
377
383
  stderr: outcome.stderr,
384
+ rateLimitEvents: outcome.rateLimitEvents,
378
385
  });
379
386
  pipelineEvidenceRef = relative(repoRoot, recorded.evidencePath).split(sep).join("/");
380
387
  const executorCompletedAt = new Date().toISOString();
@@ -387,8 +394,12 @@ export async function runInPlaceMode(opts) {
387
394
  ? "rate_limited"
388
395
  : "failed",
389
396
  attempts: outcome.attempts,
397
+ actor: outcome.actor ?? actor,
390
398
  completed_at: executorCompletedAt,
391
399
  artifact_ref: pipelineEvidenceRef,
400
+ ...(outcome.rateLimitEvents.length > 0
401
+ ? { rate_limit_events: outcome.rateLimitEvents }
402
+ : {}),
392
403
  }, executorCompletedAt);
393
404
  writePipelineState(stateLocation.path, pipelineState);
394
405
  process.stdout.write(`Executor evidence: ${pipelineEvidenceRef}\n`);
@@ -416,6 +427,8 @@ export async function runInPlaceMode(opts) {
416
427
  }, reporterStartedAt);
417
428
  writePipelineState(stateLocation.path, pipelineState);
418
429
  let reporterAttempts = 0;
430
+ let reporterActor = reporterCandidates?.[0]?.actor;
431
+ const reporterRateLimitEvents = [];
419
432
  process.stdout.write(`Running reporter: ${reporterCandidates?.[0]?.command ?? ""}\n`);
420
433
  const reporter = await runReporterWithFormatRetry({
421
434
  plan: planPrompt,
@@ -426,8 +439,12 @@ export async function runInPlaceMode(opts) {
426
439
  ...gitEnvironment(),
427
440
  SPECDOJO_SCHEDULE_PATH: schedulePath,
428
441
  SPECDOJO_EXECUTION_PATH: executionPath,
429
- }, resultPath);
442
+ }, resultPath, (opts.reporterBy ?? pinnedReporter(task))
443
+ ? resolvePinnedRateLimitRunOptions(opts, execDefaults, roster, "reporter", reporterCandidates[0])
444
+ : undefined);
430
445
  reporterAttempts += reporterOutcome.attempts;
446
+ reporterActor = reporterOutcome.actor ?? reporterActor;
447
+ reporterRateLimitEvents.push(...reporterOutcome.rateLimitEvents);
431
448
  return {
432
449
  result: reporterOutcome.result,
433
450
  stdout: reporterOutcome.stdout,
@@ -435,6 +452,14 @@ export async function runInPlaceMode(opts) {
435
452
  };
436
453
  },
437
454
  });
455
+ if (reporterRateLimitEvents.length > 0) {
456
+ recorded.evidence.rate_limit_events = [
457
+ ...(recorded.evidence.rate_limit_events ?? []),
458
+ ...reporterRateLimitEvents,
459
+ ];
460
+ reporterEvidence.rate_limit_events = recorded.evidence.rate_limit_events;
461
+ writeExecutorEvidence(recorded.evidencePath, recorded.evidence);
462
+ }
438
463
  if (reporter.result === "success" && resultPath) {
439
464
  try {
440
465
  await renderReporterResult(resultPath, reporter.output, reporterEvidence);
@@ -473,10 +498,14 @@ export async function runInPlaceMode(opts) {
473
498
  ? "rate_limited"
474
499
  : "failed",
475
500
  attempts: reporterAttempts,
501
+ actor: reporterActor ?? null,
476
502
  completed_at: reporterCompletedAt,
477
503
  artifact_ref: reporter.result === "success" && resultPath
478
504
  ? relative(repoRoot, resultPath).split(sep).join("/")
479
505
  : null,
506
+ ...(reporterRateLimitEvents.length > 0
507
+ ? { rate_limit_events: reporterRateLimitEvents }
508
+ : {}),
480
509
  }, reporterCompletedAt);
481
510
  writePipelineState(stateLocation.path, pipelineState);
482
511
  }
@@ -1,23 +1,23 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { relative, resolve, sep } from "node:path";
4
- import { selfRunArgs } from "./spawn-self.js";
5
- import { loadExecDefaultsConfig, resolveMemberCommand, } from "./exec-agent-config.js";
6
- import { activateResolvedProjectPaths, resolveProjectPaths } from "./exec-project.js";
7
- import { specdojoRootDir } from "./specdojo-config.js";
8
- import { ROUTINE_BUSY_SKIP_EXIT_CODE, ROUTINE_EXEC_ENV } from "./exec-run-lock.js";
9
- import { isResultUnfilled, readResultFrontmatterSnapshot, renderReporterResult, scaffoldResult, updateResultStatus, } from "./exec-results.js";
10
- import { formatMarkdownFile } from "./exec-format.js";
11
- import { completeJobRun, executeJobCommand, generateJobReviewPlan, isJobCommandTask, jobRunUsesReviewedIntegration, loadJobDefinition, loadJobRunRecord, materializeJobRun, recordJobRunReview, resolveJobPaths, resolveJobReviewAgentNominations, } from "./job.js";
12
- import { ensureExecWorktree, gitOutput, gitResult, resolveWorktreeBase, summarizeGitHookFailure, } from "./exec-worktree.js";
13
- import { mergeWorktreeIntoCurrent, removeWorktree, stabilizeCommitTargets, stageCommitTargets, worktreeStatusPaths, } from "./exec-worktree-ops.js";
14
- import { recordCommandEvidence } from "./exec-evidence.js";
15
- import { evidenceForReporter } from "./exec-reporter.js";
16
- import { createPipelineState, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "./exec-pipeline-state.js";
17
- import { configuredWorktreeBase, resolveAgentOverride, resolveExecDefaultsPath, selectCandidates, } from "./exec-run-shared.js";
18
- import { executorRequirements, expandPromptRefs, loadRosterForExecutionPath, resolveReporterAgentCandidates, } from "./exec-run-agent.js";
19
- import { runAgentPipeline, runReporterStage } from "./exec-run-agent-pipeline.js";
20
- import { resolveInPlaceCommand, spawnAgentInPlace } from "./exec-run-in-place.js";
4
+ import { selfRunArgs } from "../../shared/spawn-self.js";
5
+ import { loadExecDefaultsConfig, resolveMemberCommand, } from "../agent-config.js";
6
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "../project.js";
7
+ import { specdojoRootDir } from "../../shared/specdojo-config.js";
8
+ import { ROUTINE_BUSY_SKIP_EXIT_CODE, ROUTINE_EXEC_ENV } from "./lock.js";
9
+ import { isResultUnfilled, readResultFrontmatterSnapshot, renderReporterResult, scaffoldResult, updateResultStatus, } from "../results.js";
10
+ import { formatMarkdownFile } from "../format.js";
11
+ import { completeJobRun, executeJobCommand, generateJobReviewPlan, isJobCommandTask, jobRunUsesReviewedIntegration, loadJobDefinition, loadJobRunRecord, materializeJobRun, recordJobRunReview, resolveJobPaths, resolveJobReviewAgentNominations, } from "../../job/job.js";
12
+ import { ensureExecWorktree, formatGitResultFailure, gitOutput, gitResult, resolveWorktreeBase, summarizeGitHookFailure, } from "../worktree.js";
13
+ import { mergeWorktreeIntoCurrent, removeWorktree, stabilizeCommitTargets, stageCommitTargets, worktreeStatusPaths, } from "../worktree-ops.js";
14
+ import { recordCommandEvidence } from "../evidence.js";
15
+ import { evidenceForReporter } from "../reporter.js";
16
+ import { createPipelineState, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "../pipeline-state.js";
17
+ import { configuredWorktreeBase, resolveAgentOverride, resolveExecDefaultsPath, selectCandidates, } from "./shared.js";
18
+ import { executorRequirements, expandPromptRefs, loadRosterForExecutionPath, resolveReporterAgentCandidates, } from "./agent.js";
19
+ import { runAgentPipeline, runReporterStage } from "./agent-pipeline.js";
20
+ import { resolveInPlaceCommand, spawnAgentInPlace } from "./in-place.js";
21
21
  async function runCommandJobMode(params) {
22
22
  const { opts, record, runPath, planPath, projectId, schedulePath, executionPath } = params;
23
23
  if (!isJobCommandTask(record.task))
@@ -80,6 +80,9 @@ async function runCommandJobMode(params) {
80
80
  const evidenceRunId = `attempt-${record.attempts.length}`;
81
81
  process.stdout.write(`Running Job Run ${record.run_id} command in place.\n`);
82
82
  const commandOutcome = await executeJobCommand(record.task.command, repoRoot);
83
+ const commandPartial = !commandOutcome.error &&
84
+ record.task.partial_exit_code !== undefined &&
85
+ commandOutcome.exitCode === record.task.partial_exit_code;
83
86
  const recorded = recordCommandEvidence({
84
87
  repoRoot,
85
88
  worktreePath: repoRoot,
@@ -96,19 +99,21 @@ async function runCommandJobMode(params) {
96
99
  stderr: commandOutcome.stderr,
97
100
  stdoutTruncated: commandOutcome.stdoutTruncated,
98
101
  stderrTruncated: commandOutcome.stderrTruncated,
102
+ accepted: commandPartial,
99
103
  ...(commandOutcome.error ? { error: commandOutcome.error } : {}),
100
104
  });
101
105
  const evidenceRef = relative(repoRoot, recorded.evidencePath).split(sep).join("/");
102
106
  process.stdout.write(`Command evidence: ${evidenceRef}\n`);
103
107
  const commandSucceeded = commandOutcome.exitCode === 0 && !commandOutcome.error;
104
- if (!commandSucceeded || !analysisCandidate) {
108
+ const commandAccepted = commandSucceeded || commandPartial;
109
+ if (!commandAccepted || !analysisCandidate) {
105
110
  const reporterEvidence = evidenceForReporter(recorded.evidence, {
106
111
  repoRoot,
107
112
  worktreePath: repoRoot,
108
113
  executionPath,
109
114
  resultPath,
110
115
  });
111
- const reason = commandSucceeded
116
+ const reason = commandAccepted
112
117
  ? undefined
113
118
  : commandOutcome.error
114
119
  ? `command spawn failed: ${commandOutcome.error}`
@@ -119,7 +124,9 @@ async function runCommandJobMode(params) {
119
124
  summary: [
120
125
  commandSucceeded
121
126
  ? "runner が解決済みコマンドを直接実行し、終了コード 0 を確認した。"
122
- : `runner が解決済みコマンドを直接実行したが、${reason}。`,
127
+ : commandPartial
128
+ ? `runner が解決済みコマンドを直接実行し、部分成功の終了コード ${commandOutcome.exitCode} を確認した。`
129
+ : `runner が解決済みコマンドを直接実行したが、${reason}。`,
123
130
  ],
124
131
  changed_files: reporterEvidence.changes.map(({ path }) => ({
125
132
  path,
@@ -128,11 +135,11 @@ async function runCommandJobMode(params) {
128
135
  handoff: [`command evidence: ${evidenceRef}`],
129
136
  approach: "Job Definition から materialize したコマンドを agent の解釈を介さず実行し、runner evidence を正本とした。",
130
137
  }, reporterEvidence);
131
- await updateResultStatus(resultPath, commandSucceeded ? "complete" : "blocked", new Date().toISOString(), reason);
138
+ await updateResultStatus(resultPath, commandAccepted ? "complete" : "blocked", new Date().toISOString(), reason);
132
139
  completeJobRun({
133
140
  projectId,
134
141
  runPath,
135
- status: commandSucceeded ? "succeeded" : "failed",
142
+ status: commandSucceeded ? "succeeded" : commandPartial ? "partial" : "failed",
136
143
  evidenceRef,
137
144
  exitCode: commandOutcome.exitCode,
138
145
  ...(reason ? { reason } : {}),
@@ -140,6 +147,12 @@ async function runCommandJobMode(params) {
140
147
  if (commandSucceeded) {
141
148
  process.stdout.write(`Job Run complete: ${record.run_id}\n`);
142
149
  }
150
+ else if (commandPartial) {
151
+ process.stdout.write(`Job Run partial: ${record.run_id}\n`);
152
+ if (record.trigger === "routine") {
153
+ process.stdout.write(`[routine-job] complete run_id=${record.run_id} state=partial\n`);
154
+ }
155
+ }
143
156
  else {
144
157
  process.stdout.write(`Job Run failed: ${record.run_id}\n`);
145
158
  process.exitCode = commandOutcome.exitCode || 1;
@@ -191,13 +204,16 @@ async function runCommandJobMode(params) {
191
204
  completeJobRun({
192
205
  projectId,
193
206
  runPath,
194
- status: reporterOutcome.exitCode === 0 ? "succeeded" : "failed",
207
+ status: reporterOutcome.exitCode === 0 ? (commandPartial ? "partial" : "succeeded") : "failed",
195
208
  evidenceRef,
196
209
  exitCode: commandOutcome.exitCode,
197
210
  ...(reason ? { reason } : {}),
198
211
  });
199
212
  if (reporterOutcome.exitCode === 0) {
200
- process.stdout.write(`Job Run complete: ${record.run_id}\n`);
213
+ process.stdout.write(`Job Run ${commandPartial ? "partial" : "complete"}: ${record.run_id}\n`);
214
+ if (commandPartial && record.trigger === "routine") {
215
+ process.stdout.write(`[routine-job] complete run_id=${record.run_id} state=partial\n`);
216
+ }
201
217
  }
202
218
  else {
203
219
  process.stdout.write(`Job Run failed: ${record.run_id}\n`);
@@ -205,6 +221,13 @@ async function runCommandJobMode(params) {
205
221
  }
206
222
  }
207
223
  const ACCEPTED_JOB_REVIEW_VERDICTS = new Set(["complete", "complete-with-findings"]);
224
+ function acceptsJobReview(record, verdict) {
225
+ if (!verdict)
226
+ return false;
227
+ if (record.state === "partial")
228
+ return verdict === "complete-with-findings";
229
+ return record.state === "succeeded" && ACCEPTED_JOB_REVIEW_VERDICTS.has(verdict);
230
+ }
208
231
  function jobChildArgs(opts, projectId, scheduledAt) {
209
232
  const args = ["exec", "run", "--job", String(opts.job), "--project", projectId];
210
233
  const inputs = Array.isArray(opts.input) ? opts.input : opts.input ? [opts.input] : [];
@@ -226,11 +249,13 @@ function commitJobPaths(worktreePath, paths, subject, body) {
226
249
  if (unique.length === 0)
227
250
  throw new Error("Job Run produced no tracked output to commit.");
228
251
  stageCommitTargets(worktreePath, unique);
229
- const staged = gitResult(worktreePath, ["diff", "--cached", "--quiet", "--", ...unique]);
252
+ const stagedArgs = ["diff", "--cached", "--quiet", "--", ...unique];
253
+ const staged = gitResult(worktreePath, stagedArgs);
230
254
  if (staged.status === 0)
231
255
  throw new Error("Job Run output has no staged changes.");
232
- if (staged.status !== 1)
233
- throw new Error("Failed to inspect staged Job Run output.");
256
+ if (staged.status !== 1) {
257
+ throw new Error(`Failed to inspect staged Job Run output: ${formatGitResultFailure(stagedArgs, staged)}`);
258
+ }
234
259
  const commit = gitResult(worktreePath, ["commit", "-m", subject, "-m", body, "--", ...unique]);
235
260
  if (commit.status !== 0) {
236
261
  const output = [commit.stdout, commit.stderr]
@@ -358,6 +383,9 @@ async function runJobWorktreeMode(opts) {
358
383
  });
359
384
  if (preview.duplicateComplete) {
360
385
  process.stdout.write(`Job Run already complete: ${preview.record.run_id} (${preview.record.state})\n`);
386
+ if (trigger === "routine" && preview.record.state === "partial") {
387
+ process.stdout.write(`[routine-job] complete run_id=${preview.record.run_id} state=partial\n`);
388
+ }
361
389
  return;
362
390
  }
363
391
  if (opts.dryRun) {
@@ -514,7 +542,7 @@ async function runJobWorktreeMode(opts) {
514
542
  verdict = "changed-during-review";
515
543
  await overrideJobReviewDecision(resultPath, verdict, reviewReason);
516
544
  }
517
- if (unexpected.length === 0 && record.state !== "succeeded") {
545
+ if (unexpected.length === 0 && record.state !== "succeeded" && record.state !== "partial") {
518
546
  reviewReason = record.attempts.at(-1)?.reason ?? `Job Run state is ${record.state}`;
519
547
  verdict = "incomplete";
520
548
  await overrideJobReviewDecision(resultPath, verdict, reviewReason);
@@ -532,14 +560,12 @@ async function runJobWorktreeMode(opts) {
532
560
  const committableReviewPaths = worktreeStatusPaths(worktree.path).filter((path) => allowedReviewFiles.has(path) ||
533
561
  allowedReviewPrefixes.some((prefix) => path.startsWith(prefix)));
534
562
  commitJobPaths(worktree.path, committableReviewPaths, `chore(routine): review ${record.run_id}`, `Job Run: ${record.run_id}\nState: ${record.state}\nVerdict: ${verdict ?? "unavailable"}`);
535
- const accepted = record.state === "succeeded" &&
536
- verdict !== undefined &&
537
- ACCEPTED_JOB_REVIEW_VERDICTS.has(verdict) &&
538
- unexpected.length === 0;
563
+ const accepted = acceptsJobReview(record, verdict) && unexpected.length === 0;
539
564
  if (!accepted) {
540
- const reason = record.state !== "succeeded"
565
+ const reason = record.state !== "succeeded" && record.state !== "partial"
541
566
  ? `Job Run state is ${record.state}`
542
- : (reviewReason ?? `review verdict is ${verdict ?? "unavailable"}`);
567
+ : (reviewReason ??
568
+ `review verdict ${verdict ?? "unavailable"} is not accepted for Job Run state ${record.state}`);
543
569
  process.stdout.write(`[routine-job] waiting run_id=${record.run_id} review=${verdict ?? "unavailable"} worktree=${worktree.path} reason=${reason}\n`);
544
570
  process.exitCode = child.status || 1;
545
571
  return;
@@ -556,7 +582,7 @@ async function runJobWorktreeMode(opts) {
556
582
  taskId: reviewTaskId,
557
583
  deleteBranch: true,
558
584
  });
559
- process.stdout.write(`[routine-job] merged run_id=${record.run_id} review=${verdict} branch=${worktree.branch}\n`);
585
+ process.stdout.write(`[routine-job] merged run_id=${record.run_id} state=${record.state} review=${verdict} branch=${worktree.branch}\n`);
560
586
  }
561
587
  export async function runJobMode(opts, resolvePipelineAgents) {
562
588
  const resolvedPaths = resolveProjectPaths({ project: opts.project });
@@ -598,6 +624,9 @@ export async function runJobMode(opts, resolvePipelineAgents) {
598
624
  }
599
625
  if (materialized.duplicateComplete) {
600
626
  process.stdout.write(`Job Run already complete: ${record.run_id} (${record.state})\n`);
627
+ if (trigger === "routine" && record.state === "partial") {
628
+ process.stdout.write(`[routine-job] complete run_id=${record.run_id} state=partial\n`);
629
+ }
601
630
  return;
602
631
  }
603
632
  if (isJobCommandTask(record.task)) {