specdojo 0.2.1 → 0.3.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 (168) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +280 -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/dashboard.js +122 -1
  8. package/dist/devcontainer-command.js +43 -0
  9. package/dist/devcontainer-scaffold.js +165 -0
  10. package/dist/exec-agent-config.js +107 -9
  11. package/dist/exec-agent-git-state.js +18 -0
  12. package/dist/exec-agent-protected-config.js +46 -8
  13. package/dist/exec-evidence.js +254 -11
  14. package/dist/exec-handoff.js +336 -0
  15. package/dist/exec-parent-validation.js +317 -43
  16. package/dist/exec-pipeline-state.js +74 -9
  17. package/dist/exec-plans.js +115 -113
  18. package/dist/exec-protection-handoff.js +43 -2
  19. package/dist/exec-provider-scaffold.js +247 -15
  20. package/dist/exec-register-resume.js +65 -19
  21. package/dist/exec-register.js +9 -3
  22. package/dist/exec-repo-integration.js +811 -0
  23. package/dist/exec-repo-trace.js +182 -0
  24. package/dist/exec-reporter.js +613 -132
  25. package/dist/exec-results.js +81 -56
  26. package/dist/exec-run-lock.js +110 -107
  27. package/dist/exec-run.js +1585 -356
  28. package/dist/exec-shared.js +7 -0
  29. package/dist/exec-slot-lock.js +242 -0
  30. package/dist/exec-task-repos.js +415 -0
  31. package/dist/exec-trial.js +51 -25
  32. package/dist/exec-worktree-command.js +87 -43
  33. package/dist/exec-worktree-ops.js +502 -57
  34. package/dist/exec-worktree.js +114 -27
  35. package/dist/exec.js +13 -6
  36. package/dist/grade-result.js +128 -0
  37. package/dist/grade.js +809 -72
  38. package/dist/init-command.js +443 -0
  39. package/dist/job.js +160 -10
  40. package/dist/orchestrator.js +213 -0
  41. package/dist/register-event-merge.js +169 -0
  42. package/dist/register-item.js +7 -1
  43. package/dist/register.js +294 -86
  44. package/dist/review-grade.js +252 -0
  45. package/dist/review-plan.js +111 -1
  46. package/dist/review-types.js +40 -1
  47. package/dist/routine.js +72 -5
  48. package/dist/schedule-build.js +2 -2
  49. package/dist/schedule.js +17 -4
  50. package/dist/specdojo-config.js +465 -19
  51. package/dist/specdojo-gitignore.js +135 -0
  52. package/dist/specdojo.js +6 -0
  53. package/dist/viewpoint-document-kinds-check.js +128 -0
  54. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  55. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  56. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  57. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  58. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  59. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  60. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  61. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  62. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  63. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  64. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  65. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  66. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  67. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  68. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  69. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  70. package/docs/ja/specdojo/guides/exec-config-guide.md +91 -47
  71. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  72. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  73. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  74. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +25 -4
  75. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  76. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  77. package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
  78. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  79. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  80. package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
  81. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  82. package/docs/ja/specdojo/guides/routine-operation-guide.md +74 -9
  83. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  84. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  85. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  86. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  87. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  88. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  89. package/docs/ja/specdojo/index.md +2 -2
  90. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  91. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  92. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  93. package/docs/ja/specdojo/references/command-reference.md +335 -92
  94. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  95. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  96. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  97. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  98. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  99. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  100. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  101. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  102. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  103. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  104. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  105. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  106. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  107. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  108. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  109. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  110. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  111. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  112. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  113. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  114. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  115. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  116. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  117. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  118. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  119. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  120. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  121. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  122. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  123. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  124. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  125. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  126. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  127. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  128. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  129. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  130. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  131. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  132. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  133. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  134. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  135. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  136. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  137. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  138. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  139. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  140. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  141. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  142. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  143. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  144. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  145. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  146. package/package.json +15 -9
  147. package/templates/antigravity/README.md +27 -2
  148. package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
  149. package/templates/antigravity/exec-defaults-snippet.yaml +7 -6
  150. package/templates/antigravity/orchestrator.md +18 -7
  151. package/templates/antigravity/settings.global.json +55 -0
  152. package/templates/claude/agents/claude-executor.md +14 -0
  153. package/templates/claude/agents/claude-reporter.md +16 -0
  154. package/templates/claude/agents/specdojo-orchestrator.md +18 -7
  155. package/templates/claude/settings.edit.json +27 -1
  156. package/templates/codex/README.md +5 -4
  157. package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
  158. package/templates/codex/orchestrator.md +18 -7
  159. package/templates/copilot/README.md +7 -5
  160. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  161. package/templates/devcontainer/devcontainer.json +27 -0
  162. package/templates/devcontainer/emacs/init.el +88 -0
  163. package/templates/devcontainer/post-create.sh +62 -0
  164. package/templates/init-agent-members.yaml +200 -0
  165. package/templates/init-exec-defaults.yaml +72 -0
  166. package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
  167. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  168. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -1,15 +1,19 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync, } from "node:fs";
3
- import { join, relative, resolve, sep } from "node:path";
3
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
4
4
  import { load } from "js-yaml";
5
5
  import { acquireSchedulerLock, releaseSchedulerLock } from "./exec-events.js";
6
6
  import { deliverableDocPath, parsePlanTaskIdentity, targetReferenceDirsForApproach, } from "./exec-plans.js";
7
7
  import { parseResultTaskIdentity } from "./exec-results.js";
8
8
  import { stripTerminalControlSequences } from "./exec-shared.js";
9
- import { agentProtectedConfigPaths, agentProtectedConfigViolation, } from "./exec-agent-protected-config.js";
10
- import { recordProtectedConfigBlock } from "./exec-protection-handoff.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";
11
12
  import { specdojoPackageRootDir } from "./package-paths.js";
12
- import { ensureExecWorktree, execBranchExists, findExecWorktree, generateWorktreeArtifacts, gitEnvironment, gitOutput, gitResult, listRegisteredWorktrees, summarizeGitHookFailure, worktreeNameFromTaskId, } from "./exec-worktree.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";
13
17
  const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
14
18
  const DEFAULT_LOCK_STALE_MS = 300_000;
15
19
  const MAX_COMMIT_STABILIZATION_ATTEMPTS = 3;
@@ -61,6 +65,8 @@ export function isCommitTargetPath(path, executionRel, resultRel) {
61
65
  // merge 時の overlap ガードで衝突するため除外する。
62
66
  if (normalized === ".specdojo/doc-index.json")
63
67
  return false;
68
+ if (normalized === "tmp" || normalized.startsWith("tmp/"))
69
+ return false;
64
70
  if (normalized.startsWith(`${executionRel}/exec/plans/`))
65
71
  return false;
66
72
  if (normalized.startsWith(`${executionRel}/exec/results/`))
@@ -157,18 +163,47 @@ function assertNoAgentProtectedConfigChanges(context, worktree, taskId) {
157
163
  ...statusPaths(worktree.path),
158
164
  ...committed,
159
165
  ]);
160
- if (protectedPaths.length > 0) {
161
- const reason = agentProtectedConfigViolation(protectedPaths);
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));
162
174
  // commit 前の再検査でも、対象と提案差分を result の申し送りへ残してから block する。
163
- recordProtectedConfigBlock({
175
+ recordProtectedConfigBlockAcrossRepos({
164
176
  resultPath: resolve(worktree.path, resultRel),
165
- repoRoot: worktree.path,
166
- paths: protectedPaths,
177
+ changes,
167
178
  reason,
168
179
  });
169
180
  throw new Error(reason);
170
181
  }
171
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
+ }
172
207
  const DOC_INDEX_REL = ".specdojo/doc-index.json";
173
208
  // worktree の HEAD(CLI が checkpoint した版)からファイル内容を読む。
174
209
  // agent は working tree を書き換えられるが HEAD は書き換えられないため、
@@ -224,9 +259,9 @@ export function resolveCommitScope(context, worktree, taskId) {
224
259
  unresolvedTargets: [],
225
260
  };
226
261
  }
227
- // register 由来のタスクは対象成果物を特定できず targets を持たない。許可リストを
228
- // 導出する根拠が無いため、従来どおり除外リスト方式へフォールバックする(register の
229
- // 通常経路である作業ツリー差分による commit と同じ範囲になる)。
262
+ // register 由来のタスクは許可リスト方式ではなく、作業ツリー差分による commit を使う。
263
+ // 個票が targets を宣言している場合でも、commit scope は従来どおり除外リスト方式へ
264
+ // フォールバックする(target coverage 検証は evidence 側で行い、ここでは使わない)。
230
265
  if (identity.origin === "register")
231
266
  return { scope: null, unresolvedTargets: [] };
232
267
  // schedule 由来の edit タスクは targets から commit 許可リストを導出する。targets が
@@ -241,6 +276,10 @@ export function resolveCommitScope(context, worktree, taskId) {
241
276
  const unresolvedTargets = [];
242
277
  const lookup = headDocIndexLookup(worktree.path);
243
278
  for (const target of identity.targets ?? []) {
279
+ // `<repo>:<path>` はプロダクトリポジトリの対象で、プロダクト側の commit 対象に入る
280
+ // (exec-repo-integration)。プロジェクト側の doc id としては解決しない。
281
+ if (isProductRepoTarget(worktree, target))
282
+ continue;
244
283
  const fromIndex = lookup(target);
245
284
  if (fromIndex) {
246
285
  allowedFiles.add(fromIndex);
@@ -269,14 +308,107 @@ export function resolveCommitScope(context, worktree, taskId) {
269
308
  unresolvedTargets,
270
309
  };
271
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
+ }
272
390
  // worktree の変更を「commit するパス」「許可リスト外のため commit しないパス」に分ける。
273
391
  // 除外リスト(isCommitTargetPath)は許可リストの内側でも引き続き適用する。
274
392
  export function partitionCommitTargets(context, worktree, taskId) {
275
393
  const { executionRel, resultRel } = taskPaths(context, taskId);
276
394
  const candidates = statusPaths(worktree.path).filter((path) => isCommitTargetPath(path, executionRel, resultRel));
277
395
  const { scope, unresolvedTargets } = resolveCommitScope(context, worktree, taskId);
278
- if (!scope)
279
- return { targets: candidates, outOfScope: [], unresolvedTargets };
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
+ }
280
412
  const targets = [];
281
413
  const outOfScope = [];
282
414
  for (const path of candidates) {
@@ -310,6 +442,14 @@ export function stageCommitTargets(repoRoot, paths) {
310
442
  return;
311
443
  gitOutput(repoRoot, ["add", "-A", "--", ...stageable]);
312
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
+ }
313
453
  // markdownlint-cli の終了コード。1 だけが記法違反を表し、それ以外は実行環境の問題である。
314
454
  const MARKDOWNLINT_EXIT_LINT_ERRORS = 1;
315
455
  // worktree または SpecDojo package の node_modules から markdownlint-cli を探す。
@@ -366,7 +506,7 @@ export function assertResultMarkdownlint(context, worktree, taskId) {
366
506
  }
367
507
  throw new Error(`Failed to run markdownlint on ${resultRel} before commit: ${detail}`);
368
508
  }
369
- export function stabilizeCommitTargets(repoRoot, listRemainingPaths, maxAttempts = MAX_COMMIT_STABILIZATION_ATTEMPTS) {
509
+ export function stabilizeCommitTargets(repoRoot, listRemainingPaths, maxAttempts = MAX_COMMIT_STABILIZATION_ATTEMPTS, failureLogPath) {
370
510
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
371
511
  const paths = listRemainingPaths();
372
512
  if (paths.length === 0)
@@ -384,7 +524,23 @@ export function stabilizeCommitTargets(repoRoot, listRemainingPaths, maxAttempts
384
524
  }
385
525
  if (staged.status !== 1)
386
526
  throw new Error("Failed to inspect post-hook worktree changes.");
387
- gitOutput(repoRoot, ["commit", "--amend", "--no-edit", "--", ...paths]);
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
+ }
388
544
  }
389
545
  const dirty = listRemainingPaths();
390
546
  if (dirty.length > 0) {
@@ -401,6 +557,68 @@ function rootDirtyPaths(repoRoot) {
401
557
  ...zeroSeparatedPaths(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"]),
402
558
  ]);
403
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
+ }
404
622
  // Commit the task result and deliverable changes inside the worktree onto its exec branch.
405
623
  // The commit is limited to the mode-based allowlist (resolveCommitScope); out-of-scope
406
624
  // changes stay uncommitted in the worktree and are reported. Excludes plans, events,
@@ -408,15 +626,48 @@ function rootDirtyPaths(repoRoot) {
408
626
  export function commitWorktreeChanges(params) {
409
627
  const { context, worktree, taskId } = params;
410
628
  assertNoAgentProtectedConfigChanges(context, worktree, taskId);
411
- const { targets: paths, outOfScope, unresolvedTargets, } = partitionCommitTargets(context, worktree, taskId);
412
- for (const target of unresolvedTargets) {
413
- process.stdout.write(`commit-scope: unresolved target doc id (not committable): ${target}\n`);
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
+ }
414
662
  }
415
- if (outOfScope.length > 0) {
416
- process.stdout.write(`commit-scope: skipped non-target changes (left in worktree):\n${outOfScope
417
- .map((path) => ` ${path}`)
418
- .join("\n")}\n`);
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
+ }
419
669
  }
670
+ const paths = partition.targets;
420
671
  if (paths.length === 0) {
421
672
  process.stdout.write("No commit-target changes.\n");
422
673
  return { targets: [], committed: false };
@@ -434,14 +685,30 @@ export function commitWorktreeChanges(params) {
434
685
  }
435
686
  if (staged.status !== 1)
436
687
  throw new Error("Failed to inspect staged worktree changes.");
437
- gitOutput(worktree.path, [
688
+ const commitArgs = [
438
689
  "commit",
439
690
  "-m",
440
691
  params.message?.trim() || `exec(${taskId}): apply task changes`,
441
692
  "--",
442
693
  ...paths,
443
- ]);
444
- stabilizeCommitTargets(worktree.path, () => commitTargetPaths(context, worktree, taskId));
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);
445
712
  return { targets: paths, committed: true };
446
713
  }
447
714
  // The checkpoint commit lives on the exec branch only, so the root keeps its own uncommitted copy
@@ -479,6 +746,109 @@ export function restoreRootWorkingCopies(repoRoot, snapshot) {
479
746
  writeFileSync(absolute, content);
480
747
  }
481
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
+ }
482
852
  // Merge the task exec branch into the branch currently checked out at repoRoot.
483
853
  // Serializes with the scheduler lock so parallel merges do not race on root HEAD.
484
854
  // `releaseRootPaths` are root-side working copies of bookkeeping files that the exec branch also
@@ -546,9 +916,19 @@ export function mergeWorktreeIntoCurrent(params) {
546
916
  .join(mergeResult.stdout && mergeResult.stderr ? "\n" : "");
547
917
  const mergeInProgress = gitResult(context.repoRoot, ["rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status ===
548
918
  0;
549
- const abortResult = mergeInProgress
550
- ? gitResult(context.repoRoot, ["merge", "--abort"])
551
- : undefined;
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;
552
932
  if (params.failureLogPath) {
553
933
  mkdirSync(resolve(params.failureLogPath, ".."), { recursive: true });
554
934
  const abortOutput = abortResult
@@ -556,7 +936,7 @@ export function mergeWorktreeIntoCurrent(params) {
556
936
  .filter((part) => typeof part === "string" && part.length > 0)
557
937
  .join(abortResult.stdout && abortResult.stderr ? "\n" : "")
558
938
  : "";
559
- appendFileSync(params.failureLogPath, [
939
+ appendGitFailureLog(params.failureLogPath, [
560
940
  `=== ${new Date().toISOString()} git ${mergeArgs.join(" ")} ===`,
561
941
  `exit: ${mergeResult.status ?? "unknown"}`,
562
942
  "--- stdout ---",
@@ -567,7 +947,7 @@ export function mergeWorktreeIntoCurrent(params) {
567
947
  abortResult ? `exit: ${abortResult.status ?? "unknown"}` : "not required",
568
948
  abortOutput,
569
949
  "",
570
- ].join("\n"), "utf8");
950
+ ]);
571
951
  }
572
952
  const summary = summarizeGitHookFailure(mergeOutput);
573
953
  if (abortResult && abortResult.status !== 0) {
@@ -627,6 +1007,12 @@ export function removeWorktree(params) {
627
1007
  if (!params.force && !merged) {
628
1008
  throw new Error(`Exec branch is not merged into current HEAD: ${worktree.branch}`);
629
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
+ }
630
1016
  // Past the guards, any remaining uncommitted files are non-commit-target bookkeeping
631
1017
  // (doc-index, generated/, events) that were intentionally excluded from the task commit.
632
1018
  // git refuses to remove a worktree while those are dirty, so force past them: they are
@@ -640,17 +1026,20 @@ export function removeWorktree(params) {
640
1026
  process.stderr.write(`Discarding regenerated files in worktree: ${leftover.join(", ")}\n`);
641
1027
  }
642
1028
  if (params.dryRun) {
1029
+ removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch, dryRun: true });
643
1030
  process.stdout.write(`[dry-run] git worktree remove${forceGit ? " --force" : ""} ${worktree.path}\n`);
644
1031
  if (params.deleteBranch)
645
1032
  process.stdout.write(`[dry-run] git branch -d ${worktree.branch}\n`);
646
1033
  return;
647
1034
  }
1035
+ removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch });
648
1036
  gitOutput(context.repoRoot, [
649
1037
  "worktree",
650
1038
  "remove",
651
1039
  ...(forceGit ? ["--force"] : []),
652
1040
  worktree.path,
653
1041
  ]);
1042
+ removeEmptyTaskDirectory(worktree);
654
1043
  if (params.deleteBranch) {
655
1044
  try {
656
1045
  gitOutput(context.repoRoot, ["branch", "-d", worktree.branch]);
@@ -730,8 +1119,11 @@ export function discardStaleExecWorktree(params) {
730
1119
  const { context, worktreeTaskId } = params;
731
1120
  const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
732
1121
  const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
733
- if (!existing && !execBranchExists(context.repoRoot, worktreeTaskId))
734
- return null;
1122
+ // プロダクト側の残骸は、プロジェクト側に残骸が無くても片付ける(作成途中で失敗した場合など)。
1123
+ const discardedProducts = discardStaleProductWorktrees(params.products ?? [], worktreeTaskId);
1124
+ if (!existing && !execBranchExists(context.repoRoot, worktreeTaskId)) {
1125
+ return discardedProducts.length > 0 ? discardedProducts.join(", ") : null;
1126
+ }
735
1127
  if (existing) {
736
1128
  if (resolve(context.repoRoot) === resolve(existing.path)) {
737
1129
  throw new Error(`Refusing to discard the merge-target worktree as stale residue: ${branch}`);
@@ -739,13 +1131,15 @@ export function discardStaleExecWorktree(params) {
739
1131
  // Force past any uncommitted/blocked state in the abandoned worktree; its branch is discarded
740
1132
  // next, so nothing here is worth preserving.
741
1133
  gitOutput(context.repoRoot, ["worktree", "remove", "--force", existing.path]);
1134
+ if ((params.products ?? []).length > 0)
1135
+ removeEmptyTaskDirectory({ ...existing, repos: [] });
742
1136
  }
743
1137
  // The branch is unmerged (the scheduler reset the task to todo), so a safe `-d` would fail; use
744
1138
  // `-D` to drop it deliberately.
745
1139
  if (execBranchExists(context.repoRoot, worktreeTaskId)) {
746
1140
  gitOutput(context.repoRoot, ["branch", "-D", branch]);
747
1141
  }
748
- return branch;
1142
+ return [branch, ...discardedProducts].join(", ");
749
1143
  }
750
1144
  function copyCheckpointPath(sourceRoot, targetRoot, relPath) {
751
1145
  const source = resolve(sourceRoot, relPath);
@@ -779,13 +1173,54 @@ function restoreToHead(repoRoot, relPath) {
779
1173
  // the merge releases them (releaseRootWorkingCopies) right before the exec branch lands.
780
1174
  // Consequently the prepare/start bookkeeping is reachable through the merge DAG without adding a
781
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).
782
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) {
783
1203
  const { context, worktreeTaskId, base } = params;
784
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
+ };
785
1218
  const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
786
1219
  if (existing) {
787
1220
  // 依存と違い、生成物は前回実行時のまま古くなる。生成段階を持たない版が作成した
788
1221
  // worktree では存在すらしない。再利用時も作り直し、生成物起因の検証失敗を避ける。
1222
+ // 前回の準備がプロダクト worktree の作成前に失敗した場合に備え、先にそれらを揃える。
1223
+ ensureSiblingWorktrees();
789
1224
  generateWorktreeArtifacts(existing.path);
790
1225
  return existing;
791
1226
  }
@@ -793,19 +1228,24 @@ export function checkpointAndEnsureWorktree(params) {
793
1228
  if (currentBranch(context.repoRoot) === branch) {
794
1229
  throw new Error(`Prepare must run from a branch other than ${branch}.`);
795
1230
  }
796
- const staged = gitResult(context.repoRoot, ["diff", "--cached", "--quiet"]);
797
- if (staged.status === 1) {
798
- const stagedFiles = gitOutput(context.repoRoot, ["diff", "--cached", "--name-only"]).trim();
799
- throw new Error(`Root index has staged changes; commit or unstage them first:\n${stagedFiles}`);
800
- }
801
- if (staged.status !== 0)
802
- throw new Error("Failed to inspect staged changes in root worktree.");
803
1231
  const paths = params.checkpointPaths.map((path) => repoRelative(context.repoRoot, path));
804
- const worktree = ensureExecWorktree({
805
- repoRoot: context.repoRoot,
806
- worktreeBase: base,
807
- taskId: worktreeTaskId,
808
- });
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();
809
1249
  for (const path of paths)
810
1250
  copyCheckpointPath(context.repoRoot, worktree.path, path);
811
1251
  stageCommitTargets(worktree.path, paths);
@@ -820,18 +1260,27 @@ export function checkpointAndEnsureWorktree(params) {
820
1260
  ]);
821
1261
  if (committed.status !== 0) {
822
1262
  // A failing git hook (pre-commit / commit-msg) aborts the commit but leaves the staged
823
- // paths in the index. Unstage everything so the residue does not trip the staged-changes
824
- // guard for every subsequent task and abort the whole loop. The index was verified clean
825
- // above, so a full reset only drops what this checkpoint (and its hooks) staged.
826
- gitResult(worktree.path, ["reset", "--quiet"]);
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);
827
1266
  // hook(lefthook 等)の生出力には ANSI エスケープや制御文字が含まれうる。この detail は
828
1267
  // register 経路で pjr-index の結論列・result の理由欄へ伝播するため、ここで除去して
829
1268
  // 表示崩れを防ぐ(register 側の sanitize と二重だが、非 register の呼び出し元も守る)。
830
- const detail = [committed.stdout, committed.stderr]
1269
+ const output = [committed.stdout, committed.stderr]
831
1270
  .map((part) => typeof part === "string" ? stripTerminalControlSequences(part).trim() : "")
832
1271
  .filter(Boolean)
833
1272
  .join("\n");
834
- throw new Error(`Checkpoint commit failed (${params.commitMessage}); staged changes rolled back (likely a failing git hook):\n${detail}`);
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)}`);
835
1284
  }
836
1285
  }
837
1286
  else if (checkpoint.status !== 0) {
@@ -839,9 +1288,5 @@ export function checkpointAndEnsureWorktree(params) {
839
1288
  }
840
1289
  return worktree;
841
1290
  }
842
- return ensureExecWorktree({
843
- repoRoot: context.repoRoot,
844
- worktreeBase: base,
845
- taskId: worktreeTaskId,
846
- });
1291
+ return ensureProjectWorktree();
847
1292
  }