specdojo 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +65 -0
- package/README.md +77 -18
- package/dist/catalog/build-references.js +144 -0
- package/dist/catalog/build-render.js +32 -0
- package/dist/{catalog-build.js → catalog/build.js} +18 -295
- package/dist/{catalog.js → catalog/catalog.js} +11 -11
- package/dist/{catalog-generate.js → catalog/generate.js} +13 -16
- package/dist/catalog/paths.js +1 -0
- package/dist/{catalog-plan-generate.js → catalog/plan-generate.js} +5 -5
- package/dist/{catalog-plan.js → catalog/plan.js} +9 -9
- package/dist/{catalog-scaffold.js → catalog/scaffold.js} +6 -6
- package/dist/{agent.js → commands/agent.js} +11 -11
- package/dist/{build-command.js → commands/build.js} +2 -2
- package/dist/{init-command.js → commands/init.js} +103 -37
- package/dist/{orchestrator.js → commands/orchestrator.js} +2 -2
- package/dist/{watch.js → commands/watch.js} +3 -3
- package/dist/dashboard/dashboard-timeline.js +175 -0
- package/dist/{dashboard.js → dashboard/dashboard.js} +16 -549
- package/dist/dashboard/exec-records.js +105 -0
- package/dist/dashboard/routines.js +256 -0
- package/dist/dashboard/shared.js +14 -0
- package/dist/{timeline-build.js → dashboard/timeline-build.js} +2 -1
- package/dist/{timeline.js → dashboard/timeline.js} +1 -1
- package/dist/{deliverable.js → deliverable/deliverable.js} +5 -5
- package/dist/{deliverable-trash.js → deliverable/trash.js} +7 -7
- package/dist/{devcontainer-command.js → devcontainer/command.js} +5 -3
- package/dist/{devcontainer-scaffold.js → devcontainer/scaffold.js} +94 -2
- package/dist/{doc-index.js → docs/doc-index.js} +3 -3
- package/dist/{frontmatter-namespace.js → docs/frontmatter-namespace.js} +2 -2
- package/dist/{index-command.js → docs/index-command.js} +1 -1
- package/dist/docs/template-resolution.js +1 -0
- package/dist/{viewpoint-document-kinds-check.js → docs/viewpoint-document-kinds-check.js} +3 -3
- package/dist/{yaml-pages-command.js → docs/yaml-pages-command.js} +1 -1
- package/dist/{yaml-pages.js → docs/yaml-pages.js} +5 -5
- package/dist/{exec-agent-config.js → exec/agent-config.js} +33 -4
- package/dist/{exec-agent-git-state.js → exec/agent-git-state.js} +1 -1
- package/dist/{exec-agent-protected-config.js → exec/agent-protected-config.js} +1 -1
- package/dist/{exec.js → exec/commands.js} +22 -467
- package/dist/exec/core.js +457 -0
- package/dist/{exec-events.js → exec/events.js} +2 -2
- package/dist/{exec-evidence.js → exec/evidence.js} +11 -6
- package/dist/exec/exec.js +2 -0
- package/dist/exec/format.js +1 -0
- package/dist/{exec-handoff.js → exec/handoff.js} +13 -12
- package/dist/{exec-limit.js → exec/limit.js} +93 -12
- package/dist/{exec-parent-validation.js → exec/parent-validation.js} +4 -4
- package/dist/{exec-pipeline-state.js → exec/pipeline-state.js} +16 -2
- package/dist/{exec-plans.js → exec/plans-core.js} +97 -468
- package/dist/exec/plans-generation.js +249 -0
- package/dist/exec/plans-storage.js +131 -0
- package/dist/exec/plans.js +3 -0
- package/dist/{exec-project.js → exec/project.js} +1 -1
- package/dist/{exec-protection-handoff.js → exec/protection-handoff.js} +3 -3
- package/dist/{exec-register-resume.js → exec/register-resume.js} +2 -2
- package/dist/{exec-register.js → exec/register.js} +92 -9
- package/dist/exec/repo-integration-git.js +23 -0
- package/dist/exec/repo-integration-sync.js +264 -0
- package/dist/{exec-repo-integration.js → exec/repo-integration.js} +13 -287
- package/dist/{exec-repo-trace.js → exec/repo-trace.js} +3 -3
- package/dist/exec/reporter-output.js +206 -0
- package/dist/{exec-reporter.js → exec/reporter.js} +29 -216
- package/dist/{exec-results.js → exec/results.js} +277 -36
- package/dist/exec/run/agent-pipeline.js +276 -0
- package/dist/exec/run/agent.js +583 -0
- package/dist/exec/run/in-place.js +570 -0
- package/dist/exec/run/job.js +746 -0
- package/dist/exec/run/lifecycle-commands.js +530 -0
- package/dist/{exec-run-lock.js → exec/run/lock.js} +4 -3
- package/dist/exec/run/mode-shared.js +140 -0
- package/dist/exec/run/register-command.js +252 -0
- package/dist/exec/run/register-core.js +411 -0
- package/dist/exec/run/register-mode.js +210 -0
- package/dist/exec/run/register-resume.js +398 -0
- package/dist/exec/run/register-state.js +325 -0
- package/dist/exec/run/register-worktree.js +540 -0
- package/dist/exec/run/run.js +11 -0
- package/dist/exec/run/schedule-mode.js +294 -0
- package/dist/exec/run/schedule-prepare.js +366 -0
- package/dist/exec/run/schedule-task.js +599 -0
- package/dist/exec/run/shared.js +449 -0
- package/dist/{exec-schedule-calendar.js → exec/schedule/calendar.js} +1 -1
- package/dist/{exec-schedule-cpm.js → exec/schedule/cpm.js} +2 -2
- package/dist/{exec-schedule-gantt-chart-render.js → exec/schedule/gantt-chart-render.js} +2 -2
- package/dist/exec/schedule/gantt-chart.js +2 -0
- package/dist/{exec-schedule-hash.js → exec/schedule/hash.js} +2 -2
- package/dist/exec/schedule/index.js +1 -0
- package/dist/{exec-schedule-initial.js → exec/schedule/initial.js} +2 -2
- package/dist/{exec-schedule-progress.js → exec/schedule/progress.js} +2 -2
- package/dist/{exec-schedule-ready.js → exec/schedule/ready.js} +2 -2
- package/dist/{exec-schedule.js → exec/schedule/schedule.js} +11 -11
- package/dist/exec/shared.js +63 -0
- package/dist/exec/slot-lock.js +1 -0
- package/dist/{exec-strategy.js → exec/strategy.js} +2 -2
- package/dist/{exec-task-repos.js → exec/task-repos.js} +2 -2
- package/dist/{exec-task-view.js → exec/task-view.js} +4 -4
- package/dist/{exec-trial.js → exec/trial-commands.js} +23 -388
- package/dist/exec/trial-core.js +371 -0
- package/dist/exec/trial.js +2 -0
- package/dist/{exec-worktree-command.js → exec/worktree-command.js} +25 -23
- package/dist/exec/worktree-ops-commit.js +672 -0
- package/dist/exec/worktree-ops-lifecycle.js +297 -0
- package/dist/exec/worktree-ops-merge.js +344 -0
- package/dist/exec/worktree-ops.js +3 -0
- package/dist/exec/worktree.js +305 -0
- package/dist/grade/apply.js +734 -0
- package/dist/grade/command-apply.js +250 -0
- package/dist/grade/command-inspect.js +138 -0
- package/dist/grade/command-plan.js +101 -0
- package/dist/grade/command-shared.js +68 -0
- package/dist/grade/core.js +307 -0
- package/dist/grade/grade.js +19 -0
- package/dist/grade/markdown.js +274 -0
- package/dist/grade/pipeline-state.js +184 -0
- package/dist/grade/plan.js +507 -0
- package/dist/{grade-result.js → grade/result.js} +7 -96
- package/dist/grade/target-discovery.js +265 -0
- package/dist/grade/targets.js +435 -0
- package/dist/{job.js → job/definition.js} +32 -574
- package/dist/job/job.js +568 -0
- package/dist/{kata-command.js → kata/command.js} +4 -4
- package/dist/{kata.js → kata/kata.js} +5 -5
- package/dist/register/approach.js +134 -0
- package/dist/register/command-types.js +1 -0
- package/dist/register/core.js +369 -0
- package/dist/register/create-commands.js +352 -0
- package/dist/{register-date.js → register/date.js} +1 -1
- package/dist/register/derivation.js +163 -0
- package/dist/{register-event-merge.js → register/event-merge.js} +32 -3
- package/dist/{register-events.js → register/events.js} +12 -6
- package/dist/{register-history.js → register/history.js} +7 -6
- package/dist/{register-item.js → register/item.js} +28 -10
- package/dist/register/lifecycle-lock.js +5 -0
- package/dist/register/maintenance-commands.js +193 -0
- package/dist/{register-migrate-timestamps.js → register/migrate-timestamps.js} +3 -3
- package/dist/register/migration.js +268 -0
- package/dist/register/register.js +404 -0
- package/dist/register/renumber.js +341 -0
- package/dist/register/transition-commands.js +248 -0
- package/dist/register/update.js +230 -0
- package/dist/register/views.js +296 -0
- package/dist/{review-grade.js → review/grade.js} +2 -2
- package/dist/{review-plan.js → review/plan.js} +5 -5
- package/dist/routine/definition.js +401 -0
- package/dist/{routine.js → routine/routine.js} +50 -419
- package/dist/{schedule-approach.js → schedule/approach.js} +9 -9
- package/dist/{schedule-build.js → schedule/build.js} +7 -4
- package/dist/{schedule.js → schedule/schedule.js} +9 -9
- package/dist/schedule/strategy-generate-document.js +273 -0
- package/dist/schedule/strategy-generate-scope.js +199 -0
- package/dist/schedule/strategy-generate.js +348 -0
- package/dist/shared/agent-types.js +23 -0
- package/dist/shared/artifact-path.js +9 -0
- package/dist/{build-if-stale.js → shared/build-if-stale.js} +1 -1
- package/dist/shared/catalog-render.js +115 -0
- package/dist/{exec-slot-lock.js → shared/cross-process-lock.js} +3 -1
- package/dist/shared/fs.js +30 -0
- package/dist/shared/git.js +316 -0
- package/dist/shared/grade-result.js +94 -0
- package/dist/{package-paths.js → shared/package-paths.js} +3 -3
- package/dist/shared/plan-templates.js +114 -0
- package/dist/{exec-provider-scaffold.js → shared/provider-scaffold.js} +3 -1
- package/dist/shared/random.js +4 -0
- package/dist/{exec-schedule-index.js → shared/schedule-index.js} +3 -1
- package/dist/shared/schedule-paths.js +9 -0
- package/dist/{specdojo-config.js → shared/specdojo-config.js} +96 -9
- package/dist/{exec-shared.js → shared/text.js} +0 -134
- package/dist/shared/time.js +28 -0
- package/dist/shared/yaml.js +28 -0
- package/dist/specdojo.js +22 -22
- package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +29 -17
- package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +1 -2
- package/docs/ja/specdojo/exec-templates/xep-register-template.md +1 -2
- package/docs/ja/specdojo/exec-templates/xer-template.md +1 -3
- package/docs/ja/specdojo/exec-templates/xrp-job-template.md +6 -4
- package/docs/ja/specdojo/guides/exec-config-guide.md +97 -22
- package/docs/ja/specdojo/guides/exec-operation-guide.md +145 -12
- package/docs/ja/specdojo/guides/exec-worktree-guide.md +2 -0
- package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +51 -18
- package/docs/ja/specdojo/guides/quick-start-guide.md +81 -16
- package/docs/ja/specdojo/guides/register-operation-guide.md +2 -1
- package/docs/ja/specdojo/guides/remote-host-development-guide.md +10 -1
- package/docs/ja/specdojo/guides/review-guide.md +1 -1
- package/docs/ja/specdojo/guides/routine-operation-guide.md +6 -6
- package/docs/ja/specdojo/guides/use-case-guide.md +1 -1
- package/docs/ja/specdojo/references/command-reference.md +52 -28
- package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +17 -11
- package/docs/ja/specdojo/standards/job-definition-standard.md +20 -18
- package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -2
- package/docs/ja/specdojo/templates/pjr-derived-items-template.md +22 -0
- package/docs/ja/specdojo/templates/pjr-index-template.md +1 -0
- package/docs/specdojo/schemas/v1/agent-members.schema.yaml +29 -2
- package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +20 -0
- package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +23 -0
- package/docs/specdojo/schemas/v1/job-run.schema.yaml +2 -2
- package/docs/specdojo/schemas/v1/job.schema.yaml +7 -0
- package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +26 -0
- package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
- package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +70 -7
- package/docs/specdojo/schemas/v1/routine-run.schema.yaml +1 -1
- package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +1 -1
- package/package.json +4 -5
- package/templates/antigravity/README.md +7 -3
- package/templates/antigravity/agent-members-snippet.yaml +108 -12
- package/templates/antigravity/exec-defaults-snippet.yaml +10 -13
- package/templates/claude/README.md +27 -3
- package/templates/claude/agents/claude-executor.md +0 -1
- package/templates/claude/agents/claude-reporter.md +2 -1
- package/templates/claude/agents/claude-review-executor.md +0 -1
- package/templates/codex/README.md +23 -4
- package/templates/devcontainer/devcontainer.json +2 -2
- package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +69 -0
- package/templates/devcontainer/remote-host/ssh-config.sample +16 -0
- package/templates/init-agent-members.yaml +75 -25
- package/templates/init-exec-defaults.yaml +26 -8
- package/templates/opencode/README.md +17 -3
- package/templates/opencode/agents/opencode-executor.md +0 -1
- package/templates/opencode/agents/opencode-reporter.md +2 -1
- package/templates/opencode/agents/opencode-review-executor.md +0 -1
- package/dist/exec-run.js +0 -6182
- package/dist/exec-schedule-gantt-chart.js +0 -2
- package/dist/exec-worktree-ops.js +0 -1292
- package/dist/exec-worktree.js +0 -446
- package/dist/grade.js +0 -3193
- package/dist/register.js +0 -2407
- package/dist/schedule-strategy-generate.js +0 -812
- package/templates/claude/agents/claude-expert-review-executor.md +0 -14
- /package/dist/{catalog-plan-prompt.js → catalog/plan-prompt.js} +0 -0
- /package/dist/{catalog-types.js → catalog/types.js} +0 -0
- /package/dist/{template-frontmatter.js → docs/template-frontmatter.js} +0 -0
- /package/dist/{role-types.js → exec/role-types.js} +0 -0
- /package/dist/{exec-schedule-gantt-chart-scope.js → exec/schedule/gantt-chart-scope.js} +0 -0
- /package/dist/{exec-types.js → exec/types.js} +0 -0
- /package/dist/{review-types.js → review/types.js} +0 -0
- /package/dist/{schedule-phase-sets.js → schedule/phase-sets.js} +0 -0
- /package/dist/{schedule-strategy-profiles.js → schedule/strategy-profiles.js} +0 -0
- /package/dist/{agent-response.js → shared/agent-response.js} +0 -0
- /package/dist/{catalog-paths.js → shared/catalog-paths.js} +0 -0
- /package/dist/{dist-freshness.js → shared/dist-freshness.js} +0 -0
- /package/dist/{git-environment.js → shared/git-environment.js} +0 -0
- /package/dist/{exec-format.js → shared/markdown-format.js} +0 -0
- /package/dist/{practice-id.js → shared/practice-id.js} +0 -0
- /package/dist/{spawn-self.js → shared/spawn-self.js} +0 -0
- /package/dist/{specdojo-gitignore.js → shared/specdojo-gitignore.js} +0 -0
- /package/dist/{template-resolution.js → shared/template-resolution.js} +0 -0
- /package/dist/{yaml-schema-modeline.js → shared/yaml-schema-modeline.js} +0 -0
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import { copyFileSync, existsSync, lstatSync, mkdirSync, rmSync } from "node:fs";
|
|
2
|
+
import { resolve } from "node:path";
|
|
3
|
+
import { stripTerminalControlSequences } from "./shared.js";
|
|
4
|
+
import { discardStaleProductWorktrees, ensureProductWorktrees, projectRepoDirName, productWorktreeRemovalBlockers, removeEmptyTaskDirectory, removeProductWorktrees, } from "./task-repos.js";
|
|
5
|
+
import { appendGitFailureLog, appendGitResultFailureLog, ensureExecWorktree, execBranchExists, findExecWorktree, formatGitResultFailure, generateWorktreeArtifacts, gitOutput, gitResult, listRegisteredWorktrees, summarizeGitHookFailure, worktreeNameFromTaskId, } from "./worktree.js";
|
|
6
|
+
import { commitTargetPaths, currentBranch, repoRelative, stageCommitTargets, unstageCommitTargets, worktreeStatusPaths, zeroSeparatedPaths, } from "./worktree-ops-commit.js";
|
|
7
|
+
// Remove a task worktree once its commit-target changes are committed and merged.
|
|
8
|
+
export function removeWorktree(params) {
|
|
9
|
+
const { context, worktree, taskId } = params;
|
|
10
|
+
if (resolve(context.repoRoot) === resolve(worktree.path)) {
|
|
11
|
+
throw new Error("Run remove from the merge-target worktree, not the task worktree.");
|
|
12
|
+
}
|
|
13
|
+
const dirty = commitTargetPaths(context, worktree, taskId);
|
|
14
|
+
const merged = gitResult(context.repoRoot, ["merge-base", "--is-ancestor", worktree.branch, "HEAD"]).status ===
|
|
15
|
+
0;
|
|
16
|
+
if (!params.force && dirty.length > 0) {
|
|
17
|
+
throw new Error(`Worktree has uncommitted commit-target changes: ${dirty.join(", ")}`);
|
|
18
|
+
}
|
|
19
|
+
if (!params.force && !merged) {
|
|
20
|
+
throw new Error(`Exec branch is not merged into current HEAD: ${worktree.branch}`);
|
|
21
|
+
}
|
|
22
|
+
// プロダクト worktree もすべて撤去できることを先に確かめる。一部のリポジトリだけを撤去した
|
|
23
|
+
// 状態を作らないため、検査はどの worktree を消すよりも前に行う。
|
|
24
|
+
const productBlockers = params.force ? [] : productWorktreeRemovalBlockers(worktree);
|
|
25
|
+
if (productBlockers.length > 0) {
|
|
26
|
+
throw new Error(`Product worktrees cannot be removed: ${productBlockers.join("; ")}`);
|
|
27
|
+
}
|
|
28
|
+
// Past the guards, any remaining uncommitted files are non-commit-target bookkeeping
|
|
29
|
+
// (doc-index, generated/, events) that were intentionally excluded from the task commit.
|
|
30
|
+
// git refuses to remove a worktree while those are dirty, so force past them: they are
|
|
31
|
+
// regenerable, and the tool already judged the worktree removable.
|
|
32
|
+
const leftover = worktreeStatusPaths(worktree.path);
|
|
33
|
+
const forceGit = params.force || leftover.length > 0;
|
|
34
|
+
if (params.force) {
|
|
35
|
+
process.stderr.write("Warning: forcing worktree removal; uncommitted changes may be lost.\n");
|
|
36
|
+
}
|
|
37
|
+
else if (leftover.length > 0) {
|
|
38
|
+
process.stderr.write(`Discarding regenerated files in worktree: ${leftover.join(", ")}\n`);
|
|
39
|
+
}
|
|
40
|
+
if (params.dryRun) {
|
|
41
|
+
removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch, dryRun: true });
|
|
42
|
+
process.stdout.write(`[dry-run] git worktree remove${forceGit ? " --force" : ""} ${worktree.path}\n`);
|
|
43
|
+
if (params.deleteBranch)
|
|
44
|
+
process.stdout.write(`[dry-run] git branch -d ${worktree.branch}\n`);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
removeProductWorktrees({ worktree, deleteBranch: params.deleteBranch });
|
|
48
|
+
gitOutput(context.repoRoot, [
|
|
49
|
+
"worktree",
|
|
50
|
+
"remove",
|
|
51
|
+
...(forceGit ? ["--force"] : []),
|
|
52
|
+
worktree.path,
|
|
53
|
+
]);
|
|
54
|
+
removeEmptyTaskDirectory(worktree);
|
|
55
|
+
if (params.deleteBranch) {
|
|
56
|
+
try {
|
|
57
|
+
gitOutput(context.repoRoot, ["branch", "-d", worktree.branch]);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
// worktree removal and branch deletion cannot be atomic: Git refuses to delete a branch
|
|
61
|
+
// while it is checked out. Make the resulting state explicit so the caller does not report
|
|
62
|
+
// that the worktree was preserved and operators can recover it with `worktree prune`.
|
|
63
|
+
throw new WorktreeRemovedBranchDeletionError(worktree.branch, error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export class WorktreeRemovedBranchDeletionError extends Error {
|
|
68
|
+
branch;
|
|
69
|
+
constructor(branch, cause) {
|
|
70
|
+
super(`Worktree was removed, but exec branch deletion failed and the branch remains: ` +
|
|
71
|
+
`${branch}; cause=${cause instanceof Error ? cause.message : String(cause)}`);
|
|
72
|
+
this.name = "WorktreeRemovedBranchDeletionError";
|
|
73
|
+
this.branch = branch;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// List project-scoped exec branches that are no longer checked out by any registered worktree.
|
|
77
|
+
// A failed/interrupted run intentionally keeps both its worktree and branch, so it is not an
|
|
78
|
+
// orphan. The merged flag lets callers distinguish safely removable residue from unintegrated
|
|
79
|
+
// work that must be preserved.
|
|
80
|
+
export function listOrphanedExecBranches(params) {
|
|
81
|
+
const { repoRoot, projectId } = params;
|
|
82
|
+
const projectPrefix = `exec/${worktreeNameFromTaskId(projectId)}-`;
|
|
83
|
+
const registeredBranches = new Set(listRegisteredWorktrees(repoRoot)
|
|
84
|
+
.map((worktree) => worktree.branch)
|
|
85
|
+
.filter((branch) => !!branch));
|
|
86
|
+
const branches = gitOutput(repoRoot, [
|
|
87
|
+
"for-each-ref",
|
|
88
|
+
"--format=%(refname:short)",
|
|
89
|
+
"refs/heads/exec/",
|
|
90
|
+
])
|
|
91
|
+
.split(/\r?\n/)
|
|
92
|
+
.map((branch) => branch.trim())
|
|
93
|
+
.filter((branch) => branch.startsWith(projectPrefix) && !registeredBranches.has(branch))
|
|
94
|
+
.sort();
|
|
95
|
+
return branches.map((branch) => ({
|
|
96
|
+
branch,
|
|
97
|
+
mergedIntoCurrent: gitResult(repoRoot, ["merge-base", "--is-ancestor", branch, "HEAD"]).status === 0,
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
// Delete only merged orphan branches with Git's safe `-d`. Unmerged branches are always retained,
|
|
101
|
+
// even if the caller asks for a real prune. A deletion failure is not swallowed: gitOutput's
|
|
102
|
+
// stderr-backed reason is propagated so the execution log records why residue remains.
|
|
103
|
+
export function pruneOrphanedExecBranches(params) {
|
|
104
|
+
const current = currentBranch(params.repoRoot);
|
|
105
|
+
if (current.startsWith("exec/")) {
|
|
106
|
+
throw new Error("Run worktree prune from the merge-target worktree, not an exec branch.");
|
|
107
|
+
}
|
|
108
|
+
const orphaned = listOrphanedExecBranches(params);
|
|
109
|
+
for (const item of orphaned) {
|
|
110
|
+
if (!item.mergedIntoCurrent)
|
|
111
|
+
continue;
|
|
112
|
+
if (!params.dryRun) {
|
|
113
|
+
try {
|
|
114
|
+
gitOutput(params.repoRoot, ["branch", "-d", item.branch]);
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
throw new Error(`Failed to delete merged orphaned exec branch ${item.branch}; ` +
|
|
118
|
+
`cause=${error instanceof Error ? error.message : String(error)}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return orphaned;
|
|
123
|
+
}
|
|
124
|
+
// A fresh claim of a task that still owns an exec worktree/branch means a prior lifecycle
|
|
125
|
+
// (e.g. blocked or cancelled, then reset to todo) left residue behind. The scheduler has abandoned
|
|
126
|
+
// that branch, so discard it before re-preparing: otherwise checkpointAndEnsureWorktree reuses the
|
|
127
|
+
// stale worktree, skips the checkpoint commit, and the freshly-scaffolded root plan/result/claim
|
|
128
|
+
// files never reach the exec branch (the merge would land the stale branch's versions instead).
|
|
129
|
+
// Returns the discarded branch name for logging, or null when no residue existed.
|
|
130
|
+
export function discardStaleExecWorktree(params) {
|
|
131
|
+
const { context, worktreeTaskId } = params;
|
|
132
|
+
const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
|
|
133
|
+
const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
|
|
134
|
+
// プロダクト側の残骸は、プロジェクト側に残骸が無くても片付ける(作成途中で失敗した場合など)。
|
|
135
|
+
const discardedProducts = discardStaleProductWorktrees(params.products ?? [], worktreeTaskId);
|
|
136
|
+
if (!existing && !execBranchExists(context.repoRoot, worktreeTaskId)) {
|
|
137
|
+
return discardedProducts.length > 0 ? discardedProducts.join(", ") : null;
|
|
138
|
+
}
|
|
139
|
+
if (existing) {
|
|
140
|
+
if (resolve(context.repoRoot) === resolve(existing.path)) {
|
|
141
|
+
throw new Error(`Refusing to discard the merge-target worktree as stale residue: ${branch}`);
|
|
142
|
+
}
|
|
143
|
+
// Force past any uncommitted/blocked state in the abandoned worktree; its branch is discarded
|
|
144
|
+
// next, so nothing here is worth preserving.
|
|
145
|
+
gitOutput(context.repoRoot, ["worktree", "remove", "--force", existing.path]);
|
|
146
|
+
if ((params.products ?? []).length > 0)
|
|
147
|
+
removeEmptyTaskDirectory({ ...existing, repos: [] });
|
|
148
|
+
}
|
|
149
|
+
// The branch is unmerged (the scheduler reset the task to todo), so a safe `-d` would fail; use
|
|
150
|
+
// `-D` to drop it deliberately.
|
|
151
|
+
if (execBranchExists(context.repoRoot, worktreeTaskId)) {
|
|
152
|
+
gitOutput(context.repoRoot, ["branch", "-D", branch]);
|
|
153
|
+
}
|
|
154
|
+
return [branch, ...discardedProducts].join(", ");
|
|
155
|
+
}
|
|
156
|
+
function copyCheckpointPath(sourceRoot, targetRoot, relPath) {
|
|
157
|
+
const source = resolve(sourceRoot, relPath);
|
|
158
|
+
const target = resolve(targetRoot, relPath);
|
|
159
|
+
if (!existsSync(source)) {
|
|
160
|
+
rmSync(target, { recursive: true, force: true });
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
const stat = lstatSync(source);
|
|
164
|
+
if (!stat.isFile()) {
|
|
165
|
+
throw new Error(`Execution checkpoint path must be a file: ${relPath}`);
|
|
166
|
+
}
|
|
167
|
+
mkdirSync(resolve(target, ".."), { recursive: true });
|
|
168
|
+
copyFileSync(source, target);
|
|
169
|
+
}
|
|
170
|
+
export function assertCheckpointInspection(args, result, failureLogPath) {
|
|
171
|
+
if (result.status === 0 || result.status === 1)
|
|
172
|
+
return;
|
|
173
|
+
appendGitResultFailureLog(failureLogPath, "git diff checkpoint inspection", result);
|
|
174
|
+
throw new Error(`Failed to inspect execution checkpoint changes: ${formatGitResultFailure(args, result)}`);
|
|
175
|
+
}
|
|
176
|
+
// Create the task worktree from the current integration HEAD, then commit the execution
|
|
177
|
+
// checkpoint (plan / result / claim or register-start bookkeeping) on the exec branch only. The
|
|
178
|
+
// root keeps its uncommitted copies so the task state stays visible there while the agent runs;
|
|
179
|
+
// the merge releases them (releaseRootWorkingCopies) right before the exec branch lands.
|
|
180
|
+
// Consequently the prepare/start bookkeeping is reachable through the merge DAG without adding a
|
|
181
|
+
// first-parent commit to the integration branch.
|
|
182
|
+
//
|
|
183
|
+
// PJR-98G4: with declared product repositories the project worktree moves to
|
|
184
|
+
// `<base>/<task-name>/project/` and each product gets `<base>/<task-name>/<repo>/`. The checkpoint
|
|
185
|
+
// commit stays in the project repository; product exec branches start from their integration
|
|
186
|
+
// target.
|
|
187
|
+
//
|
|
188
|
+
// PJR-NN43: `specdojo build` in the project worktree loads the config, which checks that every
|
|
189
|
+
// `repos[].path` (`../<repo>` beside `project/`) exists. The product worktrees are therefore
|
|
190
|
+
// created before the project build (and before the checkpoint commit, whose hooks may load the
|
|
191
|
+
// config as well).
|
|
192
|
+
export function checkpointAndEnsureWorktree(params) {
|
|
193
|
+
const products = params.products ?? [];
|
|
194
|
+
let repos = [];
|
|
195
|
+
const worktree = checkpointAndEnsureProjectWorktree(params, projectRepoDirName(products), () => {
|
|
196
|
+
if (products.length === 0)
|
|
197
|
+
return;
|
|
198
|
+
repos = ensureProductWorktrees({
|
|
199
|
+
products,
|
|
200
|
+
worktreeBase: params.base,
|
|
201
|
+
taskId: params.worktreeTaskId,
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
if (products.length === 0)
|
|
205
|
+
return worktree;
|
|
206
|
+
return { ...worktree, repos };
|
|
207
|
+
}
|
|
208
|
+
function checkpointAndEnsureProjectWorktree(params, repoDirName, ensureSiblingWorktrees) {
|
|
209
|
+
const { context, worktreeTaskId, base } = params;
|
|
210
|
+
const branch = `exec/${worktreeNameFromTaskId(worktreeTaskId)}`;
|
|
211
|
+
// The project build runs only after the sibling product worktrees exist (see above).
|
|
212
|
+
const ensureProjectWorktree = () => {
|
|
213
|
+
const worktree = ensureExecWorktree({
|
|
214
|
+
repoRoot: context.repoRoot,
|
|
215
|
+
worktreeBase: base,
|
|
216
|
+
taskId: worktreeTaskId,
|
|
217
|
+
repoDirName,
|
|
218
|
+
generateArtifacts: () => undefined,
|
|
219
|
+
});
|
|
220
|
+
ensureSiblingWorktrees();
|
|
221
|
+
generateWorktreeArtifacts(worktree.path);
|
|
222
|
+
return worktree;
|
|
223
|
+
};
|
|
224
|
+
const existing = findExecWorktree(context.repoRoot, worktreeTaskId);
|
|
225
|
+
if (existing) {
|
|
226
|
+
// 依存と違い、生成物は前回実行時のまま古くなる。生成段階を持たない版が作成した
|
|
227
|
+
// worktree では存在すらしない。再利用時も作り直し、生成物起因の検証失敗を避ける。
|
|
228
|
+
// 前回の準備がプロダクト worktree の作成前に失敗した場合に備え、先にそれらを揃える。
|
|
229
|
+
ensureSiblingWorktrees();
|
|
230
|
+
generateWorktreeArtifacts(existing.path);
|
|
231
|
+
return existing;
|
|
232
|
+
}
|
|
233
|
+
if (!execBranchExists(context.repoRoot, worktreeTaskId)) {
|
|
234
|
+
if (currentBranch(context.repoRoot) === branch) {
|
|
235
|
+
throw new Error(`Prepare must run from a branch other than ${branch}.`);
|
|
236
|
+
}
|
|
237
|
+
const paths = params.checkpointPaths.map((path) => repoRelative(context.repoRoot, path));
|
|
238
|
+
const stagedFiles = zeroSeparatedPaths(context.repoRoot, [
|
|
239
|
+
"diff",
|
|
240
|
+
"--cached",
|
|
241
|
+
"--no-renames",
|
|
242
|
+
"--name-only",
|
|
243
|
+
"-z",
|
|
244
|
+
]);
|
|
245
|
+
const checkpointPaths = new Set(paths);
|
|
246
|
+
const overlapping = stagedFiles.filter((path) => checkpointPaths.has(path));
|
|
247
|
+
if (overlapping.length > 0) {
|
|
248
|
+
throw new Error(`Root index has staged checkpoint changes; commit or unstage them first:\n${overlapping.join("\n")}`);
|
|
249
|
+
}
|
|
250
|
+
if (stagedFiles.length > 0) {
|
|
251
|
+
process.stderr.write(`Warning: root index has unrelated staged changes; preserving them while preparing the checkpoint:\n` +
|
|
252
|
+
`${stagedFiles.map((path) => ` ${path}`).join("\n")}\n`);
|
|
253
|
+
}
|
|
254
|
+
const worktree = ensureProjectWorktree();
|
|
255
|
+
for (const path of paths)
|
|
256
|
+
copyCheckpointPath(context.repoRoot, worktree.path, path);
|
|
257
|
+
stageCommitTargets(worktree.path, paths);
|
|
258
|
+
const checkpointArgs = ["diff", "--cached", "--quiet", "--", ...paths];
|
|
259
|
+
const checkpoint = gitResult(worktree.path, checkpointArgs);
|
|
260
|
+
assertCheckpointInspection(checkpointArgs, checkpoint, params.failureLogPath);
|
|
261
|
+
if (checkpoint.status === 1) {
|
|
262
|
+
const committed = gitResult(worktree.path, [
|
|
263
|
+
"commit",
|
|
264
|
+
"-m",
|
|
265
|
+
params.commitMessage,
|
|
266
|
+
"--",
|
|
267
|
+
...paths,
|
|
268
|
+
]);
|
|
269
|
+
if (committed.status !== 0) {
|
|
270
|
+
// A failing git hook (pre-commit / commit-msg) aborts the commit but leaves the staged
|
|
271
|
+
// paths in the index. Unstage only this checkpoint so a hook or caller's unrelated staged
|
|
272
|
+
// paths remain intact.
|
|
273
|
+
unstageCommitTargets(worktree.path, paths);
|
|
274
|
+
// hook(lefthook 等)の生出力には ANSI エスケープや制御文字が含まれうる。この detail は
|
|
275
|
+
// register 経路で pjr-index の結論列・result の理由欄へ伝播するため、ここで除去して
|
|
276
|
+
// 表示崩れを防ぐ(register 側の sanitize と二重だが、非 register の呼び出し元も守る)。
|
|
277
|
+
const output = [committed.stdout, committed.stderr]
|
|
278
|
+
.map((part) => typeof part === "string" ? stripTerminalControlSequences(part).trim() : "")
|
|
279
|
+
.filter(Boolean)
|
|
280
|
+
.join("\n");
|
|
281
|
+
appendGitFailureLog(params.failureLogPath, [
|
|
282
|
+
`=== ${new Date().toISOString()} git commit checkpoint ===`,
|
|
283
|
+
`exit: ${committed.status ?? "unknown"}`,
|
|
284
|
+
"--- stdout ---",
|
|
285
|
+
typeof committed.stdout === "string" ? committed.stdout : "",
|
|
286
|
+
"--- stderr ---",
|
|
287
|
+
typeof committed.stderr === "string" ? committed.stderr : "",
|
|
288
|
+
"",
|
|
289
|
+
]);
|
|
290
|
+
throw new Error(`Checkpoint commit failed (${params.commitMessage}); staged changes rolled back ` +
|
|
291
|
+
`(likely a failing git hook): ${summarizeGitHookFailure(output)}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return worktree;
|
|
295
|
+
}
|
|
296
|
+
return ensureProjectWorktree();
|
|
297
|
+
}
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, resolve } from "node:path";
|
|
4
|
+
import { acquireSchedulerLock, releaseSchedulerLock } from "./events.js";
|
|
5
|
+
import { rebuildRegisterTicketFromEvents, unionRegisterEventLogs, } from "../register/event-merge.js";
|
|
6
|
+
import { displayIdFromRegisterEventFilename, REGISTER_EVENTS_DIRNAME } from "../register/events.js";
|
|
7
|
+
import { displayIdFromTicketFilename } from "../register/item.js";
|
|
8
|
+
import { appendGitFailureLog, gitOutput, gitResult, summarizeGitHookFailure, } from "./worktree.js";
|
|
9
|
+
import { commitTargetPaths, currentBranch, repoRelative, rootDirtyPaths, zeroSeparatedPaths, } from "./worktree-ops-commit.js";
|
|
10
|
+
const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
|
|
11
|
+
const DEFAULT_LOCK_STALE_MS = 300_000;
|
|
12
|
+
// A successful `git merge` runs post-merge, but a merge completed by the bookkeeping-conflict
|
|
13
|
+
// resolver below uses `git commit --no-verify` and therefore skips that hook. Invoke the same
|
|
14
|
+
// repository-local entry point explicitly after either path. Only a SpecDojo development checkout
|
|
15
|
+
// whose local bin points at dist is eligible; repositories consuming SpecDojo from node_modules
|
|
16
|
+
// remain unaffected. The script and this launcher are both best-effort so a dist rebuild failure
|
|
17
|
+
// never turns a completed merge into an integration failure.
|
|
18
|
+
function usesLocalSpecdojoDistBin(repoRoot) {
|
|
19
|
+
try {
|
|
20
|
+
const packageJson = JSON.parse(readFileSync(resolve(repoRoot, "package.json"), "utf8"));
|
|
21
|
+
if (packageJson.name !== "specdojo" || typeof packageJson.bin !== "object")
|
|
22
|
+
return false;
|
|
23
|
+
return packageJson.bin?.specdojo === "dist/specdojo.js";
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function runBuildIfStaleAfterMerge(repoRoot) {
|
|
30
|
+
try {
|
|
31
|
+
const scriptPath = resolve(repoRoot, "tools", "build-if-stale.mjs");
|
|
32
|
+
if (!existsSync(scriptPath) || !usesLocalSpecdojoDistBin(repoRoot))
|
|
33
|
+
return;
|
|
34
|
+
const result = spawnSync(process.execPath, [scriptPath], {
|
|
35
|
+
cwd: repoRoot,
|
|
36
|
+
stdio: "inherit",
|
|
37
|
+
shell: false,
|
|
38
|
+
});
|
|
39
|
+
if (result.error) {
|
|
40
|
+
process.stderr.write(` [integrate] warning: build-if-stale could not start: ${result.error.message}\n`);
|
|
41
|
+
}
|
|
42
|
+
else if (result.status !== 0) {
|
|
43
|
+
process.stderr.write(` [integrate] warning: build-if-stale failed with exit code ${result.status ?? "unknown"}\n`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
process.stderr.write(` [integrate] warning: build-if-stale failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// The checkpoint commit lives on the exec branch only, so the root keeps its own uncommitted copy
|
|
51
|
+
// of the bookkeeping files while the task runs (the schedule/register state must stay visible at
|
|
52
|
+
// root). Before the exec branch is merged those copies must yield to the committed versions,
|
|
53
|
+
// otherwise the overlap guard below rejects the merge. Capture them so a failed merge can put the
|
|
54
|
+
// root back exactly as it was.
|
|
55
|
+
export function releaseRootWorkingCopies(repoRoot, relPaths) {
|
|
56
|
+
const snapshot = [];
|
|
57
|
+
try {
|
|
58
|
+
for (const rel of new Set(relPaths)) {
|
|
59
|
+
const absolute = resolve(repoRoot, rel);
|
|
60
|
+
const exists = lstatSync(absolute, { throwIfNoEntry: false }) !== undefined;
|
|
61
|
+
snapshot.push({ rel, content: exists ? readFileSync(absolute) : null });
|
|
62
|
+
restoreToHead(repoRoot, rel);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
// Releasing is itself allowed to fail (for example because a path unexpectedly became a
|
|
67
|
+
// directory). Put back every copy already touched before propagating the failure; otherwise a
|
|
68
|
+
// merge that never started could still discard root-side execution state.
|
|
69
|
+
restoreRootWorkingCopies(repoRoot, snapshot);
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
return snapshot;
|
|
73
|
+
}
|
|
74
|
+
export function restoreRootWorkingCopies(repoRoot, snapshot) {
|
|
75
|
+
for (const { rel, content } of snapshot) {
|
|
76
|
+
const absolute = resolve(repoRoot, rel);
|
|
77
|
+
if (content === null) {
|
|
78
|
+
rmSync(absolute, { recursive: true, force: true });
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
mkdirSync(resolve(absolute, ".."), { recursive: true });
|
|
82
|
+
writeFileSync(absolute, content);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// `git merge --abort` (reset --merge) refuses to run when a tracked file's cached stat no longer
|
|
86
|
+
// matches the file even though its content is unchanged ("not uptodate"), which happens when another
|
|
87
|
+
// process in the same working tree (for example a routine) touches files during the merge. Refresh
|
|
88
|
+
// the index first so a stat-only drift cannot leave the tree mid-merge.
|
|
89
|
+
export function abortMerge(repoRoot) {
|
|
90
|
+
gitResult(repoRoot, ["update-index", "-q", "--refresh"]);
|
|
91
|
+
return gitResult(repoRoot, ["merge", "--abort"]);
|
|
92
|
+
}
|
|
93
|
+
// `controls/project-register/events/pjr-xxxx.yaml` 形式のイベントファイルなら表示 ID を返す。
|
|
94
|
+
function registerEventDisplayId(path) {
|
|
95
|
+
if (basename(dirname(path)) !== REGISTER_EVENTS_DIRNAME)
|
|
96
|
+
return undefined;
|
|
97
|
+
return displayIdFromRegisterEventFilename(basename(path));
|
|
98
|
+
}
|
|
99
|
+
// Resolve an in-progress merge whose conflicts are all on exec-branch-owned paths, then complete
|
|
100
|
+
// the merge commit. Register event files are resolved as the union of both sides and the matching
|
|
101
|
+
// ticket is rebuilt from the merge-target-only events; other paths take the exec branch side. Returns the resolved paths, or null when the
|
|
102
|
+
// merge has no conflicts (for example a hook rejection), conflicts on other paths, or cannot be
|
|
103
|
+
// completed; the caller then aborts the merge. The commit uses --no-verify because a regular
|
|
104
|
+
// `git merge` does not run pre-commit either, and only the item's own bookkeeping was resolved.
|
|
105
|
+
function resolveBranchOwnedConflicts(params) {
|
|
106
|
+
const { repoRoot } = params;
|
|
107
|
+
const conflicted = zeroSeparatedPaths(repoRoot, ["diff", "--name-only", "--diff-filter=U", "-z"]);
|
|
108
|
+
if (conflicted.length === 0)
|
|
109
|
+
return null;
|
|
110
|
+
const owned = new Set(params.branchOwnedPaths);
|
|
111
|
+
if (conflicted.some((path) => !owned.has(path)))
|
|
112
|
+
return null;
|
|
113
|
+
const stagesOf = (path) => gitOutput(repoRoot, ["ls-files", "-u", "-z", "--", path])
|
|
114
|
+
.split("\0")
|
|
115
|
+
.filter(Boolean)
|
|
116
|
+
.map((entry) => entry.split("\t")[0]?.split(" ")[2]);
|
|
117
|
+
// イベントファイルは両側の和集合で解決し、対応する個票はイベントから再構築する。
|
|
118
|
+
// 和集合で解決できないものは従来どおり exec branch 側で解決する。
|
|
119
|
+
const handled = new Set();
|
|
120
|
+
for (const path of conflicted) {
|
|
121
|
+
const displayId = registerEventDisplayId(path);
|
|
122
|
+
if (!displayId)
|
|
123
|
+
continue;
|
|
124
|
+
const stages = stagesOf(path);
|
|
125
|
+
if (!stages.includes("2") || !stages.includes("3"))
|
|
126
|
+
continue;
|
|
127
|
+
const ours = gitResult(repoRoot, ["show", `:2:${path}`]);
|
|
128
|
+
const theirs = gitResult(repoRoot, ["show", `:3:${path}`]);
|
|
129
|
+
if (ours.status !== 0 || theirs.status !== 0)
|
|
130
|
+
continue;
|
|
131
|
+
const union = unionRegisterEventLogs(String(ours.stdout), String(theirs.stdout), path);
|
|
132
|
+
if (!union.ok) {
|
|
133
|
+
process.stdout.write(` [integrate] could not union register events; using the exec branch side: ${union.reason}\n`);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
writeFileSync(resolve(repoRoot, path), union.content, "utf8");
|
|
137
|
+
if (gitResult(repoRoot, ["add", "--", path]).status !== 0)
|
|
138
|
+
return null;
|
|
139
|
+
handled.add(path);
|
|
140
|
+
process.stdout.write(` [integrate] merged register events as a union: ${path} ` +
|
|
141
|
+
`(kept ${union.oursOnlyIds.size} event(s) only on the merge target)\n`);
|
|
142
|
+
const ticketPath = conflicted.find((candidate) => dirname(candidate) === dirname(dirname(path)) &&
|
|
143
|
+
displayIdFromTicketFilename(basename(candidate)) === displayId);
|
|
144
|
+
if (!ticketPath || !stagesOf(ticketPath).includes("3"))
|
|
145
|
+
continue;
|
|
146
|
+
const ticket = gitResult(repoRoot, ["show", `:3:${ticketPath}`]);
|
|
147
|
+
if (ticket.status !== 0)
|
|
148
|
+
continue;
|
|
149
|
+
let rebuilt;
|
|
150
|
+
try {
|
|
151
|
+
rebuilt = rebuildRegisterTicketFromEvents(String(ticket.stdout), union.events, union.oursOnlyIds);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
process.stdout.write(` [integrate] could not rebuild ${ticketPath} from events; using the exec branch side: ` +
|
|
155
|
+
`${error instanceof Error ? error.message : String(error)}\n`);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
writeFileSync(resolve(repoRoot, ticketPath), rebuilt.content, "utf8");
|
|
159
|
+
if (gitResult(repoRoot, ["add", "--", ticketPath]).status !== 0)
|
|
160
|
+
return null;
|
|
161
|
+
handled.add(ticketPath);
|
|
162
|
+
if (rebuilt.appliedFields.length > 0) {
|
|
163
|
+
process.stdout.write(` [integrate] rebuilt ${ticketPath} from merge-target events: ${rebuilt.appliedFields.join(", ")}\n`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
for (const path of conflicted) {
|
|
167
|
+
if (handled.has(path))
|
|
168
|
+
continue;
|
|
169
|
+
const stages = stagesOf(path);
|
|
170
|
+
const step = stages.includes("3")
|
|
171
|
+
? gitResult(repoRoot, ["checkout", "--theirs", "--", path])
|
|
172
|
+
: gitResult(repoRoot, ["rm", "--quiet", "--", path]);
|
|
173
|
+
if (step.status !== 0)
|
|
174
|
+
return null;
|
|
175
|
+
if (stages.includes("3") && gitResult(repoRoot, ["add", "--", path]).status !== 0)
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
const unresolved = zeroSeparatedPaths(repoRoot, ["diff", "--name-only", "--diff-filter=U", "-z"]);
|
|
179
|
+
if (unresolved.length > 0)
|
|
180
|
+
return null;
|
|
181
|
+
const commit = gitResult(repoRoot, [
|
|
182
|
+
"commit",
|
|
183
|
+
"--no-verify",
|
|
184
|
+
...(params.message ? ["-m", params.message] : ["--no-edit"]),
|
|
185
|
+
]);
|
|
186
|
+
return commit.status === 0 ? conflicted : null;
|
|
187
|
+
}
|
|
188
|
+
// Merge the task exec branch into the branch currently checked out at repoRoot.
|
|
189
|
+
// Serializes with the scheduler lock so parallel merges do not race on root HEAD.
|
|
190
|
+
// `releaseRootPaths` are root-side working copies of bookkeeping files that the exec branch also
|
|
191
|
+
// carries (see releaseRootWorkingCopies); they are restored when the merge does not complete.
|
|
192
|
+
export function mergeWorktreeIntoCurrent(params) {
|
|
193
|
+
const { context, worktree, taskId } = params;
|
|
194
|
+
const targetBranch = currentBranch(context.repoRoot);
|
|
195
|
+
if (targetBranch === worktree.branch) {
|
|
196
|
+
throw new Error(`Merge must run from a branch other than ${worktree.branch}.`);
|
|
197
|
+
}
|
|
198
|
+
let lockDir = "";
|
|
199
|
+
let released = [];
|
|
200
|
+
let merged = false;
|
|
201
|
+
const releasePaths = (params.releaseRootPaths ?? []).map((path) => repoRelative(context.repoRoot, path));
|
|
202
|
+
const releasePathSet = new Set(releasePaths);
|
|
203
|
+
try {
|
|
204
|
+
if (!params.dryRun) {
|
|
205
|
+
lockDir = acquireSchedulerLock(context.schedulePath, {
|
|
206
|
+
actor: `worktree-merge:${targetBranch}`,
|
|
207
|
+
lockTimeoutMs: DEFAULT_LOCK_TIMEOUT_MS,
|
|
208
|
+
lockStaleMs: DEFAULT_LOCK_STALE_MS,
|
|
209
|
+
});
|
|
210
|
+
released = releaseRootWorkingCopies(context.repoRoot, releasePaths);
|
|
211
|
+
}
|
|
212
|
+
const dirty = commitTargetPaths(context, worktree, taskId);
|
|
213
|
+
if (dirty.length > 0) {
|
|
214
|
+
throw new Error(`Worktree has uncommitted commit-target changes: ${dirty.join(", ")}`);
|
|
215
|
+
}
|
|
216
|
+
const compareBase = gitOutput(context.repoRoot, ["merge-base", "HEAD", worktree.branch]).trim();
|
|
217
|
+
const count = Number.parseInt(gitOutput(context.repoRoot, [
|
|
218
|
+
"rev-list",
|
|
219
|
+
"--count",
|
|
220
|
+
`${compareBase}..${worktree.branch}`,
|
|
221
|
+
]).trim(), 10);
|
|
222
|
+
if (!Number.isFinite(count) || count < 1) {
|
|
223
|
+
throw new Error(`No commits to merge from ${worktree.branch}.`);
|
|
224
|
+
}
|
|
225
|
+
const mergePaths = new Set(zeroSeparatedPaths(context.repoRoot, [
|
|
226
|
+
"diff",
|
|
227
|
+
"--no-renames",
|
|
228
|
+
"--name-only",
|
|
229
|
+
"-z",
|
|
230
|
+
`${compareBase}..${worktree.branch}`,
|
|
231
|
+
]));
|
|
232
|
+
const overlap = [...rootDirtyPaths(context.repoRoot)].filter((path) => mergePaths.has(path) && !(params.dryRun && releasePathSet.has(path)));
|
|
233
|
+
if (overlap.length > 0) {
|
|
234
|
+
throw new Error(`Current worktree changes overlap merge paths: ${overlap.join(", ")}`);
|
|
235
|
+
}
|
|
236
|
+
if (params.dryRun) {
|
|
237
|
+
process.stdout.write(`[dry-run] git merge ${params.ffOnly ? "--ff-only" : params.message ? `--no-ff -m ${JSON.stringify(params.message)}` : "--no-ff --no-edit"} ${worktree.branch}\n`);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
const mergeArgs = params.ffOnly
|
|
241
|
+
? ["merge", "--ff-only", worktree.branch]
|
|
242
|
+
: params.message
|
|
243
|
+
? ["merge", "--no-ff", "-m", params.message, worktree.branch]
|
|
244
|
+
: ["merge", "--no-ff", "--no-edit", worktree.branch];
|
|
245
|
+
const mergeResult = gitResult(context.repoRoot, mergeArgs);
|
|
246
|
+
if (mergeResult.status === 0) {
|
|
247
|
+
merged = true;
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
const mergeOutput = [mergeResult.stdout, mergeResult.stderr]
|
|
251
|
+
.filter((part) => typeof part === "string" && part.length > 0)
|
|
252
|
+
.join(mergeResult.stdout && mergeResult.stderr ? "\n" : "");
|
|
253
|
+
const mergeInProgress = gitResult(context.repoRoot, ["rev-parse", "--verify", "--quiet", "MERGE_HEAD"]).status ===
|
|
254
|
+
0;
|
|
255
|
+
const resolved = mergeInProgress && !params.ffOnly
|
|
256
|
+
? resolveBranchOwnedConflicts({
|
|
257
|
+
repoRoot: context.repoRoot,
|
|
258
|
+
branchOwnedPaths: (params.resolveConflictsWithBranchPaths ?? []).map((path) => repoRelative(context.repoRoot, path)),
|
|
259
|
+
message: params.message,
|
|
260
|
+
})
|
|
261
|
+
: null;
|
|
262
|
+
if (resolved && resolved.length > 0) {
|
|
263
|
+
merged = true;
|
|
264
|
+
process.stdout.write(` [integrate] resolved bookkeeping conflicts with ${worktree.branch}: ${resolved.join(", ")}\n`);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
const abortResult = mergeInProgress ? abortMerge(context.repoRoot) : undefined;
|
|
268
|
+
if (params.failureLogPath) {
|
|
269
|
+
mkdirSync(resolve(params.failureLogPath, ".."), { recursive: true });
|
|
270
|
+
const abortOutput = abortResult
|
|
271
|
+
? [abortResult.stdout, abortResult.stderr]
|
|
272
|
+
.filter((part) => typeof part === "string" && part.length > 0)
|
|
273
|
+
.join(abortResult.stdout && abortResult.stderr ? "\n" : "")
|
|
274
|
+
: "";
|
|
275
|
+
appendGitFailureLog(params.failureLogPath, [
|
|
276
|
+
`=== ${new Date().toISOString()} git ${mergeArgs.join(" ")} ===`,
|
|
277
|
+
`exit: ${mergeResult.status ?? "unknown"}`,
|
|
278
|
+
"--- stdout ---",
|
|
279
|
+
typeof mergeResult.stdout === "string" ? mergeResult.stdout : "",
|
|
280
|
+
"--- stderr ---",
|
|
281
|
+
typeof mergeResult.stderr === "string" ? mergeResult.stderr : "",
|
|
282
|
+
"--- merge --abort ---",
|
|
283
|
+
abortResult ? `exit: ${abortResult.status ?? "unknown"}` : "not required",
|
|
284
|
+
abortOutput,
|
|
285
|
+
"",
|
|
286
|
+
]);
|
|
287
|
+
}
|
|
288
|
+
const summary = summarizeGitHookFailure(mergeOutput);
|
|
289
|
+
if (abortResult && abortResult.status !== 0) {
|
|
290
|
+
const abortOutput = [abortResult.stdout, abortResult.stderr]
|
|
291
|
+
.filter((part) => typeof part === "string" && part.length > 0)
|
|
292
|
+
.join("\n");
|
|
293
|
+
const abortSummary = summarizeGitHookFailure(abortOutput);
|
|
294
|
+
const instruction = `automatic git merge --abort failed; run git merge --abort manually in ` +
|
|
295
|
+
`${context.repoRoot} before continuing`;
|
|
296
|
+
process.stderr.write(`error: ${instruction}; ${abortSummary}\n`);
|
|
297
|
+
throw new Error(`git merge failed: ${summary}; ${instruction}; ${abortSummary}`);
|
|
298
|
+
}
|
|
299
|
+
throw new Error(`git merge failed: ${summary}`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
finally {
|
|
303
|
+
if (merged)
|
|
304
|
+
runBuildIfStaleAfterMerge(context.repoRoot);
|
|
305
|
+
if (!merged && released.length > 0)
|
|
306
|
+
restoreRootWorkingCopies(context.repoRoot, released);
|
|
307
|
+
if (lockDir)
|
|
308
|
+
releaseSchedulerLock(lockDir);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
// Whether the task exec branch is already contained in the merge-target HEAD. The integrate
|
|
312
|
+
// stage retry uses this to stay idempotent: when a previous attempt merged but failed afterwards
|
|
313
|
+
// (for example while removing the worktree), re-running the merge would fail with "No commits to
|
|
314
|
+
// merge", so the retry skips the merge and continues with the remaining integration steps.
|
|
315
|
+
// exec ブランチが統合ブランチへ merge 済みかを判定する。ancestor 判定だけでは、exec ブランチが
|
|
316
|
+
// 作成直後(先端が統合ブランチ上の commit のまま)の場合も true になる。runner の統合は
|
|
317
|
+
// --no-ff で merge するため、merge 済みなら先端は HEAD の first-parent 連鎖には含まれない。
|
|
318
|
+
// 先端が first-parent 連鎖上にあるなら、task の commit がまだ無い状態とみなす。
|
|
319
|
+
export function isExecBranchMergedIntoCurrent(params) {
|
|
320
|
+
const repoRoot = params.context.repoRoot;
|
|
321
|
+
const isAncestor = gitResult(repoRoot, ["merge-base", "--is-ancestor", params.worktree.branch, "HEAD"]).status ===
|
|
322
|
+
0;
|
|
323
|
+
if (!isAncestor)
|
|
324
|
+
return false;
|
|
325
|
+
const tip = gitResult(repoRoot, ["rev-parse", "--verify", `${params.worktree.branch}^{commit}`]);
|
|
326
|
+
if (tip.status !== 0 || typeof tip.stdout !== "string")
|
|
327
|
+
return false;
|
|
328
|
+
const firstParentChain = gitOutput(repoRoot, ["rev-list", "--first-parent", "HEAD"])
|
|
329
|
+
.split("\n")
|
|
330
|
+
.map((line) => line.trim());
|
|
331
|
+
return !firstParentChain.includes(tip.stdout.trim());
|
|
332
|
+
}
|
|
333
|
+
// Put a root path back to its HEAD state: tracked files are restored, paths absent from HEAD are
|
|
334
|
+
// removed (and unstaged if a hook or caller had staged them).
|
|
335
|
+
function restoreToHead(repoRoot, relPath) {
|
|
336
|
+
const tracked = gitResult(repoRoot, ["ls-files", "--error-unmatch", "--", relPath]).status === 0;
|
|
337
|
+
if (tracked) {
|
|
338
|
+
gitOutput(repoRoot, ["restore", "--source=HEAD", "--staged", "--worktree", "--", relPath]);
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
gitResult(repoRoot, ["reset", "--quiet", "--", relPath]);
|
|
342
|
+
rmSync(resolve(repoRoot, relPath), { recursive: true, force: true });
|
|
343
|
+
}
|
|
344
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { REGISTER_NEW_FILE_DIR_PREFIXES, ROOT_NEW_FILES_HANDOFF_LABEL, applyRootNewFilesHandoff, assertResultMarkdownlint, commitTargetPaths, commitWorktreeChanges, currentBranch, deliverableStatus, isCommitTargetPath, normalizeResultWhitespace, partitionCommitTargets, recordRootNewFilesHandoff, repoRelative, resolveCommitScope, selectStageablePaths, stabilizeCommitTargets, stageCommitTargets, taskPaths, taskTargetsAtHead, unstageCommitTargets, worktreeStatusPaths, } from "./worktree-ops-commit.js";
|
|
2
|
+
export { abortMerge, isExecBranchMergedIntoCurrent, mergeWorktreeIntoCurrent, releaseRootWorkingCopies, restoreRootWorkingCopies, } from "./worktree-ops-merge.js";
|
|
3
|
+
export { WorktreeRemovedBranchDeletionError, checkpointAndEnsureWorktree, discardStaleExecWorktree, listOrphanedExecBranches, pruneOrphanedExecBranches, removeWorktree, } from "./worktree-ops-lifecycle.js";
|