specdojo 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +77 -18
  3. package/dist/catalog/build-references.js +144 -0
  4. package/dist/catalog/build-render.js +32 -0
  5. package/dist/{catalog-build.js → catalog/build.js} +18 -295
  6. package/dist/{catalog.js → catalog/catalog.js} +11 -11
  7. package/dist/{catalog-generate.js → catalog/generate.js} +13 -16
  8. package/dist/catalog/paths.js +1 -0
  9. package/dist/{catalog-plan-generate.js → catalog/plan-generate.js} +5 -5
  10. package/dist/{catalog-plan.js → catalog/plan.js} +9 -9
  11. package/dist/{catalog-scaffold.js → catalog/scaffold.js} +6 -6
  12. package/dist/{agent.js → commands/agent.js} +11 -11
  13. package/dist/{build-command.js → commands/build.js} +2 -2
  14. package/dist/{init-command.js → commands/init.js} +103 -37
  15. package/dist/{orchestrator.js → commands/orchestrator.js} +2 -2
  16. package/dist/{watch.js → commands/watch.js} +3 -3
  17. package/dist/dashboard/dashboard-timeline.js +175 -0
  18. package/dist/{dashboard.js → dashboard/dashboard.js} +16 -549
  19. package/dist/dashboard/exec-records.js +105 -0
  20. package/dist/dashboard/routines.js +256 -0
  21. package/dist/dashboard/shared.js +14 -0
  22. package/dist/{timeline-build.js → dashboard/timeline-build.js} +2 -1
  23. package/dist/{timeline.js → dashboard/timeline.js} +1 -1
  24. package/dist/{deliverable.js → deliverable/deliverable.js} +5 -5
  25. package/dist/{deliverable-trash.js → deliverable/trash.js} +7 -7
  26. package/dist/{devcontainer-command.js → devcontainer/command.js} +5 -3
  27. package/dist/{devcontainer-scaffold.js → devcontainer/scaffold.js} +94 -2
  28. package/dist/{doc-index.js → docs/doc-index.js} +3 -3
  29. package/dist/{frontmatter-namespace.js → docs/frontmatter-namespace.js} +2 -2
  30. package/dist/{index-command.js → docs/index-command.js} +1 -1
  31. package/dist/docs/template-resolution.js +1 -0
  32. package/dist/{viewpoint-document-kinds-check.js → docs/viewpoint-document-kinds-check.js} +3 -3
  33. package/dist/{yaml-pages-command.js → docs/yaml-pages-command.js} +1 -1
  34. package/dist/{yaml-pages.js → docs/yaml-pages.js} +5 -5
  35. package/dist/{exec-agent-config.js → exec/agent-config.js} +33 -4
  36. package/dist/{exec-agent-git-state.js → exec/agent-git-state.js} +1 -1
  37. package/dist/{exec-agent-protected-config.js → exec/agent-protected-config.js} +1 -1
  38. package/dist/{exec.js → exec/commands.js} +22 -467
  39. package/dist/exec/core.js +457 -0
  40. package/dist/{exec-events.js → exec/events.js} +2 -2
  41. package/dist/{exec-evidence.js → exec/evidence.js} +11 -6
  42. package/dist/exec/exec.js +2 -0
  43. package/dist/exec/format.js +1 -0
  44. package/dist/{exec-handoff.js → exec/handoff.js} +13 -12
  45. package/dist/{exec-limit.js → exec/limit.js} +93 -12
  46. package/dist/{exec-parent-validation.js → exec/parent-validation.js} +4 -4
  47. package/dist/{exec-pipeline-state.js → exec/pipeline-state.js} +16 -2
  48. package/dist/{exec-plans.js → exec/plans-core.js} +97 -468
  49. package/dist/exec/plans-generation.js +249 -0
  50. package/dist/exec/plans-storage.js +131 -0
  51. package/dist/exec/plans.js +3 -0
  52. package/dist/{exec-project.js → exec/project.js} +1 -1
  53. package/dist/{exec-protection-handoff.js → exec/protection-handoff.js} +3 -3
  54. package/dist/{exec-register-resume.js → exec/register-resume.js} +2 -2
  55. package/dist/{exec-register.js → exec/register.js} +92 -9
  56. package/dist/exec/repo-integration-git.js +23 -0
  57. package/dist/exec/repo-integration-sync.js +264 -0
  58. package/dist/{exec-repo-integration.js → exec/repo-integration.js} +13 -287
  59. package/dist/{exec-repo-trace.js → exec/repo-trace.js} +3 -3
  60. package/dist/exec/reporter-output.js +206 -0
  61. package/dist/{exec-reporter.js → exec/reporter.js} +29 -216
  62. package/dist/{exec-results.js → exec/results.js} +277 -36
  63. package/dist/exec/run/agent-pipeline.js +276 -0
  64. package/dist/exec/run/agent.js +583 -0
  65. package/dist/exec/run/in-place.js +570 -0
  66. package/dist/exec/run/job.js +746 -0
  67. package/dist/exec/run/lifecycle-commands.js +530 -0
  68. package/dist/{exec-run-lock.js → exec/run/lock.js} +4 -3
  69. package/dist/exec/run/mode-shared.js +140 -0
  70. package/dist/exec/run/register-command.js +252 -0
  71. package/dist/exec/run/register-core.js +411 -0
  72. package/dist/exec/run/register-mode.js +210 -0
  73. package/dist/exec/run/register-resume.js +398 -0
  74. package/dist/exec/run/register-state.js +325 -0
  75. package/dist/exec/run/register-worktree.js +540 -0
  76. package/dist/exec/run/run.js +11 -0
  77. package/dist/exec/run/schedule-mode.js +294 -0
  78. package/dist/exec/run/schedule-prepare.js +366 -0
  79. package/dist/exec/run/schedule-task.js +599 -0
  80. package/dist/exec/run/shared.js +449 -0
  81. package/dist/{exec-schedule-calendar.js → exec/schedule/calendar.js} +1 -1
  82. package/dist/{exec-schedule-cpm.js → exec/schedule/cpm.js} +2 -2
  83. package/dist/{exec-schedule-gantt-chart-render.js → exec/schedule/gantt-chart-render.js} +2 -2
  84. package/dist/exec/schedule/gantt-chart.js +2 -0
  85. package/dist/{exec-schedule-hash.js → exec/schedule/hash.js} +2 -2
  86. package/dist/exec/schedule/index.js +1 -0
  87. package/dist/{exec-schedule-initial.js → exec/schedule/initial.js} +2 -2
  88. package/dist/{exec-schedule-progress.js → exec/schedule/progress.js} +2 -2
  89. package/dist/{exec-schedule-ready.js → exec/schedule/ready.js} +2 -2
  90. package/dist/{exec-schedule.js → exec/schedule/schedule.js} +11 -11
  91. package/dist/exec/shared.js +63 -0
  92. package/dist/exec/slot-lock.js +1 -0
  93. package/dist/{exec-strategy.js → exec/strategy.js} +2 -2
  94. package/dist/{exec-task-repos.js → exec/task-repos.js} +2 -2
  95. package/dist/{exec-task-view.js → exec/task-view.js} +4 -4
  96. package/dist/{exec-trial.js → exec/trial-commands.js} +23 -388
  97. package/dist/exec/trial-core.js +371 -0
  98. package/dist/exec/trial.js +2 -0
  99. package/dist/{exec-worktree-command.js → exec/worktree-command.js} +25 -23
  100. package/dist/exec/worktree-ops-commit.js +672 -0
  101. package/dist/exec/worktree-ops-lifecycle.js +297 -0
  102. package/dist/exec/worktree-ops-merge.js +344 -0
  103. package/dist/exec/worktree-ops.js +3 -0
  104. package/dist/exec/worktree.js +305 -0
  105. package/dist/grade/apply.js +734 -0
  106. package/dist/grade/command-apply.js +250 -0
  107. package/dist/grade/command-inspect.js +138 -0
  108. package/dist/grade/command-plan.js +101 -0
  109. package/dist/grade/command-shared.js +68 -0
  110. package/dist/grade/core.js +307 -0
  111. package/dist/grade/grade.js +19 -0
  112. package/dist/grade/markdown.js +274 -0
  113. package/dist/grade/pipeline-state.js +184 -0
  114. package/dist/grade/plan.js +507 -0
  115. package/dist/{grade-result.js → grade/result.js} +7 -96
  116. package/dist/grade/target-discovery.js +265 -0
  117. package/dist/grade/targets.js +435 -0
  118. package/dist/{job.js → job/definition.js} +32 -574
  119. package/dist/job/job.js +568 -0
  120. package/dist/{kata-command.js → kata/command.js} +4 -4
  121. package/dist/{kata.js → kata/kata.js} +5 -5
  122. package/dist/register/approach.js +134 -0
  123. package/dist/register/command-types.js +1 -0
  124. package/dist/register/core.js +369 -0
  125. package/dist/register/create-commands.js +352 -0
  126. package/dist/{register-date.js → register/date.js} +1 -1
  127. package/dist/register/derivation.js +163 -0
  128. package/dist/{register-event-merge.js → register/event-merge.js} +32 -3
  129. package/dist/{register-events.js → register/events.js} +12 -6
  130. package/dist/{register-history.js → register/history.js} +7 -6
  131. package/dist/{register-item.js → register/item.js} +28 -10
  132. package/dist/register/lifecycle-lock.js +5 -0
  133. package/dist/register/maintenance-commands.js +193 -0
  134. package/dist/{register-migrate-timestamps.js → register/migrate-timestamps.js} +3 -3
  135. package/dist/register/migration.js +268 -0
  136. package/dist/register/register.js +404 -0
  137. package/dist/register/renumber.js +341 -0
  138. package/dist/register/transition-commands.js +248 -0
  139. package/dist/register/update.js +230 -0
  140. package/dist/register/views.js +296 -0
  141. package/dist/{review-grade.js → review/grade.js} +2 -2
  142. package/dist/{review-plan.js → review/plan.js} +5 -5
  143. package/dist/routine/definition.js +401 -0
  144. package/dist/{routine.js → routine/routine.js} +50 -419
  145. package/dist/{schedule-approach.js → schedule/approach.js} +9 -9
  146. package/dist/{schedule-build.js → schedule/build.js} +7 -4
  147. package/dist/{schedule.js → schedule/schedule.js} +9 -9
  148. package/dist/schedule/strategy-generate-document.js +273 -0
  149. package/dist/schedule/strategy-generate-scope.js +199 -0
  150. package/dist/schedule/strategy-generate.js +348 -0
  151. package/dist/shared/agent-types.js +23 -0
  152. package/dist/shared/artifact-path.js +9 -0
  153. package/dist/{build-if-stale.js → shared/build-if-stale.js} +1 -1
  154. package/dist/shared/catalog-render.js +115 -0
  155. package/dist/{exec-slot-lock.js → shared/cross-process-lock.js} +3 -1
  156. package/dist/shared/fs.js +30 -0
  157. package/dist/shared/git.js +316 -0
  158. package/dist/shared/grade-result.js +94 -0
  159. package/dist/{package-paths.js → shared/package-paths.js} +3 -3
  160. package/dist/shared/plan-templates.js +114 -0
  161. package/dist/{exec-provider-scaffold.js → shared/provider-scaffold.js} +3 -1
  162. package/dist/shared/random.js +4 -0
  163. package/dist/{exec-schedule-index.js → shared/schedule-index.js} +3 -1
  164. package/dist/shared/schedule-paths.js +9 -0
  165. package/dist/{specdojo-config.js → shared/specdojo-config.js} +96 -9
  166. package/dist/{exec-shared.js → shared/text.js} +0 -134
  167. package/dist/shared/time.js +28 -0
  168. package/dist/shared/yaml.js +28 -0
  169. package/dist/specdojo.js +22 -22
  170. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +29 -17
  171. package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +1 -2
  172. package/docs/ja/specdojo/exec-templates/xep-register-template.md +1 -2
  173. package/docs/ja/specdojo/exec-templates/xer-template.md +1 -3
  174. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +6 -4
  175. package/docs/ja/specdojo/guides/exec-config-guide.md +97 -22
  176. package/docs/ja/specdojo/guides/exec-operation-guide.md +145 -12
  177. package/docs/ja/specdojo/guides/exec-worktree-guide.md +2 -0
  178. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +51 -18
  179. package/docs/ja/specdojo/guides/quick-start-guide.md +81 -16
  180. package/docs/ja/specdojo/guides/register-operation-guide.md +2 -1
  181. package/docs/ja/specdojo/guides/remote-host-development-guide.md +10 -1
  182. package/docs/ja/specdojo/guides/review-guide.md +1 -1
  183. package/docs/ja/specdojo/guides/routine-operation-guide.md +6 -6
  184. package/docs/ja/specdojo/guides/use-case-guide.md +1 -1
  185. package/docs/ja/specdojo/references/command-reference.md +52 -28
  186. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +17 -11
  187. package/docs/ja/specdojo/standards/job-definition-standard.md +20 -18
  188. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -2
  189. package/docs/ja/specdojo/templates/pjr-derived-items-template.md +22 -0
  190. package/docs/ja/specdojo/templates/pjr-index-template.md +1 -0
  191. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +29 -2
  192. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +20 -0
  193. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +23 -0
  194. package/docs/specdojo/schemas/v1/job-run.schema.yaml +2 -2
  195. package/docs/specdojo/schemas/v1/job.schema.yaml +7 -0
  196. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +26 -0
  197. package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
  198. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +70 -7
  199. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +1 -1
  200. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +1 -1
  201. package/package.json +4 -5
  202. package/templates/antigravity/README.md +7 -3
  203. package/templates/antigravity/agent-members-snippet.yaml +108 -12
  204. package/templates/antigravity/exec-defaults-snippet.yaml +10 -13
  205. package/templates/claude/README.md +27 -3
  206. package/templates/claude/agents/claude-executor.md +0 -1
  207. package/templates/claude/agents/claude-reporter.md +2 -1
  208. package/templates/claude/agents/claude-review-executor.md +0 -1
  209. package/templates/codex/README.md +23 -4
  210. package/templates/devcontainer/devcontainer.json +2 -2
  211. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +69 -0
  212. package/templates/devcontainer/remote-host/ssh-config.sample +16 -0
  213. package/templates/init-agent-members.yaml +75 -25
  214. package/templates/init-exec-defaults.yaml +26 -8
  215. package/templates/opencode/README.md +17 -3
  216. package/templates/opencode/agents/opencode-executor.md +0 -1
  217. package/templates/opencode/agents/opencode-reporter.md +2 -1
  218. package/templates/opencode/agents/opencode-review-executor.md +0 -1
  219. package/dist/exec-run.js +0 -6182
  220. package/dist/exec-schedule-gantt-chart.js +0 -2
  221. package/dist/exec-worktree-ops.js +0 -1292
  222. package/dist/exec-worktree.js +0 -446
  223. package/dist/grade.js +0 -3193
  224. package/dist/register.js +0 -2407
  225. package/dist/schedule-strategy-generate.js +0 -812
  226. package/templates/claude/agents/claude-expert-review-executor.md +0 -14
  227. /package/dist/{catalog-plan-prompt.js → catalog/plan-prompt.js} +0 -0
  228. /package/dist/{catalog-types.js → catalog/types.js} +0 -0
  229. /package/dist/{template-frontmatter.js → docs/template-frontmatter.js} +0 -0
  230. /package/dist/{role-types.js → exec/role-types.js} +0 -0
  231. /package/dist/{exec-schedule-gantt-chart-scope.js → exec/schedule/gantt-chart-scope.js} +0 -0
  232. /package/dist/{exec-types.js → exec/types.js} +0 -0
  233. /package/dist/{review-types.js → review/types.js} +0 -0
  234. /package/dist/{schedule-phase-sets.js → schedule/phase-sets.js} +0 -0
  235. /package/dist/{schedule-strategy-profiles.js → schedule/strategy-profiles.js} +0 -0
  236. /package/dist/{agent-response.js → shared/agent-response.js} +0 -0
  237. /package/dist/{catalog-paths.js → shared/catalog-paths.js} +0 -0
  238. /package/dist/{dist-freshness.js → shared/dist-freshness.js} +0 -0
  239. /package/dist/{git-environment.js → shared/git-environment.js} +0 -0
  240. /package/dist/{exec-format.js → shared/markdown-format.js} +0 -0
  241. /package/dist/{practice-id.js → shared/practice-id.js} +0 -0
  242. /package/dist/{spawn-self.js → shared/spawn-self.js} +0 -0
  243. /package/dist/{specdojo-gitignore.js → shared/specdojo-gitignore.js} +0 -0
  244. /package/dist/{template-resolution.js → shared/template-resolution.js} +0 -0
  245. /package/dist/{yaml-schema-modeline.js → shared/yaml-schema-modeline.js} +0 -0
@@ -1,1292 +0,0 @@
1
- import { spawnSync } from "node:child_process";
2
- import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
- import { load } from "js-yaml";
5
- import { acquireSchedulerLock, releaseSchedulerLock } from "./exec-events.js";
6
- import { deliverableDocPath, parsePlanTaskIdentity, targetReferenceDirsForApproach, } from "./exec-plans.js";
7
- import { parseResultTaskIdentity } from "./exec-results.js";
8
- import { stripTerminalControlSequences } from "./exec-shared.js";
9
- import { agentProtectedConfigPaths, agentProtectedConfigViolation, qualifiedRepoPaths, } from "./exec-agent-protected-config.js";
10
- import { recordProtectedConfigBlockAcrossRepos } from "./exec-protection-handoff.js";
11
- import { assertNoPendingProductChanges, discardStaleProductWorktrees, ensureProductWorktrees, productIntegrationTarget, projectRepoDirName, productWorktreeRemovalBlockers, removeEmptyTaskDirectory, removeProductWorktrees, } from "./exec-task-repos.js";
12
- import { specdojoPackageRootDir } from "./package-paths.js";
13
- import { rebuildRegisterTicketFromEvents, unionRegisterEventLogs } from "./register-event-merge.js";
14
- import { displayIdFromRegisterEventFilename, REGISTER_EVENTS_DIRNAME } from "./register-events.js";
15
- import { displayIdFromTicketFilename } from "./register-item.js";
16
- import { appendGitFailureLog, ensureExecWorktree, execBranchExists, findExecWorktree, generateWorktreeArtifacts, gitEnvironment, gitOutput, gitResult, listRegisteredWorktrees, summarizeGitHookFailure, worktreeNameFromTaskId, } from "./exec-worktree.js";
17
- const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
18
- const DEFAULT_LOCK_STALE_MS = 300_000;
19
- const MAX_COMMIT_STABILIZATION_ATTEMPTS = 3;
20
- export function repoRelative(repoRoot, path) {
21
- const value = relative(repoRoot, path);
22
- if (!value || value === ".." || value.startsWith(`..${sep}`)) {
23
- throw new Error(`Path is outside repository root: ${path}`);
24
- }
25
- return value.split(sep).join("/");
26
- }
27
- export function currentBranch(repoRoot) {
28
- const branch = gitOutput(repoRoot, ["branch", "--show-current"]).trim();
29
- if (!branch)
30
- throw new Error("Detached HEAD is not supported for exec worktree commands.");
31
- return branch;
32
- }
33
- function statusPaths(repoRoot) {
34
- const output = gitOutput(repoRoot, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
35
- const records = output.split("\0").filter(Boolean);
36
- const paths = [];
37
- for (let index = 0; index < records.length; index++) {
38
- const record = records[index];
39
- if (record.length < 4)
40
- continue;
41
- const status = record.slice(0, 2);
42
- paths.push(record.slice(3));
43
- if ((status.includes("R") || status.includes("C")) && records[index + 1]) {
44
- paths.push(records[++index]);
45
- }
46
- }
47
- return paths;
48
- }
49
- export function worktreeStatusPaths(repoRoot) {
50
- return statusPaths(repoRoot);
51
- }
52
- export function taskPaths(context, taskId) {
53
- const executionRel = repoRelative(context.repoRoot, context.executionPath);
54
- return {
55
- executionRel,
56
- planRel: `${executionRel}/exec/plans/${taskId}-plan.md`,
57
- resultRel: `${executionRel}/exec/results/${taskId}-result.md`,
58
- };
59
- }
60
- export function isCommitTargetPath(path, executionRel, resultRel) {
61
- const normalized = path.replaceAll("\\", "/");
62
- if (normalized === resultRel)
63
- return true;
64
- // doc-index は root と worktree の双方で再生成される生成物。commit-target に含めると
65
- // merge 時の overlap ガードで衝突するため除外する。
66
- if (normalized === ".specdojo/doc-index.json")
67
- return false;
68
- if (normalized === "tmp" || normalized.startsWith("tmp/"))
69
- return false;
70
- if (normalized.startsWith(`${executionRel}/exec/plans/`))
71
- return false;
72
- if (normalized.startsWith(`${executionRel}/exec/results/`))
73
- return false;
74
- if (normalized.startsWith(`${executionRel}/exec/events/`))
75
- return false;
76
- if (normalized.startsWith(`${executionRel}/generated/`))
77
- return false;
78
- return true;
79
- }
80
- // Reads a deliverable's frontmatter `status`. Markdown deliverables carry it in the
81
- // leading `---` frontmatter block; yaml/json deliverables carry it as a top-level field.
82
- // Returns undefined when absent or unparsable (treated as "not ready").
83
- export function deliverableStatus(content, relPath) {
84
- const isMarkdown = /\.md$/i.test(relPath);
85
- let source = content;
86
- if (isMarkdown) {
87
- const fm = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
88
- if (!fm)
89
- return undefined;
90
- source = fm[1];
91
- }
92
- let parsed;
93
- try {
94
- parsed = load(source);
95
- }
96
- catch {
97
- return undefined;
98
- }
99
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
100
- return undefined;
101
- // Markdown deliverables carry status in the `specdojo:` namespace; yaml/json data
102
- // files carry it as a top-level field.
103
- const container = isMarkdown
104
- ? parsed.specdojo
105
- : parsed;
106
- if (!container || typeof container !== "object" || Array.isArray(container))
107
- return undefined;
108
- const status = container.status;
109
- return typeof status === "string" ? status : undefined;
110
- }
111
- // Promotion of a deliverable's frontmatter status to "ready" is a human-only gate.
112
- // Agents commit their changes through commitWorktreeChanges, so reject (block) any run
113
- // that transitions a deliverable to "ready" here; humans promote out-of-band via a direct
114
- // edit and git commit, which never passes through this path.
115
- function assertNoAgentReadyPromotion(context, worktree, taskId, paths) {
116
- const { resultRel } = taskPaths(context, taskId);
117
- const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
118
- if (resultContent && parseResultTaskIdentity(resultContent)?.execution === "human") {
119
- return;
120
- }
121
- const promoted = [];
122
- for (const relPath of paths) {
123
- if (relPath === resultRel)
124
- continue;
125
- const absPath = resolve(worktree.path, relPath);
126
- if (!existsSync(absPath))
127
- continue; // deletion is not a promotion
128
- if (deliverableStatus(readFileSync(absPath, "utf8"), relPath) !== "ready")
129
- continue;
130
- const base = gitResult(worktree.path, ["show", `HEAD:${relPath}`]);
131
- const baseStatus = base.status === 0 && typeof base.stdout === "string"
132
- ? deliverableStatus(base.stdout, relPath)
133
- : undefined;
134
- if (baseStatus !== "ready")
135
- promoted.push(relPath);
136
- }
137
- if (promoted.length > 0) {
138
- throw new Error(`Deliverable status promotion to "ready" is human-only and must not be done by an agent run: ${promoted.join(", ")}`);
139
- }
140
- }
141
- function isHumanWorktreeExecution(context, worktree, taskId) {
142
- const { resultRel } = taskPaths(context, taskId);
143
- const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
144
- return !!resultContent && parseResultTaskIdentity(resultContent)?.execution === "human";
145
- }
146
- // worktree の未 commit 差分に加え、agent が provider 側の git 制約を回避して直接
147
- // commit した差分も検査する。human execution と通常の人間 / orchestrator commit は
148
- // agent 統合経路ではないため、このガードの対象外。
149
- function assertNoAgentProtectedConfigChanges(context, worktree, taskId) {
150
- if (isHumanWorktreeExecution(context, worktree, taskId))
151
- return;
152
- const { resultRel } = taskPaths(context, taskId);
153
- const rootHead = gitOutput(context.repoRoot, ["rev-parse", "HEAD"]).trim();
154
- const compareBase = gitOutput(worktree.path, ["merge-base", "HEAD", rootHead]).trim();
155
- const committed = zeroSeparatedPaths(worktree.path, [
156
- "diff",
157
- "--no-renames",
158
- "--name-only",
159
- "-z",
160
- `${compareBase}..HEAD`,
161
- ]);
162
- const protectedPaths = agentProtectedConfigPaths(worktree.path, [
163
- ...statusPaths(worktree.path),
164
- ...committed,
165
- ]);
166
- const changes = [
167
- ...(protectedPaths.length > 0
168
- ? [{ repo: { root: worktree.path }, paths: protectedPaths }]
169
- : []),
170
- ...productProtectedConfigChanges(worktree),
171
- ];
172
- if (changes.length > 0) {
173
- const reason = agentProtectedConfigViolation(qualifiedRepoPaths(changes));
174
- // commit 前の再検査でも、対象と提案差分を result の申し送りへ残してから block する。
175
- recordProtectedConfigBlockAcrossRepos({
176
- resultPath: resolve(worktree.path, resultRel),
177
- changes,
178
- reason,
179
- });
180
- throw new Error(reason);
181
- }
182
- }
183
- // プロダクト worktree の未 commit 差分と、統合先から進んだ exec branch の commit を保護パスで検査する。
184
- function productProtectedConfigChanges(worktree) {
185
- return (worktree.repos ?? []).flatMap((product) => {
186
- if (!existsSync(product.path))
187
- return [];
188
- const target = productIntegrationTarget(product);
189
- const base = gitResult(product.path, ["merge-base", "HEAD", target]);
190
- const compareBase = typeof base.stdout === "string" ? base.stdout.trim() : "";
191
- const committed = base.status === 0 && compareBase
192
- ? zeroSeparatedPaths(product.path, [
193
- "diff",
194
- "--no-renames",
195
- "--name-only",
196
- "-z",
197
- `${compareBase}..HEAD`,
198
- ])
199
- : [];
200
- const paths = agentProtectedConfigPaths(product.path, [
201
- ...statusPaths(product.path),
202
- ...committed,
203
- ]);
204
- return paths.length > 0 ? [{ repo: { name: product.name, root: product.path }, paths }] : [];
205
- });
206
- }
207
- const DOC_INDEX_REL = ".specdojo/doc-index.json";
208
- // worktree の HEAD(CLI が checkpoint した版)からファイル内容を読む。
209
- // agent は working tree を書き換えられるが HEAD は書き換えられないため、
210
- // ここから読む情報はプロンプトインジェクションに対して改ざん耐性がある。
211
- function readWorktreeHeadFile(worktreePath, relPath) {
212
- const result = gitResult(worktreePath, ["show", `HEAD:${relPath}`]);
213
- return result.status === 0 && typeof result.stdout === "string" ? result.stdout : undefined;
214
- }
215
- // HEAD の doc-index から doc id → repo 相対パスを引く。"path:line" 形式は path 部を使う。
216
- function headDocIndexLookup(worktreePath) {
217
- const content = readWorktreeHeadFile(worktreePath, DOC_INDEX_REL);
218
- let entries = {};
219
- if (content) {
220
- try {
221
- const parsed = JSON.parse(content);
222
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
223
- const candidate = parsed.entries;
224
- if (candidate && typeof candidate === "object" && !Array.isArray(candidate)) {
225
- entries = candidate;
226
- }
227
- }
228
- }
229
- catch {
230
- // 壊れた index は「引けない」として扱い、catalog フォールバックに委ねる。
231
- }
232
- }
233
- return (id) => {
234
- const value = entries[id];
235
- if (typeof value !== "string")
236
- return undefined;
237
- const match = value.match(/^(.+):\d+$/);
238
- return match ? match[1] : value;
239
- };
240
- }
241
- // agent は HEAD の plan、human は HEAD の result frontmatter から commit 許可リストを
242
- // 導出する。いずれも task 識別を復元できない場合は null を返し、呼び出し側は従来の
243
- // 除外リスト方式へフォールバックする。checkpoint 済みの HEAD を読むため、agent の
244
- // working tree 改変からは影響を受けない。
245
- export function resolveCommitScope(context, worktree, taskId) {
246
- const { executionRel, planRel, resultRel } = taskPaths(context, taskId);
247
- const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
248
- const resultIdentity = resultContent ? parseResultTaskIdentity(resultContent) : null;
249
- const planContent = readWorktreeHeadFile(worktree.path, planRel);
250
- const planIdentity = planContent ? parsePlanTaskIdentity(planContent) : null;
251
- // 旧版で生成済みの human plan が残っていても、明示された execution を優先して
252
- // result の targets を正本に切り替える。
253
- const identity = resultIdentity?.execution === "human" ? resultIdentity : planIdentity;
254
- if (!identity)
255
- return { scope: null, unresolvedTargets: [] };
256
- if (identity.mode === "review") {
257
- return {
258
- scope: { mode: "review", allowedFiles: [resultRel], allowedDirPrefixes: [] },
259
- unresolvedTargets: [],
260
- };
261
- }
262
- // register 由来のタスクは許可リスト方式ではなく、作業ツリー差分による commit を使う。
263
- // 個票が targets を宣言している場合でも、commit scope は従来どおり除外リスト方式へ
264
- // フォールバックする(target coverage 検証は evidence 側で行い、ここでは使わない)。
265
- if (identity.origin === "register")
266
- return { scope: null, unresolvedTargets: [] };
267
- // schedule 由来の edit タスクは targets から commit 許可リストを導出する。targets が
268
- // 無いと許可リストが result 1 件へ縮退し、成果物の変更が commit されないまま worktree に
269
- // 残る。静かに縮退させず、ここで失敗させる。
270
- if ((identity.targets ?? []).length === 0) {
271
- throw new Error(`commit-scope: no targets in plan/result frontmatter for edit task ${taskId}. ` +
272
- `Schedule-originated edit tasks must declare targets; ` +
273
- `register-originated tasks must declare "origin: register".`);
274
- }
275
- const allowedFiles = new Set([resultRel]);
276
- const unresolvedTargets = [];
277
- const lookup = headDocIndexLookup(worktree.path);
278
- for (const target of identity.targets ?? []) {
279
- // `<repo>:<path>` はプロダクトリポジトリの対象で、プロダクト側の commit 対象に入る
280
- // (exec-repo-integration)。プロジェクト側の doc id としては解決しない。
281
- if (isProductRepoTarget(worktree, target))
282
- continue;
283
- const fromIndex = lookup(target);
284
- if (fromIndex) {
285
- allowedFiles.add(fromIndex);
286
- continue;
287
- }
288
- // doc-index 未登録(未作成の新規成果物など)は catalog が宣言するパスへ解決する。
289
- const localId = identity.projectId && target.startsWith(`${identity.projectId}:`)
290
- ? target.slice(identity.projectId.length + 1)
291
- : target;
292
- const fromCatalog = context.catalogPath
293
- ? deliverableDocPath(context.catalogPath, localId)
294
- : undefined;
295
- if (fromCatalog) {
296
- allowedFiles.add(fromCatalog);
297
- continue;
298
- }
299
- unresolvedTargets.push(target);
300
- }
301
- const allowedDirPrefixes = targetReferenceDirsForApproach(identity.approach).map((dir) => `${dir}/`);
302
- // Pipeline evidence is runner-owned and stored per task/run. It must be committed together with
303
- // the eventual reporter-generated result so the structured executor record survives worktree
304
- // removal. Legacy tasks create no files under this prefix, so their commit scope is unchanged.
305
- allowedDirPrefixes.push(`${executionRel}/exec/evidence/${worktreeNameFromTaskId(taskId)}/`);
306
- return {
307
- scope: { mode: "edit", allowedFiles: [...allowedFiles], allowedDirPrefixes },
308
- unresolvedTargets,
309
- };
310
- }
311
- // checkpoint 済みの HEAD の plan(human は result)frontmatter の targets。agent の working tree
312
- // 改変の影響を受けない。プロダクトリポジトリの commit 対象(`<repo>:<path>`)の導出に使う。
313
- export function taskTargetsAtHead(context, worktree, taskId) {
314
- const { planRel, resultRel } = taskPaths(context, taskId);
315
- const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
316
- const resultIdentity = resultContent ? parseResultTaskIdentity(resultContent) : null;
317
- if (resultIdentity?.execution === "human")
318
- return resultIdentity.targets ?? [];
319
- const planContent = readWorktreeHeadFile(worktree.path, planRel);
320
- return (planContent ? parsePlanTaskIdentity(planContent) : null)?.targets ?? [];
321
- }
322
- // `<repo>:<path>` 形式で、接頭辞がタスクのプロダクト worktree のリポジトリ名である値。
323
- function isProductRepoTarget(worktree, target) {
324
- const separator = target.indexOf(":");
325
- if (separator <= 0)
326
- return false;
327
- const prefix = target.slice(0, separator);
328
- return (worktree.repos ?? []).some((product) => product.name === prefix);
329
- }
330
- // register 由来のタスクで新規ファイルの作成を許す既知の成果物ディレクトリ。HEAD に追跡
331
- // ファイルを持つ最上位ディレクトリもこれに加える(利用プロジェクト固有の構成に追従するため)。
332
- export const REGISTER_NEW_FILE_DIR_PREFIXES = [
333
- "docs/",
334
- "src/",
335
- "tests/",
336
- "tools/",
337
- "scripts/",
338
- "packages/",
339
- ];
340
- // register 由来のタスクは作業ツリー差分を commit するため、agent が作業用に作った一時ファイル
341
- // (リポジトリ直下の modify.py、patch.js など)まで commit 対象に入る。HEAD に存在しない新規
342
- // ファイルは、既知の成果物ディレクトリ・HEAD の追跡済み最上位ディレクトリ・result・task の
343
- // evidence 配下・個票 targets から解決したパスに限り、それ以外を commit 範囲外とする。
344
- // 既存ファイルの変更と削除は従来どおり除外リスト方式で判定する。
345
- function registerNewFileIsAllowed(worktree, context, taskId) {
346
- const { executionRel, planRel, resultRel } = taskPaths(context, taskId);
347
- const topLevelDirs = zeroSeparatedPaths(worktree.path, [
348
- "ls-tree",
349
- "-d",
350
- "--name-only",
351
- "-z",
352
- "HEAD",
353
- ]).map((dir) => `${dir}/`);
354
- const allowedDirPrefixes = [
355
- ...REGISTER_NEW_FILE_DIR_PREFIXES,
356
- ...topLevelDirs,
357
- `${executionRel}/exec/evidence/${worktreeNameFromTaskId(taskId)}/`,
358
- ];
359
- const planContent = readWorktreeHeadFile(worktree.path, planRel);
360
- const targets = (planContent ? parsePlanTaskIdentity(planContent) : null)?.targets ?? [];
361
- const lookup = headDocIndexLookup(worktree.path);
362
- const allowedFiles = new Set([resultRel]);
363
- for (const target of targets) {
364
- const resolved = lookup(target);
365
- if (resolved)
366
- allowedFiles.add(resolved);
367
- }
368
- return (path) => !path.includes("/") ||
369
- allowedFiles.has(path) ||
370
- allowedDirPrefixes.some((prefix) => path.startsWith(prefix));
371
- }
372
- function pathsTrackedAtHead(worktreePath, paths) {
373
- if (paths.length === 0)
374
- return new Set();
375
- return new Set(zeroSeparatedPaths(worktreePath, [
376
- "ls-tree",
377
- "-r",
378
- "--name-only",
379
- "--full-tree",
380
- "-z",
381
- "HEAD",
382
- "--",
383
- ...paths,
384
- ]));
385
- }
386
- function isRegisterOriginTask(context, worktree, taskId) {
387
- const planContent = readWorktreeHeadFile(worktree.path, taskPaths(context, taskId).planRel);
388
- return (planContent ? parsePlanTaskIdentity(planContent) : null)?.origin === "register";
389
- }
390
- // worktree の変更を「commit するパス」「許可リスト外のため commit しないパス」に分ける。
391
- // 除外リスト(isCommitTargetPath)は許可リストの内側でも引き続き適用する。
392
- export function partitionCommitTargets(context, worktree, taskId) {
393
- const { executionRel, resultRel } = taskPaths(context, taskId);
394
- const candidates = statusPaths(worktree.path).filter((path) => isCommitTargetPath(path, executionRel, resultRel));
395
- const { scope, unresolvedTargets } = resolveCommitScope(context, worktree, taskId);
396
- if (!scope) {
397
- // 人間の作業は agent の一時ファイル対策の対象外とし、従来どおり除外リスト方式で commit する。
398
- if (!isRegisterOriginTask(context, worktree, taskId) ||
399
- isHumanWorktreeExecution(context, worktree, taskId)) {
400
- return { targets: candidates, outOfScope: [], unresolvedTargets };
401
- }
402
- const tracked = pathsTrackedAtHead(worktree.path, candidates);
403
- const isAllowedNewFile = registerNewFileIsAllowed(worktree, context, taskId);
404
- const targets = [];
405
- const outOfScope = [];
406
- for (const path of candidates) {
407
- const allowed = tracked.has(path) || isAllowedNewFile(path);
408
- (allowed ? targets : outOfScope).push(path);
409
- }
410
- return { targets, outOfScope, unresolvedTargets };
411
- }
412
- const targets = [];
413
- const outOfScope = [];
414
- for (const path of candidates) {
415
- const allowed = scope.allowedFiles.includes(path) ||
416
- scope.allowedDirPrefixes.some((prefix) => path.startsWith(prefix));
417
- (allowed ? targets : outOfScope).push(path);
418
- }
419
- return { targets, outOfScope, unresolvedTargets };
420
- }
421
- export function commitTargetPaths(context, worktree, taskId) {
422
- return partitionCommitTargets(context, worktree, taskId).targets;
423
- }
424
- // `git add` の pathspec は作業ツリーと index だけを照合する。削除が既に index へ入っている
425
- // パスはそのどちらにも存在しないため、`-A` を付けても「pathspec did not match any files」で
426
- // fatal になる。このようなパスは追加で stage する内容が無いので、add の対象から除外する。
427
- // commit / commit --amend の pathspec は HEAD も照合するため、対象から外さずに削除を記録できる。
428
- export function selectStageablePaths(repoRoot, paths) {
429
- if (paths.length === 0)
430
- return [];
431
- const indexed = new Set(zeroSeparatedPaths(repoRoot, ["ls-files", "--full-name", "-z", "--", ...paths]));
432
- // 作業ツリー側の存在確認は lstat で行う。git は symlink 自体を追跡するため、リンク先が
433
- // 無い symlink も add の対象になる(existsSync はリンク先を辿るため false になる)。
434
- const existsInWorktree = (path) => lstatSync(resolve(repoRoot, path), { throwIfNoEntry: false }) !== undefined;
435
- return paths.filter((path) => indexed.has(path) || existsInWorktree(path));
436
- }
437
- // commit 対象を stage する。stage できる対象が無い場合(staged 済みの削除だけが残る場合)は
438
- // git add を実行しない。commit 対象の限定は呼び出し側の paths が担うため、範囲は変わらない。
439
- export function stageCommitTargets(repoRoot, paths) {
440
- const stageable = selectStageablePaths(repoRoot, paths);
441
- if (stageable.length === 0)
442
- return;
443
- gitOutput(repoRoot, ["add", "-A", "--", ...stageable]);
444
- }
445
- // runner が stage した対象だけを index から戻す。利用者や別処理が stage 済みの無関係な
446
- // パスは保持し、commit / hook の失敗を後続の exec run へ持ち越さない。
447
- export function unstageCommitTargets(repoRoot, paths) {
448
- const unique = [...new Set(paths)];
449
- if (unique.length === 0)
450
- return;
451
- gitOutput(repoRoot, ["reset", "--quiet", "--", ...unique]);
452
- }
453
- // markdownlint-cli の終了コード。1 だけが記法違反を表し、それ以外は実行環境の問題である。
454
- const MARKDOWNLINT_EXIT_LINT_ERRORS = 1;
455
- // worktree または SpecDojo package の node_modules から markdownlint-cli を探す。
456
- // markdownlint-cli は devDependency のため、配布先の利用プロジェクトでは存在しないことがある。
457
- function findMarkdownlintExecutable(worktreePath) {
458
- const executableName = process.platform === "win32" ? "markdownlint.cmd" : "markdownlint";
459
- const candidates = [
460
- join(worktreePath, "node_modules", ".bin", executableName),
461
- join(specdojoPackageRootDir(), "node_modules", ".bin", executableName),
462
- ];
463
- return candidates.find(existsSync);
464
- }
465
- // result は commit hook の Prettier 実行対象から除外するため(.prettierignore)、runner が
466
- // commit 前に markdownlint を直接実行する。hook 由来の汎用的な git commit 失敗ではなく、
467
- // result の記法違反として block 理由を残せるようにする。
468
- // markdownlint-cli が見つからない環境では検査を省略し、hook 側の検査に委ねる。
469
- // 行末の空白を除き、ファイル末尾を改行 1 つに揃える。強調記法など内容に関わる置換は行わない。
470
- export function normalizeResultWhitespace(resultPath) {
471
- const content = readFileSync(resultPath, "utf8");
472
- const normalized = content.replace(/[ \t]+$/gm, "").replace(/\n*$/, "\n");
473
- if (normalized !== content)
474
- writeFileSync(resultPath, normalized, "utf8");
475
- }
476
- export function assertResultMarkdownlint(context, worktree, taskId) {
477
- const { resultRel } = taskPaths(context, taskId);
478
- const resultPath = resolve(worktree.path, resultRel);
479
- if (!existsSync(resultPath)) {
480
- process.stdout.write(`result-markdownlint: result ${resultRel} not found; skipped pre-commit lint\n`);
481
- return;
482
- }
483
- // reporter の出力に由来する行末の空白と末尾改行の不足は、内容に影響しない空白だけの違反
484
- // (MD009 / MD047)であり、以前は commit hook の Prettier が黙って整えていた。Prettier の
485
- // 対象外にした分をここで補い、記法違反として block するのは内容に関わる違反に限る。
486
- normalizeResultWhitespace(resultPath);
487
- const executable = findMarkdownlintExecutable(worktree.path);
488
- if (!executable) {
489
- process.stdout.write(`result-markdownlint: markdownlint-cli not found; skipped pre-commit lint of ${resultRel}\n`);
490
- return;
491
- }
492
- const result = spawnSync(executable, [resultRel], {
493
- cwd: worktree.path,
494
- encoding: "utf8",
495
- env: gitEnvironment(),
496
- stdio: ["ignore", "pipe", "pipe"],
497
- });
498
- if (!result.error && result.status === 0)
499
- return;
500
- const output = stripTerminalControlSequences([result.stdout, result.stderr, result.error?.message].filter(Boolean).join("\n"))
501
- .trim()
502
- .replace(/\s+/g, " ");
503
- const detail = output ? output.slice(0, 1_000) : `exit ${result.status ?? "unknown"}`;
504
- if (!result.error && result.status === MARKDOWNLINT_EXIT_LINT_ERRORS) {
505
- throw new Error(`Result Markdown notation violation before commit: ${detail}`);
506
- }
507
- throw new Error(`Failed to run markdownlint on ${resultRel} before commit: ${detail}`);
508
- }
509
- export function stabilizeCommitTargets(repoRoot, listRemainingPaths, maxAttempts = MAX_COMMIT_STABILIZATION_ATTEMPTS, failureLogPath) {
510
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
511
- const paths = listRemainingPaths();
512
- if (paths.length === 0)
513
- return;
514
- stageCommitTargets(repoRoot, paths);
515
- const staged = gitResult(repoRoot, ["diff", "--cached", "--quiet", "--", ...paths]);
516
- if (staged.status === 0) {
517
- // pathspec commit は hook が再stageした内容を commit した後、元の index を復元して
518
- // HEAD と逆向きの差分を残す場合がある。この場合は add が index を HEAD へ揃えて
519
- // 差分を解消するため、再取得して消えていれば正常な収束として扱う。
520
- const remaining = listRemainingPaths();
521
- if (remaining.length === 0)
522
- return;
523
- throw new Error(`Failed to stage post-hook commit-target changes: ${remaining.join(", ")}`);
524
- }
525
- if (staged.status !== 1)
526
- throw new Error("Failed to inspect post-hook worktree changes.");
527
- const commitArgs = ["commit", "--amend", "--no-edit", "--", ...paths];
528
- const commit = gitResult(repoRoot, commitArgs);
529
- if (commit.status !== 0) {
530
- const output = [commit.stdout, commit.stderr]
531
- .filter((part) => typeof part === "string" && part.length > 0)
532
- .join("\n");
533
- appendGitFailureLog(failureLogPath, [
534
- `=== ${new Date().toISOString()} git commit --amend ===`,
535
- `exit: ${commit.status ?? "unknown"}`,
536
- "--- stdout ---",
537
- typeof commit.stdout === "string" ? commit.stdout : "",
538
- "--- stderr ---",
539
- typeof commit.stderr === "string" ? commit.stderr : "",
540
- "",
541
- ]);
542
- throw new Error(`git commit --amend failed: ${summarizeGitHookFailure(output)}`);
543
- }
544
- }
545
- const dirty = listRemainingPaths();
546
- if (dirty.length > 0) {
547
- throw new Error(`Pre-commit hooks kept changing commit-target files: ${dirty.join(", ")}`);
548
- }
549
- }
550
- function zeroSeparatedPaths(repoRoot, args) {
551
- return gitOutput(repoRoot, args).split("\0").filter(Boolean);
552
- }
553
- function rootDirtyPaths(repoRoot) {
554
- return new Set([
555
- ...zeroSeparatedPaths(repoRoot, ["diff", "--no-renames", "--name-only", "-z"]),
556
- ...zeroSeparatedPaths(repoRoot, ["diff", "--cached", "--no-renames", "--name-only", "-z"]),
557
- ...zeroSeparatedPaths(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"]),
558
- ]);
559
- }
560
- export const ROOT_NEW_FILES_HANDOFF_LABEL = "最上位に追加したファイル";
561
- export function applyRootNewFilesHandoff(content, files) {
562
- const normalized = content.replace(/\r\n/g, "\n");
563
- const uniqueFiles = [...new Set(files)];
564
- if (uniqueFiles.length === 0)
565
- return normalized;
566
- const linePattern = new RegExp(`^[ \\t]*- +${ROOT_NEW_FILES_HANDOFF_LABEL}: *(.*)$`, "m");
567
- const match = linePattern.exec(normalized);
568
- if (match) {
569
- const existingMatches = [...match[1].matchAll(/`([^`]+)`/g)].map((m) => m[1]);
570
- const merged = [...new Set([...existingMatches, ...uniqueFiles])];
571
- const newLine = `- ${ROOT_NEW_FILES_HANDOFF_LABEL}: ${merged.map((f) => `\`${f}\``).join(", ")}`;
572
- return normalized.replace(match[0], newLine);
573
- }
574
- const handoffHeading = /^## +\d+\. +申し送り[ \t]*$/m.exec(normalized);
575
- if (handoffHeading) {
576
- const start = handoffHeading.index + handoffHeading[0].length;
577
- const rest = normalized.slice(start);
578
- const nextHeading = /^##\s+/m.exec(rest);
579
- const end = nextHeading ? start + nextHeading.index : normalized.length;
580
- const sectionBody = normalized.slice(start, end);
581
- const newLine = `- ${ROOT_NEW_FILES_HANDOFF_LABEL}: ${uniqueFiles.map((f) => `\`${f}\``).join(", ")}`;
582
- const markerIndex = sectionBody.indexOf("<!-- specdojo:agent-protection-handoff -->");
583
- const beforeMarker = markerIndex === -1 ? sectionBody : sectionBody.slice(0, markerIndex);
584
- const afterMarker = markerIndex === -1 ? "" : sectionBody.slice(markerIndex);
585
- const trimmedBefore = beforeMarker.trim();
586
- let updatedBefore;
587
- if (trimmedBefore === "" ||
588
- trimmedBefore === "- なし" ||
589
- trimmedBefore === "なし" ||
590
- trimmedBefore.includes("_TODO_")) {
591
- updatedBefore = newLine;
592
- }
593
- else {
594
- updatedBefore = `${trimmedBefore}\n${newLine}`;
595
- }
596
- const newSectionBody = afterMarker
597
- ? `\n\n${updatedBefore}\n\n${afterMarker}\n\n`
598
- : `\n\n${updatedBefore}\n\n`;
599
- const updated = `${normalized.slice(0, start)}${newSectionBody}${normalized.slice(end)}`;
600
- return updated.replace(/\n{3,}/g, "\n\n").replace(/\n*$/, "\n");
601
- }
602
- const numbers = [...normalized.matchAll(/^##\s+(\d+)\./gm)].map((m) => Number(m[1]));
603
- const nextNum = numbers.length === 0 ? 1 : Math.max(...numbers) + 1;
604
- const newLine = `- ${ROOT_NEW_FILES_HANDOFF_LABEL}: ${uniqueFiles.map((f) => `\`${f}\``).join(", ")}`;
605
- return `${normalized.trimEnd()}\n\n## ${nextNum}. 申し送り\n\n${newLine}\n`;
606
- }
607
- export function recordRootNewFilesHandoff(resultPath, files) {
608
- if (!resultPath || !existsSync(resultPath) || files.length === 0)
609
- return false;
610
- try {
611
- const content = readFileSync(resultPath, "utf8");
612
- const updated = applyRootNewFilesHandoff(content, files);
613
- if (updated === content)
614
- return false;
615
- writeFileSync(resultPath, updated, "utf8");
616
- return true;
617
- }
618
- catch {
619
- return false;
620
- }
621
- }
622
- // Commit the task result and deliverable changes inside the worktree onto its exec branch.
623
- // The commit is limited to the mode-based allowlist (resolveCommitScope); out-of-scope
624
- // changes stay uncommitted in the worktree and are reported. Excludes plans, events,
625
- // generated files, and other tasks' results (see isCommitTargetPath).
626
- export function commitWorktreeChanges(params) {
627
- const { context, worktree, taskId } = params;
628
- assertNoAgentProtectedConfigChanges(context, worktree, taskId);
629
- if (!params.productsIntegratedByCaller)
630
- assertNoPendingProductChanges(worktree);
631
- let partition = partitionCommitTargets(context, worktree, taskId);
632
- const scopeWarnings = [
633
- ...partition.unresolvedTargets.map((target) => `commit-scope: unresolved target doc id (not committable): ${target}\n`),
634
- ...(partition.outOfScope.length > 0
635
- ? [
636
- `commit-scope: skipped non-target changes (left in worktree):\n${partition.outOfScope
637
- .map((path) => ` ${path}`)
638
- .join("\n")}\n`,
639
- ]
640
- : []),
641
- ];
642
- for (const warning of scopeWarnings)
643
- process.stdout.write(warning);
644
- if (scopeWarnings.length > 0 && params.scopeLogPath && !params.dryRun) {
645
- mkdirSync(resolve(params.scopeLogPath, ".."), { recursive: true });
646
- appendFileSync(params.scopeLogPath, scopeWarnings.join(""), "utf8");
647
- // 追記したログ自体を commit 対象に含めるため、分類をやり直す。
648
- partition = partitionCommitTargets(context, worktree, taskId);
649
- }
650
- const { resultRel } = taskPaths(context, taskId);
651
- const trackedAtHead = pathsTrackedAtHead(worktree.path, partition.targets);
652
- const projectRootNewFiles = partition.targets.filter((path) => !path.includes("/") && !trackedAtHead.has(path) && path !== resultRel);
653
- if (projectRootNewFiles.length > 0) {
654
- const rootNewWarning = `最上位に追加したファイル:\n` +
655
- `${projectRootNewFiles.map((path) => ` ${path}`).join("\n")}\n`;
656
- process.stdout.write(rootNewWarning);
657
- if (params.scopeLogPath && !params.dryRun) {
658
- mkdirSync(resolve(params.scopeLogPath, ".."), { recursive: true });
659
- appendFileSync(params.scopeLogPath, rootNewWarning, "utf8");
660
- partition = partitionCommitTargets(context, worktree, taskId);
661
- }
662
- }
663
- const allRootNewFiles = [...(params.productRootNewFiles ?? []), ...projectRootNewFiles];
664
- if (allRootNewFiles.length > 0 && !params.dryRun) {
665
- const resultPath = resolve(worktree.path, resultRel);
666
- if (recordRootNewFilesHandoff(resultPath, allRootNewFiles)) {
667
- partition = partitionCommitTargets(context, worktree, taskId);
668
- }
669
- }
670
- const paths = partition.targets;
671
- if (paths.length === 0) {
672
- process.stdout.write("No commit-target changes.\n");
673
- return { targets: [], committed: false };
674
- }
675
- assertNoAgentReadyPromotion(context, worktree, taskId, paths);
676
- process.stdout.write(`commit-targets:\n${paths.map((path) => ` ${path}`).join("\n")}\n`);
677
- if (params.dryRun)
678
- return { targets: paths, committed: false };
679
- assertResultMarkdownlint(context, worktree, taskId);
680
- stageCommitTargets(worktree.path, paths);
681
- const staged = gitResult(worktree.path, ["diff", "--cached", "--quiet", "--", ...paths]);
682
- if (staged.status === 0) {
683
- process.stdout.write("No staged commit-target changes.\n");
684
- return { targets: paths, committed: false };
685
- }
686
- if (staged.status !== 1)
687
- throw new Error("Failed to inspect staged worktree changes.");
688
- const commitArgs = [
689
- "commit",
690
- "-m",
691
- params.message?.trim() || `exec(${taskId}): apply task changes`,
692
- "--",
693
- ...paths,
694
- ];
695
- const commit = gitResult(worktree.path, commitArgs);
696
- if (commit.status !== 0) {
697
- const output = [commit.stdout, commit.stderr]
698
- .filter((part) => typeof part === "string" && part.length > 0)
699
- .join("\n");
700
- appendGitFailureLog(params.failureLogPath, [
701
- `=== ${new Date().toISOString()} git commit task changes ===`,
702
- `exit: ${commit.status ?? "unknown"}`,
703
- "--- stdout ---",
704
- typeof commit.stdout === "string" ? commit.stdout : "",
705
- "--- stderr ---",
706
- typeof commit.stderr === "string" ? commit.stderr : "",
707
- "",
708
- ]);
709
- throw new Error(`git commit failed: ${summarizeGitHookFailure(output)}`);
710
- }
711
- stabilizeCommitTargets(worktree.path, () => commitTargetPaths(context, worktree, taskId), undefined, params.failureLogPath);
712
- return { targets: paths, committed: true };
713
- }
714
- // The checkpoint commit lives on the exec branch only, so the root keeps its own uncommitted copy
715
- // of the bookkeeping files while the task runs (the schedule/register state must stay visible at
716
- // root). Before the exec branch is merged those copies must yield to the committed versions,
717
- // otherwise the overlap guard below rejects the merge. Capture them so a failed merge can put the
718
- // root back exactly as it was.
719
- export function releaseRootWorkingCopies(repoRoot, relPaths) {
720
- const snapshot = [];
721
- try {
722
- for (const rel of new Set(relPaths)) {
723
- const absolute = resolve(repoRoot, rel);
724
- const exists = lstatSync(absolute, { throwIfNoEntry: false }) !== undefined;
725
- snapshot.push({ rel, content: exists ? readFileSync(absolute) : null });
726
- restoreToHead(repoRoot, rel);
727
- }
728
- }
729
- catch (error) {
730
- // Releasing is itself allowed to fail (for example because a path unexpectedly became a
731
- // directory). Put back every copy already touched before propagating the failure; otherwise a
732
- // merge that never started could still discard root-side execution state.
733
- restoreRootWorkingCopies(repoRoot, snapshot);
734
- throw error;
735
- }
736
- return snapshot;
737
- }
738
- export function restoreRootWorkingCopies(repoRoot, snapshot) {
739
- for (const { rel, content } of snapshot) {
740
- const absolute = resolve(repoRoot, rel);
741
- if (content === null) {
742
- rmSync(absolute, { recursive: true, force: true });
743
- continue;
744
- }
745
- mkdirSync(resolve(absolute, ".."), { recursive: true });
746
- writeFileSync(absolute, content);
747
- }
748
- }
749
- // `git merge --abort` (reset --merge) refuses to run when a tracked file's cached stat no longer
750
- // matches the file even though its content is unchanged ("not uptodate"), which happens when another
751
- // process in the same working tree (for example a routine) touches files during the merge. Refresh
752
- // the index first so a stat-only drift cannot leave the tree mid-merge.
753
- export function abortMerge(repoRoot) {
754
- gitResult(repoRoot, ["update-index", "-q", "--refresh"]);
755
- return gitResult(repoRoot, ["merge", "--abort"]);
756
- }
757
- // `controls/project-register/events/pjr-xxxx.yaml` 形式のイベントファイルなら表示 ID を返す。
758
- function registerEventDisplayId(path) {
759
- if (basename(dirname(path)) !== REGISTER_EVENTS_DIRNAME)
760
- return undefined;
761
- return displayIdFromRegisterEventFilename(basename(path));
762
- }
763
- // Resolve an in-progress merge whose conflicts are all on exec-branch-owned paths, then complete
764
- // the merge commit. Register event files are resolved as the union of both sides and the matching
765
- // ticket is rebuilt from the merge-target-only events; other paths take the exec branch side. Returns the resolved paths, or null when the
766
- // merge has no conflicts (for example a hook rejection), conflicts on other paths, or cannot be
767
- // completed; the caller then aborts the merge. The commit uses --no-verify because a regular
768
- // `git merge` does not run pre-commit either, and only the item's own bookkeeping was resolved.
769
- function resolveBranchOwnedConflicts(params) {
770
- const { repoRoot } = params;
771
- const conflicted = zeroSeparatedPaths(repoRoot, ["diff", "--name-only", "--diff-filter=U", "-z"]);
772
- if (conflicted.length === 0)
773
- return null;
774
- const owned = new Set(params.branchOwnedPaths);
775
- if (conflicted.some((path) => !owned.has(path)))
776
- return null;
777
- const stagesOf = (path) => gitOutput(repoRoot, ["ls-files", "-u", "-z", "--", path])
778
- .split("\0")
779
- .filter(Boolean)
780
- .map((entry) => entry.split("\t")[0]?.split(" ")[2]);
781
- // イベントファイルは両側の和集合で解決し、対応する個票はイベントから再構築する。
782
- // 和集合で解決できないものは従来どおり exec branch 側で解決する。
783
- const handled = new Set();
784
- for (const path of conflicted) {
785
- const displayId = registerEventDisplayId(path);
786
- if (!displayId)
787
- continue;
788
- const stages = stagesOf(path);
789
- if (!stages.includes("2") || !stages.includes("3"))
790
- continue;
791
- const ours = gitResult(repoRoot, ["show", `:2:${path}`]);
792
- const theirs = gitResult(repoRoot, ["show", `:3:${path}`]);
793
- if (ours.status !== 0 || theirs.status !== 0)
794
- continue;
795
- const union = unionRegisterEventLogs(String(ours.stdout), String(theirs.stdout), path);
796
- if (!union.ok) {
797
- process.stdout.write(` [integrate] could not union register events; using the exec branch side: ${union.reason}\n`);
798
- continue;
799
- }
800
- writeFileSync(resolve(repoRoot, path), union.content, "utf8");
801
- if (gitResult(repoRoot, ["add", "--", path]).status !== 0)
802
- return null;
803
- handled.add(path);
804
- process.stdout.write(` [integrate] merged register events as a union: ${path} ` +
805
- `(kept ${union.oursOnlyIds.size} event(s) only on the merge target)\n`);
806
- const ticketPath = conflicted.find((candidate) => dirname(candidate) === dirname(dirname(path)) &&
807
- displayIdFromTicketFilename(basename(candidate)) === displayId);
808
- if (!ticketPath || !stagesOf(ticketPath).includes("3"))
809
- continue;
810
- const ticket = gitResult(repoRoot, ["show", `:3:${ticketPath}`]);
811
- if (ticket.status !== 0)
812
- continue;
813
- let rebuilt;
814
- try {
815
- rebuilt = rebuildRegisterTicketFromEvents(String(ticket.stdout), union.events, union.oursOnlyIds);
816
- }
817
- catch (error) {
818
- process.stdout.write(` [integrate] could not rebuild ${ticketPath} from events; using the exec branch side: ` +
819
- `${error instanceof Error ? error.message : String(error)}\n`);
820
- continue;
821
- }
822
- writeFileSync(resolve(repoRoot, ticketPath), rebuilt.content, "utf8");
823
- if (gitResult(repoRoot, ["add", "--", ticketPath]).status !== 0)
824
- return null;
825
- handled.add(ticketPath);
826
- if (rebuilt.appliedFields.length > 0) {
827
- process.stdout.write(` [integrate] rebuilt ${ticketPath} from merge-target events: ${rebuilt.appliedFields.join(", ")}\n`);
828
- }
829
- }
830
- for (const path of conflicted) {
831
- if (handled.has(path))
832
- continue;
833
- const stages = stagesOf(path);
834
- const step = stages.includes("3")
835
- ? gitResult(repoRoot, ["checkout", "--theirs", "--", path])
836
- : gitResult(repoRoot, ["rm", "--quiet", "--", path]);
837
- if (step.status !== 0)
838
- return null;
839
- if (stages.includes("3") && gitResult(repoRoot, ["add", "--", path]).status !== 0)
840
- return null;
841
- }
842
- const unresolved = zeroSeparatedPaths(repoRoot, ["diff", "--name-only", "--diff-filter=U", "-z"]);
843
- if (unresolved.length > 0)
844
- return null;
845
- const commit = gitResult(repoRoot, [
846
- "commit",
847
- "--no-verify",
848
- ...(params.message ? ["-m", params.message] : ["--no-edit"]),
849
- ]);
850
- return commit.status === 0 ? conflicted : null;
851
- }
852
- // Merge the task exec branch into the branch currently checked out at repoRoot.
853
- // Serializes with the scheduler lock so parallel merges do not race on root HEAD.
854
- // `releaseRootPaths` are root-side working copies of bookkeeping files that the exec branch also
855
- // carries (see releaseRootWorkingCopies); they are restored when the merge does not complete.
856
- export function mergeWorktreeIntoCurrent(params) {
857
- const { context, worktree, taskId } = params;
858
- const targetBranch = currentBranch(context.repoRoot);
859
- if (targetBranch === worktree.branch) {
860
- throw new Error(`Merge must run from a branch other than ${worktree.branch}.`);
861
- }
862
- let lockDir = "";
863
- let released = [];
864
- let merged = false;
865
- const releasePaths = (params.releaseRootPaths ?? []).map((path) => repoRelative(context.repoRoot, path));
866
- const releasePathSet = new Set(releasePaths);
867
- try {
868
- if (!params.dryRun) {
869
- lockDir = acquireSchedulerLock(context.schedulePath, {
870
- actor: `worktree-merge:${targetBranch}`,
871
- lockTimeoutMs: DEFAULT_LOCK_TIMEOUT_MS,
872
- lockStaleMs: DEFAULT_LOCK_STALE_MS,
873
- });
874
- released = releaseRootWorkingCopies(context.repoRoot, releasePaths);
875
- }
876
- const dirty = commitTargetPaths(context, worktree, taskId);
877
- if (dirty.length > 0) {
878
- throw new Error(`Worktree has uncommitted commit-target changes: ${dirty.join(", ")}`);
879
- }
880
- const compareBase = gitOutput(context.repoRoot, ["merge-base", "HEAD", worktree.branch]).trim();
881
- const count = Number.parseInt(gitOutput(context.repoRoot, [
882
- "rev-list",
883
- "--count",
884
- `${compareBase}..${worktree.branch}`,
885
- ]).trim(), 10);
886
- if (!Number.isFinite(count) || count < 1) {
887
- throw new Error(`No commits to merge from ${worktree.branch}.`);
888
- }
889
- const mergePaths = new Set(zeroSeparatedPaths(context.repoRoot, [
890
- "diff",
891
- "--no-renames",
892
- "--name-only",
893
- "-z",
894
- `${compareBase}..${worktree.branch}`,
895
- ]));
896
- const overlap = [...rootDirtyPaths(context.repoRoot)].filter((path) => mergePaths.has(path) && !(params.dryRun && releasePathSet.has(path)));
897
- if (overlap.length > 0) {
898
- throw new Error(`Current worktree changes overlap merge paths: ${overlap.join(", ")}`);
899
- }
900
- if (params.dryRun) {
901
- process.stdout.write(`[dry-run] git merge ${params.ffOnly ? "--ff-only" : params.message ? `--no-ff -m ${JSON.stringify(params.message)}` : "--no-ff --no-edit"} ${worktree.branch}\n`);
902
- return;
903
- }
904
- const mergeArgs = params.ffOnly
905
- ? ["merge", "--ff-only", worktree.branch]
906
- : params.message
907
- ? ["merge", "--no-ff", "-m", params.message, worktree.branch]
908
- : ["merge", "--no-ff", "--no-edit", worktree.branch];
909
- const mergeResult = gitResult(context.repoRoot, mergeArgs);
910
- if (mergeResult.status === 0) {
911
- merged = true;
912
- }
913
- else {
914
- const mergeOutput = [mergeResult.stdout, mergeResult.stderr]
915
- .filter((part) => typeof part === "string" && part.length > 0)
916
- .join(mergeResult.stdout && mergeResult.stderr ? "\n" : "");
917
- const mergeInProgress = gitResult(context.repoRoot, ["rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status ===
918
- 0;
919
- const resolved = mergeInProgress && !params.ffOnly
920
- ? resolveBranchOwnedConflicts({
921
- repoRoot: context.repoRoot,
922
- branchOwnedPaths: (params.resolveConflictsWithBranchPaths ?? []).map((path) => repoRelative(context.repoRoot, path)),
923
- message: params.message,
924
- })
925
- : null;
926
- if (resolved && resolved.length > 0) {
927
- merged = true;
928
- process.stdout.write(` [integrate] resolved bookkeeping conflicts with ${worktree.branch}: ${resolved.join(", ")}\n`);
929
- return;
930
- }
931
- const abortResult = mergeInProgress ? abortMerge(context.repoRoot) : undefined;
932
- if (params.failureLogPath) {
933
- mkdirSync(resolve(params.failureLogPath, ".."), { recursive: true });
934
- const abortOutput = abortResult
935
- ? [abortResult.stdout, abortResult.stderr]
936
- .filter((part) => typeof part === "string" && part.length > 0)
937
- .join(abortResult.stdout && abortResult.stderr ? "\n" : "")
938
- : "";
939
- appendGitFailureLog(params.failureLogPath, [
940
- `=== ${new Date().toISOString()} git ${mergeArgs.join(" ")} ===`,
941
- `exit: ${mergeResult.status ?? "unknown"}`,
942
- "--- stdout ---",
943
- typeof mergeResult.stdout === "string" ? mergeResult.stdout : "",
944
- "--- stderr ---",
945
- typeof mergeResult.stderr === "string" ? mergeResult.stderr : "",
946
- "--- merge --abort ---",
947
- abortResult ? `exit: ${abortResult.status ?? "unknown"}` : "not required",
948
- abortOutput,
949
- "",
950
- ]);
951
- }
952
- const summary = summarizeGitHookFailure(mergeOutput);
953
- if (abortResult && abortResult.status !== 0) {
954
- const abortOutput = [abortResult.stdout, abortResult.stderr]
955
- .filter((part) => typeof part === "string" && part.length > 0)
956
- .join("\n");
957
- const abortSummary = summarizeGitHookFailure(abortOutput);
958
- const instruction = `automatic git merge --abort failed; run git merge --abort manually in ` +
959
- `${context.repoRoot} before continuing`;
960
- process.stderr.write(`error: ${instruction}; ${abortSummary}\n`);
961
- throw new Error(`git merge failed: ${summary}; ${instruction}; ${abortSummary}`);
962
- }
963
- throw new Error(`git merge failed: ${summary}`);
964
- }
965
- }
966
- finally {
967
- if (!merged && released.length > 0)
968
- restoreRootWorkingCopies(context.repoRoot, released);
969
- if (lockDir)
970
- releaseSchedulerLock(lockDir);
971
- }
972
- }
973
- // Whether the task exec branch is already contained in the merge-target HEAD. The integrate
974
- // stage retry uses this to stay idempotent: when a previous attempt merged but failed afterwards
975
- // (for example while removing the worktree), re-running the merge would fail with "No commits to
976
- // merge", so the retry skips the merge and continues with the remaining integration steps.
977
- // exec ブランチが統合ブランチへ merge 済みかを判定する。ancestor 判定だけでは、exec ブランチが
978
- // 作成直後(先端が統合ブランチ上の commit のまま)の場合も true になる。runner の統合は
979
- // --no-ff で merge するため、merge 済みなら先端は HEAD の first-parent 連鎖には含まれない。
980
- // 先端が first-parent 連鎖上にあるなら、task の commit がまだ無い状態とみなす。
981
- export function isExecBranchMergedIntoCurrent(params) {
982
- const repoRoot = params.context.repoRoot;
983
- const isAncestor = gitResult(repoRoot, ["merge-base", "--is-ancestor", params.worktree.branch, "HEAD"]).status ===
984
- 0;
985
- if (!isAncestor)
986
- return false;
987
- const tip = gitResult(repoRoot, ["rev-parse", "--verify", `${params.worktree.branch}^{commit}`]);
988
- if (tip.status !== 0 || typeof tip.stdout !== "string")
989
- return false;
990
- const firstParentChain = gitOutput(repoRoot, ["rev-list", "--first-parent", "HEAD"])
991
- .split("\n")
992
- .map((line) => line.trim());
993
- return !firstParentChain.includes(tip.stdout.trim());
994
- }
995
- // Remove a task worktree once its commit-target changes are committed and merged.
996
- export function removeWorktree(params) {
997
- const { context, worktree, taskId } = params;
998
- if (resolve(context.repoRoot) === resolve(worktree.path)) {
999
- throw new Error("Run remove from the merge-target worktree, not the task worktree.");
1000
- }
1001
- const dirty = commitTargetPaths(context, worktree, taskId);
1002
- const merged = gitResult(context.repoRoot, ["merge-base", "--is-ancestor", worktree.branch, "HEAD"]).status ===
1003
- 0;
1004
- if (!params.force && dirty.length > 0) {
1005
- throw new Error(`Worktree has uncommitted commit-target changes: ${dirty.join(", ")}`);
1006
- }
1007
- if (!params.force && !merged) {
1008
- throw new Error(`Exec branch is not merged into current HEAD: ${worktree.branch}`);
1009
- }
1010
- // プロダクト worktree もすべて撤去できることを先に確かめる。一部のリポジトリだけを撤去した
1011
- // 状態を作らないため、検査はどの worktree を消すよりも前に行う。
1012
- const productBlockers = params.force ? [] : productWorktreeRemovalBlockers(worktree);
1013
- if (productBlockers.length > 0) {
1014
- throw new Error(`Product worktrees cannot be removed: ${productBlockers.join("; ")}`);
1015
- }
1016
- // Past the guards, any remaining uncommitted files are non-commit-target bookkeeping
1017
- // (doc-index, generated/, events) that were intentionally excluded from the task commit.
1018
- // git refuses to remove a worktree while those are dirty, so force past them: they are
1019
- // regenerable, and the tool already judged the worktree removable.
1020
- const leftover = worktreeStatusPaths(worktree.path);
1021
- const forceGit = params.force || leftover.length > 0;
1022
- if (params.force) {
1023
- process.stderr.write("Warning: forcing worktree removal; uncommitted changes may be lost.\n");
1024
- }
1025
- else if (leftover.length > 0) {
1026
- process.stderr.write(`Discarding regenerated files in worktree: ${leftover.join(", ")}\n`);
1027
- }
1028
- if (params.dryRun) {
1029
- removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch, dryRun: true });
1030
- process.stdout.write(`[dry-run] git worktree remove${forceGit ? " --force" : ""} ${worktree.path}\n`);
1031
- if (params.deleteBranch)
1032
- process.stdout.write(`[dry-run] git branch -d ${worktree.branch}\n`);
1033
- return;
1034
- }
1035
- removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch });
1036
- gitOutput(context.repoRoot, [
1037
- "worktree",
1038
- "remove",
1039
- ...(forceGit ? ["--force"] : []),
1040
- worktree.path,
1041
- ]);
1042
- removeEmptyTaskDirectory(worktree);
1043
- if (params.deleteBranch) {
1044
- try {
1045
- gitOutput(context.repoRoot, ["branch", "-d", worktree.branch]);
1046
- }
1047
- catch (error) {
1048
- // worktree removal and branch deletion cannot be atomic: Git refuses to delete a branch
1049
- // while it is checked out. Make the resulting state explicit so the caller does not report
1050
- // that the worktree was preserved and operators can recover it with `worktree prune`.
1051
- throw new WorktreeRemovedBranchDeletionError(worktree.branch, error);
1052
- }
1053
- }
1054
- }
1055
- export class WorktreeRemovedBranchDeletionError extends Error {
1056
- branch;
1057
- constructor(branch, cause) {
1058
- super(`Worktree was removed, but exec branch deletion failed and the branch remains: ` +
1059
- `${branch}; cause=${cause instanceof Error ? cause.message : String(cause)}`);
1060
- this.name = "WorktreeRemovedBranchDeletionError";
1061
- this.branch = branch;
1062
- }
1063
- }
1064
- // List project-scoped exec branches that are no longer checked out by any registered worktree.
1065
- // A failed/interrupted run intentionally keeps both its worktree and branch, so it is not an
1066
- // orphan. The merged flag lets callers distinguish safely removable residue from unintegrated
1067
- // work that must be preserved.
1068
- export function listOrphanedExecBranches(params) {
1069
- const { repoRoot, projectId } = params;
1070
- const projectPrefix = `exec/${worktreeNameFromTaskId(projectId)}-`;
1071
- const registeredBranches = new Set(listRegisteredWorktrees(repoRoot)
1072
- .map((worktree) => worktree.branch)
1073
- .filter((branch) => !!branch));
1074
- const branches = gitOutput(repoRoot, [
1075
- "for-each-ref",
1076
- "--format=%(refname:short)",
1077
- "refs/heads/exec/",
1078
- ])
1079
- .split(/\r?\n/)
1080
- .map((branch) => branch.trim())
1081
- .filter((branch) => branch.startsWith(projectPrefix) && !registeredBranches.has(branch))
1082
- .sort();
1083
- return branches.map((branch) => ({
1084
- branch,
1085
- mergedIntoCurrent: gitResult(repoRoot, ["merge-base", "--is-ancestor", branch, "HEAD"]).status === 0,
1086
- }));
1087
- }
1088
- // Delete only merged orphan branches with Git's safe `-d`. Unmerged branches are always retained,
1089
- // even if the caller asks for a real prune. A deletion failure is not swallowed: gitOutput's
1090
- // stderr-backed reason is propagated so the execution log records why residue remains.
1091
- export function pruneOrphanedExecBranches(params) {
1092
- const current = currentBranch(params.repoRoot);
1093
- if (current.startsWith("exec/")) {
1094
- throw new Error("Run worktree prune from the merge-target worktree, not an exec branch.");
1095
- }
1096
- const orphaned = listOrphanedExecBranches(params);
1097
- for (const item of orphaned) {
1098
- if (!item.mergedIntoCurrent)
1099
- continue;
1100
- if (!params.dryRun) {
1101
- try {
1102
- gitOutput(params.repoRoot, ["branch", "-d", item.branch]);
1103
- }
1104
- catch (error) {
1105
- throw new Error(`Failed to delete merged orphaned exec branch ${item.branch}; ` +
1106
- `cause=${error instanceof Error ? error.message : String(error)}`);
1107
- }
1108
- }
1109
- }
1110
- return orphaned;
1111
- }
1112
- // A fresh claim of a task that still owns an exec worktree/branch means a prior lifecycle
1113
- // (e.g. blocked or cancelled, then reset to todo) left residue behind. The scheduler has abandoned
1114
- // that branch, so discard it before re-preparing: otherwise checkpointAndEnsureWorktree reuses the
1115
- // stale worktree, skips the checkpoint commit, and the freshly-scaffolded root plan/result/claim
1116
- // files never reach the exec branch (the merge would land the stale branch's versions instead).
1117
- // Returns the discarded branch name for logging, or null when no residue existed.
1118
- export function discardStaleExecWorktree(params) {
1119
- const { context, worktreeTaskId } = params;
1120
- const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
1121
- const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
1122
- // プロダクト側の残骸は、プロジェクト側に残骸が無くても片付ける(作成途中で失敗した場合など)。
1123
- const discardedProducts = discardStaleProductWorktrees(params.products ?? [], worktreeTaskId);
1124
- if (!existing && !execBranchExists(context.repoRoot, worktreeTaskId)) {
1125
- return discardedProducts.length > 0 ? discardedProducts.join(", ") : null;
1126
- }
1127
- if (existing) {
1128
- if (resolve(context.repoRoot) === resolve(existing.path)) {
1129
- throw new Error(`Refusing to discard the merge-target worktree as stale residue: ${branch}`);
1130
- }
1131
- // Force past any uncommitted/blocked state in the abandoned worktree; its branch is discarded
1132
- // next, so nothing here is worth preserving.
1133
- gitOutput(context.repoRoot, ["worktree", "remove", "--force", existing.path]);
1134
- if ((params.products ?? []).length > 0)
1135
- removeEmptyTaskDirectory({ ...existing, repos: [] });
1136
- }
1137
- // The branch is unmerged (the scheduler reset the task to todo), so a safe `-d` would fail; use
1138
- // `-D` to drop it deliberately.
1139
- if (execBranchExists(context.repoRoot, worktreeTaskId)) {
1140
- gitOutput(context.repoRoot, ["branch", "-D", branch]);
1141
- }
1142
- return [branch, ...discardedProducts].join(", ");
1143
- }
1144
- function copyCheckpointPath(sourceRoot, targetRoot, relPath) {
1145
- const source = resolve(sourceRoot, relPath);
1146
- const target = resolve(targetRoot, relPath);
1147
- if (!existsSync(source)) {
1148
- rmSync(target, { recursive: true, force: true });
1149
- return;
1150
- }
1151
- const stat = lstatSync(source);
1152
- if (!stat.isFile()) {
1153
- throw new Error(`Execution checkpoint path must be a file: ${relPath}`);
1154
- }
1155
- mkdirSync(resolve(target, ".."), { recursive: true });
1156
- copyFileSync(source, target);
1157
- }
1158
- // Put a root path back to its HEAD state: tracked files are restored, paths absent from HEAD are
1159
- // removed (and unstaged if a hook or caller had staged them).
1160
- function restoreToHead(repoRoot, relPath) {
1161
- const tracked = gitResult(repoRoot, ["ls-files", "--error-unmatch", "--", relPath]).status === 0;
1162
- if (tracked) {
1163
- gitOutput(repoRoot, ["restore", "--source=HEAD", "--staged", "--worktree", "--", relPath]);
1164
- }
1165
- else {
1166
- gitResult(repoRoot, ["reset", "--quiet", "--", relPath]);
1167
- rmSync(resolve(repoRoot, relPath), { recursive: true, force: true });
1168
- }
1169
- }
1170
- // Create the task worktree from the current integration HEAD, then commit the execution
1171
- // checkpoint (plan / result / claim or register-start bookkeeping) on the exec branch only. The
1172
- // root keeps its uncommitted copies so the task state stays visible there while the agent runs;
1173
- // the merge releases them (releaseRootWorkingCopies) right before the exec branch lands.
1174
- // Consequently the prepare/start bookkeeping is reachable through the merge DAG without adding a
1175
- // first-parent commit to the integration branch.
1176
- //
1177
- // PJR-98G4: with declared product repositories the project worktree moves to
1178
- // `<base>/<task-name>/project/` and each product gets `<base>/<task-name>/<repo>/`. The checkpoint
1179
- // commit stays in the project repository; product exec branches start from their integration
1180
- // target.
1181
- //
1182
- // PJR-NN43: `specdojo build` in the project worktree loads the config, which checks that every
1183
- // `repos[].path` (`../<repo>` beside `project/`) exists. The product worktrees are therefore
1184
- // created before the project build (and before the checkpoint commit, whose hooks may load the
1185
- // config as well).
1186
- export function checkpointAndEnsureWorktree(params) {
1187
- const products = params.products ?? [];
1188
- let repos = [];
1189
- const worktree = checkpointAndEnsureProjectWorktree(params, projectRepoDirName(products), () => {
1190
- if (products.length === 0)
1191
- return;
1192
- repos = ensureProductWorktrees({
1193
- products,
1194
- worktreeBase: params.base,
1195
- taskId: params.worktreeTaskId,
1196
- });
1197
- });
1198
- if (products.length === 0)
1199
- return worktree;
1200
- return { ...worktree, repos };
1201
- }
1202
- function checkpointAndEnsureProjectWorktree(params, repoDirName, ensureSiblingWorktrees) {
1203
- const { context, worktreeTaskId, base } = params;
1204
- const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
1205
- // The project build runs only after the sibling product worktrees exist (see above).
1206
- const ensureProjectWorktree = () => {
1207
- const worktree = ensureExecWorktree({
1208
- repoRoot: context.repoRoot,
1209
- worktreeBase: base,
1210
- taskId: worktreeTaskId,
1211
- repoDirName,
1212
- generateArtifacts: () => undefined,
1213
- });
1214
- ensureSiblingWorktrees();
1215
- generateWorktreeArtifacts(worktree.path);
1216
- return worktree;
1217
- };
1218
- const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
1219
- if (existing) {
1220
- // 依存と違い、生成物は前回実行時のまま古くなる。生成段階を持たない版が作成した
1221
- // worktree では存在すらしない。再利用時も作り直し、生成物起因の検証失敗を避ける。
1222
- // 前回の準備がプロダクト worktree の作成前に失敗した場合に備え、先にそれらを揃える。
1223
- ensureSiblingWorktrees();
1224
- generateWorktreeArtifacts(existing.path);
1225
- return existing;
1226
- }
1227
- if (!execBranchExists(context.repoRoot, worktreeTaskId)) {
1228
- if (currentBranch(context.repoRoot) === branch) {
1229
- throw new Error(`Prepare must run from a branch other than ${branch}.`);
1230
- }
1231
- const paths = params.checkpointPaths.map((path) => repoRelative(context.repoRoot, path));
1232
- const stagedFiles = zeroSeparatedPaths(context.repoRoot, [
1233
- "diff",
1234
- "--cached",
1235
- "--no-renames",
1236
- "--name-only",
1237
- "-z",
1238
- ]);
1239
- const checkpointPaths = new Set(paths);
1240
- const overlapping = stagedFiles.filter((path) => checkpointPaths.has(path));
1241
- if (overlapping.length > 0) {
1242
- throw new Error(`Root index has staged checkpoint changes; commit or unstage them first:\n${overlapping.join("\n")}`);
1243
- }
1244
- if (stagedFiles.length > 0) {
1245
- process.stderr.write(`Warning: root index has unrelated staged changes; preserving them while preparing the checkpoint:\n` +
1246
- `${stagedFiles.map((path) => ` ${path}`).join("\n")}\n`);
1247
- }
1248
- const worktree = ensureProjectWorktree();
1249
- for (const path of paths)
1250
- copyCheckpointPath(context.repoRoot, worktree.path, path);
1251
- stageCommitTargets(worktree.path, paths);
1252
- const checkpoint = gitResult(worktree.path, ["diff", "--cached", "--quiet", "--", ...paths]);
1253
- if (checkpoint.status === 1) {
1254
- const committed = gitResult(worktree.path, [
1255
- "commit",
1256
- "-m",
1257
- params.commitMessage,
1258
- "--",
1259
- ...paths,
1260
- ]);
1261
- if (committed.status !== 0) {
1262
- // A failing git hook (pre-commit / commit-msg) aborts the commit but leaves the staged
1263
- // paths in the index. Unstage only this checkpoint so a hook or caller's unrelated staged
1264
- // paths remain intact.
1265
- unstageCommitTargets(worktree.path, paths);
1266
- // hook(lefthook 等)の生出力には ANSI エスケープや制御文字が含まれうる。この detail は
1267
- // register 経路で pjr-index の結論列・result の理由欄へ伝播するため、ここで除去して
1268
- // 表示崩れを防ぐ(register 側の sanitize と二重だが、非 register の呼び出し元も守る)。
1269
- const output = [committed.stdout, committed.stderr]
1270
- .map((part) => typeof part === "string" ? stripTerminalControlSequences(part).trim() : "")
1271
- .filter(Boolean)
1272
- .join("\n");
1273
- appendGitFailureLog(params.failureLogPath, [
1274
- `=== ${new Date().toISOString()} git commit checkpoint ===`,
1275
- `exit: ${committed.status ?? "unknown"}`,
1276
- "--- stdout ---",
1277
- typeof committed.stdout === "string" ? committed.stdout : "",
1278
- "--- stderr ---",
1279
- typeof committed.stderr === "string" ? committed.stderr : "",
1280
- "",
1281
- ]);
1282
- throw new Error(`Checkpoint commit failed (${params.commitMessage}); staged changes rolled back ` +
1283
- `(likely a failing git hook): ${summarizeGitHookFailure(output)}`);
1284
- }
1285
- }
1286
- else if (checkpoint.status !== 0) {
1287
- throw new Error("Failed to inspect execution checkpoint changes.");
1288
- }
1289
- return worktree;
1290
- }
1291
- return ensureProjectWorktree();
1292
- }