specdojo 0.2.0 → 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.
- package/.github/agents/specdojo-orchestrator.md +165 -0
- package/CHANGELOG.md +280 -0
- package/README.md +143 -30
- package/dist/agent-response.js +20 -0
- package/dist/agent.js +4 -4
- package/dist/build-command.js +28 -8
- package/dist/dashboard.js +140 -9
- package/dist/devcontainer-command.js +43 -0
- package/dist/devcontainer-scaffold.js +165 -0
- package/dist/exec-agent-config.js +107 -9
- package/dist/exec-agent-git-state.js +18 -0
- package/dist/exec-agent-protected-config.js +46 -8
- package/dist/exec-evidence.js +254 -11
- package/dist/exec-format.js +13 -4
- package/dist/exec-handoff.js +336 -0
- package/dist/exec-parent-validation.js +317 -43
- package/dist/exec-pipeline-state.js +74 -9
- package/dist/exec-plans.js +115 -113
- package/dist/exec-protection-handoff.js +43 -2
- package/dist/exec-provider-scaffold.js +247 -15
- package/dist/exec-register-resume.js +65 -19
- package/dist/exec-register.js +9 -3
- package/dist/exec-repo-integration.js +811 -0
- package/dist/exec-repo-trace.js +182 -0
- package/dist/exec-reporter.js +613 -132
- package/dist/exec-results.js +81 -56
- package/dist/exec-run-lock.js +110 -107
- package/dist/exec-run.js +1585 -356
- package/dist/exec-shared.js +7 -0
- package/dist/exec-slot-lock.js +242 -0
- package/dist/exec-task-repos.js +415 -0
- package/dist/exec-trial.js +51 -25
- package/dist/exec-worktree-command.js +87 -43
- package/dist/exec-worktree-ops.js +502 -57
- package/dist/exec-worktree.js +114 -27
- package/dist/exec.js +13 -6
- package/dist/grade-result.js +128 -0
- package/dist/grade.js +809 -72
- package/dist/init-command.js +443 -0
- package/dist/job.js +160 -10
- package/dist/orchestrator.js +213 -0
- package/dist/package-paths.js +19 -1
- package/dist/register-event-merge.js +169 -0
- package/dist/register-item.js +7 -1
- package/dist/register.js +294 -86
- package/dist/review-grade.js +252 -0
- package/dist/review-plan.js +111 -1
- package/dist/review-types.js +40 -1
- package/dist/routine.js +72 -5
- package/dist/schedule-build.js +2 -2
- package/dist/schedule.js +17 -4
- package/dist/specdojo-config.js +466 -20
- package/dist/specdojo-gitignore.js +135 -0
- package/dist/specdojo.js +8 -1
- package/dist/viewpoint-document-kinds-check.js +128 -0
- package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
- package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
- package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
- package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
- package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
- package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
- package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
- package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
- package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
- package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
- package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
- package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
- package/docs/ja/specdojo/guides/exec-config-guide.md +91 -47
- package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
- package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
- package/docs/ja/specdojo/guides/kata-guide.md +4 -4
- package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +25 -4
- package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
- package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
- package/docs/ja/specdojo/guides/quick-start-guide.md +261 -32
- package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
- package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
- package/docs/ja/specdojo/guides/remote-host-development-guide.md +184 -0
- package/docs/ja/specdojo/guides/review-guide.md +195 -158
- package/docs/ja/specdojo/guides/routine-operation-guide.md +74 -9
- package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
- package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
- package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
- package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
- package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
- package/docs/ja/specdojo/guides/waza-guide.md +15 -2
- package/docs/ja/specdojo/index.md +2 -2
- package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
- package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
- package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
- package/docs/ja/specdojo/references/command-reference.md +336 -93
- package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
- package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
- package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
- package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
- package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
- package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
- package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
- package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
- package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
- package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
- package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
- package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
- package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
- package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
- package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
- package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
- package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
- package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
- package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
- package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
- package/docs/ja/specdojo/samples/bps-sample.md +74 -21
- package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
- package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
- package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
- package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
- package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
- package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
- package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
- package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
- package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
- package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
- package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
- package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
- package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
- package/docs/ja/specdojo/templates/bps-template.md +91 -0
- package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
- package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
- package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
- package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
- package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
- package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
- package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
- package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
- package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
- package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
- package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
- package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
- package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
- package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
- package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
- package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
- package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
- package/package.json +16 -9
- package/templates/antigravity/README.md +60 -0
- package/templates/antigravity/agent-members-snippet.yaml +61 -0
- package/templates/antigravity/exec-defaults-snippet.yaml +39 -0
- package/templates/antigravity/orchestrator.md +157 -0
- package/templates/antigravity/settings.global.json +55 -0
- package/templates/claude/agents/claude-executor.md +14 -0
- package/templates/claude/agents/claude-reporter.md +16 -0
- package/templates/claude/agents/specdojo-orchestrator.md +164 -0
- package/templates/claude/settings.edit.json +27 -1
- package/templates/codex/README.md +5 -4
- package/templates/codex/agents/specdojo-orchestrator.toml +165 -0
- package/templates/codex/orchestrator.md +157 -0
- package/templates/copilot/README.md +7 -5
- package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
- package/templates/devcontainer/devcontainer.json +27 -0
- package/templates/devcontainer/emacs/init.el +88 -0
- package/templates/devcontainer/post-create.sh +62 -0
- package/templates/init-agent-members.yaml +200 -0
- package/templates/init-exec-defaults.yaml +72 -0
- package/templates/opencode/agents/specdojo-orchestrator.md +204 -0
- package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
- package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
|
@@ -0,0 +1,811 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { dirname, resolve } from "node:path";
|
|
3
|
+
import { acquireSchedulerLock, releaseSchedulerLock } from "./exec-events.js";
|
|
4
|
+
import { productIntegrationTarget } from "./exec-task-repos.js";
|
|
5
|
+
import { abortMerge, commitTargetPaths, isExecBranchMergedIntoCurrent, recordRootNewFilesHandoff, REGISTER_NEW_FILE_DIR_PREFIXES, repoRelative, stabilizeCommitTargets, stageCommitTargets, worktreeStatusPaths, } from "./exec-worktree-ops.js";
|
|
6
|
+
import { appendGitFailureLog, gitOutput, gitResult, listRegisteredWorktrees, summarizeGitHookFailure, } from "./exec-worktree.js";
|
|
7
|
+
import { PROJECT_REPO_WORKTREE_DIRNAME, resolveRepoQualifiedRef } from "./specdojo-config.js";
|
|
8
|
+
// PJR-0WAA: 1 つのタスクがプロジェクトリポジトリと宣言済みのプロダクトリポジトリ(`repos`)を
|
|
9
|
+
// 変更する場合の統合段。commit 対象の算出と commit はリポジトリごとに行い、統合の前に全リポジトリ
|
|
10
|
+
// で merge 可否を確かめる。統合は宣言順にプロダクト、最後にプロジェクトの順で行い、リポジトリ別の
|
|
11
|
+
// 状態を pipeline state(`stages.integrate.repos`)へ記録する。再開では統合済みのリポジトリを
|
|
12
|
+
// Git の状態から判定して飛ばし、失敗した位置から続ける。`repos` を持たない project では、
|
|
13
|
+
// プロジェクト側の手順だけを従来どおりの順で実行する。
|
|
14
|
+
/** Name under which the project repository is recorded in `stages.integrate.repos`. */
|
|
15
|
+
export const PROJECT_REPO_NAME = PROJECT_REPO_WORKTREE_DIRNAME;
|
|
16
|
+
const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
|
|
17
|
+
const DEFAULT_LOCK_STALE_MS = 300_000;
|
|
18
|
+
// プロダクト側でも生成物として再生成されるため commit 対象にしないパス。
|
|
19
|
+
const PRODUCT_EXCLUDED_PATHS = new Set([".specdojo/doc-index.json"]);
|
|
20
|
+
export function isProductExcludedPath(path) {
|
|
21
|
+
const normalized = path.replaceAll("\\", "/");
|
|
22
|
+
if (PRODUCT_EXCLUDED_PATHS.has(normalized))
|
|
23
|
+
return true;
|
|
24
|
+
if (normalized === "tmp" || normalized.startsWith("tmp/"))
|
|
25
|
+
return true;
|
|
26
|
+
return false;
|
|
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
|
+
// ── commit 対象の算出と commit ─────────────────────────────────────────────
|
|
35
|
+
/**
|
|
36
|
+
* Split `targets` of the task by product repository: `<repo>:<path>` values whose prefix is a
|
|
37
|
+
* product of the task become repository-relative paths. Doc ids and invalid values are ignored
|
|
38
|
+
* (the project side and the config validation handle them).
|
|
39
|
+
*/
|
|
40
|
+
export function productTargetPaths(targets, products) {
|
|
41
|
+
const byRepo = new Map();
|
|
42
|
+
for (const target of targets) {
|
|
43
|
+
let ref;
|
|
44
|
+
try {
|
|
45
|
+
ref = resolveRepoQualifiedRef(target, products);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (ref.kind !== "repo" || ref.path === ".")
|
|
51
|
+
continue;
|
|
52
|
+
byRepo.set(ref.repo, [...(byRepo.get(ref.repo) ?? []), ref.path]);
|
|
53
|
+
}
|
|
54
|
+
return byRepo;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Commit targets of a product worktree. Changes and deletions of files tracked at HEAD are always
|
|
58
|
+
* committed. A new file is committed only under the known deliverable directories, a top-level
|
|
59
|
+
* directory tracked at HEAD, or a path named by the task's `<repo>:<path>` targets, so scratch
|
|
60
|
+
* files the agent left at the repository root are not committed (same policy as register tasks).
|
|
61
|
+
*/
|
|
62
|
+
export function partitionProductCommitTargets(product, targetPaths = []) {
|
|
63
|
+
const candidates = worktreeStatusPaths(product.path).filter((path) => !isProductExcludedPath(path));
|
|
64
|
+
if (candidates.length === 0)
|
|
65
|
+
return { targets: [], outOfScope: [] };
|
|
66
|
+
const tracked = new Set(zeroSeparated(product.path, [
|
|
67
|
+
"ls-tree",
|
|
68
|
+
"-r",
|
|
69
|
+
"--name-only",
|
|
70
|
+
"--full-tree",
|
|
71
|
+
"-z",
|
|
72
|
+
"HEAD",
|
|
73
|
+
"--",
|
|
74
|
+
...candidates,
|
|
75
|
+
]));
|
|
76
|
+
const allowedPrefixes = [
|
|
77
|
+
...REGISTER_NEW_FILE_DIR_PREFIXES,
|
|
78
|
+
...zeroSeparated(product.path, ["ls-tree", "-d", "--name-only", "-z", "HEAD"]).map((dir) => `${dir}/`),
|
|
79
|
+
...targetPaths.map((path) => `${path}/`),
|
|
80
|
+
];
|
|
81
|
+
const allowedFiles = new Set(targetPaths);
|
|
82
|
+
const targets = [];
|
|
83
|
+
const outOfScope = [];
|
|
84
|
+
for (const path of candidates) {
|
|
85
|
+
const isTopLevel = !path.includes("/");
|
|
86
|
+
const allowed = tracked.has(path) ||
|
|
87
|
+
allowedFiles.has(path) ||
|
|
88
|
+
isTopLevel ||
|
|
89
|
+
allowedPrefixes.some((prefix) => path.startsWith(prefix));
|
|
90
|
+
(allowed ? targets : outOfScope).push(path);
|
|
91
|
+
}
|
|
92
|
+
return { targets, outOfScope };
|
|
93
|
+
}
|
|
94
|
+
/** Commit the commit targets of one product worktree onto its exec branch. */
|
|
95
|
+
export function commitProductWorktree(product, params) {
|
|
96
|
+
const targetPaths = params.targetPaths ?? [];
|
|
97
|
+
const { targets, outOfScope } = partitionProductCommitTargets(product, targetPaths);
|
|
98
|
+
const tracked = new Set(zeroSeparated(product.path, [
|
|
99
|
+
"ls-tree",
|
|
100
|
+
"-r",
|
|
101
|
+
"--name-only",
|
|
102
|
+
"--full-tree",
|
|
103
|
+
"-z",
|
|
104
|
+
"HEAD",
|
|
105
|
+
"--",
|
|
106
|
+
...targets,
|
|
107
|
+
]));
|
|
108
|
+
const rootNewFiles = targets.filter((path) => !path.includes("/") && !tracked.has(path));
|
|
109
|
+
if (targets.length === 0) {
|
|
110
|
+
return { repo: product.name, targets, outOfScope, committed: false, rootNewFiles: [] };
|
|
111
|
+
}
|
|
112
|
+
stageCommitTargets(product.path, targets);
|
|
113
|
+
const staged = gitResult(product.path, ["diff", "--cached", "--quiet", "--", ...targets]);
|
|
114
|
+
if (staged.status === 0) {
|
|
115
|
+
return { repo: product.name, targets, outOfScope, committed: false, rootNewFiles: [] };
|
|
116
|
+
}
|
|
117
|
+
if (staged.status !== 1) {
|
|
118
|
+
throw new Error(`${product.name}: failed to inspect staged changes in ${product.path}`);
|
|
119
|
+
}
|
|
120
|
+
const commit = gitResult(product.path, ["commit", "-m", params.message, "--", ...targets]);
|
|
121
|
+
if (commit.status !== 0) {
|
|
122
|
+
// hook が失敗すると stage が残る。範囲を限った reset で後続の検査を誤らせない。
|
|
123
|
+
gitResult(product.path, ["reset", "--quiet", "--", ...targets]);
|
|
124
|
+
const output = [gitText(commit.stdout), gitText(commit.stderr)].filter(Boolean).join("\n");
|
|
125
|
+
appendGitFailureLog(params.failureLogPath, [
|
|
126
|
+
`=== ${new Date().toISOString()} ${product.name}: git commit ===`,
|
|
127
|
+
`exit: ${commit.status ?? "unknown"}`,
|
|
128
|
+
"--- stdout ---",
|
|
129
|
+
gitText(commit.stdout),
|
|
130
|
+
"--- stderr ---",
|
|
131
|
+
gitText(commit.stderr),
|
|
132
|
+
"",
|
|
133
|
+
]);
|
|
134
|
+
throw new Error(`${product.name}: commit failed: ${summarizeGitHookFailure(output)}`);
|
|
135
|
+
}
|
|
136
|
+
stabilizeCommitTargets(product.path, () => partitionProductCommitTargets(product, targetPaths).targets, undefined, params.failureLogPath);
|
|
137
|
+
return { repo: product.name, targets, outOfScope, committed: true, rootNewFiles };
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Commit every product worktree of the task (declaration order). Out-of-scope files stay in the
|
|
141
|
+
* worktree and are reported to stdout and `scopeLogPath`; the pre-integration check then blocks
|
|
142
|
+
* the integration so they are never discarded with the worktree.
|
|
143
|
+
*/
|
|
144
|
+
export function commitProductWorktrees(params) {
|
|
145
|
+
const products = params.worktree.repos ?? [];
|
|
146
|
+
if (products.length === 0)
|
|
147
|
+
return [];
|
|
148
|
+
const targetPaths = productTargetPaths(params.targets ?? [], products);
|
|
149
|
+
const outcomes = [];
|
|
150
|
+
for (const product of products) {
|
|
151
|
+
if (!existsSync(product.path))
|
|
152
|
+
continue;
|
|
153
|
+
const outcome = commitProductWorktree(product, {
|
|
154
|
+
message: params.message,
|
|
155
|
+
targetPaths: targetPaths.get(product.name),
|
|
156
|
+
failureLogPath: params.failureLogPath,
|
|
157
|
+
});
|
|
158
|
+
if (outcome.targets.length > 0) {
|
|
159
|
+
process.stdout.write(`commit-targets (${product.name}):\n${outcome.targets
|
|
160
|
+
.map((path) => ` ${product.name}:${path}`)
|
|
161
|
+
.join("\n")}\n`);
|
|
162
|
+
}
|
|
163
|
+
if (outcome.committed && outcome.rootNewFiles.length > 0) {
|
|
164
|
+
const rootNewWarning = `最上位に追加したファイル:\n` +
|
|
165
|
+
`${outcome.rootNewFiles.map((path) => ` ${product.name}:${path}`).join("\n")}\n`;
|
|
166
|
+
process.stdout.write(rootNewWarning);
|
|
167
|
+
if (params.scopeLogPath) {
|
|
168
|
+
mkdirSync(dirname(params.scopeLogPath), { recursive: true });
|
|
169
|
+
appendFileSync(params.scopeLogPath, rootNewWarning, "utf8");
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (outcome.outOfScope.length > 0) {
|
|
173
|
+
const warning = `commit-scope: skipped non-target changes (left in worktree):\n` +
|
|
174
|
+
`${outcome.outOfScope.map((path) => ` ${product.name}:${path}`).join("\n")}\n`;
|
|
175
|
+
process.stdout.write(warning);
|
|
176
|
+
if (params.scopeLogPath) {
|
|
177
|
+
mkdirSync(dirname(params.scopeLogPath), { recursive: true });
|
|
178
|
+
appendFileSync(params.scopeLogPath, warning, "utf8");
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
outcomes.push(outcome);
|
|
182
|
+
}
|
|
183
|
+
const allProductRootNewFiles = outcomes
|
|
184
|
+
.filter((outcome) => outcome.committed)
|
|
185
|
+
.flatMap((outcome) => outcome.rootNewFiles.map((path) => `${outcome.repo}:${path}`));
|
|
186
|
+
if (params.resultPath && allProductRootNewFiles.length > 0) {
|
|
187
|
+
recordRootNewFilesHandoff(params.resultPath, allProductRootNewFiles);
|
|
188
|
+
}
|
|
189
|
+
return outcomes;
|
|
190
|
+
}
|
|
191
|
+
export function productMergeState(product) {
|
|
192
|
+
const target = productIntegrationTarget(product);
|
|
193
|
+
const tip = gitResult(product.repoRoot, ["rev-parse", "--verify", `${product.branch}^{commit}`]);
|
|
194
|
+
if (tip.status !== 0)
|
|
195
|
+
return "pending";
|
|
196
|
+
const ancestor = gitResult(product.repoRoot, [
|
|
197
|
+
"merge-base",
|
|
198
|
+
"--is-ancestor",
|
|
199
|
+
product.branch,
|
|
200
|
+
target,
|
|
201
|
+
]);
|
|
202
|
+
if (ancestor.status !== 0)
|
|
203
|
+
return "pending";
|
|
204
|
+
const firstParent = gitOutput(product.repoRoot, ["rev-list", "--first-parent", target])
|
|
205
|
+
.split("\n")
|
|
206
|
+
.map((line) => line.trim());
|
|
207
|
+
return firstParent.includes(gitText(tip.stdout).trim()) ? "unchanged" : "merged";
|
|
208
|
+
}
|
|
209
|
+
// 作業ツリーを変えずに merge の結果を求める(git 2.38 以降の `merge-tree --write-tree`)。
|
|
210
|
+
function mergeTree(repoRoot, target, branch) {
|
|
211
|
+
const result = gitResult(repoRoot, [
|
|
212
|
+
"merge-tree",
|
|
213
|
+
"--write-tree",
|
|
214
|
+
"--name-only",
|
|
215
|
+
"--no-messages",
|
|
216
|
+
target,
|
|
217
|
+
branch,
|
|
218
|
+
]);
|
|
219
|
+
const lines = gitText(result.stdout)
|
|
220
|
+
.split("\n")
|
|
221
|
+
.map((line) => line.trim())
|
|
222
|
+
.filter(Boolean);
|
|
223
|
+
if (result.status === 0 && lines[0])
|
|
224
|
+
return { kind: "clean", tree: lines[0] };
|
|
225
|
+
if (result.status === 1)
|
|
226
|
+
return { kind: "conflicts", paths: [...new Set(lines.slice(1))] };
|
|
227
|
+
const detail = gitText(result.stderr).trim() || `exit ${result.status ?? "unknown"}`;
|
|
228
|
+
return { kind: "error", detail };
|
|
229
|
+
}
|
|
230
|
+
function mergeChangedPaths(repoRoot, target, branch) {
|
|
231
|
+
return new Set(zeroSeparated(repoRoot, ["diff", "--no-renames", "--name-only", "-z", `${target}...${branch}`]));
|
|
232
|
+
}
|
|
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
|
+
// 統合先ブランチを checkout している worktree(主 checkout を含む)。無ければ undefined。
|
|
244
|
+
function checkoutOfBranch(repoRoot, branch) {
|
|
245
|
+
return listRegisteredWorktrees(repoRoot).find((worktree) => worktree.branch === branch)?.path;
|
|
246
|
+
}
|
|
247
|
+
function branchExists(repoRoot, branch) {
|
|
248
|
+
return (gitResult(repoRoot, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).status === 0);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Reasons why a product repository cannot be integrated. Checked for every repository before any
|
|
252
|
+
* of them is merged, so a failure found here leaves every repository unintegrated.
|
|
253
|
+
*/
|
|
254
|
+
export function productMergeBlockers(product) {
|
|
255
|
+
const block = (message) => ({ repo: product.name, message });
|
|
256
|
+
if (!existsSync(product.path))
|
|
257
|
+
return [block(`worktree is missing: ${product.path}`)];
|
|
258
|
+
const blockers = [];
|
|
259
|
+
const leftover = worktreeStatusPaths(product.path).filter((path) => !isProductExcludedPath(path));
|
|
260
|
+
if (leftover.length > 0) {
|
|
261
|
+
blockers.push(block(`uncommitted changes outside the commit scope: ` +
|
|
262
|
+
leftover.map((path) => `${product.name}:${path}`).join(", ")));
|
|
263
|
+
}
|
|
264
|
+
const target = productIntegrationTarget(product);
|
|
265
|
+
if (target === "HEAD" || !branchExists(product.repoRoot, target)) {
|
|
266
|
+
blockers.push(block(`integration branch ${target === "HEAD" ? "(detached HEAD)" : target} is not a local ` +
|
|
267
|
+
`branch; set repos[].integration_branch`));
|
|
268
|
+
return blockers;
|
|
269
|
+
}
|
|
270
|
+
if (target === product.branch) {
|
|
271
|
+
blockers.push(block(`integration branch must differ from the exec branch ${product.branch}`));
|
|
272
|
+
return blockers;
|
|
273
|
+
}
|
|
274
|
+
if (productMergeState(product) !== "pending")
|
|
275
|
+
return blockers;
|
|
276
|
+
const merged = mergeTree(product.repoRoot, target, product.branch);
|
|
277
|
+
if (merged.kind === "conflicts") {
|
|
278
|
+
blockers.push(block(`merge conflicts with ${target}: ${merged.paths.join(", ")}`));
|
|
279
|
+
}
|
|
280
|
+
else if (merged.kind === "error") {
|
|
281
|
+
blockers.push(block(`cannot check the merge into ${target}: ${merged.detail}`));
|
|
282
|
+
}
|
|
283
|
+
const checkout = checkoutOfBranch(product.repoRoot, target);
|
|
284
|
+
if (checkout) {
|
|
285
|
+
if (mergeInProgress(checkout)) {
|
|
286
|
+
blockers.push(block(`a merge is in progress in ${checkout}`));
|
|
287
|
+
}
|
|
288
|
+
else {
|
|
289
|
+
const changed = mergeChangedPaths(product.repoRoot, target, product.branch);
|
|
290
|
+
const overlap = [...dirtyPaths(checkout)].filter((path) => changed.has(path));
|
|
291
|
+
if (overlap.length > 0) {
|
|
292
|
+
blockers.push(block(`uncommitted changes in ${checkout} overlap merge paths: ${overlap.join(", ")}`));
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return blockers;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Reasons why the project exec branch cannot be merged into the branch checked out at the project
|
|
300
|
+
* root. Conflicts on `ownedPaths` (the item's own bookkeeping) are resolved by the merge itself and
|
|
301
|
+
* root working copies of `releasePaths` are released right before the merge, so neither blocks.
|
|
302
|
+
*/
|
|
303
|
+
export function projectMergeBlockers(params) {
|
|
304
|
+
const { context, worktree } = params;
|
|
305
|
+
const repoRoot = context.repoRoot;
|
|
306
|
+
const block = (message) => ({ repo: PROJECT_REPO_NAME, message });
|
|
307
|
+
if (isExecBranchMergedIntoCurrent({ context, worktree }))
|
|
308
|
+
return [];
|
|
309
|
+
const target = gitText(gitResult(repoRoot, ["branch", "--show-current"]).stdout).trim();
|
|
310
|
+
if (!target)
|
|
311
|
+
return [block("detached HEAD is not supported as the integration target")];
|
|
312
|
+
if (target === worktree.branch) {
|
|
313
|
+
return [block(`merge must run from a branch other than ${worktree.branch}`)];
|
|
314
|
+
}
|
|
315
|
+
if (mergeInProgress(repoRoot))
|
|
316
|
+
return [block(`a merge is in progress in ${repoRoot}`)];
|
|
317
|
+
const blockers = [];
|
|
318
|
+
const uncommitted = commitTargetPaths(context, worktree, params.taskId);
|
|
319
|
+
if (uncommitted.length > 0) {
|
|
320
|
+
blockers.push(block(`uncommitted commit-target changes: ${uncommitted.join(", ")}`));
|
|
321
|
+
}
|
|
322
|
+
const toRelative = (paths) => new Set((paths ?? []).map((path) => repoRelative(repoRoot, resolve(path))));
|
|
323
|
+
const owned = toRelative(params.ownedPaths);
|
|
324
|
+
const released = toRelative(params.releasePaths);
|
|
325
|
+
const merged = mergeTree(repoRoot, "HEAD", worktree.branch);
|
|
326
|
+
if (merged.kind === "conflicts") {
|
|
327
|
+
const unexpected = merged.paths.filter((path) => !owned.has(path));
|
|
328
|
+
if (unexpected.length > 0) {
|
|
329
|
+
blockers.push(block(`merge conflicts with ${target}: ${unexpected.join(", ")}`));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
else if (merged.kind === "error") {
|
|
333
|
+
blockers.push(block(`cannot check the merge into ${target}: ${merged.detail}`));
|
|
334
|
+
}
|
|
335
|
+
const changed = mergeChangedPaths(repoRoot, "HEAD", worktree.branch);
|
|
336
|
+
const overlap = [...dirtyPaths(repoRoot)].filter((path) => changed.has(path) && !released.has(path));
|
|
337
|
+
if (overlap.length > 0) {
|
|
338
|
+
blockers.push(block(`uncommitted changes at root overlap merge paths: ${overlap.join(", ")}`));
|
|
339
|
+
}
|
|
340
|
+
return blockers;
|
|
341
|
+
}
|
|
342
|
+
// ── プロダクトの merge ─────────────────────────────────────────────────────
|
|
343
|
+
/**
|
|
344
|
+
* Merge the product exec branch into its integration target with a merge commit and return the
|
|
345
|
+
* merge commit. When the target is checked out (normally the product's main checkout), a regular
|
|
346
|
+
* `git merge --no-ff` updates that working tree; a failed merge is aborted. Otherwise the merge
|
|
347
|
+
* commit is written with `merge-tree` / `commit-tree` and the branch is moved with a
|
|
348
|
+
* compare-and-swap `update-ref`, so a concurrent update of the target is never overwritten.
|
|
349
|
+
*/
|
|
350
|
+
export function mergeProductIntoTarget(params) {
|
|
351
|
+
const { product, message } = params;
|
|
352
|
+
const target = productIntegrationTarget(product);
|
|
353
|
+
const checkout = checkoutOfBranch(product.repoRoot, target);
|
|
354
|
+
const header = `=== ${new Date().toISOString()} ${product.name}: merge ${product.branch} into ${target} ===`;
|
|
355
|
+
if (checkout) {
|
|
356
|
+
const result = gitResult(checkout, ["merge", "--no-ff", "-m", message, product.branch]);
|
|
357
|
+
if (result.status === 0)
|
|
358
|
+
return gitOutput(checkout, ["rev-parse", "HEAD"]).trim();
|
|
359
|
+
const output = [gitText(result.stdout), gitText(result.stderr)].filter(Boolean).join("\n");
|
|
360
|
+
const abort = mergeInProgress(checkout) ? abortMerge(checkout) : undefined;
|
|
361
|
+
appendGitFailureLog(params.failureLogPath, [
|
|
362
|
+
header,
|
|
363
|
+
`git -C ${checkout} merge --no-ff ${product.branch}`,
|
|
364
|
+
`exit: ${result.status ?? "unknown"}`,
|
|
365
|
+
"--- stdout ---",
|
|
366
|
+
gitText(result.stdout),
|
|
367
|
+
"--- stderr ---",
|
|
368
|
+
gitText(result.stderr),
|
|
369
|
+
"--- merge --abort ---",
|
|
370
|
+
abort ? `exit: ${abort.status ?? "unknown"}` : "not required",
|
|
371
|
+
"",
|
|
372
|
+
]);
|
|
373
|
+
const summary = summarizeGitHookFailure(output);
|
|
374
|
+
if (abort && abort.status !== 0) {
|
|
375
|
+
throw new Error(`git merge into ${target} failed: ${summary}; automatic git merge --abort failed; ` +
|
|
376
|
+
`run git merge --abort manually in ${checkout} before continuing`);
|
|
377
|
+
}
|
|
378
|
+
throw new Error(`git merge into ${target} failed: ${summary}`);
|
|
379
|
+
}
|
|
380
|
+
const merged = mergeTree(product.repoRoot, target, product.branch);
|
|
381
|
+
if (merged.kind !== "clean") {
|
|
382
|
+
const detail = merged.kind === "conflicts" ? `conflicts: ${merged.paths.join(", ")}` : merged.detail;
|
|
383
|
+
appendGitFailureLog(params.failureLogPath, [header, `merge-tree: ${detail}`, ""]);
|
|
384
|
+
throw new Error(`merge into ${target} failed: ${detail}`);
|
|
385
|
+
}
|
|
386
|
+
const parent = gitOutput(product.repoRoot, ["rev-parse", `refs/heads/${target}`]).trim();
|
|
387
|
+
const tip = gitOutput(product.repoRoot, ["rev-parse", `${product.branch}^{commit}`]).trim();
|
|
388
|
+
const commit = gitOutput(product.repoRoot, [
|
|
389
|
+
"commit-tree",
|
|
390
|
+
merged.tree,
|
|
391
|
+
"-p",
|
|
392
|
+
parent,
|
|
393
|
+
"-p",
|
|
394
|
+
tip,
|
|
395
|
+
"-m",
|
|
396
|
+
message,
|
|
397
|
+
]).trim();
|
|
398
|
+
const update = gitResult(product.repoRoot, [
|
|
399
|
+
"update-ref",
|
|
400
|
+
"-m",
|
|
401
|
+
`exec: merge ${product.branch}`,
|
|
402
|
+
`refs/heads/${target}`,
|
|
403
|
+
commit,
|
|
404
|
+
parent,
|
|
405
|
+
]);
|
|
406
|
+
if (update.status !== 0) {
|
|
407
|
+
const detail = gitText(update.stderr).trim() || `exit ${update.status ?? "unknown"}`;
|
|
408
|
+
appendGitFailureLog(params.failureLogPath, [header, `update-ref: ${detail}`, ""]);
|
|
409
|
+
throw new Error(`failed to update ${target}: ${detail}`);
|
|
410
|
+
}
|
|
411
|
+
return commit;
|
|
412
|
+
}
|
|
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
|
+
}
|
|
672
|
+
/** Integration failure that names the integrated and the remaining repositories. */
|
|
673
|
+
export class RepoIntegrationError extends Error {
|
|
674
|
+
repo;
|
|
675
|
+
integrated;
|
|
676
|
+
pending;
|
|
677
|
+
constructor(params) {
|
|
678
|
+
super(`${params.repo}: ${params.cause}; integrated repositories: ` +
|
|
679
|
+
`${params.integrated.length > 0 ? params.integrated.join(", ") : "none"}; ` +
|
|
680
|
+
`not integrated: ${params.pending.join(", ")}`);
|
|
681
|
+
this.name = "RepoIntegrationError";
|
|
682
|
+
this.repo = params.repo;
|
|
683
|
+
this.integrated = params.integrated;
|
|
684
|
+
this.pending = params.pending;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
function errorMessage(error) {
|
|
688
|
+
return error instanceof Error ? error.message : String(error);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Integrate a task. Without product worktrees this runs `beforeProjectMerge` and `mergeProject`
|
|
692
|
+
* only (the single-repository sequence, unchanged). With product worktrees:
|
|
693
|
+
*
|
|
694
|
+
* 1. check every product that still has commits to integrate and the project (`checkProject`); if
|
|
695
|
+
* any repository cannot be integrated, nothing is merged
|
|
696
|
+
* 2. merge the products in declaration order, skipping those already merged (resume)
|
|
697
|
+
* 3. run `beforeProjectMerge` (record and commit the project-side state) and `mergeProject`
|
|
698
|
+
*
|
|
699
|
+
* Each repository's state is passed to `record`. The project is recorded as merged before
|
|
700
|
+
* `beforeProjectMerge` commits the state, because its merge commit contains the state itself;
|
|
701
|
+
* a failure overwrites the record with `failed`. Failures are thrown as RepoIntegrationError.
|
|
702
|
+
*/
|
|
703
|
+
export function integrateTaskRepositories(params) {
|
|
704
|
+
const products = params.worktree.repos ?? [];
|
|
705
|
+
if (products.length === 0) {
|
|
706
|
+
params.beforeProjectMerge();
|
|
707
|
+
params.mergeProject();
|
|
708
|
+
return;
|
|
709
|
+
}
|
|
710
|
+
const record = params.record ?? (() => undefined);
|
|
711
|
+
const order = [...products.map((product) => product.name), PROJECT_REPO_NAME];
|
|
712
|
+
const done = new Set();
|
|
713
|
+
// 統合済み(merge 済み、または統合する変更が無い)のリポジトリ。
|
|
714
|
+
const integratedLabels = () => order.filter((name) => done.has(name));
|
|
715
|
+
const pendingNames = () => order.filter((name) => !done.has(name));
|
|
716
|
+
const fail = (repo, cause) => {
|
|
717
|
+
record(repo, { status: "failed", error: cause });
|
|
718
|
+
return new RepoIntegrationError({
|
|
719
|
+
repo,
|
|
720
|
+
cause,
|
|
721
|
+
integrated: integratedLabels(),
|
|
722
|
+
pending: pendingNames(),
|
|
723
|
+
});
|
|
724
|
+
};
|
|
725
|
+
const states = new Map();
|
|
726
|
+
for (const product of products) {
|
|
727
|
+
const state = productMergeState(product);
|
|
728
|
+
states.set(product.name, state);
|
|
729
|
+
if (state === "pending")
|
|
730
|
+
continue;
|
|
731
|
+
done.add(product.name);
|
|
732
|
+
process.stdout.write(` [integrate] ${product.name}: ${state === "merged" ? "already merged" : "no changes"}; skipped\n`);
|
|
733
|
+
}
|
|
734
|
+
// `checkProject` は project worktree の未 commit 対象も検査する。state を先に書くと、その
|
|
735
|
+
// runner-owned 変更自体を未 commit と誤認するため、全 repository の検査後に初期状態を記録する。
|
|
736
|
+
const recordInitialStates = () => {
|
|
737
|
+
for (const product of products) {
|
|
738
|
+
const status = states.get(product.name) ?? "pending";
|
|
739
|
+
record(product.name, status === "pending" ? { status, commit: null, merged_at: null } : { status });
|
|
740
|
+
}
|
|
741
|
+
record(PROJECT_REPO_NAME, { status: "pending", commit: null, merged_at: null });
|
|
742
|
+
};
|
|
743
|
+
// 1. 事前検査。どれか 1 つでも統合できなければ、どのリポジトリも統合しない。
|
|
744
|
+
const blockers = [...products.flatMap(productMergeBlockers), ...params.checkProject()];
|
|
745
|
+
if (blockers.length > 0) {
|
|
746
|
+
recordInitialStates();
|
|
747
|
+
const failedRepos = [...new Set(blockers.map((blocker) => blocker.repo))];
|
|
748
|
+
for (const repo of failedRepos) {
|
|
749
|
+
const messages = blockers.filter((blocker) => blocker.repo === repo);
|
|
750
|
+
record(repo, { status: "failed", error: messages.map((item) => item.message).join("; ") });
|
|
751
|
+
}
|
|
752
|
+
for (const name of pendingNames()) {
|
|
753
|
+
if (!failedRepos.includes(name))
|
|
754
|
+
record(name, { status: "pending" });
|
|
755
|
+
}
|
|
756
|
+
throw new RepoIntegrationError({
|
|
757
|
+
repo: failedRepos.join(", "),
|
|
758
|
+
cause: `pre-integration check failed (no repository was integrated in this attempt): ` +
|
|
759
|
+
blockers.map((blocker) => `${blocker.repo}: ${blocker.message}`).join("; "),
|
|
760
|
+
integrated: integratedLabels(),
|
|
761
|
+
pending: pendingNames(),
|
|
762
|
+
});
|
|
763
|
+
}
|
|
764
|
+
recordInitialStates();
|
|
765
|
+
// 2. 宣言順にプロダクトを統合する。
|
|
766
|
+
for (const product of products) {
|
|
767
|
+
if (states.get(product.name) !== "pending")
|
|
768
|
+
continue;
|
|
769
|
+
let lockDir = "";
|
|
770
|
+
let commit;
|
|
771
|
+
try {
|
|
772
|
+
if (params.lockPath) {
|
|
773
|
+
lockDir = acquireSchedulerLock(params.lockPath, {
|
|
774
|
+
actor: `worktree-merge:${product.name}`,
|
|
775
|
+
lockTimeoutMs: DEFAULT_LOCK_TIMEOUT_MS,
|
|
776
|
+
lockStaleMs: DEFAULT_LOCK_STALE_MS,
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
commit = mergeProductIntoTarget({
|
|
780
|
+
product,
|
|
781
|
+
message: params.productMergeMessage ?? params.mergeMessage,
|
|
782
|
+
failureLogPath: params.failureLogPath,
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
catch (error) {
|
|
786
|
+
throw fail(product.name, errorMessage(error));
|
|
787
|
+
}
|
|
788
|
+
finally {
|
|
789
|
+
if (lockDir)
|
|
790
|
+
releaseSchedulerLock(lockDir);
|
|
791
|
+
}
|
|
792
|
+
done.add(product.name);
|
|
793
|
+
record(product.name, { status: "merged", commit, merged_at: new Date().toISOString() });
|
|
794
|
+
process.stdout.write(` [integrate] ${product.name}: merged ${product.branch} into ` +
|
|
795
|
+
`${productIntegrationTarget(product)} (${commit.slice(0, 12)})\n`);
|
|
796
|
+
}
|
|
797
|
+
// 3. 最後にプロジェクトを統合する。
|
|
798
|
+
record(PROJECT_REPO_NAME, {
|
|
799
|
+
status: "merged",
|
|
800
|
+
commit: null,
|
|
801
|
+
merged_at: new Date().toISOString(),
|
|
802
|
+
});
|
|
803
|
+
try {
|
|
804
|
+
params.beforeProjectMerge();
|
|
805
|
+
params.mergeProject();
|
|
806
|
+
}
|
|
807
|
+
catch (error) {
|
|
808
|
+
throw fail(PROJECT_REPO_NAME, errorMessage(error));
|
|
809
|
+
}
|
|
810
|
+
done.add(PROJECT_REPO_NAME);
|
|
811
|
+
}
|