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,294 @@
1
+ import { existsSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { createProviderCapacityTracker, loadExecDefaultsConfig } from "./exec-agent-config.js";
4
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "./exec-project.js";
5
+ import { readAllEventFiles, foldEventsToState } from "./exec-events.js";
6
+ import { buildScheduleIndex, findStaleGeneratedTracks } from "./exec-schedule.js";
7
+ import { buildInitialStateFromStrategy } from "./exec-schedule-initial.js";
8
+ import { readReadySnapshot } from "./exec-schedule-ready.js";
9
+ import { specdojoRootDir } from "./specdojo-config.js";
10
+ import { extractLocalId, extractPhaseSuffix } from "./schedule-phase-sets.js";
11
+ import { resolveWorktreeBase } from "./exec-worktree.js";
12
+ import { buildPhaseModeIndex, resolveAgentAssignment, resolveAgentPipeline, resolveApproach, resolveTaskCapabilities, resolveTaskExecution, resolveTaskMode, resolveTaskProficiency, } from "./exec-strategy.js";
13
+ import { SerialAsyncLock, buildTaskPhaseMap, configuredWorktreeBase, parseParallel, resolveExecDefaultsPath, runCompletionDrivenWorkerPool, } from "./exec-run-shared.js";
14
+ import { loadRosterForExecutionPath } from "./exec-run-agent.js";
15
+ import { prepareSingleTask, } from "./exec-run-schedule-prepare.js";
16
+ import { runPreparedTask, runPreparedTaskSafely, } from "./exec-run-schedule-task.js";
17
+ import { spawnIndexBuild, spawnRefresh, spawnScheduleBuild } from "./exec-run-mode-shared.js";
18
+ // Rebuild only generated tracks whose strategy input is missing a generated track or has a newer
19
+ // mtime. The same structured detector feeds exec validate warnings, keeping manual validation and
20
+ // cycle automation on one freshness rule. No output is emitted when every track is fresh.
21
+ export async function rebuildStaleGeneratedTracksForCycle(schedulePath, projectId, dryRun, dependencies = {}) {
22
+ const staleTracks = findStaleGeneratedTracks(schedulePath);
23
+ if (staleTracks.length === 0)
24
+ return { status: "not-needed", tracks: [] };
25
+ const write = dependencies.write ?? ((message) => process.stdout.write(message));
26
+ const buildTrack = dependencies.buildTrack ?? ((track) => spawnScheduleBuild(projectId, track));
27
+ const tracks = [];
28
+ for (const stale of staleTracks) {
29
+ const projectArgs = projectId ? ` --project ${projectId}` : "";
30
+ if (dryRun) {
31
+ write(` [dry-run] specdojo schedule build --track ${stale.track} --force${projectArgs}\n`);
32
+ tracks.push(stale.track);
33
+ continue;
34
+ }
35
+ write(`[cycle] step 3/5: rebuild stale schedule track ${basename(stale.strategyFile)} (${stale.reason})\n`);
36
+ if (!(await buildTrack(stale.track))) {
37
+ write(`[cycle] schedule build failed for track ${stale.track} — aborting auto step\n`);
38
+ return { status: "failure", tracks: [...tracks, stale.track] };
39
+ }
40
+ tracks.push(stale.track);
41
+ }
42
+ return { status: "success", tracks };
43
+ }
44
+ export async function runBatchMode(opts) {
45
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
46
+ activateResolvedProjectPaths(resolvedPaths);
47
+ const { schedulePath, executionPath, catalogPath, rolesPath, viewpointsPath, projectContext } = resolvedPaths;
48
+ // Use the resolved project id (which honors current_project / SPECDOJO_PROJECT), not the raw
49
+ // --project flag. This keeps worktree branches project-qualified even when --project is omitted.
50
+ const projectId = resolvedPaths.projectId ?? opts.project;
51
+ const planGenPaths = { catalogPath, rolesPath, viewpointsPath, projectContext };
52
+ const repoRoot = specdojoRootDir();
53
+ const worktreeBase = resolveWorktreeBase(repoRoot, opts.worktreeBase, configuredWorktreeBase(schedulePath));
54
+ const parallel = parseParallel(opts.parallel);
55
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
56
+ const roster = loadRosterForExecutionPath(executionPath);
57
+ const { localIdToPhaseSets, phaseSetSuffixToId } = buildTaskPhaseMap(schedulePath);
58
+ const readyJsonPath = join(executionPath, "generated", "ready.json");
59
+ const loop = !!opts.loop;
60
+ const maxRounds = opts.maxRounds ? Math.max(1, parseInt(opts.maxRounds, 10) || 1) : null;
61
+ const dryRun = !!opts.dryRun;
62
+ const strategy = opts.strategy ?? "critical-first";
63
+ const prepareReadyTasks = async (capacity, limit) => {
64
+ if (!existsSync(readyJsonPath)) {
65
+ process.stdout.write(`ready.json not found: ${readyJsonPath}\nRun: specdojo exec refresh\n`);
66
+ process.exitCode = 1;
67
+ return { preparedTasks: [], readyCount: 0 };
68
+ }
69
+ const readySnapshot = readReadySnapshot(readyJsonPath);
70
+ const orderedIds = strategy === "fifo"
71
+ ? readySnapshot.strategies.fifo.ordered_task_ids
72
+ : readySnapshot.strategies["critical-first"].ordered_task_ids;
73
+ if (orderedIds.length === 0)
74
+ return { preparedTasks: [], readyCount: 0 };
75
+ const taskMap = new Map(readySnapshot.tasks.map((t) => [t.id, t]));
76
+ const preparedTasks = [];
77
+ for (const taskId of orderedIds) {
78
+ if (preparedTasks.length >= limit)
79
+ break;
80
+ const task = taskMap.get(taskId);
81
+ if (!task)
82
+ continue;
83
+ try {
84
+ const prepared = await prepareSingleTask(task, projectId, repoRoot, schedulePath, executionPath, roster, localIdToPhaseSets, phaseSetSuffixToId, opts.by, { edit: opts.editBy, review: opts.reviewBy }, { executor: opts.executorBy, reporter: opts.reporterBy }, opts.by, dryRun, false, worktreeBase, planGenPaths, execDefaults, capacity.hasCapacity);
85
+ // "deferred": every candidate provider is at its cap; try it again after a slot frees.
86
+ if (prepared === "deferred")
87
+ continue;
88
+ if (typeof prepared !== "string") {
89
+ preparedTasks.push(prepared);
90
+ capacity.reserve(prepared.agentCandidates[0]?.provider);
91
+ }
92
+ }
93
+ catch (error) {
94
+ const message = error instanceof Error ? error.message : String(error);
95
+ process.stderr.write(`[run] setup error for ${task.id}: ${message}\n`);
96
+ }
97
+ }
98
+ return { preparedTasks, readyCount: orderedIds.length };
99
+ };
100
+ if (!loop || dryRun) {
101
+ const capacity = createProviderCapacityTracker(execDefaults);
102
+ const { preparedTasks, readyCount } = await prepareReadyTasks(capacity, parallel);
103
+ if (preparedTasks.length === 0) {
104
+ process.stdout.write(readyCount === 0 ? "[run] no ready tasks — exit\n" : "[run] no executable tasks — exit\n");
105
+ if (readyCount > 0 || process.exitCode)
106
+ process.exitCode = 1;
107
+ return;
108
+ }
109
+ const outcomes = await Promise.all(preparedTasks.map((prepared) => runPreparedTaskSafely(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun)));
110
+ const results = outcomes.map((outcome) => outcome.result);
111
+ const completed = results.filter((result) => result === "success").length;
112
+ process.stdout.write(`[run] all ${completed} instance(s) completed\n`);
113
+ if (results.some((result) => result === "failure"))
114
+ process.exitCode = 1;
115
+ return;
116
+ }
117
+ const lifecycleLock = new SerialAsyncLock();
118
+ const capacity = createProviderCapacityTracker(execDefaults);
119
+ let schedulingPass = 0;
120
+ let stopNewTasks = false;
121
+ let lastReadyCount = 0;
122
+ const scheduleAvailable = async (openSlots) => {
123
+ if (stopNewTasks || openSlots <= 0)
124
+ return [];
125
+ if (maxRounds !== null && schedulingPass >= maxRounds) {
126
+ process.stdout.write(`[run] reached max-rounds ${maxRounds} — drain running tasks\n`);
127
+ stopNewTasks = true;
128
+ return [];
129
+ }
130
+ schedulingPass++;
131
+ const roundSuffix = ` (round ${schedulingPass}${maxRounds !== null ? `/${maxRounds}` : "/-"})`;
132
+ if (schedulingPass > 1) {
133
+ // Rebuild doc-index before refresh so deliverables created by the previous round (e.g. a
134
+ // newly authored document referenced by wikilink) are resolvable when this round's tasks
135
+ // are prepared, instead of only becoming resolvable on a later, out-of-band index build.
136
+ process.stdout.write(`[run] index build${roundSuffix}...\n`);
137
+ if (!spawnIndexBuild()) {
138
+ process.stdout.write("[run] index build failed — drain running tasks\n");
139
+ process.exitCode = 1;
140
+ stopNewTasks = true;
141
+ return [];
142
+ }
143
+ // Only exec cycle opts into schedule regeneration. A strategy task completed by the prior
144
+ // auto round can therefore expose the next track in this same cycle, while standalone
145
+ // `exec run --auto --loop` keeps its existing refresh-only behavior.
146
+ if (opts.cycleRebuildStaleTracks) {
147
+ const rebuild = await rebuildStaleGeneratedTracksForCycle(schedulePath, projectId, false);
148
+ if (rebuild.status === "failure") {
149
+ process.exitCode = 1;
150
+ stopNewTasks = true;
151
+ return [];
152
+ }
153
+ }
154
+ process.stdout.write(`[run] exec refresh${roundSuffix}...\n`);
155
+ if (!spawnRefresh(projectId)) {
156
+ process.stdout.write("[run] exec refresh failed — drain running tasks\n");
157
+ process.exitCode = 1;
158
+ stopNewTasks = true;
159
+ return [];
160
+ }
161
+ }
162
+ const { preparedTasks, readyCount } = await prepareReadyTasks(capacity, openSlots);
163
+ lastReadyCount = readyCount;
164
+ return preparedTasks;
165
+ };
166
+ const poolResult = await runCompletionDrivenWorkerPool({
167
+ maxParallel: parallel,
168
+ fillSlots: (openSlots) => lifecycleLock.runExclusive(() => scheduleAvailable(openSlots)),
169
+ runItem: (prepared) => runPreparedTaskSafely(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun, lifecycleLock),
170
+ onSettled: (prepared, outcome) => {
171
+ capacity.release(prepared.agentCandidates[0]?.provider);
172
+ if (outcome.result === "failure")
173
+ process.exitCode = 1;
174
+ const critical = (prepared.task.cpm?.slack ?? 1) === 0;
175
+ if (critical && outcome.result === "failure") {
176
+ process.stdout.write(`[run] stopping: failure on critical task.\n`);
177
+ process.exitCode = 1;
178
+ stopNewTasks = true;
179
+ return { stop: true };
180
+ }
181
+ },
182
+ });
183
+ if (poolResult.launched === 0) {
184
+ process.stdout.write(lastReadyCount > 0 ? "[run] no executable tasks — exit\n" : "[run] no ready tasks — exit\n");
185
+ if (lastReadyCount > 0 || process.exitCode)
186
+ process.exitCode = 1;
187
+ return;
188
+ }
189
+ process.stdout.write(`[run] all ${poolResult.completed} of ${poolResult.launched} launched instance(s) completed\n`);
190
+ }
191
+ // For a task already in "doing" state, resume with the actor who claimed it so a re-run does not
192
+ // reselect a different agent. The actor is a roster nickname and its command is resolved later.
193
+ // `resumed` is true only when the claiming actor was adopted, which callers use to skip a claim.
194
+ export function resolveClaimingActor(taskState, byOverride) {
195
+ if (byOverride)
196
+ return { actor: byOverride, resumed: false };
197
+ if (taskState?.state !== "doing" || !taskState.last_by) {
198
+ return { actor: undefined, resumed: false };
199
+ }
200
+ const actor = taskState.last_by;
201
+ process.stdout.write(` Resuming with claiming actor: ${actor}\n`);
202
+ return { actor, resumed: true };
203
+ }
204
+ export async function runManualMode(opts) {
205
+ const taskId = opts.task;
206
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
207
+ activateResolvedProjectPaths(resolvedPaths);
208
+ const { schedulePath, executionPath, catalogPath, rolesPath, viewpointsPath, projectContext } = resolvedPaths;
209
+ // Use the resolved project id (which honors current_project / SPECDOJO_PROJECT), not the raw
210
+ // --project flag. This keeps worktree branches project-qualified even when --project is omitted.
211
+ const projectId = resolvedPaths.projectId ?? opts.project;
212
+ const planGenPaths = { catalogPath, rolesPath, viewpointsPath, projectContext };
213
+ const repoRoot = specdojoRootDir();
214
+ const worktreeBase = resolveWorktreeBase(repoRoot, opts.worktreeBase, configuredWorktreeBase(schedulePath));
215
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
216
+ const roster = loadRosterForExecutionPath(executionPath);
217
+ const { localIdToPhaseSets, phaseSetSuffixToId } = buildTaskPhaseMap(schedulePath);
218
+ const phaseModeIndex = buildPhaseModeIndex(schedulePath);
219
+ const readyJsonPath = join(executionPath, "generated", "ready.json");
220
+ let task = { id: taskId, schedule_file: "", fifo_rank: 0, critical_first_rank: 0 };
221
+ if (existsSync(readyJsonPath)) {
222
+ const snap = readReadySnapshot(readyJsonPath);
223
+ const found = snap.tasks.find((t) => t.id === taskId);
224
+ if (found)
225
+ task = found;
226
+ }
227
+ // If task not in ready.json (e.g. already "doing"), derive local_id from task id pattern.
228
+ if (!task.local_id) {
229
+ const parts = taskId.split("-");
230
+ const localId = extractLocalId(taskId);
231
+ if (localId && parts[0] === "T" && parts[1]) {
232
+ const track = parts[1];
233
+ task = {
234
+ ...task,
235
+ local_id: localId,
236
+ phase_suffix: extractPhaseSuffix(taskId),
237
+ schedule_file: `sch-track-${track.toLowerCase()}.yaml`,
238
+ };
239
+ }
240
+ }
241
+ if (task.local_id) {
242
+ task = {
243
+ ...task,
244
+ mode: task.mode ??
245
+ resolveTaskMode(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set),
246
+ execution: task.execution ??
247
+ resolveTaskExecution(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set),
248
+ approach: task.approach ??
249
+ resolveApproach(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set),
250
+ };
251
+ if (!task.capabilities) {
252
+ const capabilities = resolveTaskCapabilities(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
253
+ if (capabilities.length > 0)
254
+ task.capabilities = capabilities;
255
+ }
256
+ task.proficiency =
257
+ task.proficiency ??
258
+ resolveTaskProficiency(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
259
+ task.agent_pipeline =
260
+ task.agent_pipeline ??
261
+ resolveAgentPipeline(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
262
+ task.agent =
263
+ task.agent ??
264
+ resolveAgentAssignment(task.local_id, task.id, phaseModeIndex, task.phase_suffix, task.phase_set);
265
+ }
266
+ // If the task is already in "doing" state and --by is not specified,
267
+ // use the actor who claimed it and their command to avoid re-selecting a different agent.
268
+ // Read from events directly (not state.json cache) to reflect recent scheduler claims.
269
+ let actorOverride = opts.by;
270
+ let alreadyClaimed = false;
271
+ if (!actorOverride) {
272
+ try {
273
+ const sch = buildScheduleIndex(schedulePath);
274
+ const evts = readAllEventFiles(schedulePath);
275
+ const initTasks = buildInitialStateFromStrategy(schedulePath, sch);
276
+ const snap = foldEventsToState(evts, sch, schedulePath, initTasks);
277
+ const resolved = resolveClaimingActor(snap.tasks?.[taskId], undefined);
278
+ actorOverride = resolved.actor;
279
+ alreadyClaimed = resolved.resumed;
280
+ }
281
+ catch {
282
+ // ignore errors reading state; fall through to normal agent selection
283
+ }
284
+ }
285
+ const prepared = await prepareSingleTask(task, projectId, repoRoot, schedulePath, executionPath, roster, localIdToPhaseSets, phaseSetSuffixToId, actorOverride, { edit: opts.editBy, review: opts.reviewBy }, { executor: opts.executorBy, reporter: opts.reporterBy }, actorOverride, !!opts.dryRun, alreadyClaimed, worktreeBase, planGenPaths, execDefaults);
286
+ if (typeof prepared === "string") {
287
+ if (prepared === "failure")
288
+ process.exitCode = 1;
289
+ return;
290
+ }
291
+ const result = await runPreparedTask(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, !!opts.dryRun);
292
+ if (result === "failure")
293
+ process.exitCode = 1;
294
+ }
@@ -0,0 +1,353 @@
1
+ import { join } from "node:path";
2
+ import { resolveMemberCommand } from "./exec-agent-config.js";
3
+ import { canCompleteTask, readAllEventFiles, foldEventsToState } from "./exec-events.js";
4
+ import { buildScheduleIndex } from "./exec-schedule.js";
5
+ import { buildInitialStateFromStrategy } from "./exec-schedule-initial.js";
6
+ import { qualifyTaskId, randomHex } from "./exec-shared.js";
7
+ import { generateSinglePlan, finalizeResultSectionsForDeliverable, targetDocIdsForScheduledTask, reviewGradeSubject, } from "./exec-plans.js";
8
+ import { ensureReviewGrade } from "./review-grade.js";
9
+ import { isResultUnfilled, readResultFrontmatterSnapshot, scaffoldResult } from "./exec-results.js";
10
+ import { worktreeNameFromTaskId } from "./exec-worktree.js";
11
+ import { configuredProductRepos, plannedProjectWorktreePath } from "./exec-task-repos.js";
12
+ import { checkpointAndEnsureWorktree, discardStaleExecWorktree } from "./exec-worktree-ops.js";
13
+ import { pipelineStateLocation } from "./exec-pipeline-state.js";
14
+ import { collectBusyActors, pinnedExecutor, pinnedReporter, resolveAgentOverride, resolveTaskPhaseContext, selectCandidates, } from "./exec-run-shared.js";
15
+ import { buildExecutorPrompt, executorRequirements, loadPrompt, reportProductWorktrees, reporterRequirements, resolveReporterAgentCandidates, } from "./exec-run-agent.js";
16
+ import { integrateLogPath, spawnClaim, spawnRelease } from "./exec-run-mode-shared.js";
17
+ export function findClaimEventPath(schedulePath, taskId) {
18
+ const claims = readAllEventFiles(schedulePath).filter((item) => item.event.task_id === taskId && item.event.type === "claim");
19
+ return claims[claims.length - 1]?.path ?? null;
20
+ }
21
+ // review フェーズの前段で runner が対象文書へ grade を実行する(PJR-KCMH、PJR-2ZVS 3.6)。
22
+ // executor には実行させない。評価結果が最新(content_hash 一致)なら再実行しない。
23
+ // grade の失敗は review を止めず、結果を plan に示して review の verdict に委ねる。
24
+ export async function gradeBeforeReviewPlan(params) {
25
+ const { task, projectId } = params;
26
+ if ((task.mode ?? "edit") !== "review" || !projectId)
27
+ return undefined;
28
+ const subject = reviewGradeSubject(params.catalogPath ?? "", task);
29
+ if (!subject) {
30
+ process.stdout.write(" [grade] skipped: grade subject is not resolvable\n");
31
+ return { action: "not-run", detail: "評価対象のパスを解決できない" };
32
+ }
33
+ process.stdout.write(` [grade] checking ${subject.path} (--target ${subject.target})\n`);
34
+ const outcome = await ensureReviewGrade({
35
+ taskId: qualifyTaskId(projectId, task.id),
36
+ projectId,
37
+ subjectPath: subject.path,
38
+ target: subject.target,
39
+ repoRoot: params.repoRoot,
40
+ dryRun: params.dryRun,
41
+ });
42
+ const summary = outcome.action === "skipped"
43
+ ? "skipped: content_hash matches the stored grade"
44
+ : outcome.action === "executed"
45
+ ? `executed: run id ${outcome.runId}`
46
+ : outcome.action === "failed"
47
+ ? `failed: run id ${outcome.runId}; ${outcome.detail}`
48
+ : `not run: ${outcome.detail}`;
49
+ process.stdout.write(` [grade] ${summary}\n`);
50
+ return outcome;
51
+ }
52
+ export async function prepareSingleTask(task, projectId, repoRoot, schedulePath, executionPath, roster, localIdToPhaseSets, phaseSetSuffixToId, agentNicknameOverride, modeAgentOverrides, stageAgentOverrides, actorOverride, dryRun, skipClaim, worktreeBase, planGenPaths, execDefaults, hasProviderCapacity, pipelineResume) {
53
+ const mode = task.mode ?? "edit";
54
+ process.stdout.write(`Task: ${task.id}${task.name ? ` — ${task.name}` : ""} [${mode}]\n`);
55
+ if (!task.agent_pipeline && (stageAgentOverrides.executor || stageAgentOverrides.reporter)) {
56
+ process.stdout.write(" --executor-by / --reporter-by require an agent_pipeline task.\n");
57
+ return "failure";
58
+ }
59
+ // Mode-specific overrides (--edit-by / --review-by) let nightly batch runs route edit and
60
+ // review to different agents (e.g. local LLMs) without editing the roster. They take an agent
61
+ // nickname whose command is resolved from agent-members.yaml; a mode without an override falls back
62
+ // to normal auto-selection.
63
+ const overrideResolution = resolveAgentOverride(mode, task.agent_pipeline
64
+ ? (stageAgentOverrides.executor ?? agentNicknameOverride ?? pinnedExecutor(task))
65
+ : (agentNicknameOverride ?? pinnedExecutor(task)), modeAgentOverrides, roster, execDefaults, task.agent_pipeline ? "executor" : undefined);
66
+ if (overrideResolution.kind === "error") {
67
+ process.stdout.write(` ${overrideResolution.message}\n`);
68
+ return "failure";
69
+ }
70
+ const agentCandidates = overrideResolution.kind === "command"
71
+ ? [
72
+ {
73
+ command: overrideResolution.command,
74
+ actor: overrideResolution.actor,
75
+ provider: overrideResolution.provider,
76
+ },
77
+ ]
78
+ : [];
79
+ let actor = actorOverride ?? "auto-agent";
80
+ if (!actorOverride && overrideResolution.kind === "command" && overrideResolution.actor) {
81
+ actor = overrideResolution.actor;
82
+ }
83
+ if (agentCandidates.length === 0) {
84
+ // Human tasks cannot be run automatically without an explicit registered agent override.
85
+ if ((task.execution ?? "agent") === "human") {
86
+ process.stdout.write(` Task "${task.name ?? task.id}" (${task.id}) has execution: human.\n` +
87
+ ` This task requires human execution. Use --by <nickname> to override.\n`);
88
+ return "failure";
89
+ }
90
+ const phaseCtx = resolveTaskPhaseContext(task, localIdToPhaseSets, phaseSetSuffixToId);
91
+ if (!phaseCtx) {
92
+ process.stdout.write(` Cannot resolve phase context for "${task.name ?? task.id}": not found in sch-strategy files\n`);
93
+ return "failure";
94
+ }
95
+ const requirements = executorRequirements(task) ?? {
96
+ capabilities: task.capabilities ?? [],
97
+ proficiency: task.proficiency,
98
+ };
99
+ const busyActors = collectBusyActors(schedulePath);
100
+ const candidates = selectCandidates(requirements, roster, mode, busyActors, execDefaults);
101
+ if (candidates.length === 0) {
102
+ process.stdout.write(` No agents found for mode: ${mode}, capabilities: [${requirements.capabilities.join(", ")}]${requirements.proficiency ? `, proficiency: ${requirements.proficiency}` : ""}${requirements.stage_role ? `, stage_role: ${requirements.stage_role}` : ""}\n`);
103
+ return "failure";
104
+ }
105
+ // Per-provider concurrency caps (exec-defaults providers.<name>.max_concurrency) drop any
106
+ // candidate whose provider already reached its limit this round. If a non-capped provider
107
+ // remains it becomes the primary; if every candidate's provider is at capacity, defer the
108
+ // task to a later round before claiming or setting up its worktree.
109
+ const available = hasProviderCapacity
110
+ ? candidates.filter((c) => hasProviderCapacity(c.provider))
111
+ : candidates;
112
+ if (available.length === 0) {
113
+ process.stdout.write(` [run] deferred: ${task.id} — all candidate providers at concurrency cap this round\n`);
114
+ return "deferred";
115
+ }
116
+ // Expand each candidate's launch command. A broken provider template (unresolved
117
+ // placeholder, ambiguous command_params) skips that candidate with a warning so a
118
+ // misconfigured provider does not block fallback to other providers.
119
+ const runnable = [];
120
+ for (const candidate of available) {
121
+ try {
122
+ const command = resolveMemberCommand(execDefaults, candidate);
123
+ if (!command)
124
+ continue;
125
+ agentCandidates.push({
126
+ command,
127
+ actor: candidate.nickname,
128
+ provider: candidate.provider,
129
+ });
130
+ runnable.push(candidate);
131
+ }
132
+ catch (error) {
133
+ process.stdout.write(` Skipping ${candidate.nickname}: ${error instanceof Error ? error.message : String(error)}\n`);
134
+ }
135
+ }
136
+ if (runnable.length === 0) {
137
+ process.stdout.write(` No agent with a resolvable command for mode: ${mode} (check providers.<provider>.command_template in exec-defaults.yaml)\n`);
138
+ return "failure";
139
+ }
140
+ if (!actorOverride)
141
+ actor = runnable[0].nickname;
142
+ process.stdout.write(` Phase: ${phaseCtx.phaseSet}/${phaseCtx.phaseId} Mode: ${mode} Agent: ${runnable[0].nickname}\n`);
143
+ }
144
+ let reporterCandidates;
145
+ if (task.agent_pipeline) {
146
+ const requirements = reporterRequirements(task);
147
+ reporterCandidates = resolveReporterAgentCandidates(task, roster, execDefaults, collectBusyActors(schedulePath), stageAgentOverrides.reporter ?? pinnedReporter(task));
148
+ if (reporterCandidates.length === 0) {
149
+ process.stdout.write(` No agents found for reporter stage${requirements?.proficiency ? `, proficiency: ${requirements.proficiency}` : ""}\n`);
150
+ return "failure";
151
+ }
152
+ }
153
+ const reviewGradeOutcome = await gradeBeforeReviewPlan({
154
+ task,
155
+ projectId,
156
+ catalogPath: planGenPaths.catalogPath,
157
+ repoRoot,
158
+ dryRun,
159
+ });
160
+ // Plans are generated on demand here; `exec refresh` does not manage them.
161
+ await generateSinglePlan({
162
+ executionPath,
163
+ projectId: projectId ?? "",
164
+ catalogPath: planGenPaths.catalogPath ?? "",
165
+ rolesPath: planGenPaths.rolesPath,
166
+ viewpointsPath: planGenPaths.viewpointsPath,
167
+ projectContext: planGenPaths.projectContext,
168
+ task,
169
+ ...(reviewGradeOutcome ? { reviewGradeOutcome } : {}),
170
+ });
171
+ const planPrompt = loadPrompt(executionPath, task.id);
172
+ if (!planPrompt) {
173
+ process.stdout.write(` Plan not found for ${task.id}.\n`);
174
+ return "failure";
175
+ }
176
+ const prompt = task.agent_pipeline
177
+ ? buildExecutorPrompt(planPrompt, execDefaults.pipeline?.parent_validations)
178
+ : planPrompt;
179
+ const pipelineRunId = task.agent_pipeline
180
+ ? `${new Date().toISOString().replace(/[-:.]/g, "").replace("Z", "Z")}-${randomHex(4)}`
181
+ : undefined;
182
+ const worktreeTaskId = qualifyTaskId(projectId, task.id);
183
+ const worktreeName = worktreeNameFromTaskId(worktreeTaskId);
184
+ // PJR-98G4: repos を宣言した project では <base>/<task>/project/ と <base>/<task>/<repo>/ を作る。
185
+ const products = configuredProductRepos(schedulePath);
186
+ if (dryRun) {
187
+ const worktree = {
188
+ path: plannedProjectWorktreePath(worktreeBase, worktreeTaskId, products),
189
+ branch: `exec/${worktreeName}`,
190
+ name: worktreeName,
191
+ created: false,
192
+ };
193
+ process.stdout.write(` [run] would setup: worktree ${worktree.path} (${worktree.branch})\n`);
194
+ for (const product of products) {
195
+ process.stdout.write(` [run] would setup: worktree ${join(worktreeBase, worktreeName, product.name)} ` +
196
+ `(${worktree.branch} in ${product.repoRoot})\n`);
197
+ }
198
+ const claimMsg = skipClaim
199
+ ? ` [dry-run] already claimed: ${task.id} as ${actor} (skip claim)`
200
+ : ` [dry-run] would claim: ${task.id} as ${actor}`;
201
+ process.stdout.write(claimMsg + "\n");
202
+ process.stdout.write(` [dry-run] Command: ${agentCandidates[0]?.command ?? ""}\n`);
203
+ process.stdout.write(` [dry-run] CWD: ${worktree.path}\n`);
204
+ process.stdout.write(` [dry-run] Plan: ${prompt.length} chars\n`);
205
+ return {
206
+ task,
207
+ actor,
208
+ agentCandidates,
209
+ plan: planPrompt,
210
+ prompt,
211
+ worktree,
212
+ pipelineRunId,
213
+ pipelineResumeStage: pipelineResume?.stage,
214
+ pipelineStateRef: pipelineResume?.stateRef,
215
+ reporterCandidates,
216
+ };
217
+ }
218
+ if (skipClaim) {
219
+ process.stdout.write(` Already claimed: ${task.id} as ${actor}\n`);
220
+ }
221
+ else {
222
+ process.stdout.write(` Claiming: ${task.id} as ${actor}\n`);
223
+ if (!spawnClaim(projectId, task.id, actor)) {
224
+ process.stdout.write(` Claim failed: ${task.id}\n`);
225
+ return "failure";
226
+ }
227
+ }
228
+ const planRef = `exec/plans/${task.id}-plan.md`;
229
+ const startedAt = new Date().toISOString();
230
+ const finalizeSections = task.approach === "finalize" || task.approach === "bootstrap-finalize"
231
+ ? finalizeResultSectionsForDeliverable(planGenPaths.catalogPath ?? "", task.local_id, task.approach)
232
+ : undefined;
233
+ const targets = targetDocIdsForScheduledTask(planGenPaths.catalogPath ?? "", task, projectId ?? "");
234
+ const { resultPath } = await scaffoldResult({
235
+ executionPath,
236
+ taskId: task.id,
237
+ mode: task.mode ?? "edit",
238
+ projectId: projectId ?? "",
239
+ planRef,
240
+ agent: actor,
241
+ startedAt,
242
+ ...(task.approach ? { approach: task.approach } : {}),
243
+ ...(targets ? { targets } : {}),
244
+ ...(finalizeSections ? { finalizeSections } : {}),
245
+ });
246
+ // Keep the execution checkpoint visible at root, but commit it only on the exec branch. The
247
+ // successful merge later brings plan/result/claim and deliverables to root in one first-parent
248
+ // commit (see runPreparedTask).
249
+ const claimEventPath = findClaimEventPath(schedulePath, task.id);
250
+ if (!claimEventPath) {
251
+ process.stdout.write(` Claim event not found for ${task.id}\n`);
252
+ return "failure";
253
+ }
254
+ // A fresh claim (not a resume) of a task that still owns an exec worktree/branch means a prior
255
+ // lifecycle left residue. Discard it so the checkpoint commit below runs and the root scaffold is
256
+ // committed instead of stranded as untracked changes that later trip the merge-back guard.
257
+ if (!skipClaim) {
258
+ const discarded = discardStaleExecWorktree({
259
+ context: { repoRoot, schedulePath, executionPath },
260
+ worktreeTaskId,
261
+ products,
262
+ });
263
+ if (discarded) {
264
+ process.stdout.write(` [run] discarded stale worktree/branch: ${discarded}\n`);
265
+ }
266
+ }
267
+ const checkpointPaths = [
268
+ join(executionPath, "exec", "plans", `${task.id}-plan.md`),
269
+ resultPath,
270
+ claimEventPath,
271
+ ];
272
+ const checkpointFailureLogPath = pipelineRunId
273
+ ? integrateLogPath(pipelineStateLocation({
274
+ repoRoot,
275
+ worktreePath: repoRoot,
276
+ executionPath,
277
+ taskId: task.id,
278
+ runId: pipelineRunId,
279
+ }).path)
280
+ : undefined;
281
+ let worktree;
282
+ try {
283
+ worktree = checkpointAndEnsureWorktree({
284
+ context: { repoRoot, schedulePath, executionPath },
285
+ worktreeTaskId,
286
+ base: worktreeBase,
287
+ checkpointPaths,
288
+ commitMessage: `exec(${task.id}): prepare execution`,
289
+ products,
290
+ failureLogPath: checkpointFailureLogPath,
291
+ });
292
+ }
293
+ catch (error) {
294
+ // We claimed this task in this call (skipClaim is false); the checkpoint failed, so release the
295
+ // claim (doing → todo). Otherwise the task is stranded in "doing" with no worktree and drops out
296
+ // of ready.json. Resumed tasks (skipClaim) were already doing, so leave their state untouched.
297
+ if (!skipClaim) {
298
+ spawnRelease(projectId, task.id, actor, "rollback: checkpoint failed");
299
+ process.stdout.write(` Claim rolled back (checkpoint failed): ${task.id}\n`);
300
+ }
301
+ throw error;
302
+ }
303
+ const setupAction = worktree.created ? "setup" : "reuse";
304
+ process.stdout.write(` [run] ${setupAction}: worktree ${worktree.path} (${worktree.branch})\n`);
305
+ reportProductWorktrees(worktree);
306
+ return {
307
+ task,
308
+ actor,
309
+ agentCandidates,
310
+ plan: planPrompt,
311
+ prompt,
312
+ worktree,
313
+ resultPath,
314
+ resultScaffold: readResultFrontmatterSnapshot(resultPath),
315
+ checkpointPaths,
316
+ pipelineRunId,
317
+ pipelineResumeStage: pipelineResume?.stage,
318
+ pipelineStateRef: pipelineResume?.stateRef,
319
+ reporterCandidates,
320
+ };
321
+ }
322
+ // An agent can exit 0 without doing the work (e.g. a permission-denied tool call is fed back as a
323
+ // tool error and the model ends its turn normally). The agent's core duty is to fill the result while
324
+ // preserving its scaffold frontmatter, so treat an incomplete or modified result as a block on exit 0. This
325
+ // mirrors the in-place guard in runInPlaceMode; on the worktree path it also prevents an empty task
326
+ // from being committed, merged, and unblocking downstream tasks. Only a successful run is reconsidered;
327
+ // rate-limit and failure outcomes pass through unchanged.
328
+ export function downgradeUnfilledResult(agentResult, resultPath, mode, scaffoldFrontmatter, originalScaffoldFrontmatter) {
329
+ if (agentResult === "success" &&
330
+ resultPath &&
331
+ isResultUnfilled(resultPath, mode, scaffoldFrontmatter, originalScaffoldFrontmatter)) {
332
+ return { result: "failure", unfilledBlock: true };
333
+ }
334
+ return { result: agentResult, unfilledBlock: false };
335
+ }
336
+ export function checkCompletionBeforeIntegration(schedule, snapshot, taskId, actor) {
337
+ return canCompleteTask(schedule, snapshot, taskId, actor);
338
+ }
339
+ export function readCompletionPreflight(schedulePath, taskId, actor) {
340
+ try {
341
+ const schedule = buildScheduleIndex(schedulePath);
342
+ const events = readAllEventFiles(schedulePath);
343
+ const initialTasks = buildInitialStateFromStrategy(schedulePath, schedule);
344
+ const snapshot = foldEventsToState(events, schedule, schedulePath, initialTasks);
345
+ return checkCompletionBeforeIntegration(schedule, snapshot, taskId, actor);
346
+ }
347
+ catch (error) {
348
+ return {
349
+ ok: false,
350
+ reason: `could not validate current task state: ${error instanceof Error ? error.message : String(error)}`,
351
+ };
352
+ }
353
+ }