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,292 @@
1
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, rmSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { stripTerminalControlSequences } from "./exec-shared.js";
4
+ import { discardStaleProductWorktrees, ensureProductWorktrees, projectRepoDirName, productWorktreeRemovalBlockers, removeEmptyTaskDirectory, removeProductWorktrees, } from "./exec-task-repos.js";
5
+ import { appendGitFailureLog, ensureExecWorktree, execBranchExists, findExecWorktree, generateWorktreeArtifacts, gitOutput, gitResult, listRegisteredWorktrees, summarizeGitHookFailure, worktreeNameFromTaskId, } from "./exec-worktree.js";
6
+ import { commitTargetPaths, currentBranch, repoRelative, stageCommitTargets, unstageCommitTargets, worktreeStatusPaths, zeroSeparatedPaths, } from "./exec-worktree-ops-commit.js";
7
+ // Remove a task worktree once its commit-target changes are committed and merged.
8
+ export function removeWorktree(params) {
9
+ const { context, worktree, taskId } = params;
10
+ if (resolve(context.repoRoot) === resolve(worktree.path)) {
11
+ throw new Error("Run remove from the merge-target worktree, not the task worktree.");
12
+ }
13
+ const dirty = commitTargetPaths(context, worktree, taskId);
14
+ const merged = gitResult(context.repoRoot, ["merge-base", "--is-ancestor", worktree.branch, "HEAD"]).status ===
15
+ 0;
16
+ if (!params.force && dirty.length > 0) {
17
+ throw new Error(`Worktree has uncommitted commit-target changes: ${dirty.join(", ")}`);
18
+ }
19
+ if (!params.force && !merged) {
20
+ throw new Error(`Exec branch is not merged into current HEAD: ${worktree.branch}`);
21
+ }
22
+ // プロダクト worktree もすべて撤去できることを先に確かめる。一部のリポジトリだけを撤去した
23
+ // 状態を作らないため、検査はどの worktree を消すよりも前に行う。
24
+ const productBlockers = params.force ? [] : productWorktreeRemovalBlockers(worktree);
25
+ if (productBlockers.length > 0) {
26
+ throw new Error(`Product worktrees cannot be removed: ${productBlockers.join("; ")}`);
27
+ }
28
+ // Past the guards, any remaining uncommitted files are non-commit-target bookkeeping
29
+ // (doc-index, generated/, events) that were intentionally excluded from the task commit.
30
+ // git refuses to remove a worktree while those are dirty, so force past them: they are
31
+ // regenerable, and the tool already judged the worktree removable.
32
+ const leftover = worktreeStatusPaths(worktree.path);
33
+ const forceGit = params.force || leftover.length > 0;
34
+ if (params.force) {
35
+ process.stderr.write("Warning: forcing worktree removal; uncommitted changes may be lost.\n");
36
+ }
37
+ else if (leftover.length > 0) {
38
+ process.stderr.write(`Discarding regenerated files in worktree: ${leftover.join(", ")}\n`);
39
+ }
40
+ if (params.dryRun) {
41
+ removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch, dryRun: true });
42
+ process.stdout.write(`[dry-run] git worktree remove${forceGit ? " --force" : ""} ${worktree.path}\n`);
43
+ if (params.deleteBranch)
44
+ process.stdout.write(`[dry-run] git branch -d ${worktree.branch}\n`);
45
+ return;
46
+ }
47
+ removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch });
48
+ gitOutput(context.repoRoot, [
49
+ "worktree",
50
+ "remove",
51
+ ...(forceGit ? ["--force"] : []),
52
+ worktree.path,
53
+ ]);
54
+ removeEmptyTaskDirectory(worktree);
55
+ if (params.deleteBranch) {
56
+ try {
57
+ gitOutput(context.repoRoot, ["branch", "-d", worktree.branch]);
58
+ }
59
+ catch (error) {
60
+ // worktree removal and branch deletion cannot be atomic: Git refuses to delete a branch
61
+ // while it is checked out. Make the resulting state explicit so the caller does not report
62
+ // that the worktree was preserved and operators can recover it with `worktree prune`.
63
+ throw new WorktreeRemovedBranchDeletionError(worktree.branch, error);
64
+ }
65
+ }
66
+ }
67
+ export class WorktreeRemovedBranchDeletionError extends Error {
68
+ branch;
69
+ constructor(branch, cause) {
70
+ super(`Worktree was removed, but exec branch deletion failed and the branch remains: ` +
71
+ `${branch}; cause=${cause instanceof Error ? cause.message : String(cause)}`);
72
+ this.name = "WorktreeRemovedBranchDeletionError";
73
+ this.branch = branch;
74
+ }
75
+ }
76
+ // List project-scoped exec branches that are no longer checked out by any registered worktree.
77
+ // A failed/interrupted run intentionally keeps both its worktree and branch, so it is not an
78
+ // orphan. The merged flag lets callers distinguish safely removable residue from unintegrated
79
+ // work that must be preserved.
80
+ export function listOrphanedExecBranches(params) {
81
+ const { repoRoot, projectId } = params;
82
+ const projectPrefix = `exec/${worktreeNameFromTaskId(projectId)}-`;
83
+ const registeredBranches = new Set(listRegisteredWorktrees(repoRoot)
84
+ .map((worktree) => worktree.branch)
85
+ .filter((branch) => !!branch));
86
+ const branches = gitOutput(repoRoot, [
87
+ "for-each-ref",
88
+ "--format=%(refname:short)",
89
+ "refs/heads/exec/",
90
+ ])
91
+ .split(/\r?\n/)
92
+ .map((branch) => branch.trim())
93
+ .filter((branch) => branch.startsWith(projectPrefix) && !registeredBranches.has(branch))
94
+ .sort();
95
+ return branches.map((branch) => ({
96
+ branch,
97
+ mergedIntoCurrent: gitResult(repoRoot, ["merge-base", "--is-ancestor", branch, "HEAD"]).status === 0,
98
+ }));
99
+ }
100
+ // Delete only merged orphan branches with Git's safe `-d`. Unmerged branches are always retained,
101
+ // even if the caller asks for a real prune. A deletion failure is not swallowed: gitOutput's
102
+ // stderr-backed reason is propagated so the execution log records why residue remains.
103
+ export function pruneOrphanedExecBranches(params) {
104
+ const current = currentBranch(params.repoRoot);
105
+ if (current.startsWith("exec/")) {
106
+ throw new Error("Run worktree prune from the merge-target worktree, not an exec branch.");
107
+ }
108
+ const orphaned = listOrphanedExecBranches(params);
109
+ for (const item of orphaned) {
110
+ if (!item.mergedIntoCurrent)
111
+ continue;
112
+ if (!params.dryRun) {
113
+ try {
114
+ gitOutput(params.repoRoot, ["branch", "-d", item.branch]);
115
+ }
116
+ catch (error) {
117
+ throw new Error(`Failed to delete merged orphaned exec branch ${item.branch}; ` +
118
+ `cause=${error instanceof Error ? error.message : String(error)}`);
119
+ }
120
+ }
121
+ }
122
+ return orphaned;
123
+ }
124
+ // A fresh claim of a task that still owns an exec worktree/branch means a prior lifecycle
125
+ // (e.g. blocked or cancelled, then reset to todo) left residue behind. The scheduler has abandoned
126
+ // that branch, so discard it before re-preparing: otherwise checkpointAndEnsureWorktree reuses the
127
+ // stale worktree, skips the checkpoint commit, and the freshly-scaffolded root plan/result/claim
128
+ // files never reach the exec branch (the merge would land the stale branch's versions instead).
129
+ // Returns the discarded branch name for logging, or null when no residue existed.
130
+ export function discardStaleExecWorktree(params) {
131
+ const { context, worktreeTaskId } = params;
132
+ const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
133
+ const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
134
+ // プロダクト側の残骸は、プロジェクト側に残骸が無くても片付ける(作成途中で失敗した場合など)。
135
+ const discardedProducts = discardStaleProductWorktrees(params.products ?? [], worktreeTaskId);
136
+ if (!existing && !execBranchExists(context.repoRoot, worktreeTaskId)) {
137
+ return discardedProducts.length > 0 ? discardedProducts.join(", ") : null;
138
+ }
139
+ if (existing) {
140
+ if (resolve(context.repoRoot) === resolve(existing.path)) {
141
+ throw new Error(`Refusing to discard the merge-target worktree as stale residue: ${branch}`);
142
+ }
143
+ // Force past any uncommitted/blocked state in the abandoned worktree; its branch is discarded
144
+ // next, so nothing here is worth preserving.
145
+ gitOutput(context.repoRoot, ["worktree", "remove", "--force", existing.path]);
146
+ if ((params.products ?? []).length > 0)
147
+ removeEmptyTaskDirectory({ ...existing, repos: [] });
148
+ }
149
+ // The branch is unmerged (the scheduler reset the task to todo), so a safe `-d` would fail; use
150
+ // `-D` to drop it deliberately.
151
+ if (execBranchExists(context.repoRoot, worktreeTaskId)) {
152
+ gitOutput(context.repoRoot, ["branch", "-D", branch]);
153
+ }
154
+ return [branch, ...discardedProducts].join(", ");
155
+ }
156
+ function copyCheckpointPath(sourceRoot, targetRoot, relPath) {
157
+ const source = resolve(sourceRoot, relPath);
158
+ const target = resolve(targetRoot, relPath);
159
+ if (!existsSync(source)) {
160
+ rmSync(target, { recursive: true, force: true });
161
+ return;
162
+ }
163
+ const stat = lstatSync(source);
164
+ if (!stat.isFile()) {
165
+ throw new Error(`Execution checkpoint path must be a file: ${relPath}`);
166
+ }
167
+ mkdirSync(resolve(target, ".."), { recursive: true });
168
+ copyFileSync(source, target);
169
+ }
170
+ // Create the task worktree from the current integration HEAD, then commit the execution
171
+ // checkpoint (plan / result / claim or register-start bookkeeping) on the exec branch only. The
172
+ // root keeps its uncommitted copies so the task state stays visible there while the agent runs;
173
+ // the merge releases them (releaseRootWorkingCopies) right before the exec branch lands.
174
+ // Consequently the prepare/start bookkeeping is reachable through the merge DAG without adding a
175
+ // first-parent commit to the integration branch.
176
+ //
177
+ // PJR-98G4: with declared product repositories the project worktree moves to
178
+ // `<base>/<task-name>/project/` and each product gets `<base>/<task-name>/<repo>/`. The checkpoint
179
+ // commit stays in the project repository; product exec branches start from their integration
180
+ // target.
181
+ //
182
+ // PJR-NN43: `specdojo build` in the project worktree loads the config, which checks that every
183
+ // `repos[].path` (`../<repo>` beside `project/`) exists. The product worktrees are therefore
184
+ // created before the project build (and before the checkpoint commit, whose hooks may load the
185
+ // config as well).
186
+ export function checkpointAndEnsureWorktree(params) {
187
+ const products = params.products ?? [];
188
+ let repos = [];
189
+ const worktree = checkpointAndEnsureProjectWorktree(params, projectRepoDirName(products), () => {
190
+ if (products.length === 0)
191
+ return;
192
+ repos = ensureProductWorktrees({
193
+ products,
194
+ worktreeBase: params.base,
195
+ taskId: params.worktreeTaskId,
196
+ });
197
+ });
198
+ if (products.length === 0)
199
+ return worktree;
200
+ return { ...worktree, repos };
201
+ }
202
+ function checkpointAndEnsureProjectWorktree(params, repoDirName, ensureSiblingWorktrees) {
203
+ const { context, worktreeTaskId, base } = params;
204
+ const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
205
+ // The project build runs only after the sibling product worktrees exist (see above).
206
+ const ensureProjectWorktree = () => {
207
+ const worktree = ensureExecWorktree({
208
+ repoRoot: context.repoRoot,
209
+ worktreeBase: base,
210
+ taskId: worktreeTaskId,
211
+ repoDirName,
212
+ generateArtifacts: () => undefined,
213
+ });
214
+ ensureSiblingWorktrees();
215
+ generateWorktreeArtifacts(worktree.path);
216
+ return worktree;
217
+ };
218
+ const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
219
+ if (existing) {
220
+ // 依存と違い、生成物は前回実行時のまま古くなる。生成段階を持たない版が作成した
221
+ // worktree では存在すらしない。再利用時も作り直し、生成物起因の検証失敗を避ける。
222
+ // 前回の準備がプロダクト worktree の作成前に失敗した場合に備え、先にそれらを揃える。
223
+ ensureSiblingWorktrees();
224
+ generateWorktreeArtifacts(existing.path);
225
+ return existing;
226
+ }
227
+ if (!execBranchExists(context.repoRoot, worktreeTaskId)) {
228
+ if (currentBranch(context.repoRoot) === branch) {
229
+ throw new Error(`Prepare must run from a branch other than ${branch}.`);
230
+ }
231
+ const paths = params.checkpointPaths.map((path) => repoRelative(context.repoRoot, path));
232
+ const stagedFiles = zeroSeparatedPaths(context.repoRoot, [
233
+ "diff",
234
+ "--cached",
235
+ "--no-renames",
236
+ "--name-only",
237
+ "-z",
238
+ ]);
239
+ const checkpointPaths = new Set(paths);
240
+ const overlapping = stagedFiles.filter((path) => checkpointPaths.has(path));
241
+ if (overlapping.length > 0) {
242
+ throw new Error(`Root index has staged checkpoint changes; commit or unstage them first:\n${overlapping.join("\n")}`);
243
+ }
244
+ if (stagedFiles.length > 0) {
245
+ process.stderr.write(`Warning: root index has unrelated staged changes; preserving them while preparing the checkpoint:\n` +
246
+ `${stagedFiles.map((path) => ` ${path}`).join("\n")}\n`);
247
+ }
248
+ const worktree = ensureProjectWorktree();
249
+ for (const path of paths)
250
+ copyCheckpointPath(context.repoRoot, worktree.path, path);
251
+ stageCommitTargets(worktree.path, paths);
252
+ const checkpoint = gitResult(worktree.path, ["diff", "--cached", "--quiet", "--", ...paths]);
253
+ if (checkpoint.status === 1) {
254
+ const committed = gitResult(worktree.path, [
255
+ "commit",
256
+ "-m",
257
+ params.commitMessage,
258
+ "--",
259
+ ...paths,
260
+ ]);
261
+ if (committed.status !== 0) {
262
+ // A failing git hook (pre-commit / commit-msg) aborts the commit but leaves the staged
263
+ // paths in the index. Unstage only this checkpoint so a hook or caller's unrelated staged
264
+ // paths remain intact.
265
+ unstageCommitTargets(worktree.path, paths);
266
+ // hook(lefthook 等)の生出力には ANSI エスケープや制御文字が含まれうる。この detail は
267
+ // register 経路で pjr-index の結論列・result の理由欄へ伝播するため、ここで除去して
268
+ // 表示崩れを防ぐ(register 側の sanitize と二重だが、非 register の呼び出し元も守る)。
269
+ const output = [committed.stdout, committed.stderr]
270
+ .map((part) => typeof part === "string" ? stripTerminalControlSequences(part).trim() : "")
271
+ .filter(Boolean)
272
+ .join("\n");
273
+ appendGitFailureLog(params.failureLogPath, [
274
+ `=== ${new Date().toISOString()} git commit checkpoint ===`,
275
+ `exit: ${committed.status ?? "unknown"}`,
276
+ "--- stdout ---",
277
+ typeof committed.stdout === "string" ? committed.stdout : "",
278
+ "--- stderr ---",
279
+ typeof committed.stderr === "string" ? committed.stderr : "",
280
+ "",
281
+ ]);
282
+ throw new Error(`Checkpoint commit failed (${params.commitMessage}); staged changes rolled back ` +
283
+ `(likely a failing git hook): ${summarizeGitHookFailure(output)}`);
284
+ }
285
+ }
286
+ else if (checkpoint.status !== 0) {
287
+ throw new Error("Failed to inspect execution checkpoint changes.");
288
+ }
289
+ return worktree;
290
+ }
291
+ return ensureProjectWorktree();
292
+ }
@@ -0,0 +1,303 @@
1
+ import { lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { acquireSchedulerLock, releaseSchedulerLock } from "./exec-events.js";
4
+ import { rebuildRegisterTicketFromEvents, unionRegisterEventLogs } from "./register-event-merge.js";
5
+ import { displayIdFromRegisterEventFilename, REGISTER_EVENTS_DIRNAME } from "./register-events.js";
6
+ import { displayIdFromTicketFilename } from "./register-item.js";
7
+ import { appendGitFailureLog, gitOutput, gitResult, summarizeGitHookFailure, } from "./exec-worktree.js";
8
+ import { commitTargetPaths, currentBranch, repoRelative, rootDirtyPaths, zeroSeparatedPaths, } from "./exec-worktree-ops-commit.js";
9
+ const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
10
+ const DEFAULT_LOCK_STALE_MS = 300_000;
11
+ // The checkpoint commit lives on the exec branch only, so the root keeps its own uncommitted copy
12
+ // of the bookkeeping files while the task runs (the schedule/register state must stay visible at
13
+ // root). Before the exec branch is merged those copies must yield to the committed versions,
14
+ // otherwise the overlap guard below rejects the merge. Capture them so a failed merge can put the
15
+ // root back exactly as it was.
16
+ export function releaseRootWorkingCopies(repoRoot, relPaths) {
17
+ const snapshot = [];
18
+ try {
19
+ for (const rel of new Set(relPaths)) {
20
+ const absolute = resolve(repoRoot, rel);
21
+ const exists = lstatSync(absolute, { throwIfNoEntry: false }) !== undefined;
22
+ snapshot.push({ rel, content: exists ? readFileSync(absolute) : null });
23
+ restoreToHead(repoRoot, rel);
24
+ }
25
+ }
26
+ catch (error) {
27
+ // Releasing is itself allowed to fail (for example because a path unexpectedly became a
28
+ // directory). Put back every copy already touched before propagating the failure; otherwise a
29
+ // merge that never started could still discard root-side execution state.
30
+ restoreRootWorkingCopies(repoRoot, snapshot);
31
+ throw error;
32
+ }
33
+ return snapshot;
34
+ }
35
+ export function restoreRootWorkingCopies(repoRoot, snapshot) {
36
+ for (const { rel, content } of snapshot) {
37
+ const absolute = resolve(repoRoot, rel);
38
+ if (content === null) {
39
+ rmSync(absolute, { recursive: true, force: true });
40
+ continue;
41
+ }
42
+ mkdirSync(resolve(absolute, ".."), { recursive: true });
43
+ writeFileSync(absolute, content);
44
+ }
45
+ }
46
+ // `git merge --abort` (reset --merge) refuses to run when a tracked file's cached stat no longer
47
+ // matches the file even though its content is unchanged ("not uptodate"), which happens when another
48
+ // process in the same working tree (for example a routine) touches files during the merge. Refresh
49
+ // the index first so a stat-only drift cannot leave the tree mid-merge.
50
+ export function abortMerge(repoRoot) {
51
+ gitResult(repoRoot, ["update-index", "-q", "--refresh"]);
52
+ return gitResult(repoRoot, ["merge", "--abort"]);
53
+ }
54
+ // `controls/project-register/events/pjr-xxxx.yaml` 形式のイベントファイルなら表示 ID を返す。
55
+ function registerEventDisplayId(path) {
56
+ if (basename(dirname(path)) !== REGISTER_EVENTS_DIRNAME)
57
+ return undefined;
58
+ return displayIdFromRegisterEventFilename(basename(path));
59
+ }
60
+ // Resolve an in-progress merge whose conflicts are all on exec-branch-owned paths, then complete
61
+ // the merge commit. Register event files are resolved as the union of both sides and the matching
62
+ // ticket is rebuilt from the merge-target-only events; other paths take the exec branch side. Returns the resolved paths, or null when the
63
+ // merge has no conflicts (for example a hook rejection), conflicts on other paths, or cannot be
64
+ // completed; the caller then aborts the merge. The commit uses --no-verify because a regular
65
+ // `git merge` does not run pre-commit either, and only the item's own bookkeeping was resolved.
66
+ function resolveBranchOwnedConflicts(params) {
67
+ const { repoRoot } = params;
68
+ const conflicted = zeroSeparatedPaths(repoRoot, ["diff", "--name-only", "--diff-filter=U", "-z"]);
69
+ if (conflicted.length === 0)
70
+ return null;
71
+ const owned = new Set(params.branchOwnedPaths);
72
+ if (conflicted.some((path) => !owned.has(path)))
73
+ return null;
74
+ const stagesOf = (path) => gitOutput(repoRoot, ["ls-files", "-u", "-z", "--", path])
75
+ .split("\0")
76
+ .filter(Boolean)
77
+ .map((entry) => entry.split("\t")[0]?.split(" ")[2]);
78
+ // イベントファイルは両側の和集合で解決し、対応する個票はイベントから再構築する。
79
+ // 和集合で解決できないものは従来どおり exec branch 側で解決する。
80
+ const handled = new Set();
81
+ for (const path of conflicted) {
82
+ const displayId = registerEventDisplayId(path);
83
+ if (!displayId)
84
+ continue;
85
+ const stages = stagesOf(path);
86
+ if (!stages.includes("2") || !stages.includes("3"))
87
+ continue;
88
+ const ours = gitResult(repoRoot, ["show", `:2:${path}`]);
89
+ const theirs = gitResult(repoRoot, ["show", `:3:${path}`]);
90
+ if (ours.status !== 0 || theirs.status !== 0)
91
+ continue;
92
+ const union = unionRegisterEventLogs(String(ours.stdout), String(theirs.stdout), path);
93
+ if (!union.ok) {
94
+ process.stdout.write(` [integrate] could not union register events; using the exec branch side: ${union.reason}\n`);
95
+ continue;
96
+ }
97
+ writeFileSync(resolve(repoRoot, path), union.content, "utf8");
98
+ if (gitResult(repoRoot, ["add", "--", path]).status !== 0)
99
+ return null;
100
+ handled.add(path);
101
+ process.stdout.write(` [integrate] merged register events as a union: ${path} ` +
102
+ `(kept ${union.oursOnlyIds.size} event(s) only on the merge target)\n`);
103
+ const ticketPath = conflicted.find((candidate) => dirname(candidate) === dirname(dirname(path)) &&
104
+ displayIdFromTicketFilename(basename(candidate)) === displayId);
105
+ if (!ticketPath || !stagesOf(ticketPath).includes("3"))
106
+ continue;
107
+ const ticket = gitResult(repoRoot, ["show", `:3:${ticketPath}`]);
108
+ if (ticket.status !== 0)
109
+ continue;
110
+ let rebuilt;
111
+ try {
112
+ rebuilt = rebuildRegisterTicketFromEvents(String(ticket.stdout), union.events, union.oursOnlyIds);
113
+ }
114
+ catch (error) {
115
+ process.stdout.write(` [integrate] could not rebuild ${ticketPath} from events; using the exec branch side: ` +
116
+ `${error instanceof Error ? error.message : String(error)}\n`);
117
+ continue;
118
+ }
119
+ writeFileSync(resolve(repoRoot, ticketPath), rebuilt.content, "utf8");
120
+ if (gitResult(repoRoot, ["add", "--", ticketPath]).status !== 0)
121
+ return null;
122
+ handled.add(ticketPath);
123
+ if (rebuilt.appliedFields.length > 0) {
124
+ process.stdout.write(` [integrate] rebuilt ${ticketPath} from merge-target events: ${rebuilt.appliedFields.join(", ")}\n`);
125
+ }
126
+ }
127
+ for (const path of conflicted) {
128
+ if (handled.has(path))
129
+ continue;
130
+ const stages = stagesOf(path);
131
+ const step = stages.includes("3")
132
+ ? gitResult(repoRoot, ["checkout", "--theirs", "--", path])
133
+ : gitResult(repoRoot, ["rm", "--quiet", "--", path]);
134
+ if (step.status !== 0)
135
+ return null;
136
+ if (stages.includes("3") && gitResult(repoRoot, ["add", "--", path]).status !== 0)
137
+ return null;
138
+ }
139
+ const unresolved = zeroSeparatedPaths(repoRoot, ["diff", "--name-only", "--diff-filter=U", "-z"]);
140
+ if (unresolved.length > 0)
141
+ return null;
142
+ const commit = gitResult(repoRoot, [
143
+ "commit",
144
+ "--no-verify",
145
+ ...(params.message ? ["-m", params.message] : ["--no-edit"]),
146
+ ]);
147
+ return commit.status === 0 ? conflicted : null;
148
+ }
149
+ // Merge the task exec branch into the branch currently checked out at repoRoot.
150
+ // Serializes with the scheduler lock so parallel merges do not race on root HEAD.
151
+ // `releaseRootPaths` are root-side working copies of bookkeeping files that the exec branch also
152
+ // carries (see releaseRootWorkingCopies); they are restored when the merge does not complete.
153
+ export function mergeWorktreeIntoCurrent(params) {
154
+ const { context, worktree, taskId } = params;
155
+ const targetBranch = currentBranch(context.repoRoot);
156
+ if (targetBranch === worktree.branch) {
157
+ throw new Error(`Merge must run from a branch other than ${worktree.branch}.`);
158
+ }
159
+ let lockDir = "";
160
+ let released = [];
161
+ let merged = false;
162
+ const releasePaths = (params.releaseRootPaths ?? []).map((path) => repoRelative(context.repoRoot, path));
163
+ const releasePathSet = new Set(releasePaths);
164
+ try {
165
+ if (!params.dryRun) {
166
+ lockDir = acquireSchedulerLock(context.schedulePath, {
167
+ actor: `worktree-merge:${targetBranch}`,
168
+ lockTimeoutMs: DEFAULT_LOCK_TIMEOUT_MS,
169
+ lockStaleMs: DEFAULT_LOCK_STALE_MS,
170
+ });
171
+ released = releaseRootWorkingCopies(context.repoRoot, releasePaths);
172
+ }
173
+ const dirty = commitTargetPaths(context, worktree, taskId);
174
+ if (dirty.length > 0) {
175
+ throw new Error(`Worktree has uncommitted commit-target changes: ${dirty.join(", ")}`);
176
+ }
177
+ const compareBase = gitOutput(context.repoRoot, ["merge-base", "HEAD", worktree.branch]).trim();
178
+ const count = Number.parseInt(gitOutput(context.repoRoot, [
179
+ "rev-list",
180
+ "--count",
181
+ `${compareBase}..${worktree.branch}`,
182
+ ]).trim(), 10);
183
+ if (!Number.isFinite(count) || count < 1) {
184
+ throw new Error(`No commits to merge from ${worktree.branch}.`);
185
+ }
186
+ const mergePaths = new Set(zeroSeparatedPaths(context.repoRoot, [
187
+ "diff",
188
+ "--no-renames",
189
+ "--name-only",
190
+ "-z",
191
+ `${compareBase}..${worktree.branch}`,
192
+ ]));
193
+ const overlap = [...rootDirtyPaths(context.repoRoot)].filter((path) => mergePaths.has(path) && !(params.dryRun && releasePathSet.has(path)));
194
+ if (overlap.length > 0) {
195
+ throw new Error(`Current worktree changes overlap merge paths: ${overlap.join(", ")}`);
196
+ }
197
+ if (params.dryRun) {
198
+ 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`);
199
+ return;
200
+ }
201
+ const mergeArgs = params.ffOnly
202
+ ? ["merge", "--ff-only", worktree.branch]
203
+ : params.message
204
+ ? ["merge", "--no-ff", "-m", params.message, worktree.branch]
205
+ : ["merge", "--no-ff", "--no-edit", worktree.branch];
206
+ const mergeResult = gitResult(context.repoRoot, mergeArgs);
207
+ if (mergeResult.status === 0) {
208
+ merged = true;
209
+ }
210
+ else {
211
+ const mergeOutput = [mergeResult.stdout, mergeResult.stderr]
212
+ .filter((part) => typeof part === "string" && part.length > 0)
213
+ .join(mergeResult.stdout && mergeResult.stderr ? "\n" : "");
214
+ const mergeInProgress = gitResult(context.repoRoot, ["rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status ===
215
+ 0;
216
+ const resolved = mergeInProgress && !params.ffOnly
217
+ ? resolveBranchOwnedConflicts({
218
+ repoRoot: context.repoRoot,
219
+ branchOwnedPaths: (params.resolveConflictsWithBranchPaths ?? []).map((path) => repoRelative(context.repoRoot, path)),
220
+ message: params.message,
221
+ })
222
+ : null;
223
+ if (resolved && resolved.length > 0) {
224
+ merged = true;
225
+ process.stdout.write(` [integrate] resolved bookkeeping conflicts with ${worktree.branch}: ${resolved.join(", ")}\n`);
226
+ return;
227
+ }
228
+ const abortResult = mergeInProgress ? abortMerge(context.repoRoot) : undefined;
229
+ if (params.failureLogPath) {
230
+ mkdirSync(resolve(params.failureLogPath, ".."), { recursive: true });
231
+ const abortOutput = abortResult
232
+ ? [abortResult.stdout, abortResult.stderr]
233
+ .filter((part) => typeof part === "string" && part.length > 0)
234
+ .join(abortResult.stdout && abortResult.stderr ? "\n" : "")
235
+ : "";
236
+ appendGitFailureLog(params.failureLogPath, [
237
+ `=== ${new Date().toISOString()} git ${mergeArgs.join(" ")} ===`,
238
+ `exit: ${mergeResult.status ?? "unknown"}`,
239
+ "--- stdout ---",
240
+ typeof mergeResult.stdout === "string" ? mergeResult.stdout : "",
241
+ "--- stderr ---",
242
+ typeof mergeResult.stderr === "string" ? mergeResult.stderr : "",
243
+ "--- merge --abort ---",
244
+ abortResult ? `exit: ${abortResult.status ?? "unknown"}` : "not required",
245
+ abortOutput,
246
+ "",
247
+ ]);
248
+ }
249
+ const summary = summarizeGitHookFailure(mergeOutput);
250
+ if (abortResult && abortResult.status !== 0) {
251
+ const abortOutput = [abortResult.stdout, abortResult.stderr]
252
+ .filter((part) => typeof part === "string" && part.length > 0)
253
+ .join("\n");
254
+ const abortSummary = summarizeGitHookFailure(abortOutput);
255
+ const instruction = `automatic git merge --abort failed; run git merge --abort manually in ` +
256
+ `${context.repoRoot} before continuing`;
257
+ process.stderr.write(`error: ${instruction}; ${abortSummary}\n`);
258
+ throw new Error(`git merge failed: ${summary}; ${instruction}; ${abortSummary}`);
259
+ }
260
+ throw new Error(`git merge failed: ${summary}`);
261
+ }
262
+ }
263
+ finally {
264
+ if (!merged && released.length > 0)
265
+ restoreRootWorkingCopies(context.repoRoot, released);
266
+ if (lockDir)
267
+ releaseSchedulerLock(lockDir);
268
+ }
269
+ }
270
+ // Whether the task exec branch is already contained in the merge-target HEAD. The integrate
271
+ // stage retry uses this to stay idempotent: when a previous attempt merged but failed afterwards
272
+ // (for example while removing the worktree), re-running the merge would fail with "No commits to
273
+ // merge", so the retry skips the merge and continues with the remaining integration steps.
274
+ // exec ブランチが統合ブランチへ merge 済みかを判定する。ancestor 判定だけでは、exec ブランチが
275
+ // 作成直後(先端が統合ブランチ上の commit のまま)の場合も true になる。runner の統合は
276
+ // --no-ff で merge するため、merge 済みなら先端は HEAD の first-parent 連鎖には含まれない。
277
+ // 先端が first-parent 連鎖上にあるなら、task の commit がまだ無い状態とみなす。
278
+ export function isExecBranchMergedIntoCurrent(params) {
279
+ const repoRoot = params.context.repoRoot;
280
+ const isAncestor = gitResult(repoRoot, ["merge-base", "--is-ancestor", params.worktree.branch, "HEAD"]).status ===
281
+ 0;
282
+ if (!isAncestor)
283
+ return false;
284
+ const tip = gitResult(repoRoot, ["rev-parse", "--verify", `${params.worktree.branch}^{commit}`]);
285
+ if (tip.status !== 0 || typeof tip.stdout !== "string")
286
+ return false;
287
+ const firstParentChain = gitOutput(repoRoot, ["rev-list", "--first-parent", "HEAD"])
288
+ .split("\n")
289
+ .map((line) => line.trim());
290
+ return !firstParentChain.includes(tip.stdout.trim());
291
+ }
292
+ // Put a root path back to its HEAD state: tracked files are restored, paths absent from HEAD are
293
+ // removed (and unstaged if a hook or caller had staged them).
294
+ function restoreToHead(repoRoot, relPath) {
295
+ const tracked = gitResult(repoRoot, ["ls-files", "--error-unmatch", "--", relPath]).status === 0;
296
+ if (tracked) {
297
+ gitOutput(repoRoot, ["restore", "--source=HEAD", "--staged", "--worktree", "--", relPath]);
298
+ }
299
+ else {
300
+ gitResult(repoRoot, ["reset", "--quiet", "--", relPath]);
301
+ rmSync(resolve(repoRoot, relPath), { recursive: true, force: true });
302
+ }
303
+ }