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,572 @@
1
+ import { relative, resolve, sep } from "node:path";
2
+ import { limitEventMeta } from "./exec-limit.js";
3
+ import { readResultFrontmatterSnapshot, renderReporterResult, updateResultStatus, } from "./exec-results.js";
4
+ import { gitOutput } from "./exec-worktree.js";
5
+ import { withProductRepoPrompt } from "./exec-task-repos.js";
6
+ import { commitTargetPaths, commitWorktreeChanges, isExecBranchMergedIntoCurrent, mergeWorktreeIntoCurrent, releaseRootWorkingCopies, removeWorktree, taskTargetsAtHead, WorktreeRemovedBranchDeletionError, worktreeStatusPaths, } from "./exec-worktree-ops.js";
7
+ import { commitProductWorktrees, integrateTaskRepositories, projectMergeBlockers, PROJECT_REPO_NAME, RepoIntegrationError, } from "./exec-repo-integration.js";
8
+ import { recordExecutorEvidence, recordReporterFailureOutput } from "./exec-evidence.js";
9
+ import { deriveReporterFacts, evidenceForReporter, runReporterWithFormatRetry, } from "./exec-reporter.js";
10
+ import { createPipelineState, loadPipelineResumeCheckpoint, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "./exec-pipeline-state.js";
11
+ import { agentEnvironment, appendParentValidationsToExecutorEvidence, buildExecutorPrompt, extractBlockReason, pathInsideWorktree, resumedTargetCoverageFailure, runWithRetry, } from "./exec-run-agent.js";
12
+ import { refreshParentValidationsForReporterResume } from "./exec-run-agent-pipeline.js";
13
+ import { downgradeUnfilledResult, readCompletionPreflight, } from "./exec-run-schedule-prepare.js";
14
+ import { commitSubject, integrateLogPath, pipelineRecoveryMeta, recordIntegrateStage, recordRepoIntegration, repoRelativePath, spawnBlock, spawnComplete, } from "./exec-run-mode-shared.js";
15
+ export async function runPreparedTask(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun, lifecycleLock) {
16
+ if (dryRun)
17
+ return "success";
18
+ const worktreeResultPath = prepared.resultPath
19
+ ? pathInsideWorktree(repoRoot, prepared.worktree.path, prepared.resultPath)
20
+ : undefined;
21
+ // A resumed worktree may legitimately contain runner-owned blocked lifecycle fields that differ
22
+ // from the root checkpoint. Use the actual pre-run result for this attempt's exact comparison,
23
+ // while retaining the root scaffold below to reject changes to immutable fields across attempts.
24
+ const attemptResultScaffold = worktreeResultPath
25
+ ? readResultFrontmatterSnapshot(worktreeResultPath)
26
+ : undefined;
27
+ process.stdout.write(` CWD: ${prepared.worktree.path}\n`);
28
+ let result = "success";
29
+ let stderr = "";
30
+ let exitCode = 0;
31
+ let stdout = "";
32
+ let attempts = 0;
33
+ let limit;
34
+ let executorEvidenceRef;
35
+ let executorEvidencePath;
36
+ let executorEvidence;
37
+ let pipelineFailureStage = "executor";
38
+ let pipelineBlockReason;
39
+ let reporterLimit;
40
+ let reporterAttempts = 0;
41
+ let pipelineState;
42
+ let pipelineStatePath;
43
+ let pipelineStateRef;
44
+ let resumeReporter = false;
45
+ let resumeIntegration = false;
46
+ if (!prepared.pipelineRunId) {
47
+ process.stdout.write(` Running: ${prepared.agentCandidates[0]?.command ?? ""}\n`);
48
+ const outcome = await runWithRetry(prepared.agentCandidates, withProductRepoPrompt(prepared.prompt, prepared.worktree.repos), execDefaults, prepared.worktree.path, agentEnvironment(repoRoot, prepared.worktree.path, schedulePath, executionPath, prepared.worktree.repos), worktreeResultPath);
49
+ result = outcome.result;
50
+ stderr = outcome.stderr;
51
+ exitCode = outcome.exitCode;
52
+ stdout = outcome.stdout;
53
+ attempts = outcome.attempts;
54
+ limit = outcome.limit;
55
+ }
56
+ if (prepared.pipelineRunId && prepared.pipelineStateRef) {
57
+ const checkpoint = loadPipelineResumeCheckpoint({
58
+ worktreePath: prepared.worktree.path,
59
+ stateRef: prepared.pipelineStateRef,
60
+ taskId: prepared.task.id,
61
+ });
62
+ if (checkpoint) {
63
+ pipelineState = checkpoint.state;
64
+ pipelineStatePath = checkpoint.statePath;
65
+ pipelineStateRef = prepared.pipelineStateRef;
66
+ if (prepared.pipelineResumeStage === "integrate") {
67
+ if (checkpoint.state.stages.executor.status !== "succeeded" ||
68
+ checkpoint.state.stages.reporter.status !== "succeeded") {
69
+ throw new Error(`integration resume requires succeeded executor and reporter stages for ${prepared.task.id}`);
70
+ }
71
+ executorEvidenceRef = checkpoint.state.stages.executor.artifact_ref ?? undefined;
72
+ resumeIntegration = true;
73
+ process.stdout.write(` Resuming runner-owned integration from pipeline state: ${prepared.pipelineStateRef}\n`);
74
+ }
75
+ else if (prepared.pipelineResumeStage === "reporter" &&
76
+ checkpoint.evidence &&
77
+ checkpoint.state.stages.executor.artifact_ref) {
78
+ executorEvidence = checkpoint.evidence;
79
+ executorEvidenceRef = checkpoint.state.stages.executor.artifact_ref;
80
+ executorEvidencePath = resolve(prepared.worktree.path, executorEvidenceRef);
81
+ resumeReporter = true;
82
+ process.stdout.write(` Resuming reporter from persisted executor evidence: ${executorEvidenceRef}\n`);
83
+ executorEvidence = await refreshParentValidationsForReporterResume({
84
+ execDefaults,
85
+ cwd: prepared.worktree.path,
86
+ productWorktrees: prepared.worktree.repos,
87
+ evidence: executorEvidence,
88
+ evidencePath: executorEvidencePath,
89
+ });
90
+ }
91
+ else if (prepared.pipelineResumeStage === "reporter") {
92
+ process.stdout.write(" Persisted executor evidence is invalid; starting a new executor run.\n");
93
+ pipelineState = undefined;
94
+ pipelineStatePath = undefined;
95
+ pipelineStateRef = undefined;
96
+ }
97
+ }
98
+ }
99
+ if (prepared.pipelineResumeStage === "integrate" && !resumeIntegration) {
100
+ throw new Error(`pipeline state is missing or invalid for integration resume: ${prepared.task.id}`);
101
+ }
102
+ if (prepared.pipelineRunId && !pipelineState) {
103
+ const now = new Date().toISOString();
104
+ const location = pipelineStateLocation({
105
+ repoRoot,
106
+ worktreePath: prepared.worktree.path,
107
+ executionPath,
108
+ taskId: prepared.task.id,
109
+ runId: prepared.pipelineRunId,
110
+ });
111
+ pipelineState = createPipelineState({
112
+ taskId: prepared.task.id,
113
+ runId: prepared.pipelineRunId,
114
+ updatedAt: now,
115
+ executorActor: prepared.agentCandidates[0]?.actor ?? prepared.actor,
116
+ reporterActor: prepared.reporterCandidates?.[0]?.actor,
117
+ });
118
+ pipelineStatePath = location.path;
119
+ pipelineStateRef = location.ref;
120
+ writePipelineState(pipelineStatePath, pipelineState);
121
+ }
122
+ if (prepared.pipelineRunId &&
123
+ !resumeReporter &&
124
+ !resumeIntegration &&
125
+ pipelineState &&
126
+ pipelineStatePath) {
127
+ const executorStartedAt = new Date().toISOString();
128
+ pipelineState = updatePipelineStage(pipelineState, "executor", {
129
+ status: "running",
130
+ actor: prepared.agentCandidates[0]?.actor ?? prepared.actor,
131
+ started_at: executorStartedAt,
132
+ completed_at: null,
133
+ }, executorStartedAt);
134
+ writePipelineState(pipelineStatePath, pipelineState);
135
+ process.stdout.write(` Running executor: ${prepared.agentCandidates[0]?.command ?? ""}\n`);
136
+ const executorPrompt = prepared.pipelineResumeStage === "executor"
137
+ ? buildExecutorPrompt(prepared.plan, execDefaults.pipeline?.parent_validations, {
138
+ resumed: true,
139
+ existingChanges: worktreeStatusPaths(prepared.worktree.path),
140
+ })
141
+ : prepared.prompt;
142
+ const executorOutcome = await runWithRetry(prepared.agentCandidates, withProductRepoPrompt(executorPrompt, prepared.worktree.repos), execDefaults, prepared.worktree.path, agentEnvironment(repoRoot, prepared.worktree.path, schedulePath, executionPath, prepared.worktree.repos), worktreeResultPath);
143
+ result = executorOutcome.result;
144
+ stderr = executorOutcome.stderr;
145
+ exitCode = executorOutcome.exitCode;
146
+ stdout = executorOutcome.stdout;
147
+ attempts = executorOutcome.attempts;
148
+ limit = executorOutcome.limit;
149
+ const recorded = recordExecutorEvidence({
150
+ repoRoot,
151
+ worktreePath: prepared.worktree.path,
152
+ executionPath,
153
+ taskId: prepared.task.id,
154
+ runId: pipelineState.run_id,
155
+ actor: prepared.actor,
156
+ status: result === "success" ? "succeeded" : result === "rate_limit" ? "rate_limited" : "failed",
157
+ startedAt: executorStartedAt,
158
+ completedAt: new Date().toISOString(),
159
+ exitCode,
160
+ attempts,
161
+ stdout,
162
+ stderr,
163
+ productWorktrees: prepared.worktree.repos,
164
+ });
165
+ executorEvidenceRef = relative(prepared.worktree.path, recorded.evidencePath)
166
+ .split(sep)
167
+ .join("/");
168
+ executorEvidencePath = recorded.evidencePath;
169
+ executorEvidence = recorded.evidence;
170
+ const coverageFailure = result === "success"
171
+ ? resumedTargetCoverageFailure({
172
+ resumed: prepared.pipelineResumeStage === "executor",
173
+ plan: prepared.plan,
174
+ evidence: executorEvidence,
175
+ evidencePath: executorEvidencePath,
176
+ })
177
+ : undefined;
178
+ if (result === "success" && coverageFailure) {
179
+ result = "failure";
180
+ stderr = coverageFailure;
181
+ pipelineBlockReason = coverageFailure;
182
+ }
183
+ const executorCompletedAt = new Date().toISOString();
184
+ pipelineState = updatePipelineStage(pipelineState, "executor", {
185
+ status: result === "success"
186
+ ? "succeeded"
187
+ : executorOutcome.protectionBlock
188
+ ? "blocked"
189
+ : result === "rate_limit"
190
+ ? "rate_limited"
191
+ : "failed",
192
+ attempts: pipelineState.stages.executor.attempts + attempts,
193
+ completed_at: executorCompletedAt,
194
+ artifact_ref: executorEvidenceRef,
195
+ }, executorCompletedAt);
196
+ writePipelineState(pipelineStatePath, pipelineState);
197
+ process.stdout.write(` Executor evidence: ${executorEvidenceRef}\n`);
198
+ if (result === "success") {
199
+ executorEvidence = await appendParentValidationsToExecutorEvidence({
200
+ execDefaults,
201
+ cwd: prepared.worktree.path,
202
+ productWorktrees: prepared.worktree.repos,
203
+ evidence: executorEvidence,
204
+ evidencePath: executorEvidencePath,
205
+ });
206
+ }
207
+ }
208
+ if (prepared.pipelineRunId && result === "success" && !resumeIntegration) {
209
+ pipelineFailureStage = "reporter";
210
+ if (!executorEvidence ||
211
+ !worktreeResultPath ||
212
+ !prepared.reporterCandidates?.length ||
213
+ !pipelineState ||
214
+ !pipelineStatePath) {
215
+ result = "failure";
216
+ pipelineBlockReason = "reporter stage could not start because its managed inputs are missing";
217
+ stderr = pipelineBlockReason;
218
+ }
219
+ else {
220
+ const reporterEvidence = evidenceForReporter(executorEvidence, {
221
+ repoRoot,
222
+ worktreePath: prepared.worktree.path,
223
+ executionPath,
224
+ resultPath: worktreeResultPath,
225
+ });
226
+ const reporterStartedAt = new Date().toISOString();
227
+ pipelineState = updatePipelineStage(pipelineState, "reporter", {
228
+ status: "running",
229
+ actor: prepared.reporterCandidates[0].actor ?? null,
230
+ started_at: reporterStartedAt,
231
+ completed_at: null,
232
+ }, reporterStartedAt);
233
+ writePipelineState(pipelineStatePath, pipelineState);
234
+ process.stdout.write(` Running reporter: ${prepared.reporterCandidates[0].command}\n`);
235
+ const reporter = await runReporterWithFormatRetry({
236
+ plan: prepared.plan,
237
+ evidence: reporterEvidence,
238
+ mode: prepared.task.mode ?? "edit",
239
+ invoke: async (reporterPrompt) => {
240
+ const outcome = await runWithRetry(prepared.reporterCandidates ?? [], reporterPrompt, execDefaults, prepared.worktree.path, agentEnvironment(repoRoot, prepared.worktree.path, schedulePath, executionPath, prepared.worktree.repos), worktreeResultPath);
241
+ reporterAttempts += outcome.attempts;
242
+ if (outcome.limit)
243
+ reporterLimit = outcome.limit;
244
+ return { result: outcome.result, stdout: outcome.stdout, stderr: outcome.stderr };
245
+ },
246
+ });
247
+ if (reporter.result === "success") {
248
+ try {
249
+ await renderReporterResult(worktreeResultPath, reporter.output, reporterEvidence);
250
+ const facts = deriveReporterFacts(reporterEvidence, {
251
+ mode: prepared.task.mode ?? "edit",
252
+ });
253
+ result = facts.outcome === "complete" ? "success" : "failure";
254
+ pipelineBlockReason = facts.block_reason || undefined;
255
+ if (pipelineBlockReason)
256
+ stderr = pipelineBlockReason;
257
+ process.stdout.write(` Reporter complete: ${prepared.reporterCandidates[0].actor ?? "reporter"} (format attempts: ${reporter.formatAttempts})\n`);
258
+ if (result === "success") {
259
+ const reporterCompletedAt = new Date().toISOString();
260
+ pipelineState = updatePipelineStage(pipelineState, "reporter", {
261
+ status: "succeeded",
262
+ attempts: pipelineState.stages.reporter.attempts + reporterAttempts,
263
+ completed_at: reporterCompletedAt,
264
+ artifact_ref: relative(prepared.worktree.path, worktreeResultPath)
265
+ .split(sep)
266
+ .join("/"),
267
+ }, reporterCompletedAt);
268
+ writePipelineState(pipelineStatePath, pipelineState);
269
+ }
270
+ }
271
+ catch (error) {
272
+ result = "failure";
273
+ pipelineBlockReason =
274
+ error instanceof Error
275
+ ? `reporter result rendering failed: ${error.message}`
276
+ : String(error);
277
+ stderr = pipelineBlockReason;
278
+ }
279
+ }
280
+ else {
281
+ result = reporter.result;
282
+ pipelineBlockReason = reporter.reason;
283
+ stderr = reporter.reason;
284
+ if (executorEvidencePath) {
285
+ executorEvidence = recordReporterFailureOutput({
286
+ worktreePath: prepared.worktree.path,
287
+ evidencePath: executorEvidencePath,
288
+ evidence: executorEvidence,
289
+ invocationOutputs: reporter.invocationOutputs,
290
+ });
291
+ }
292
+ }
293
+ if (result !== "success") {
294
+ const reporterCompletedAt = new Date().toISOString();
295
+ pipelineState = updatePipelineStage(pipelineState, "reporter", {
296
+ status: result === "rate_limit" ? "rate_limited" : "failed",
297
+ attempts: pipelineState.stages.reporter.attempts + reporterAttempts,
298
+ completed_at: reporterCompletedAt,
299
+ artifact_ref: reporter.result === "success"
300
+ ? relative(prepared.worktree.path, worktreeResultPath).split(sep).join("/")
301
+ : pipelineState.stages.reporter.artifact_ref,
302
+ }, reporterCompletedAt);
303
+ writePipelineState(pipelineStatePath, pipelineState);
304
+ }
305
+ }
306
+ }
307
+ const finalize = async () => {
308
+ const completedAt = new Date().toISOString();
309
+ const context = {
310
+ repoRoot,
311
+ schedulePath,
312
+ executionPath,
313
+ ...(catalogPath ? { catalogPath } : {}),
314
+ };
315
+ const downgraded = downgradeUnfilledResult(result, worktreeResultPath, prepared.task.mode ?? "edit", attemptResultScaffold, prepared.resultScaffold);
316
+ const effectiveResult = downgraded.result;
317
+ const unfilledBlock = downgraded.unfilledBlock;
318
+ if (effectiveResult === "success") {
319
+ // Validate the same state/actor constraints as `exec complete` before touching Git. In
320
+ // particular, resume --by may run a different agent from the one that owns the claim; if we
321
+ // merged first, the subsequent complete command would reject that actor and leave schedule
322
+ // state at doing even though the deliverables had already landed and the worktree was gone.
323
+ const completionPreflight = readCompletionPreflight(schedulePath, prepared.task.id, prepared.actor);
324
+ if (!completionPreflight.ok) {
325
+ const reason = `completion preflight failed: ${completionPreflight.reason ?? "unknown reason"}`;
326
+ process.stderr.write(`${reason}\n`);
327
+ process.stdout.write(` Blocked before integration: ${prepared.task.id} (worktree kept: ${prepared.worktree.path})\n`);
328
+ return "failure";
329
+ }
330
+ // A previous attempt may have merged successfully and failed only while removing the
331
+ // worktree. In that case the branch is already contained in HEAD: do not create another
332
+ // commit or merge. Discard only runner-owned lifecycle diffs left by the failure handler,
333
+ // then continue with removal and completion.
334
+ const alreadyMerged = resumeIntegration &&
335
+ isExecBranchMergedIntoCurrent({ context, worktree: prepared.worktree });
336
+ try {
337
+ if (alreadyMerged) {
338
+ const lifecyclePaths = new Set([worktreeResultPath, pipelineStatePath]
339
+ .filter((path) => !!path)
340
+ .map((path) => relative(prepared.worktree.path, path).split(sep).join("/")));
341
+ const dirtyTargets = commitTargetPaths(context, prepared.worktree, prepared.task.id);
342
+ const unexpected = dirtyTargets.filter((path) => !lifecyclePaths.has(path));
343
+ if (unexpected.length > 0) {
344
+ throw new Error(`already-merged worktree has new task changes: ${unexpected.join(", ")}`);
345
+ }
346
+ if (dirtyTargets.length > 0) {
347
+ gitOutput(prepared.worktree.path, [
348
+ "restore",
349
+ "--source=HEAD",
350
+ "--staged",
351
+ "--worktree",
352
+ "--",
353
+ ...dirtyTargets,
354
+ ]);
355
+ }
356
+ // The merged versions are already at root HEAD; drop the root's stale working copies
357
+ // of the checkpoint files so they do not linger as reverse diffs.
358
+ releaseRootWorkingCopies(repoRoot, (prepared.checkpointPaths ?? []).map((path) => repoRelativePath(repoRoot, path)));
359
+ process.stdout.write(` [integrate] already merged: ${prepared.worktree.branch} (skipping commit and merge)\n`);
360
+ }
361
+ else {
362
+ // Record completion and integration start before the first commit. The succeeded state
363
+ // is committed on the project exec branch before its merge, so successful runs retain a
364
+ // durable integrate checkpoint after all worktrees are removed.
365
+ if (worktreeResultPath)
366
+ await updateResultStatus(worktreeResultPath, "complete", completedAt);
367
+ const integrateStartedAt = new Date().toISOString();
368
+ recordIntegrateStage(pipelineStatePath, integrateStartedAt, (current) => ({
369
+ status: "running",
370
+ actor: prepared.actor,
371
+ attempts: (current?.attempts ?? 0) + 1,
372
+ started_at: integrateStartedAt,
373
+ completed_at: null,
374
+ }));
375
+ const mergeMessage = commitSubject(`exec(${prepared.task.id}): `, prepared.task.name?.trim() || "apply task changes");
376
+ const productNames = (prepared.worktree.repos ?? []).map((product) => product.name);
377
+ try {
378
+ const productOutcomes = commitProductWorktrees({
379
+ worktree: prepared.worktree,
380
+ message: mergeMessage,
381
+ targets: taskTargetsAtHead(context, prepared.worktree, prepared.task.id),
382
+ scopeLogPath: integrateLogPath(pipelineStatePath),
383
+ failureLogPath: integrateLogPath(pipelineStatePath),
384
+ resultPath: worktreeResultPath,
385
+ });
386
+ const productRootNewFiles = productOutcomes.flatMap((outcome) => outcome.rootNewFiles.map((path) => `${outcome.repo}:${path}`));
387
+ commitWorktreeChanges({
388
+ context,
389
+ worktree: prepared.worktree,
390
+ taskId: prepared.task.id,
391
+ scopeLogPath: integrateLogPath(pipelineStatePath),
392
+ failureLogPath: integrateLogPath(pipelineStatePath),
393
+ productsIntegratedByCaller: true,
394
+ productRootNewFiles,
395
+ });
396
+ }
397
+ catch (error) {
398
+ const message = error instanceof Error ? error.message : String(error);
399
+ const repo = productNames.find((name) => message.startsWith(`${name}:`)) ?? PROJECT_REPO_NAME;
400
+ recordRepoIntegration(pipelineStatePath, repo, {
401
+ status: "failed",
402
+ error: message,
403
+ });
404
+ throw new RepoIntegrationError({
405
+ repo,
406
+ cause: message,
407
+ integrated: [],
408
+ pending: [...productNames, PROJECT_REPO_NAME],
409
+ });
410
+ }
411
+ integrateTaskRepositories({
412
+ worktree: prepared.worktree,
413
+ mergeMessage,
414
+ checkProject: () => projectMergeBlockers({
415
+ context,
416
+ worktree: prepared.worktree,
417
+ taskId: prepared.task.id,
418
+ releasePaths: prepared.checkpointPaths,
419
+ }),
420
+ beforeProjectMerge: () => {
421
+ if (!pipelineStatePath)
422
+ return;
423
+ const integrateCompletedAt = new Date().toISOString();
424
+ recordIntegrateStage(pipelineStatePath, integrateCompletedAt, () => ({
425
+ status: "succeeded",
426
+ completed_at: integrateCompletedAt,
427
+ }));
428
+ commitWorktreeChanges({
429
+ context,
430
+ worktree: prepared.worktree,
431
+ taskId: prepared.task.id,
432
+ failureLogPath: integrateLogPath(pipelineStatePath),
433
+ productsIntegratedByCaller: true,
434
+ });
435
+ },
436
+ mergeProject: () => mergeWorktreeIntoCurrent({
437
+ context,
438
+ worktree: prepared.worktree,
439
+ taskId: prepared.task.id,
440
+ message: mergeMessage,
441
+ releaseRootPaths: prepared.checkpointPaths,
442
+ failureLogPath: integrateLogPath(pipelineStatePath),
443
+ }),
444
+ record: (repo, patch) => recordRepoIntegration(pipelineStatePath, repo, patch),
445
+ failureLogPath: integrateLogPath(pipelineStatePath),
446
+ lockPath: schedulePath,
447
+ });
448
+ }
449
+ removeWorktree({
450
+ context,
451
+ worktree: prepared.worktree,
452
+ taskId: prepared.task.id,
453
+ deleteBranch: true,
454
+ });
455
+ }
456
+ catch (error) {
457
+ if (error instanceof WorktreeRemovedBranchDeletionError) {
458
+ // The task changes are already merged and the worktree is gone. Keep task completion
459
+ // independent from branch housekeeping, but make the residue and recovery command clear.
460
+ process.stderr.write(`Warning: ${error.message}; run exec worktree prune.\n`);
461
+ }
462
+ else {
463
+ const reason = error instanceof Error ? error.message : String(error);
464
+ const integrateFailedAt = new Date().toISOString();
465
+ recordIntegrateStage(pipelineStatePath, integrateFailedAt, () => ({
466
+ status: "failed",
467
+ completed_at: integrateFailedAt,
468
+ }));
469
+ if (worktreeResultPath)
470
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
471
+ spawnBlock(projectId, prepared.task.id, prepared.actor, reason, pipelineStateRef
472
+ ? pipelineRecoveryMeta({
473
+ stage: "integrate",
474
+ evidenceRef: executorEvidenceRef,
475
+ stateRef: pipelineStateRef,
476
+ runId: pipelineState?.run_id ?? prepared.pipelineRunId,
477
+ })
478
+ : { limit_deferred: "false" });
479
+ process.stderr.write(`${reason}\n`);
480
+ process.stdout.write(` Blocked: ${prepared.task.id} (worktree kept: ${prepared.worktree.path})\n`);
481
+ return "failure";
482
+ }
483
+ }
484
+ spawnComplete(projectId, prepared.task.id, prepared.actor);
485
+ process.stdout.write(` Done: ${prepared.task.id}\n`);
486
+ }
487
+ else if (effectiveResult === "rate_limit") {
488
+ // Keep the worktree for the due-time resume path; do not merge partial changes.
489
+ const activeLimit = pipelineFailureStage === "reporter" ? reporterLimit : limit;
490
+ const activeAttempts = pipelineFailureStage === "reporter" ? reporterAttempts : attempts;
491
+ const totalAttempts = (prepared.priorLimitAttempts ?? 0) + activeAttempts;
492
+ const reason = activeLimit
493
+ ? `${activeLimit.kind} reached${activeLimit.resume_at ? `; resume_at=${activeLimit.resume_at}` : ""}`
494
+ : (pipelineBlockReason ?? "rate limit reached");
495
+ if (worktreeResultPath)
496
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
497
+ spawnBlock(projectId, prepared.task.id, prepared.actor, reason, activeLimit
498
+ ? {
499
+ ...limitEventMeta(activeLimit, {
500
+ attempts: totalAttempts,
501
+ worktree: prepared.worktree.path,
502
+ }),
503
+ ...(prepared.pipelineRunId
504
+ ? pipelineRecoveryMeta({
505
+ stage: pipelineFailureStage,
506
+ evidenceRef: executorEvidenceRef,
507
+ stateRef: pipelineStateRef,
508
+ runId: pipelineState?.run_id ?? prepared.pipelineRunId,
509
+ })
510
+ : {}),
511
+ }
512
+ : {
513
+ limit_deferred: "false",
514
+ ...(prepared.pipelineRunId
515
+ ? pipelineRecoveryMeta({
516
+ stage: pipelineFailureStage,
517
+ evidenceRef: executorEvidenceRef,
518
+ stateRef: pipelineStateRef,
519
+ runId: pipelineState?.run_id ?? prepared.pipelineRunId,
520
+ })
521
+ : {}),
522
+ });
523
+ process.stdout.write(activeLimit?.auto_resume
524
+ ? ` Deferred: ${prepared.task.id} until ${activeLimit.resume_at} (worktree kept: ${prepared.worktree.path})\n`
525
+ : ` Rate limited: ${prepared.task.id}; automatic resume unavailable (worktree kept: ${prepared.worktree.path})\n`);
526
+ }
527
+ else {
528
+ const blockReason = unfilledBlock
529
+ ? "agent exited 0 but result is incomplete or its frontmatter differs from the scaffold (treated as blocked)"
530
+ : (pipelineBlockReason ?? extractBlockReason(stderr));
531
+ if (worktreeResultPath)
532
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, blockReason);
533
+ spawnBlock(projectId, prepared.task.id, prepared.actor, blockReason, {
534
+ limit_deferred: "false",
535
+ ...(prepared.pipelineRunId
536
+ ? pipelineRecoveryMeta({
537
+ stage: pipelineFailureStage,
538
+ evidenceRef: executorEvidenceRef,
539
+ stateRef: pipelineStateRef,
540
+ runId: pipelineState?.run_id ?? prepared.pipelineRunId,
541
+ })
542
+ : {}),
543
+ });
544
+ process.stdout.write(` ${unfilledBlock ? "Blocked (result incomplete or frontmatter changed)" : "Failed"}: ${prepared.task.id} (worktree kept: ${prepared.worktree.path})\n`);
545
+ }
546
+ return effectiveResult;
547
+ };
548
+ return lifecycleLock ? lifecycleLock.runExclusive(finalize) : finalize();
549
+ }
550
+ export async function runPreparedTaskSafely(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun, lifecycleLock) {
551
+ try {
552
+ const result = await runPreparedTask(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun, lifecycleLock);
553
+ return { prepared, result };
554
+ }
555
+ catch (error) {
556
+ const message = error instanceof Error ? error.message : String(error);
557
+ process.stderr.write(`[run] error: ${prepared.worktree.name}: ${message}\n`);
558
+ const block = async () => {
559
+ if (!dryRun) {
560
+ const completedAt = new Date().toISOString();
561
+ if (prepared.resultPath)
562
+ await updateResultStatus(prepared.resultPath, "blocked", completedAt);
563
+ spawnBlock(projectId, prepared.task.id, prepared.actor, `runner error: ${message}`);
564
+ }
565
+ };
566
+ if (lifecycleLock)
567
+ await lifecycleLock.runExclusive(block);
568
+ else
569
+ await block();
570
+ return { prepared, result: "failure" };
571
+ }
572
+ }