specdojo 0.3.0 → 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 (104) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/catalog-build-references.js +144 -0
  3. package/dist/catalog-build-render.js +144 -0
  4. package/dist/catalog-build.js +13 -290
  5. package/dist/catalog-generate.js +6 -9
  6. package/dist/catalog-plan-generate.js +2 -2
  7. package/dist/catalog-plan.js +6 -6
  8. package/dist/catalog-scaffold.js +4 -4
  9. package/dist/catalog.js +2 -2
  10. package/dist/dashboard-exec-records.js +105 -0
  11. package/dist/dashboard-routines.js +255 -0
  12. package/dist/dashboard-shared.js +14 -0
  13. package/dist/dashboard-timeline.js +175 -0
  14. package/dist/dashboard.js +10 -544
  15. package/dist/deliverable-trash.js +3 -3
  16. package/dist/doc-index.js +3 -3
  17. package/dist/exec-commands.js +557 -0
  18. package/dist/exec-core.js +457 -0
  19. package/dist/exec-plans-core.js +693 -0
  20. package/dist/exec-plans-generation.js +206 -0
  21. package/dist/exec-plans-storage.js +131 -0
  22. package/dist/exec-plans.js +3 -1018
  23. package/dist/exec-repo-integration-git.js +23 -0
  24. package/dist/exec-repo-integration-sync.js +264 -0
  25. package/dist/exec-repo-integration.js +4 -281
  26. package/dist/exec-reporter-output.js +206 -0
  27. package/dist/exec-reporter.js +2 -206
  28. package/dist/exec-results.js +22 -15
  29. package/dist/exec-run-agent-pipeline.js +256 -0
  30. package/dist/exec-run-agent.js +531 -0
  31. package/dist/exec-run-in-place.js +541 -0
  32. package/dist/exec-run-job.js +717 -0
  33. package/dist/exec-run-lifecycle-commands.js +522 -0
  34. package/dist/exec-run-mode-shared.js +140 -0
  35. package/dist/exec-run-register-command.js +244 -0
  36. package/dist/exec-run-register-core.js +386 -0
  37. package/dist/exec-run-register-mode.js +206 -0
  38. package/dist/exec-run-register-resume.js +393 -0
  39. package/dist/exec-run-register-state.js +322 -0
  40. package/dist/exec-run-register-worktree.js +509 -0
  41. package/dist/exec-run-schedule-mode.js +294 -0
  42. package/dist/exec-run-schedule-prepare.js +353 -0
  43. package/dist/exec-run-schedule-task.js +572 -0
  44. package/dist/exec-run-shared.js +399 -0
  45. package/dist/exec-run.js +11 -6182
  46. package/dist/exec-shared.js +2 -2
  47. package/dist/exec-trial-commands.js +558 -0
  48. package/dist/exec-trial-core.js +371 -0
  49. package/dist/exec-trial.js +2 -921
  50. package/dist/exec-worktree-ops-commit.js +707 -0
  51. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  52. package/dist/exec-worktree-ops-merge.js +303 -0
  53. package/dist/exec-worktree-ops.js +3 -1292
  54. package/dist/exec-worktree.js +32 -4
  55. package/dist/exec.js +2 -1006
  56. package/dist/frontmatter-namespace.js +2 -2
  57. package/dist/grade-apply.js +734 -0
  58. package/dist/grade-command-apply.js +250 -0
  59. package/dist/grade-command-inspect.js +138 -0
  60. package/dist/grade-command-plan.js +101 -0
  61. package/dist/grade-command-shared.js +68 -0
  62. package/dist/grade-core.js +307 -0
  63. package/dist/grade-markdown.js +274 -0
  64. package/dist/grade-pipeline-state.js +184 -0
  65. package/dist/grade-plan.js +507 -0
  66. package/dist/grade-result.js +5 -5
  67. package/dist/grade-target-discovery.js +265 -0
  68. package/dist/grade-targets.js +432 -0
  69. package/dist/grade.js +14 -3188
  70. package/dist/init-command.js +7 -7
  71. package/dist/job-definition.js +670 -0
  72. package/dist/job.js +9 -673
  73. package/dist/kata-command.js +2 -2
  74. package/dist/register-command-types.js +1 -0
  75. package/dist/register-core.js +363 -0
  76. package/dist/register-create-commands.js +245 -0
  77. package/dist/register-events.js +4 -4
  78. package/dist/register-item.js +6 -6
  79. package/dist/register-maintenance-commands.js +187 -0
  80. package/dist/register-migration.js +268 -0
  81. package/dist/register-renumber.js +314 -0
  82. package/dist/register-transition-commands.js +248 -0
  83. package/dist/register-update.js +230 -0
  84. package/dist/register-views.js +256 -0
  85. package/dist/register.js +61 -2069
  86. package/dist/review-plan.js +3 -3
  87. package/dist/routine-definition.js +401 -0
  88. package/dist/routine.js +6 -402
  89. package/dist/schedule-approach.js +2 -2
  90. package/dist/schedule-strategy-generate-document.js +273 -0
  91. package/dist/schedule-strategy-generate-scope.js +199 -0
  92. package/dist/schedule-strategy-generate.js +9 -473
  93. package/dist/schedule.js +4 -4
  94. package/dist/specdojo-config.js +3 -4
  95. package/dist/viewpoint-document-kinds-check.js +3 -3
  96. package/dist/yaml-pages.js +4 -4
  97. package/dist/yaml.js +28 -0
  98. package/docs/ja/specdojo/guides/exec-config-guide.md +6 -6
  99. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +20 -18
  100. package/docs/ja/specdojo/guides/routine-operation-guide.md +1 -1
  101. package/package.json +4 -5
  102. package/templates/antigravity/README.md +3 -3
  103. package/templates/antigravity/exec-defaults-snippet.yaml +6 -4
  104. package/templates/init-exec-defaults.yaml +3 -1
@@ -0,0 +1,23 @@
1
+ import { gitOutput, gitResult } from "./exec-worktree.js";
2
+ import { PROJECT_REPO_WORKTREE_DIRNAME } from "./specdojo-config.js";
3
+ /** Name under which the project repository is recorded in `stages.integrate.repos`. */
4
+ export const PROJECT_REPO_NAME = PROJECT_REPO_WORKTREE_DIRNAME;
5
+ export function zeroSeparated(cwd, args) {
6
+ return gitOutput(cwd, args).split("\0").filter(Boolean);
7
+ }
8
+ export function gitText(value) {
9
+ return typeof value === "string" ? value : "";
10
+ }
11
+ export function dirtyPaths(cwd) {
12
+ return new Set([
13
+ ...zeroSeparated(cwd, ["diff", "--no-renames", "--name-only", "-z"]),
14
+ ...zeroSeparated(cwd, ["diff", "--cached", "--no-renames", "--name-only", "-z"]),
15
+ ...zeroSeparated(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
16
+ ]);
17
+ }
18
+ export function mergeInProgress(cwd) {
19
+ return gitResult(cwd, ["rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status === 0;
20
+ }
21
+ export function branchExists(repoRoot, branch) {
22
+ return (gitResult(repoRoot, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status === 0);
23
+ }
@@ -0,0 +1,264 @@
1
+ import { existsSync } from "node:fs";
2
+ import { productIntegrationTarget } from "./exec-task-repos.js";
3
+ import { abortMerge } from "./exec-worktree-ops.js";
4
+ import { gitOutput, gitResult } from "./exec-worktree.js";
5
+ import { PROJECT_REPO_NAME, branchExists, dirtyPaths, gitText, mergeInProgress, zeroSeparated, } from "./exec-repo-integration-git.js";
6
+ function isAncestor(cwd, ancestor, descendant) {
7
+ return gitResult(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]).status === 0;
8
+ }
9
+ function hasPathAt(cwd, ref, path) {
10
+ return gitResult(cwd, ["cat-file", "-e", `${ref}:${path}`]).status === 0;
11
+ }
12
+ function gitFailure(result) {
13
+ return [gitText(result.stdout), gitText(result.stderr)]
14
+ .join("\n")
15
+ .split("\n")
16
+ .map((line) => line.trim())
17
+ .filter(Boolean)
18
+ .join(" ");
19
+ }
20
+ function stashWorktreeChanges(cwd, repo) {
21
+ if (dirtyPaths(cwd).size === 0)
22
+ return undefined;
23
+ const untrackedPaths = zeroSeparated(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]);
24
+ const stash = gitResult(cwd, [
25
+ "stash",
26
+ "push",
27
+ "--include-untracked",
28
+ "--message",
29
+ `specdojo: ${repo} integration-target sync`,
30
+ ]);
31
+ if (stash.status !== 0) {
32
+ const detail = gitFailure(stash) || `exit ${stash.status ?? "unknown"}`;
33
+ throw new Error(`${repo}: cannot preserve uncommitted changes before sync: ${detail}`);
34
+ }
35
+ return {
36
+ oid: gitOutput(cwd, ["rev-parse", "--verify", "refs/stash"]).trim(),
37
+ untrackedPaths,
38
+ };
39
+ }
40
+ function dropStash(cwd, stashOid) {
41
+ const stashes = gitOutput(cwd, ["stash", "list", "--format=%H"])
42
+ .split("\n")
43
+ .map((line) => line.trim());
44
+ const index = stashes.indexOf(stashOid);
45
+ if (index >= 0)
46
+ gitOutput(cwd, ["stash", "drop", `stash@{${index}}`]);
47
+ }
48
+ function applyStashedWorktree(cwd, stashOid) {
49
+ // `--index` は merge commit 側の index と衝突し、同一ファイルの非競合 hunk も戻せないため使わない。
50
+ return gitResult(cwd, ["stash", "apply", "--quiet", stashOid]);
51
+ }
52
+ function treeObjectAt(cwd, ref, path) {
53
+ const entry = gitResult(cwd, ["ls-tree", "-z", ref, "--", path]);
54
+ if (entry.status !== 0)
55
+ return undefined;
56
+ const output = gitText(entry.stdout);
57
+ const separator = output.indexOf("\t");
58
+ if (separator < 0)
59
+ return undefined;
60
+ return output.slice(0, separator).split(" ").at(-1);
61
+ }
62
+ function classifyTrackedStashedUntrackedPaths(cwd, stash) {
63
+ const identical = [];
64
+ const conflicting = [];
65
+ const untrackedRef = `${stash.oid}^3`;
66
+ for (const path of stash.untrackedPaths) {
67
+ const mergedObject = treeObjectAt(cwd, "HEAD", path);
68
+ if (!mergedObject)
69
+ continue;
70
+ const stashedObject = treeObjectAt(cwd, untrackedRef, path);
71
+ (stashedObject === mergedObject ? identical : conflicting).push(path);
72
+ }
73
+ return { identical, conflicting };
74
+ }
75
+ function restoreOriginalWorktree(params) {
76
+ const reset = gitResult(params.cwd, ["reset", "--hard", params.originalHead]);
77
+ if (reset.status === 0 && params.stash.untrackedPaths.length > 0) {
78
+ gitResult(params.cwd, ["clean", "-d", "-f", "--", ...params.stash.untrackedPaths]);
79
+ }
80
+ if (reset.status !== 0) {
81
+ const detail = gitFailure(reset) || `exit ${reset.status ?? "unknown"}`;
82
+ throw new Error(`${params.repo}: ${params.reason}; failed to restore the original HEAD: ${detail}; ` +
83
+ `executor changes remain preserved in stash ${params.stash.oid}`);
84
+ }
85
+ const restored = applyStashedWorktree(params.cwd, params.stash.oid);
86
+ if (restored.status !== 0) {
87
+ const detail = gitFailure(restored) || `exit ${restored.status ?? "unknown"}`;
88
+ throw new Error(`${params.repo}: ${params.reason}; failed to restore executor changes: ${detail}; ` +
89
+ `executor changes remain preserved in stash ${params.stash.oid}`);
90
+ }
91
+ dropStash(params.cwd, params.stash.oid);
92
+ throw new Error(`${params.repo}: ${params.reason}`);
93
+ }
94
+ /**
95
+ * Merge `target` into the branch checked out at `cwd` (an exec worktree) with a merge commit.
96
+ * Uncommitted changes (including untracked files) are stashed before the merge and restored
97
+ * without restoring the old index. Conflicts on `theirsPaths` (repository-relative) take the
98
+ * target side. Any other committed conflict aborts the merge. If restoring the stash conflicts,
99
+ * the merge commit is rolled back and the executor changes are restored on the original HEAD.
100
+ */
101
+ export function syncWorktreeWithIntegrationTarget(params) {
102
+ const { repo, cwd, target, message } = params;
103
+ if (isAncestor(cwd, target, "HEAD"))
104
+ return { repo, target, status: "up-to-date" };
105
+ const originalHead = gitOutput(cwd, ["rev-parse", "HEAD"]).trim();
106
+ const stash = stashWorktreeChanges(cwd, repo);
107
+ const merge = gitResult(cwd, [
108
+ "merge",
109
+ "--no-commit",
110
+ "--no-ff",
111
+ "--no-verify",
112
+ "-m",
113
+ message,
114
+ target,
115
+ ]);
116
+ if (merge.status !== 0 && !mergeInProgress(cwd)) {
117
+ const output = gitFailure(merge);
118
+ const reason = `cannot merge ${target} into the exec branch` + (output ? `: ${output}` : "");
119
+ if (stash) {
120
+ restoreOriginalWorktree({ cwd, repo, originalHead, stash, reason });
121
+ }
122
+ throw new Error(`${repo}: ${reason}`);
123
+ }
124
+ try {
125
+ const conflicted = zeroSeparated(cwd, ["diff", "--name-only", "--diff-filter=U", "-z"]);
126
+ const theirs = new Set(params.theirsPaths ?? []);
127
+ const unexpected = conflicted.filter((path) => !theirs.has(path));
128
+ if (unexpected.length > 0) {
129
+ throw new Error(`${repo}: merge conflicts with ${target}: ${unexpected.join(", ")}`);
130
+ }
131
+ for (const path of conflicted) {
132
+ if (hasPathAt(cwd, target, path)) {
133
+ gitOutput(cwd, ["checkout", target, "--", path]);
134
+ gitOutput(cwd, ["add", "--", path]);
135
+ }
136
+ else {
137
+ gitOutput(cwd, ["rm", "--quiet", "--force", "--", path]);
138
+ }
139
+ }
140
+ const unresolved = zeroSeparated(cwd, ["diff", "--name-only", "--diff-filter=U", "-z"]);
141
+ if (unresolved.length > 0) {
142
+ throw new Error(`${repo}: unresolved conflicts with ${target}: ${unresolved.join(", ")}`);
143
+ }
144
+ // The merge is runner-internal; hooks would re-run the very checks the resume is about to run.
145
+ gitOutput(cwd, ["commit", "--no-verify", "-m", message]);
146
+ }
147
+ catch (error) {
148
+ if (mergeInProgress(cwd))
149
+ abortMerge(cwd);
150
+ if (stash) {
151
+ restoreOriginalWorktree({
152
+ cwd,
153
+ repo,
154
+ originalHead,
155
+ stash,
156
+ reason: error instanceof Error ? error.message.replace(`${repo}: `, "") : String(error),
157
+ });
158
+ }
159
+ throw error;
160
+ }
161
+ if (stash) {
162
+ const trackedUntracked = classifyTrackedStashedUntrackedPaths(cwd, stash);
163
+ if (trackedUntracked.conflicting.length > 0) {
164
+ restoreOriginalWorktree({
165
+ cwd,
166
+ repo,
167
+ originalHead,
168
+ stash,
169
+ reason: `uncommitted executor changes conflict with ${target}: ` +
170
+ `untracked files differ from tracked integration files: ${trackedUntracked.conflicting.join(", ")}`,
171
+ });
172
+ }
173
+ if (trackedUntracked.identical.length > 0) {
174
+ const removed = gitResult(cwd, [
175
+ "rm",
176
+ "--quiet",
177
+ "--force",
178
+ "--",
179
+ ...trackedUntracked.identical,
180
+ ]);
181
+ if (removed.status !== 0) {
182
+ const detail = gitFailure(removed) || `exit ${removed.status ?? "unknown"}`;
183
+ restoreOriginalWorktree({
184
+ cwd,
185
+ repo,
186
+ originalHead,
187
+ stash,
188
+ reason: `cannot prepare identical untracked files for restore: ${detail}`,
189
+ });
190
+ }
191
+ }
192
+ const restored = applyStashedWorktree(cwd, stash.oid);
193
+ if (restored.status !== 0) {
194
+ const detail = gitFailure(restored) || `exit ${restored.status ?? "unknown"}`;
195
+ restoreOriginalWorktree({
196
+ cwd,
197
+ repo,
198
+ originalHead,
199
+ stash,
200
+ reason: `uncommitted executor changes conflict with ${target}: ${detail}`,
201
+ });
202
+ }
203
+ if (trackedUntracked.identical.length > 0) {
204
+ const resolved = gitResult(cwd, ["checkout", "HEAD", "--", ...trackedUntracked.identical]);
205
+ if (resolved.status !== 0) {
206
+ const detail = gitFailure(resolved) || `exit ${resolved.status ?? "unknown"}`;
207
+ restoreOriginalWorktree({
208
+ cwd,
209
+ repo,
210
+ originalHead,
211
+ stash,
212
+ reason: `cannot finish restoring identical untracked files: ${detail}`,
213
+ });
214
+ }
215
+ }
216
+ dropStash(cwd, stash.oid);
217
+ }
218
+ return { repo, target, status: "merged" };
219
+ }
220
+ /**
221
+ * Bring every repository of a task up to date with its integration target before a resumed stage
222
+ * re-runs parent validations: products in declaration order, then the project. A product whose
223
+ * integration target is not a local branch is skipped (the integration preflight reports it).
224
+ * Products named in `integratedProducts` are skipped too: merging into an already integrated exec
225
+ * branch would make the integration stage merge it again.
226
+ * Throws on the first repository that cannot be synced; earlier repositories keep their merge.
227
+ */
228
+ export function syncTaskWorktreesWithIntegrationTargets(params) {
229
+ const synced = [];
230
+ for (const product of params.worktree.repos ?? []) {
231
+ const target = productIntegrationTarget(product);
232
+ if (params.integratedProducts?.has(product.name)) {
233
+ synced.push({ repo: product.name, target, status: "skipped", detail: "already integrated" });
234
+ continue;
235
+ }
236
+ if (!existsSync(product.path)) {
237
+ synced.push({ repo: product.name, target, status: "skipped", detail: "worktree missing" });
238
+ continue;
239
+ }
240
+ if (target === "HEAD" || target === product.branch || !branchExists(product.repoRoot, target)) {
241
+ synced.push({
242
+ repo: product.name,
243
+ target,
244
+ status: "skipped",
245
+ detail: "integration branch is not a local branch",
246
+ });
247
+ continue;
248
+ }
249
+ synced.push(syncWorktreeWithIntegrationTarget({
250
+ repo: product.name,
251
+ cwd: product.path,
252
+ target,
253
+ message: params.message,
254
+ }));
255
+ }
256
+ synced.push(syncWorktreeWithIntegrationTarget({
257
+ repo: PROJECT_REPO_NAME,
258
+ cwd: params.worktree.path,
259
+ target: params.projectTarget,
260
+ message: params.message,
261
+ theirsPaths: params.projectTheirsPaths,
262
+ }));
263
+ return synced;
264
+ }
@@ -4,15 +4,15 @@ import { acquireSchedulerLock, releaseSchedulerLock } from "./exec-events.js";
4
4
  import { productIntegrationTarget } from "./exec-task-repos.js";
5
5
  import { abortMerge, commitTargetPaths, isExecBranchMergedIntoCurrent, recordRootNewFilesHandoff, REGISTER_NEW_FILE_DIR_PREFIXES, repoRelative, stabilizeCommitTargets, stageCommitTargets, worktreeStatusPaths, } from "./exec-worktree-ops.js";
6
6
  import { appendGitFailureLog, gitOutput, gitResult, listRegisteredWorktrees, summarizeGitHookFailure, } from "./exec-worktree.js";
7
- import { PROJECT_REPO_WORKTREE_DIRNAME, resolveRepoQualifiedRef } from "./specdojo-config.js";
7
+ import { resolveRepoQualifiedRef } from "./specdojo-config.js";
8
+ import { PROJECT_REPO_NAME, branchExists, dirtyPaths, gitText, mergeInProgress, zeroSeparated, } from "./exec-repo-integration-git.js";
9
+ export { PROJECT_REPO_NAME } from "./exec-repo-integration-git.js";
8
10
  // PJR-0WAA: 1 つのタスクがプロジェクトリポジトリと宣言済みのプロダクトリポジトリ(`repos`)を
9
11
  // 変更する場合の統合段。commit 対象の算出と commit はリポジトリごとに行い、統合の前に全リポジトリ
10
12
  // で merge 可否を確かめる。統合は宣言順にプロダクト、最後にプロジェクトの順で行い、リポジトリ別の
11
13
  // 状態を pipeline state(`stages.integrate.repos`)へ記録する。再開では統合済みのリポジトリを
12
14
  // Git の状態から判定して飛ばし、失敗した位置から続ける。`repos` を持たない project では、
13
15
  // プロジェクト側の手順だけを従来どおりの順で実行する。
14
- /** Name under which the project repository is recorded in `stages.integrate.repos`. */
15
- export const PROJECT_REPO_NAME = PROJECT_REPO_WORKTREE_DIRNAME;
16
16
  const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
17
17
  const DEFAULT_LOCK_STALE_MS = 300_000;
18
18
  // プロダクト側でも生成物として再生成されるため commit 対象にしないパス。
@@ -25,12 +25,6 @@ export function isProductExcludedPath(path) {
25
25
  return true;
26
26
  return false;
27
27
  }
28
- function zeroSeparated(cwd, args) {
29
- return gitOutput(cwd, args).split("\0").filter(Boolean);
30
- }
31
- function gitText(value) {
32
- return typeof value === "string" ? value : "";
33
- }
34
28
  // ── commit 対象の算出と commit ─────────────────────────────────────────────
35
29
  /**
36
30
  * Split `targets` of the task by product repository: `<repo>:<path>` values whose prefix is a
@@ -230,23 +224,10 @@ function mergeTree(repoRoot, target, branch) {
230
224
  function mergeChangedPaths(repoRoot, target, branch) {
231
225
  return new Set(zeroSeparated(repoRoot, ["diff", "--no-renames", "--name-only", "-z", `${target}...${branch}`]));
232
226
  }
233
- function dirtyPaths(cwd) {
234
- return new Set([
235
- ...zeroSeparated(cwd, ["diff", "--no-renames", "--name-only", "-z"]),
236
- ...zeroSeparated(cwd, ["diff", "--cached", "--no-renames", "--name-only", "-z"]),
237
- ...zeroSeparated(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]),
238
- ]);
239
- }
240
- function mergeInProgress(cwd) {
241
- return gitResult(cwd, ["rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status === 0;
242
- }
243
227
  // 統合先ブランチを checkout している worktree(主 checkout を含む)。無ければ undefined。
244
228
  function checkoutOfBranch(repoRoot, branch) {
245
229
  return listRegisteredWorktrees(repoRoot).find((worktree) => worktree.branch === branch)?.path;
246
230
  }
247
- function branchExists(repoRoot, branch) {
248
- return (gitResult(repoRoot, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status === 0);
249
- }
250
231
  /**
251
232
  * Reasons why a product repository cannot be integrated. Checked for every repository before any
252
233
  * of them is merged, so a failure found here leaves every repository unintegrated.
@@ -410,265 +391,7 @@ export function mergeProductIntoTarget(params) {
410
391
  }
411
392
  return commit;
412
393
  }
413
- function isAncestor(cwd, ancestor, descendant) {
414
- return gitResult(cwd, ["merge-base", "--is-ancestor", ancestor, descendant]).status === 0;
415
- }
416
- function hasPathAt(cwd, ref, path) {
417
- return gitResult(cwd, ["cat-file", "-e", `${ref}:${path}`]).status === 0;
418
- }
419
- function gitFailure(result) {
420
- return [gitText(result.stdout), gitText(result.stderr)]
421
- .join("\n")
422
- .split("\n")
423
- .map((line) => line.trim())
424
- .filter(Boolean)
425
- .join(" ");
426
- }
427
- function stashWorktreeChanges(cwd, repo) {
428
- if (dirtyPaths(cwd).size === 0)
429
- return undefined;
430
- const untrackedPaths = zeroSeparated(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]);
431
- const stash = gitResult(cwd, [
432
- "stash",
433
- "push",
434
- "--include-untracked",
435
- "--message",
436
- `specdojo: ${repo} integration-target sync`,
437
- ]);
438
- if (stash.status !== 0) {
439
- const detail = gitFailure(stash) || `exit ${stash.status ?? "unknown"}`;
440
- throw new Error(`${repo}: cannot preserve uncommitted changes before sync: ${detail}`);
441
- }
442
- return {
443
- oid: gitOutput(cwd, ["rev-parse", "--verify", "refs/stash"]).trim(),
444
- untrackedPaths,
445
- };
446
- }
447
- function dropStash(cwd, stashOid) {
448
- const stashes = gitOutput(cwd, ["stash", "list", "--format=%H"])
449
- .split("\n")
450
- .map((line) => line.trim());
451
- const index = stashes.indexOf(stashOid);
452
- if (index >= 0)
453
- gitOutput(cwd, ["stash", "drop", `stash@{${index}}`]);
454
- }
455
- function applyStashedWorktree(cwd, stashOid) {
456
- // `--index` は merge commit 側の index と衝突し、同一ファイルの非競合 hunk も戻せないため使わない。
457
- return gitResult(cwd, ["stash", "apply", "--quiet", stashOid]);
458
- }
459
- function treeObjectAt(cwd, ref, path) {
460
- const entry = gitResult(cwd, ["ls-tree", "-z", ref, "--", path]);
461
- if (entry.status !== 0)
462
- return undefined;
463
- const output = gitText(entry.stdout);
464
- const separator = output.indexOf("\t");
465
- if (separator < 0)
466
- return undefined;
467
- return output.slice(0, separator).split(" ").at(-1);
468
- }
469
- function classifyTrackedStashedUntrackedPaths(cwd, stash) {
470
- const identical = [];
471
- const conflicting = [];
472
- const untrackedRef = `${stash.oid}^3`;
473
- for (const path of stash.untrackedPaths) {
474
- const mergedObject = treeObjectAt(cwd, "HEAD", path);
475
- if (!mergedObject)
476
- continue;
477
- const stashedObject = treeObjectAt(cwd, untrackedRef, path);
478
- (stashedObject === mergedObject ? identical : conflicting).push(path);
479
- }
480
- return { identical, conflicting };
481
- }
482
- function restoreOriginalWorktree(params) {
483
- const reset = gitResult(params.cwd, ["reset", "--hard", params.originalHead]);
484
- if (reset.status === 0 && params.stash.untrackedPaths.length > 0) {
485
- gitResult(params.cwd, ["clean", "-d", "-f", "--", ...params.stash.untrackedPaths]);
486
- }
487
- if (reset.status !== 0) {
488
- const detail = gitFailure(reset) || `exit ${reset.status ?? "unknown"}`;
489
- throw new Error(`${params.repo}: ${params.reason}; failed to restore the original HEAD: ${detail}; ` +
490
- `executor changes remain preserved in stash ${params.stash.oid}`);
491
- }
492
- const restored = applyStashedWorktree(params.cwd, params.stash.oid);
493
- if (restored.status !== 0) {
494
- const detail = gitFailure(restored) || `exit ${restored.status ?? "unknown"}`;
495
- throw new Error(`${params.repo}: ${params.reason}; failed to restore executor changes: ${detail}; ` +
496
- `executor changes remain preserved in stash ${params.stash.oid}`);
497
- }
498
- dropStash(params.cwd, params.stash.oid);
499
- throw new Error(`${params.repo}: ${params.reason}`);
500
- }
501
- /**
502
- * Merge `target` into the branch checked out at `cwd` (an exec worktree) with a merge commit.
503
- * Uncommitted changes (including untracked files) are stashed before the merge and restored
504
- * without restoring the old index. Conflicts on `theirsPaths` (repository-relative) take the
505
- * target side. Any other committed conflict aborts the merge. If restoring the stash conflicts,
506
- * the merge commit is rolled back and the executor changes are restored on the original HEAD.
507
- */
508
- export function syncWorktreeWithIntegrationTarget(params) {
509
- const { repo, cwd, target, message } = params;
510
- if (isAncestor(cwd, target, "HEAD"))
511
- return { repo, target, status: "up-to-date" };
512
- const originalHead = gitOutput(cwd, ["rev-parse", "HEAD"]).trim();
513
- const stash = stashWorktreeChanges(cwd, repo);
514
- const merge = gitResult(cwd, [
515
- "merge",
516
- "--no-commit",
517
- "--no-ff",
518
- "--no-verify",
519
- "-m",
520
- message,
521
- target,
522
- ]);
523
- if (merge.status !== 0 && !mergeInProgress(cwd)) {
524
- const output = gitFailure(merge);
525
- const reason = `cannot merge ${target} into the exec branch` + (output ? `: ${output}` : "");
526
- if (stash) {
527
- restoreOriginalWorktree({ cwd, repo, originalHead, stash, reason });
528
- }
529
- throw new Error(`${repo}: ${reason}`);
530
- }
531
- try {
532
- const conflicted = zeroSeparated(cwd, ["diff", "--name-only", "--diff-filter=U", "-z"]);
533
- const theirs = new Set(params.theirsPaths ?? []);
534
- const unexpected = conflicted.filter((path) => !theirs.has(path));
535
- if (unexpected.length > 0) {
536
- throw new Error(`${repo}: merge conflicts with ${target}: ${unexpected.join(", ")}`);
537
- }
538
- for (const path of conflicted) {
539
- if (hasPathAt(cwd, target, path)) {
540
- gitOutput(cwd, ["checkout", target, "--", path]);
541
- gitOutput(cwd, ["add", "--", path]);
542
- }
543
- else {
544
- gitOutput(cwd, ["rm", "--quiet", "--force", "--", path]);
545
- }
546
- }
547
- const unresolved = zeroSeparated(cwd, ["diff", "--name-only", "--diff-filter=U", "-z"]);
548
- if (unresolved.length > 0) {
549
- throw new Error(`${repo}: unresolved conflicts with ${target}: ${unresolved.join(", ")}`);
550
- }
551
- // The merge is runner-internal; hooks would re-run the very checks the resume is about to run.
552
- gitOutput(cwd, ["commit", "--no-verify", "-m", message]);
553
- }
554
- catch (error) {
555
- if (mergeInProgress(cwd))
556
- abortMerge(cwd);
557
- if (stash) {
558
- restoreOriginalWorktree({
559
- cwd,
560
- repo,
561
- originalHead,
562
- stash,
563
- reason: error instanceof Error ? error.message.replace(`${repo}: `, "") : String(error),
564
- });
565
- }
566
- throw error;
567
- }
568
- if (stash) {
569
- const trackedUntracked = classifyTrackedStashedUntrackedPaths(cwd, stash);
570
- if (trackedUntracked.conflicting.length > 0) {
571
- restoreOriginalWorktree({
572
- cwd,
573
- repo,
574
- originalHead,
575
- stash,
576
- reason: `uncommitted executor changes conflict with ${target}: ` +
577
- `untracked files differ from tracked integration files: ${trackedUntracked.conflicting.join(", ")}`,
578
- });
579
- }
580
- if (trackedUntracked.identical.length > 0) {
581
- const removed = gitResult(cwd, [
582
- "rm",
583
- "--quiet",
584
- "--force",
585
- "--",
586
- ...trackedUntracked.identical,
587
- ]);
588
- if (removed.status !== 0) {
589
- const detail = gitFailure(removed) || `exit ${removed.status ?? "unknown"}`;
590
- restoreOriginalWorktree({
591
- cwd,
592
- repo,
593
- originalHead,
594
- stash,
595
- reason: `cannot prepare identical untracked files for restore: ${detail}`,
596
- });
597
- }
598
- }
599
- const restored = applyStashedWorktree(cwd, stash.oid);
600
- if (restored.status !== 0) {
601
- const detail = gitFailure(restored) || `exit ${restored.status ?? "unknown"}`;
602
- restoreOriginalWorktree({
603
- cwd,
604
- repo,
605
- originalHead,
606
- stash,
607
- reason: `uncommitted executor changes conflict with ${target}: ${detail}`,
608
- });
609
- }
610
- if (trackedUntracked.identical.length > 0) {
611
- const resolved = gitResult(cwd, ["checkout", "HEAD", "--", ...trackedUntracked.identical]);
612
- if (resolved.status !== 0) {
613
- const detail = gitFailure(resolved) || `exit ${resolved.status ?? "unknown"}`;
614
- restoreOriginalWorktree({
615
- cwd,
616
- repo,
617
- originalHead,
618
- stash,
619
- reason: `cannot finish restoring identical untracked files: ${detail}`,
620
- });
621
- }
622
- }
623
- dropStash(cwd, stash.oid);
624
- }
625
- return { repo, target, status: "merged" };
626
- }
627
- /**
628
- * Bring every repository of a task up to date with its integration target before a resumed stage
629
- * re-runs parent validations: products in declaration order, then the project. A product whose
630
- * integration target is not a local branch is skipped (the integration preflight reports it).
631
- * Products named in `integratedProducts` are skipped too: merging into an already integrated exec
632
- * branch would make the integration stage merge it again.
633
- * Throws on the first repository that cannot be synced; earlier repositories keep their merge.
634
- */
635
- export function syncTaskWorktreesWithIntegrationTargets(params) {
636
- const synced = [];
637
- for (const product of params.worktree.repos ?? []) {
638
- const target = productIntegrationTarget(product);
639
- if (params.integratedProducts?.has(product.name)) {
640
- synced.push({ repo: product.name, target, status: "skipped", detail: "already integrated" });
641
- continue;
642
- }
643
- if (!existsSync(product.path)) {
644
- synced.push({ repo: product.name, target, status: "skipped", detail: "worktree missing" });
645
- continue;
646
- }
647
- if (target === "HEAD" || target === product.branch || !branchExists(product.repoRoot, target)) {
648
- synced.push({
649
- repo: product.name,
650
- target,
651
- status: "skipped",
652
- detail: "integration branch is not a local branch",
653
- });
654
- continue;
655
- }
656
- synced.push(syncWorktreeWithIntegrationTarget({
657
- repo: product.name,
658
- cwd: product.path,
659
- target,
660
- message: params.message,
661
- }));
662
- }
663
- synced.push(syncWorktreeWithIntegrationTarget({
664
- repo: PROJECT_REPO_NAME,
665
- cwd: params.worktree.path,
666
- target: params.projectTarget,
667
- message: params.message,
668
- theirsPaths: params.projectTheirsPaths,
669
- }));
670
- return synced;
671
- }
394
+ export { syncTaskWorktreesWithIntegrationTargets, syncWorktreeWithIntegrationTarget, } from "./exec-repo-integration-sync.js";
672
395
  /** Integration failure that names the integrated and the remaining repositories. */
673
396
  export class RepoIntegrationError extends Error {
674
397
  repo;