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,509 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { qualifyTaskId, randomHex } from "./exec-shared.js";
4
+ import { buildInPlaceStem } from "./exec-plans.js";
5
+ import { generateRegisterPlan, requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, ticketPathFromItem, } from "./exec-register.js";
6
+ import { readResultFrontmatterSnapshot, scaffoldResult, updateResultStatus, } from "./exec-results.js";
7
+ import { findExecWorktree, gitOutput } from "./exec-worktree.js";
8
+ import { configuredProductRepos, withProductRepoPrompt } from "./exec-task-repos.js";
9
+ import { checkpointAndEnsureWorktree, commitTargetPaths, commitWorktreeChanges, discardStaleExecWorktree, isExecBranchMergedIntoCurrent, mergeWorktreeIntoCurrent, removeWorktree, taskTargetsAtHead, WorktreeRemovedBranchDeletionError, worktreeStatusPaths, } from "./exec-worktree-ops.js";
10
+ import { commitProductWorktrees, integrateTaskRepositories, projectMergeBlockers, PROJECT_REPO_NAME, RepoIntegrationError, } from "./exec-repo-integration.js";
11
+ import { productIntegrationTrace, recordResultTrace, refsTrailer, registerProjectMergeMessage, traceKey, withCommitTrailers, } from "./exec-repo-trace.js";
12
+ import { pipelineStateLocation, readPipelineState } from "./exec-pipeline-state.js";
13
+ import { findResumableRegisterRun } from "./exec-register-resume.js";
14
+ import { agentEnvironment, expandPromptRefs, extractBlockReason, pathInsideWorktree, reportProductWorktrees, runWithRetry, } from "./exec-run-agent.js";
15
+ import { runAgentPipeline } from "./exec-run-agent-pipeline.js";
16
+ import { downgradeUnfilledResult } from "./exec-run-schedule-prepare.js";
17
+ import { commitSubject, integrateLogPath, recordIntegrateStage, recordRepoIntegration, repoRelativePath, } from "./exec-run-mode-shared.js";
18
+ import { resolveRegisterCommand, isRegisterPipelineRequested, resolveRegisterPipelineCommand, spawnRegisterTransition, registerRunnerManagedPaths, registerReporterManagedPaths, } from "./exec-run-register-core.js";
19
+ import { commitRegisterState, registerPathsInsideWorktree, rebuildRootRegisterViews, registerWaitSummary, } from "./exec-run-register-state.js";
20
+ // 全体再実行が既存 run の未統合成果を破棄しないための保護。既存 worktree に再開可能な run
21
+ // (executor 成功済みで reporter か統合が未完了)が残っている場合だけ理由を返し、呼び出し側が
22
+ // 破壊的操作(discardStaleExecWorktree)の手前で中断できるようにする。--force-restart で無効化できる。
23
+ export function protectResumableRegisterWorktree(context, opts, taskId, worktreeTaskId) {
24
+ if (opts.forceRestart)
25
+ return null;
26
+ const worktree = findExecWorktree(context.repoRoot, worktreeTaskId);
27
+ if (!worktree)
28
+ return null;
29
+ const lookup = findResumableRegisterRun({
30
+ repoRoot: context.repoRoot,
31
+ worktreePath: worktree.path,
32
+ executionPath: context.executionPath,
33
+ taskId,
34
+ });
35
+ if (lookup.kind !== "resumable")
36
+ return null;
37
+ const { stage, runId } = lookup.target;
38
+ const stopped = stage === "integrate"
39
+ ? `run ${runId} finished the reporter but not the integration`
40
+ : stage === "reporter"
41
+ ? `executor already succeeded in run ${runId}`
42
+ : `executor was interrupted in run ${runId}`;
43
+ return (`refusing to re-run ${taskId}: ${stopped}; ` +
44
+ `its changes are still unintegrated in ${worktree.path}. ` +
45
+ `Resume the ${stage} stage with --resume, or discard the worktree with --force-restart.`);
46
+ }
47
+ // register worktree 実行の Phase 3(成果物統合と状態遷移)。成功なら worktree の成果物を
48
+ // commit → worktree 側で register review → 統合ブランチへ merge commit 1件 → worktree 撤去、
49
+ // 失敗なら worktree を保持したまま waiting へ戻す(wait commit 1件)。通常実行・reporter 再開・
50
+ // 統合再開で同じ後処理を通す。統合ブランチの first-parent に増えるのは、成功時の merge commit
51
+ // (start → review の遷移事象、plan / result、成果物を含む)か失敗時の wait commit だけになる。
52
+ export async function finalizeRegisterWorktreeRun(params) {
53
+ const { context, registerPaths, item, ticketPath, worktree, stem, agentResult, actor } = params;
54
+ const { projectId, schedulePath, executionPath, repoRoot } = context;
55
+ const wtContext = { repoRoot, schedulePath, executionPath };
56
+ const worktreeRegisterPaths = registerPathsInsideWorktree(repoRoot, worktree.path, registerPaths);
57
+ const worktreeTicketPath = ticketPath
58
+ ? pathInsideWorktree(repoRoot, worktree.path, ticketPath)
59
+ : null;
60
+ const waitSummary = (reason) => registerWaitSummary({
61
+ repoRoot,
62
+ projectId,
63
+ registerPaths,
64
+ item,
65
+ ticketPath,
66
+ reason,
67
+ actor,
68
+ worktree,
69
+ bookkeepingPaths: params.bookkeepingPaths,
70
+ });
71
+ const completedAt = new Date().toISOString();
72
+ const worktreeResultPath = params.worktreeResultPath;
73
+ const { result: effectiveResult, unfilledBlock } = downgradeUnfilledResult(agentResult, worktreeResultPath, "edit", params.resultScaffold);
74
+ if (effectiveResult === "success") {
75
+ // A prior integration attempt may have completed the merge and failed only while removing the
76
+ // worktree. The register item and result at root are already in their final review/complete
77
+ // state, so an integration resume must only clean up. Replaying start/review or advancing the
78
+ // exec branch here would force a second merge commit for the same task.
79
+ if (params.resumedIntegration &&
80
+ isExecBranchMergedIntoCurrent({ context: wtContext, worktree })) {
81
+ try {
82
+ const lifecyclePaths = new Set([worktreeResultPath, params.pipelineStatePath]
83
+ .filter((path) => !!path)
84
+ .map((path) => repoRelativePath(worktree.path, path)));
85
+ const dirtyTargets = commitTargetPaths(wtContext, worktree, stem);
86
+ const unexpected = dirtyTargets.filter((path) => !lifecyclePaths.has(path));
87
+ if (unexpected.length > 0) {
88
+ throw new Error(`already-merged worktree has new task changes: ${unexpected.join(", ")}`);
89
+ }
90
+ if (dirtyTargets.length > 0) {
91
+ gitOutput(worktree.path, [
92
+ "restore",
93
+ "--source=HEAD",
94
+ "--staged",
95
+ "--worktree",
96
+ "--",
97
+ ...dirtyTargets,
98
+ ]);
99
+ }
100
+ process.stdout.write(` [integrate] already merged: ${worktree.branch} (skipping transitions, commit, and merge)\n`);
101
+ removeWorktree({ context: wtContext, worktree, taskId: stem, deleteBranch: true });
102
+ }
103
+ catch (error) {
104
+ if (error instanceof WorktreeRemovedBranchDeletionError) {
105
+ process.stderr.write(`Warning: ${error.message}; run exec worktree prune.\n`);
106
+ }
107
+ else {
108
+ const reason = sanitizeRegisterConclusion(`integrate cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
109
+ const integrateFailedAt = new Date().toISOString();
110
+ recordIntegrateStage(params.pipelineStatePath, integrateFailedAt, () => ({
111
+ status: "failed",
112
+ completed_at: integrateFailedAt,
113
+ }));
114
+ process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
115
+ return {
116
+ id: item.id,
117
+ title: item.title,
118
+ outcome: "failure",
119
+ transition: "review",
120
+ commit: "incomplete",
121
+ reason,
122
+ };
123
+ }
124
+ }
125
+ rebuildRootRegisterViews(projectId, item.id);
126
+ const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
127
+ process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
128
+ return {
129
+ id: item.id,
130
+ title: item.title,
131
+ outcome: "success",
132
+ transition: "review",
133
+ commit: `committed ${sha}`,
134
+ };
135
+ }
136
+ await updateResultStatus(worktreeResultPath, "complete", completedAt);
137
+ const subject = commitSubject(`exec(register ${item.id}): `, item.title);
138
+ // PJR-30SW: プロダクト側の commit と merge commit、プロジェクト側の merge commit に
139
+ // `Refs: <project-id>:<item-id>` を付ける(PJR-1SXK)。
140
+ const itemTraceKey = traceKey(projectId, item.id);
141
+ const productMessage = withCommitTrailers(subject, [refsTrailer(projectId, item.id)]);
142
+ const integrateStartedAt = new Date().toISOString();
143
+ recordIntegrateStage(params.pipelineStatePath, integrateStartedAt, (current) => ({
144
+ status: "running",
145
+ actor,
146
+ attempts: (current?.attempts ?? 0) + 1,
147
+ started_at: integrateStartedAt,
148
+ completed_at: null,
149
+ }));
150
+ try {
151
+ const productNames = (worktree.repos ?? []).map((product) => product.name);
152
+ try {
153
+ const productOutcomes = commitProductWorktrees({
154
+ worktree,
155
+ message: productMessage,
156
+ targets: taskTargetsAtHead(wtContext, worktree, stem),
157
+ scopeLogPath: integrateLogPath(params.pipelineStatePath),
158
+ failureLogPath: integrateLogPath(params.pipelineStatePath),
159
+ resultPath: worktreeResultPath,
160
+ });
161
+ const productRootNewFiles = productOutcomes.flatMap((outcome) => outcome.rootNewFiles.map((path) => `${outcome.repo}:${path}`));
162
+ commitWorktreeChanges({
163
+ context: wtContext,
164
+ worktree,
165
+ taskId: stem,
166
+ message: subject,
167
+ scopeLogPath: integrateLogPath(params.pipelineStatePath),
168
+ failureLogPath: integrateLogPath(params.pipelineStatePath),
169
+ productsIntegratedByCaller: true,
170
+ productRootNewFiles,
171
+ });
172
+ }
173
+ catch (error) {
174
+ const message = error instanceof Error ? error.message : String(error);
175
+ const repo = productNames.find((name) => message.startsWith(`${name}:`)) ?? PROJECT_REPO_NAME;
176
+ recordRepoIntegration(params.pipelineStatePath, repo, {
177
+ status: "failed",
178
+ error: message,
179
+ });
180
+ throw new RepoIntegrationError({
181
+ repo,
182
+ cause: message,
183
+ integrated: [],
184
+ pending: [...productNames, PROJECT_REPO_NAME],
185
+ });
186
+ }
187
+ let executor = actor;
188
+ let reporter = "-";
189
+ if (params.pipelineStatePath && existsSync(params.pipelineStatePath)) {
190
+ const state = readPipelineState(params.pipelineStatePath);
191
+ executor = state.stages.executor.actor ?? executor;
192
+ reporter = state.stages.reporter.actor ?? reporter;
193
+ }
194
+ const mergeMessage = registerProjectMergeMessage({
195
+ subject,
196
+ executor,
197
+ reporter,
198
+ projectId,
199
+ itemId: item.id,
200
+ });
201
+ integrateTaskRepositories({
202
+ worktree,
203
+ mergeMessage,
204
+ productMergeMessage: productMessage,
205
+ checkProject: () => projectMergeBlockers({
206
+ context: wtContext,
207
+ worktree,
208
+ taskId: stem,
209
+ releasePaths: params.bookkeepingPaths,
210
+ ownedPaths: params.bookkeepingPaths,
211
+ }),
212
+ beforeProjectMerge: () => {
213
+ // review は exec branch 側(worktree)で記録し、最後の project merge commit に
214
+ // 同梱する。統合ブランチで遷移すると first-parent に独立した commit が増える。
215
+ if (!spawnRegisterTransition(projectId, ["review", "--id", item.id, "--by", actor], worktree.path)) {
216
+ throw new Error(`register review transition failed: ${item.id}`);
217
+ }
218
+ // プロダクトの統合後・プロジェクトの統合前に、統合先の commit snapshot を result の
219
+ // trace 表へ記録し、プロジェクト側の merge commit に同梱する。宣言の無い project では
220
+ // 記録せず、result は従来どおりになる。
221
+ const products = worktree.repos ?? [];
222
+ const tracePaths = [];
223
+ if (products.length > 0 && existsSync(worktreeResultPath)) {
224
+ recordResultTrace({
225
+ resultPath: worktreeResultPath,
226
+ traceKey: itemTraceKey,
227
+ traces: products.map(productIntegrationTrace),
228
+ });
229
+ tracePaths.push(worktreeResultPath);
230
+ }
231
+ const integrateCompletedAt = new Date().toISOString();
232
+ recordIntegrateStage(params.pipelineStatePath, integrateCompletedAt, () => ({
233
+ status: "succeeded",
234
+ completed_at: integrateCompletedAt,
235
+ }));
236
+ commitRegisterState(worktree.path, worktreeRegisterPaths, `exec(register ${item.id}): review`, worktreeTicketPath, [...(params.pipelineStatePath ? [params.pipelineStatePath] : []), ...tracePaths], integrateLogPath(params.pipelineStatePath));
237
+ },
238
+ mergeProject: () => mergeWorktreeIntoCurrent({
239
+ context: wtContext,
240
+ worktree,
241
+ taskId: stem,
242
+ message: mergeMessage,
243
+ releaseRootPaths: [...params.bookkeepingPaths],
244
+ // waiting を複数回経た項目では、wait 時の同期後も統合先と exec branch の双方で
245
+ // 記帳ファイルが変わる。項目自身の記帳ファイルだけの競合は exec branch 側で解決する。
246
+ resolveConflictsWithBranchPaths: [...params.bookkeepingPaths],
247
+ failureLogPath: integrateLogPath(params.pipelineStatePath),
248
+ }),
249
+ record: (repo, patch) => recordRepoIntegration(params.pipelineStatePath, repo, patch),
250
+ failureLogPath: integrateLogPath(params.pipelineStatePath),
251
+ lockPath: schedulePath,
252
+ });
253
+ // 撤去も統合の一部として扱う。merge 前に失敗した場合は waiting へ戻し、merge 後の撤去
254
+ // だけが失敗した場合は review を維持して `--resume` で cleanup だけをやり直す。撤去後の
255
+ // branch 削除だけが失敗した場合は、成果の統合を取り消さず cleanup 警告として扱う。
256
+ removeWorktree({ context: wtContext, worktree, taskId: stem, deleteBranch: true });
257
+ }
258
+ catch (error) {
259
+ if (error instanceof WorktreeRemovedBranchDeletionError) {
260
+ // The task changes are already merged and the worktree is gone. Treat the integration as
261
+ // complete while preserving an explicit cleanup warning in the run log.
262
+ process.stderr.write(`Warning: ${error.message}; run exec worktree prune.\n`);
263
+ }
264
+ else {
265
+ const reason = sanitizeRegisterConclusion(`integrate failed: ${error instanceof Error ? error.message : String(error)}`);
266
+ const integrateFailedAt = new Date().toISOString();
267
+ recordIntegrateStage(params.pipelineStatePath, integrateFailedAt, () => ({
268
+ status: "failed",
269
+ completed_at: integrateFailedAt,
270
+ }));
271
+ // The merge may already have succeeded and only worktree removal failed. Root now contains
272
+ // the complete result and review transition; adding a wait commit would create a second
273
+ // first-parent entry and a resume would create a third. Keep review intact and let
274
+ // integration resume perform cleanup only.
275
+ if (isExecBranchMergedIntoCurrent({ context: wtContext, worktree })) {
276
+ rebuildRootRegisterViews(projectId, item.id);
277
+ process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
278
+ return {
279
+ id: item.id,
280
+ title: item.title,
281
+ outcome: "failure",
282
+ transition: "review",
283
+ commit: "incomplete",
284
+ reason,
285
+ };
286
+ }
287
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, reason);
288
+ process.stdout.write(` Blocked: ${item.id} (worktree kept: ${worktree.path})\n`);
289
+ const summary = waitSummary(reason);
290
+ return { ...summary, commit: "incomplete" };
291
+ }
292
+ }
293
+ // review は merge で root の個票に入る。非追跡の派生ビューだけ root で作り直す。
294
+ rebuildRootRegisterViews(projectId, item.id);
295
+ const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
296
+ process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
297
+ return {
298
+ id: item.id,
299
+ title: item.title,
300
+ outcome: "success",
301
+ transition: "review",
302
+ commit: `committed ${sha}`,
303
+ };
304
+ }
305
+ // 失敗 / rate limit: worktree は保持し(調査・再開のため)、waiting へ遷移する。
306
+ const reason = params.runnerBlockReason
307
+ ? params.runnerBlockReason
308
+ : unfilledBlock
309
+ ? "agent exited 0 but result is incomplete or its frontmatter differs from the scaffold (treated as blocked)"
310
+ : agentResult === "rate_limit"
311
+ ? "rate limit reached"
312
+ : extractBlockReason(params.stderr);
313
+ await updateResultStatus(worktreeResultPath, "blocked", completedAt, sanitizeRegisterConclusion(reason));
314
+ process.stdout.write(`run failed: ${item.id} (status: waiting; worktree kept: ${worktree.path})\n`);
315
+ return waitSummary(reason);
316
+ }
317
+ // register 項目1件の worktree 実行。成果物は worktree に隔離し、短い setup/finalize だけを
318
+ // lifecycleLock で直列化する。start の checkpoint と成功時の review は exec branch に置き、
319
+ // project develop の first-parent には task 単位の merge commit だけを追加する。失敗時は
320
+ // start を含む管理成果物を root へ戻し、wait 遷移と同じ commit にまとめる。
321
+ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecycleLock) {
322
+ const { projectId, schedulePath, executionPath, repoRoot, worktreeBase } = context;
323
+ const wtContext = { repoRoot, schedulePath, executionPath };
324
+ const { registerPaths, item } = resolveRegisterRunTarget(projectId, pjrId);
325
+ // 状態遷移の書き込み先(登録項目の正本)。commit 対象に必ず含める。
326
+ const ticketPath = ticketPathFromItem(item, registerPaths.projectRegisterPath);
327
+ requireRunnableRegisterItem(item);
328
+ const pipelineMode = isRegisterPipelineRequested(opts);
329
+ const pipelineAgents = pipelineMode
330
+ ? resolveRegisterPipelineCommand(context.roster, opts, context.execDefaults)
331
+ : undefined;
332
+ // agent(result frontmatter へ記録する actor)は executor 側にする。Schedule の
333
+ // agent_pipeline(scaffoldResult 呼び出し時に executor の actor を渡す)と揃える。
334
+ const { command, actor, provider } = pipelineAgents
335
+ ? {
336
+ command: pipelineAgents.executor.command,
337
+ actor: pipelineAgents.executor.actor,
338
+ provider: pipelineAgents.executor.provider,
339
+ }
340
+ : {
341
+ ...resolveRegisterCommand(item, context.roster, opts, context.execDefaults),
342
+ provider: undefined,
343
+ };
344
+ const resolvedProvider = provider ??
345
+ context.roster?.members.find((m) => m.nickname === actor && m.type === "agent")?.provider;
346
+ const stem = buildInPlaceStem(pjrId.toLowerCase());
347
+ const worktreeTaskId = qualifyTaskId(projectId, item.id);
348
+ const pipelineRunId = pipelineAgents
349
+ ? `${new Date().toISOString().replace(/[-:.]/g, "")}-${randomHex(4)}`
350
+ : undefined;
351
+ // PJR-98G4: repos を宣言した project では、プロダクトの worktree も同じタスクの下に作る。
352
+ const products = configuredProductRepos(schedulePath);
353
+ // Phase 1: plan/result 生成 → register start → checkpoint → worktree 作成(root で直列化)。
354
+ const setup = async () => {
355
+ // executor が成功した run の worktree を、全体再実行が破棄しないよう保護する。
356
+ // discardStaleExecWorktree は worktree と exec ブランチを強制削除するため、未コミットの
357
+ // executor 成果が失われる。この場合は何も壊さずに中断し、再開か明示的な破棄を促す。
358
+ const protection = protectResumableRegisterWorktree(context, opts, item.id, worktreeTaskId);
359
+ if (protection) {
360
+ process.stderr.write(`${protection}\n`);
361
+ return {
362
+ id: item.id,
363
+ title: item.title,
364
+ outcome: "failure",
365
+ transition: "none",
366
+ commit: "off",
367
+ reason: sanitizeRegisterConclusion(protection),
368
+ };
369
+ }
370
+ const discarded = discardStaleExecWorktree({ context: wtContext, worktreeTaskId, products });
371
+ if (discarded)
372
+ process.stdout.write(` [run] discarded stale worktree/branch: ${discarded}\n`);
373
+ const { planPath } = await generateRegisterPlan({
374
+ executionPath,
375
+ projectId,
376
+ registerPaths,
377
+ item,
378
+ stem,
379
+ });
380
+ const prompt = expandPromptRefs(readFileSync(planPath, "utf8"));
381
+ const { resultPath, supersededPaths } = await scaffoldResult({
382
+ executionPath,
383
+ taskId: item.id,
384
+ mode: "edit",
385
+ projectId,
386
+ origin: "register",
387
+ planRef: `exec/plans/${stem}-plan.md`,
388
+ agent: actor,
389
+ startedAt: new Date().toISOString(),
390
+ stem,
391
+ });
392
+ const resultScaffold = readResultFrontmatterSnapshot(resultPath);
393
+ process.stdout.write(`Register item: ${item.id} — ${item.title} [${item.type}]\n`);
394
+ process.stdout.write(` Agent: ${actor}\n`);
395
+ if (!spawnRegisterTransition(projectId, ["start", "--id", item.id, "--by", actor])) {
396
+ throw new Error(`register start failed: ${item.id}`);
397
+ }
398
+ const checkpointRel = registerRunnerManagedPaths(repoRoot, registerPaths, planPath, resultPath, worktreeStatusPaths(repoRoot), ticketPath, supersededPaths);
399
+ const checkpointPaths = checkpointRel.map((rel) => resolve(repoRoot, rel));
400
+ const checkpointFailureLogPath = pipelineRunId
401
+ ? integrateLogPath(pipelineStateLocation({
402
+ repoRoot,
403
+ worktreePath: repoRoot,
404
+ executionPath,
405
+ taskId: item.id,
406
+ runId: pipelineRunId,
407
+ }).path)
408
+ : undefined;
409
+ try {
410
+ const worktree = checkpointAndEnsureWorktree({
411
+ context: wtContext,
412
+ worktreeTaskId,
413
+ base: worktreeBase,
414
+ checkpointPaths,
415
+ commitMessage: `exec(register ${item.id}): start`,
416
+ products,
417
+ failureLogPath: checkpointFailureLogPath,
418
+ });
419
+ const setupAction = worktree.created ? "setup" : "reuse";
420
+ process.stdout.write(` [run] ${setupAction}: worktree ${worktree.path} (${worktree.branch})\n`);
421
+ reportProductWorktrees(worktree);
422
+ return {
423
+ worktree,
424
+ planPath,
425
+ resultPath,
426
+ resultScaffold,
427
+ prompt,
428
+ bookkeepingPaths: checkpointPaths,
429
+ };
430
+ }
431
+ catch (error) {
432
+ // checkpoint 失敗時は exec branch に commit が無く、root の実行管理ファイルが正本のまま。
433
+ // start を巻き戻して waiting にし、その状態を root の wait commit 1件にまとめる
434
+ // (作りかけの worktree は次回実行の discardStaleExecWorktree が片付ける)。
435
+ return registerWaitSummary({
436
+ repoRoot,
437
+ projectId,
438
+ registerPaths,
439
+ item,
440
+ ticketPath,
441
+ reason: `checkpoint failed: ${error instanceof Error ? error.message : String(error)}`,
442
+ actor,
443
+ bookkeepingPaths: [
444
+ ...checkpointPaths,
445
+ ...(checkpointFailureLogPath && existsSync(checkpointFailureLogPath)
446
+ ? [checkpointFailureLogPath]
447
+ : []),
448
+ ],
449
+ });
450
+ }
451
+ };
452
+ const prepared = lifecycleLock ? await lifecycleLock.runExclusive(setup) : await setup();
453
+ if ("outcome" in prepared)
454
+ return prepared;
455
+ const { worktree, planPath, resultPath, resultScaffold, prompt, bookkeepingPaths } = prepared;
456
+ // Phase 2: agent を worktree 内で実行(ロック外・並列可能な長時間部分)。
457
+ const env = agentEnvironment(repoRoot, worktree.path, schedulePath, executionPath, worktree.repos);
458
+ let agentResult;
459
+ let stderr = "";
460
+ // pipeline 実行のみ run state を持つ。統合段の記録先として Phase 3 へ渡す。
461
+ let pipelineStatePath;
462
+ if (pipelineAgents) {
463
+ process.stdout.write(`Running ${item.id} in worktree (executor/reporter pipeline)\n CWD: ${worktree.path}\n`);
464
+ const worktreeResultPathForPipeline = pathInsideWorktree(repoRoot, worktree.path, resultPath);
465
+ const pipelineOutcome = await runAgentPipeline({
466
+ repoRoot,
467
+ cwd: worktree.path,
468
+ schedulePath,
469
+ executionPath,
470
+ taskId: item.id,
471
+ executor: pipelineAgents.executor,
472
+ reporterCandidates: pipelineAgents.reporterCandidates,
473
+ planPath,
474
+ planPrompt: prompt,
475
+ resultPath: worktreeResultPathForPipeline,
476
+ registerPaths: registerReporterManagedPaths(registerPaths),
477
+ execDefaults: context.execDefaults,
478
+ providerConcurrencyGate: context.providerConcurrencyGate,
479
+ productWorktrees: worktree.repos,
480
+ runId: pipelineRunId,
481
+ });
482
+ agentResult = pipelineOutcome.runResult;
483
+ stderr = pipelineOutcome.blockReason ?? "";
484
+ pipelineStatePath = resolve(worktree.path, pipelineOutcome.stateRef);
485
+ }
486
+ else {
487
+ process.stdout.write(`Running ${item.id} in worktree: ${command}\n CWD: ${worktree.path}\n`);
488
+ const outcome = await runWithRetry([{ command, actor, provider: resolvedProvider }], withProductRepoPrompt(prompt, worktree.repos), context.execDefaults, worktree.path, env, pathInsideWorktree(repoRoot, worktree.path, resultPath));
489
+ agentResult = outcome.result;
490
+ stderr = outcome.stderr;
491
+ }
492
+ // Phase 3: 成果物統合と状態遷移(root で直列化)。通常実行と再開経路で共通化する。
493
+ const finalize = async () => finalizeRegisterWorktreeRun({
494
+ context,
495
+ registerPaths,
496
+ item,
497
+ ticketPath,
498
+ worktree,
499
+ stem,
500
+ worktreeResultPath: pathInsideWorktree(repoRoot, worktree.path, resultPath),
501
+ resultScaffold,
502
+ agentResult,
503
+ stderr,
504
+ actor,
505
+ bookkeepingPaths,
506
+ pipelineStatePath,
507
+ });
508
+ return lifecycleLock ? lifecycleLock.runExclusive(finalize) : finalize();
509
+ }