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,672 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { load } from "../shared/yaml.js";
|
|
5
|
+
import { deliverableDocPath, parsePlanTaskIdentity, targetReferenceDirsForApproach, } from "./plans.js";
|
|
6
|
+
import { parseResultTaskIdentity } from "./results.js";
|
|
7
|
+
import { stripTerminalControlSequences } from "./shared.js";
|
|
8
|
+
import { agentProtectedConfigPaths, agentProtectedConfigViolation, qualifiedRepoPaths, } from "./agent-protected-config.js";
|
|
9
|
+
import { recordProtectedConfigBlockAcrossRepos } from "./protection-handoff.js";
|
|
10
|
+
import { assertNoPendingProductChanges, productIntegrationTarget } from "./task-repos.js";
|
|
11
|
+
import { specdojoPackageRootDir } from "../shared/package-paths.js";
|
|
12
|
+
import { repoRelative, stageCommitTargets, worktreeStatusPaths as statusPaths, } from "../shared/git.js";
|
|
13
|
+
export { repoRelative, selectStageablePaths, stageCommitTargets, worktreeStatusPaths, } from "../shared/git.js";
|
|
14
|
+
import { appendGitFailureLog, appendGitResultFailureLog, formatGitResultFailure, gitEnvironment, gitOutput, gitResult, summarizeGitHookFailure, worktreeNameFromTaskId, } from "./worktree.js";
|
|
15
|
+
const MAX_COMMIT_STABILIZATION_ATTEMPTS = 3;
|
|
16
|
+
export function currentBranch(repoRoot) {
|
|
17
|
+
const branch = gitOutput(repoRoot, ["branch", "--show-current"]).trim();
|
|
18
|
+
if (!branch)
|
|
19
|
+
throw new Error("Detached HEAD is not supported for exec worktree commands.");
|
|
20
|
+
return branch;
|
|
21
|
+
}
|
|
22
|
+
export function taskPaths(context, taskId) {
|
|
23
|
+
const executionRel = repoRelative(context.repoRoot, context.executionPath);
|
|
24
|
+
return {
|
|
25
|
+
executionRel,
|
|
26
|
+
planRel: `${executionRel}/exec/plans/${taskId}-plan.md`,
|
|
27
|
+
resultRel: `${executionRel}/exec/results/${taskId}-result.md`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export function isCommitTargetPath(path, executionRel, resultRel) {
|
|
31
|
+
const normalized = path.replaceAll("\\", "/");
|
|
32
|
+
if (normalized === resultRel)
|
|
33
|
+
return true;
|
|
34
|
+
// doc-index は root と worktree の双方で再生成される生成物。commit-target に含めると
|
|
35
|
+
// merge 時の overlap ガードで衝突するため除外する。
|
|
36
|
+
if (normalized === ".specdojo/doc-index.json")
|
|
37
|
+
return false;
|
|
38
|
+
if (normalized === "tmp" || normalized.startsWith("tmp/"))
|
|
39
|
+
return false;
|
|
40
|
+
if (normalized.startsWith(`${executionRel}/exec/plans/`))
|
|
41
|
+
return false;
|
|
42
|
+
if (normalized.startsWith(`${executionRel}/exec/results/`))
|
|
43
|
+
return false;
|
|
44
|
+
if (normalized.startsWith(`${executionRel}/exec/events/`))
|
|
45
|
+
return false;
|
|
46
|
+
if (normalized.startsWith(`${executionRel}/generated/`))
|
|
47
|
+
return false;
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
// Reads a deliverable's frontmatter `status`. Markdown deliverables carry it in the
|
|
51
|
+
// leading `---` frontmatter block; yaml/json deliverables carry it as a top-level field.
|
|
52
|
+
// Returns undefined when absent or unparsable (treated as "not ready").
|
|
53
|
+
export function deliverableStatus(content, relPath) {
|
|
54
|
+
const isMarkdown = /\.md$/i.test(relPath);
|
|
55
|
+
let source = content;
|
|
56
|
+
if (isMarkdown) {
|
|
57
|
+
const fm = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
58
|
+
if (!fm)
|
|
59
|
+
return undefined;
|
|
60
|
+
source = fm[1];
|
|
61
|
+
}
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = load(source);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
70
|
+
return undefined;
|
|
71
|
+
// Markdown deliverables carry status in the `specdojo:` namespace; yaml/json data
|
|
72
|
+
// files carry it as a top-level field.
|
|
73
|
+
const container = isMarkdown
|
|
74
|
+
? parsed.specdojo
|
|
75
|
+
: parsed;
|
|
76
|
+
if (!container || typeof container !== "object" || Array.isArray(container))
|
|
77
|
+
return undefined;
|
|
78
|
+
const status = container.status;
|
|
79
|
+
return typeof status === "string" ? status : undefined;
|
|
80
|
+
}
|
|
81
|
+
// Promotion of a deliverable's frontmatter status to "ready" is a human-only gate.
|
|
82
|
+
// Agents commit their changes through commitWorktreeChanges, so reject (block) any run
|
|
83
|
+
// that transitions a deliverable to "ready" here; humans promote out-of-band via a direct
|
|
84
|
+
// edit and git commit, which never passes through this path.
|
|
85
|
+
function assertNoAgentReadyPromotion(context, worktree, taskId, paths) {
|
|
86
|
+
const { resultRel } = taskPaths(context, taskId);
|
|
87
|
+
const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
|
|
88
|
+
if (resultContent && parseResultTaskIdentity(resultContent)?.execution === "human") {
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const promoted = [];
|
|
92
|
+
for (const relPath of paths) {
|
|
93
|
+
if (relPath === resultRel)
|
|
94
|
+
continue;
|
|
95
|
+
const absPath = resolve(worktree.path, relPath);
|
|
96
|
+
if (!existsSync(absPath))
|
|
97
|
+
continue; // deletion is not a promotion
|
|
98
|
+
if (deliverableStatus(readFileSync(absPath, "utf8"), relPath) !== "ready")
|
|
99
|
+
continue;
|
|
100
|
+
const base = gitResult(worktree.path, ["show", `HEAD:${relPath}`]);
|
|
101
|
+
const baseStatus = base.status === 0 && typeof base.stdout === "string"
|
|
102
|
+
? deliverableStatus(base.stdout, relPath)
|
|
103
|
+
: undefined;
|
|
104
|
+
if (baseStatus !== "ready")
|
|
105
|
+
promoted.push(relPath);
|
|
106
|
+
}
|
|
107
|
+
if (promoted.length > 0) {
|
|
108
|
+
throw new Error(`Deliverable status promotion to "ready" is human-only and must not be done by an agent run: ${promoted.join(", ")}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function isHumanWorktreeExecution(context, worktree, taskId) {
|
|
112
|
+
const { resultRel } = taskPaths(context, taskId);
|
|
113
|
+
const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
|
|
114
|
+
return !!resultContent && parseResultTaskIdentity(resultContent)?.execution === "human";
|
|
115
|
+
}
|
|
116
|
+
// worktree の未 commit 差分に加え、agent が provider 側の git 制約を回避して直接
|
|
117
|
+
// commit した差分も検査する。human execution と通常の人間 / orchestrator commit は
|
|
118
|
+
// agent 統合経路ではないため、このガードの対象外。
|
|
119
|
+
function assertNoAgentProtectedConfigChanges(context, worktree, taskId) {
|
|
120
|
+
if (isHumanWorktreeExecution(context, worktree, taskId))
|
|
121
|
+
return;
|
|
122
|
+
const { resultRel } = taskPaths(context, taskId);
|
|
123
|
+
const rootHead = gitOutput(context.repoRoot, ["rev-parse", "HEAD"]).trim();
|
|
124
|
+
const compareBase = gitOutput(worktree.path, ["merge-base", "HEAD", rootHead]).trim();
|
|
125
|
+
const committed = zeroSeparatedPaths(worktree.path, [
|
|
126
|
+
"diff",
|
|
127
|
+
"--no-renames",
|
|
128
|
+
"--name-only",
|
|
129
|
+
"-z",
|
|
130
|
+
`${compareBase}..HEAD`,
|
|
131
|
+
]);
|
|
132
|
+
const protectedPaths = agentProtectedConfigPaths(worktree.path, [
|
|
133
|
+
...statusPaths(worktree.path),
|
|
134
|
+
...committed,
|
|
135
|
+
]);
|
|
136
|
+
const changes = [
|
|
137
|
+
...(protectedPaths.length > 0
|
|
138
|
+
? [{ repo: { root: worktree.path }, paths: protectedPaths }]
|
|
139
|
+
: []),
|
|
140
|
+
...productProtectedConfigChanges(worktree),
|
|
141
|
+
];
|
|
142
|
+
if (changes.length > 0) {
|
|
143
|
+
const reason = agentProtectedConfigViolation(qualifiedRepoPaths(changes));
|
|
144
|
+
// commit 前の再検査でも、対象と提案差分を result の申し送りへ残してから block する。
|
|
145
|
+
recordProtectedConfigBlockAcrossRepos({
|
|
146
|
+
resultPath: resolve(worktree.path, resultRel),
|
|
147
|
+
changes,
|
|
148
|
+
reason,
|
|
149
|
+
});
|
|
150
|
+
throw new Error(reason);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
// プロダクト worktree の未 commit 差分と、統合先から進んだ exec branch の commit を保護パスで検査する。
|
|
154
|
+
function productProtectedConfigChanges(worktree) {
|
|
155
|
+
return (worktree.repos ?? []).flatMap((product) => {
|
|
156
|
+
if (!existsSync(product.path))
|
|
157
|
+
return [];
|
|
158
|
+
const target = productIntegrationTarget(product);
|
|
159
|
+
const base = gitResult(product.path, ["merge-base", "HEAD", target]);
|
|
160
|
+
const compareBase = typeof base.stdout === "string" ? base.stdout.trim() : "";
|
|
161
|
+
const committed = base.status === 0 && compareBase
|
|
162
|
+
? zeroSeparatedPaths(product.path, [
|
|
163
|
+
"diff",
|
|
164
|
+
"--no-renames",
|
|
165
|
+
"--name-only",
|
|
166
|
+
"-z",
|
|
167
|
+
`${compareBase}..HEAD`,
|
|
168
|
+
])
|
|
169
|
+
: [];
|
|
170
|
+
const paths = agentProtectedConfigPaths(product.path, [
|
|
171
|
+
...statusPaths(product.path),
|
|
172
|
+
...committed,
|
|
173
|
+
]);
|
|
174
|
+
return paths.length > 0 ? [{ repo: { name: product.name, root: product.path }, paths }] : [];
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const DOC_INDEX_REL = ".specdojo/doc-index.json";
|
|
178
|
+
// worktree の HEAD(CLI が checkpoint した版)からファイル内容を読む。
|
|
179
|
+
// agent は working tree を書き換えられるが HEAD は書き換えられないため、
|
|
180
|
+
// ここから読む情報はプロンプトインジェクションに対して改ざん耐性がある。
|
|
181
|
+
function readWorktreeHeadFile(worktreePath, relPath) {
|
|
182
|
+
const result = gitResult(worktreePath, ["show", `HEAD:${relPath}`]);
|
|
183
|
+
return result.status === 0 && typeof result.stdout === "string" ? result.stdout : undefined;
|
|
184
|
+
}
|
|
185
|
+
// HEAD の doc-index から doc id → repo 相対パスを引く。"path:line" 形式は path 部を使う。
|
|
186
|
+
function headDocIndexLookup(worktreePath) {
|
|
187
|
+
const content = readWorktreeHeadFile(worktreePath, DOC_INDEX_REL);
|
|
188
|
+
let entries = {};
|
|
189
|
+
if (content) {
|
|
190
|
+
try {
|
|
191
|
+
const parsed = JSON.parse(content);
|
|
192
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
193
|
+
const candidate = parsed.entries;
|
|
194
|
+
if (candidate && typeof candidate === "object" && !Array.isArray(candidate)) {
|
|
195
|
+
entries = candidate;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
// 壊れた index は「引けない」として扱い、catalog フォールバックに委ねる。
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return (id) => {
|
|
204
|
+
const value = entries[id];
|
|
205
|
+
if (typeof value !== "string")
|
|
206
|
+
return undefined;
|
|
207
|
+
const match = value.match(/^(.+):\d+$/);
|
|
208
|
+
return match ? match[1] : value;
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
// agent は HEAD の plan、human は HEAD の result frontmatter から commit 許可リストを
|
|
212
|
+
// 導出する。いずれも task 識別を復元できない場合は null を返し、呼び出し側は従来の
|
|
213
|
+
// 除外リスト方式へフォールバックする。checkpoint 済みの HEAD を読むため、agent の
|
|
214
|
+
// working tree 改変からは影響を受けない。
|
|
215
|
+
export function resolveCommitScope(context, worktree, taskId) {
|
|
216
|
+
const { executionRel, planRel, resultRel } = taskPaths(context, taskId);
|
|
217
|
+
const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
|
|
218
|
+
const resultIdentity = resultContent ? parseResultTaskIdentity(resultContent) : null;
|
|
219
|
+
const planContent = readWorktreeHeadFile(worktree.path, planRel);
|
|
220
|
+
const planIdentity = planContent ? parsePlanTaskIdentity(planContent) : null;
|
|
221
|
+
// 旧版で生成済みの human plan が残っていても、明示された execution を優先して
|
|
222
|
+
// result の targets を正本に切り替える。
|
|
223
|
+
const identity = resultIdentity?.execution === "human" ? resultIdentity : planIdentity;
|
|
224
|
+
if (!identity)
|
|
225
|
+
return { scope: null, unresolvedTargets: [] };
|
|
226
|
+
if (identity.mode === "review") {
|
|
227
|
+
return {
|
|
228
|
+
scope: { mode: "review", allowedFiles: [resultRel], allowedDirPrefixes: [] },
|
|
229
|
+
unresolvedTargets: [],
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
// register 由来のタスクは許可リスト方式ではなく、作業ツリー差分による commit を使う。
|
|
233
|
+
// 個票が targets を宣言している場合でも、commit scope は従来どおり除外リスト方式へ
|
|
234
|
+
// フォールバックする(target coverage 検証は evidence 側で行い、ここでは使わない)。
|
|
235
|
+
if (identity.origin === "register")
|
|
236
|
+
return { scope: null, unresolvedTargets: [] };
|
|
237
|
+
// schedule 由来の edit タスクは targets から commit 許可リストを導出する。targets が
|
|
238
|
+
// 無いと許可リストが result 1 件へ縮退し、成果物の変更が commit されないまま worktree に
|
|
239
|
+
// 残る。静かに縮退させず、ここで失敗させる。
|
|
240
|
+
if ((identity.targets ?? []).length === 0) {
|
|
241
|
+
throw new Error(`commit-scope: no targets in plan/result frontmatter for edit task ${taskId}. ` +
|
|
242
|
+
`Schedule-originated edit tasks must declare targets; ` +
|
|
243
|
+
`register-originated tasks must declare "origin: register".`);
|
|
244
|
+
}
|
|
245
|
+
const allowedFiles = new Set([resultRel]);
|
|
246
|
+
const unresolvedTargets = [];
|
|
247
|
+
const lookup = headDocIndexLookup(worktree.path);
|
|
248
|
+
for (const target of identity.targets ?? []) {
|
|
249
|
+
// `<repo>:<path>` はプロダクトリポジトリの対象で、プロダクト側の commit 対象に入る
|
|
250
|
+
// (exec-repo-integration)。プロジェクト側の doc id としては解決しない。
|
|
251
|
+
if (isProductRepoTarget(worktree, target))
|
|
252
|
+
continue;
|
|
253
|
+
const fromIndex = lookup(target);
|
|
254
|
+
if (fromIndex) {
|
|
255
|
+
allowedFiles.add(fromIndex);
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
// doc-index 未登録(未作成の新規成果物など)は catalog が宣言するパスへ解決する。
|
|
259
|
+
const localId = identity.projectId && target.startsWith(`${identity.projectId}:`)
|
|
260
|
+
? target.slice(identity.projectId.length + 1)
|
|
261
|
+
: target;
|
|
262
|
+
const fromCatalog = context.catalogPath
|
|
263
|
+
? deliverableDocPath(context.catalogPath, localId)
|
|
264
|
+
: undefined;
|
|
265
|
+
if (fromCatalog) {
|
|
266
|
+
allowedFiles.add(fromCatalog);
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
unresolvedTargets.push(target);
|
|
270
|
+
}
|
|
271
|
+
const allowedDirPrefixes = targetReferenceDirsForApproach(identity.approach).map((dir) => `${dir}/`);
|
|
272
|
+
// Pipeline evidence is runner-owned and stored per task/run. It must be committed together with
|
|
273
|
+
// the eventual reporter-generated result so the structured executor record survives worktree
|
|
274
|
+
// removal. Legacy tasks create no files under this prefix, so their commit scope is unchanged.
|
|
275
|
+
allowedDirPrefixes.push(`${executionRel}/exec/evidence/${worktreeNameFromTaskId(taskId)}/`);
|
|
276
|
+
return {
|
|
277
|
+
scope: { mode: "edit", allowedFiles: [...allowedFiles], allowedDirPrefixes },
|
|
278
|
+
unresolvedTargets,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
// checkpoint 済みの HEAD の plan(human は result)frontmatter の targets。agent の working tree
|
|
282
|
+
// 改変の影響を受けない。プロダクトリポジトリの commit 対象(`<repo>:<path>`)の導出に使う。
|
|
283
|
+
export function taskTargetsAtHead(context, worktree, taskId) {
|
|
284
|
+
const { planRel, resultRel } = taskPaths(context, taskId);
|
|
285
|
+
const resultContent = readWorktreeHeadFile(worktree.path, resultRel);
|
|
286
|
+
const resultIdentity = resultContent ? parseResultTaskIdentity(resultContent) : null;
|
|
287
|
+
if (resultIdentity?.execution === "human")
|
|
288
|
+
return resultIdentity.targets ?? [];
|
|
289
|
+
const planContent = readWorktreeHeadFile(worktree.path, planRel);
|
|
290
|
+
return (planContent ? parsePlanTaskIdentity(planContent) : null)?.targets ?? [];
|
|
291
|
+
}
|
|
292
|
+
// `<repo>:<path>` 形式で、接頭辞がタスクのプロダクト worktree のリポジトリ名である値。
|
|
293
|
+
function isProductRepoTarget(worktree, target) {
|
|
294
|
+
const separator = target.indexOf(":");
|
|
295
|
+
if (separator <= 0)
|
|
296
|
+
return false;
|
|
297
|
+
const prefix = target.slice(0, separator);
|
|
298
|
+
return (worktree.repos ?? []).some((product) => product.name === prefix);
|
|
299
|
+
}
|
|
300
|
+
// register 由来のタスクで新規ファイルの作成を許す既知の成果物ディレクトリ。HEAD に追跡
|
|
301
|
+
// ファイルを持つ最上位ディレクトリもこれに加える(利用プロジェクト固有の構成に追従するため)。
|
|
302
|
+
export const REGISTER_NEW_FILE_DIR_PREFIXES = [
|
|
303
|
+
"docs/",
|
|
304
|
+
"src/",
|
|
305
|
+
"tests/",
|
|
306
|
+
"tools/",
|
|
307
|
+
"scripts/",
|
|
308
|
+
"packages/",
|
|
309
|
+
];
|
|
310
|
+
// register 由来のタスクは作業ツリー差分を commit するため、agent が作業用に作った一時ファイル
|
|
311
|
+
// (リポジトリ直下の modify.py、patch.js など)まで commit 対象に入る。HEAD に存在しない新規
|
|
312
|
+
// ファイルは、既知の成果物ディレクトリ・HEAD の追跡済み最上位ディレクトリ・result・task の
|
|
313
|
+
// evidence 配下・個票 targets から解決したパスに限り、それ以外を commit 範囲外とする。
|
|
314
|
+
// 既存ファイルの変更と削除は従来どおり除外リスト方式で判定する。
|
|
315
|
+
function registerNewFileIsAllowed(worktree, context, taskId) {
|
|
316
|
+
const { executionRel, planRel, resultRel } = taskPaths(context, taskId);
|
|
317
|
+
const topLevelDirs = zeroSeparatedPaths(worktree.path, [
|
|
318
|
+
"ls-tree",
|
|
319
|
+
"-d",
|
|
320
|
+
"--name-only",
|
|
321
|
+
"-z",
|
|
322
|
+
"HEAD",
|
|
323
|
+
]).map((dir) => `${dir}/`);
|
|
324
|
+
const allowedDirPrefixes = [
|
|
325
|
+
...REGISTER_NEW_FILE_DIR_PREFIXES,
|
|
326
|
+
...topLevelDirs,
|
|
327
|
+
`${executionRel}/exec/evidence/${worktreeNameFromTaskId(taskId)}/`,
|
|
328
|
+
];
|
|
329
|
+
const planContent = readWorktreeHeadFile(worktree.path, planRel);
|
|
330
|
+
const targets = (planContent ? parsePlanTaskIdentity(planContent) : null)?.targets ?? [];
|
|
331
|
+
const lookup = headDocIndexLookup(worktree.path);
|
|
332
|
+
const allowedFiles = new Set([resultRel]);
|
|
333
|
+
for (const target of targets) {
|
|
334
|
+
const resolved = lookup(target);
|
|
335
|
+
if (resolved)
|
|
336
|
+
allowedFiles.add(resolved);
|
|
337
|
+
}
|
|
338
|
+
return (path) => !path.includes("/") ||
|
|
339
|
+
allowedFiles.has(path) ||
|
|
340
|
+
allowedDirPrefixes.some((prefix) => path.startsWith(prefix));
|
|
341
|
+
}
|
|
342
|
+
function pathsTrackedAtHead(worktreePath, paths) {
|
|
343
|
+
if (paths.length === 0)
|
|
344
|
+
return new Set();
|
|
345
|
+
return new Set(zeroSeparatedPaths(worktreePath, [
|
|
346
|
+
"ls-tree",
|
|
347
|
+
"-r",
|
|
348
|
+
"--name-only",
|
|
349
|
+
"--full-tree",
|
|
350
|
+
"-z",
|
|
351
|
+
"HEAD",
|
|
352
|
+
"--",
|
|
353
|
+
...paths,
|
|
354
|
+
]));
|
|
355
|
+
}
|
|
356
|
+
function isRegisterOriginTask(context, worktree, taskId) {
|
|
357
|
+
const planContent = readWorktreeHeadFile(worktree.path, taskPaths(context, taskId).planRel);
|
|
358
|
+
return (planContent ? parsePlanTaskIdentity(planContent) : null)?.origin === "register";
|
|
359
|
+
}
|
|
360
|
+
// worktree の変更を「commit するパス」「許可リスト外のため commit しないパス」に分ける。
|
|
361
|
+
// 除外リスト(isCommitTargetPath)は許可リストの内側でも引き続き適用する。
|
|
362
|
+
export function partitionCommitTargets(context, worktree, taskId) {
|
|
363
|
+
const { executionRel, resultRel } = taskPaths(context, taskId);
|
|
364
|
+
const candidates = statusPaths(worktree.path).filter((path) => isCommitTargetPath(path, executionRel, resultRel));
|
|
365
|
+
const { scope, unresolvedTargets } = resolveCommitScope(context, worktree, taskId);
|
|
366
|
+
if (!scope) {
|
|
367
|
+
// 人間の作業は agent の一時ファイル対策の対象外とし、従来どおり除外リスト方式で commit する。
|
|
368
|
+
if (!isRegisterOriginTask(context, worktree, taskId) ||
|
|
369
|
+
isHumanWorktreeExecution(context, worktree, taskId)) {
|
|
370
|
+
return { targets: candidates, outOfScope: [], unresolvedTargets };
|
|
371
|
+
}
|
|
372
|
+
const tracked = pathsTrackedAtHead(worktree.path, candidates);
|
|
373
|
+
const isAllowedNewFile = registerNewFileIsAllowed(worktree, context, taskId);
|
|
374
|
+
const targets = [];
|
|
375
|
+
const outOfScope = [];
|
|
376
|
+
for (const path of candidates) {
|
|
377
|
+
const allowed = tracked.has(path) || isAllowedNewFile(path);
|
|
378
|
+
(allowed ? targets : outOfScope).push(path);
|
|
379
|
+
}
|
|
380
|
+
return { targets, outOfScope, unresolvedTargets };
|
|
381
|
+
}
|
|
382
|
+
const targets = [];
|
|
383
|
+
const outOfScope = [];
|
|
384
|
+
for (const path of candidates) {
|
|
385
|
+
const allowed = scope.allowedFiles.includes(path) ||
|
|
386
|
+
scope.allowedDirPrefixes.some((prefix) => path.startsWith(prefix));
|
|
387
|
+
(allowed ? targets : outOfScope).push(path);
|
|
388
|
+
}
|
|
389
|
+
return { targets, outOfScope, unresolvedTargets };
|
|
390
|
+
}
|
|
391
|
+
export function commitTargetPaths(context, worktree, taskId) {
|
|
392
|
+
return partitionCommitTargets(context, worktree, taskId).targets;
|
|
393
|
+
}
|
|
394
|
+
// `git add` の pathspec は作業ツリーと index だけを照合する。削除が既に index へ入っている
|
|
395
|
+
// パスはそのどちらにも存在しないため、`-A` を付けても「pathspec did not match any files」で
|
|
396
|
+
// fatal になる。このようなパスは追加で stage する内容が無いので、add の対象から除外する。
|
|
397
|
+
// commit / commit --amend の pathspec は HEAD も照合するため、対象から外さずに削除を記録できる。
|
|
398
|
+
// runner が stage した対象だけを index から戻す。利用者や別処理が stage 済みの無関係な
|
|
399
|
+
// パスは保持し、commit / hook の失敗を後続の exec run へ持ち越さない。
|
|
400
|
+
export function unstageCommitTargets(repoRoot, paths) {
|
|
401
|
+
const unique = [...new Set(paths)];
|
|
402
|
+
if (unique.length === 0)
|
|
403
|
+
return;
|
|
404
|
+
gitOutput(repoRoot, ["reset", "--quiet", "--", ...unique]);
|
|
405
|
+
}
|
|
406
|
+
// markdownlint-cli の終了コード。1 だけが記法違反を表し、それ以外は実行環境の問題である。
|
|
407
|
+
const MARKDOWNLINT_EXIT_LINT_ERRORS = 1;
|
|
408
|
+
// worktree または SpecDojo package の node_modules から markdownlint-cli を探す。
|
|
409
|
+
// markdownlint-cli は devDependency のため、配布先の利用プロジェクトでは存在しないことがある。
|
|
410
|
+
function findMarkdownlintExecutable(worktreePath) {
|
|
411
|
+
const executableName = process.platform === "win32" ? "markdownlint.cmd" : "markdownlint";
|
|
412
|
+
const candidates = [
|
|
413
|
+
join(worktreePath, "node_modules", ".bin", executableName),
|
|
414
|
+
join(specdojoPackageRootDir(), "node_modules", ".bin", executableName),
|
|
415
|
+
];
|
|
416
|
+
return candidates.find(existsSync);
|
|
417
|
+
}
|
|
418
|
+
// result は commit hook の Prettier 実行対象から除外するため(.prettierignore)、runner が
|
|
419
|
+
// commit 前に markdownlint を直接実行する。hook 由来の汎用的な git commit 失敗ではなく、
|
|
420
|
+
// result の記法違反として block 理由を残せるようにする。
|
|
421
|
+
// markdownlint-cli が見つからない環境では検査を省略し、hook 側の検査に委ねる。
|
|
422
|
+
// 行末の空白を除き、ファイル末尾を改行 1 つに揃える。強調記法など内容に関わる置換は行わない。
|
|
423
|
+
export function normalizeResultWhitespace(resultPath) {
|
|
424
|
+
const content = readFileSync(resultPath, "utf8");
|
|
425
|
+
const normalized = content.replace(/[ \t]+$/gm, "").replace(/\n*$/, "\n");
|
|
426
|
+
if (normalized !== content)
|
|
427
|
+
writeFileSync(resultPath, normalized, "utf8");
|
|
428
|
+
}
|
|
429
|
+
export function assertResultMarkdownlint(context, worktree, taskId) {
|
|
430
|
+
const { resultRel } = taskPaths(context, taskId);
|
|
431
|
+
const resultPath = resolve(worktree.path, resultRel);
|
|
432
|
+
if (!existsSync(resultPath)) {
|
|
433
|
+
process.stdout.write(`result-markdownlint: result ${resultRel} not found; skipped pre-commit lint\n`);
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
// reporter の出力に由来する行末の空白と末尾改行の不足は、内容に影響しない空白だけの違反
|
|
437
|
+
// (MD009 / MD047)であり、以前は commit hook の Prettier が黙って整えていた。Prettier の
|
|
438
|
+
// 対象外にした分をここで補い、記法違反として block するのは内容に関わる違反に限る。
|
|
439
|
+
normalizeResultWhitespace(resultPath);
|
|
440
|
+
const executable = findMarkdownlintExecutable(worktree.path);
|
|
441
|
+
if (!executable) {
|
|
442
|
+
process.stdout.write(`result-markdownlint: markdownlint-cli not found; skipped pre-commit lint of ${resultRel}\n`);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const result = spawnSync(executable, [resultRel], {
|
|
446
|
+
cwd: worktree.path,
|
|
447
|
+
encoding: "utf8",
|
|
448
|
+
env: gitEnvironment(),
|
|
449
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
450
|
+
});
|
|
451
|
+
if (!result.error && result.status === 0)
|
|
452
|
+
return;
|
|
453
|
+
const output = stripTerminalControlSequences([result.stdout, result.stderr, result.error?.message].filter(Boolean).join("\n"))
|
|
454
|
+
.trim()
|
|
455
|
+
.replace(/\s+/g, " ");
|
|
456
|
+
const detail = output ? output.slice(0, 1_000) : `exit ${result.status ?? "unknown"}`;
|
|
457
|
+
if (!result.error && result.status === MARKDOWNLINT_EXIT_LINT_ERRORS) {
|
|
458
|
+
throw new Error(`Result Markdown notation violation before commit: ${detail}`);
|
|
459
|
+
}
|
|
460
|
+
throw new Error(`Failed to run markdownlint on ${resultRel} before commit: ${detail}`);
|
|
461
|
+
}
|
|
462
|
+
export function stabilizeCommitTargets(repoRoot, listRemainingPaths, maxAttempts = MAX_COMMIT_STABILIZATION_ATTEMPTS, failureLogPath) {
|
|
463
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
464
|
+
const paths = listRemainingPaths();
|
|
465
|
+
if (paths.length === 0)
|
|
466
|
+
return;
|
|
467
|
+
stageCommitTargets(repoRoot, paths);
|
|
468
|
+
const stagedArgs = ["diff", "--cached", "--quiet", "--", ...paths];
|
|
469
|
+
const staged = gitResult(repoRoot, stagedArgs);
|
|
470
|
+
if (staged.status === 0) {
|
|
471
|
+
// pathspec commit は hook が再stageした内容を commit した後、元の index を復元して
|
|
472
|
+
// HEAD と逆向きの差分を残す場合がある。この場合は add が index を HEAD へ揃えて
|
|
473
|
+
// 差分を解消するため、再取得して消えていれば正常な収束として扱う。
|
|
474
|
+
const remaining = listRemainingPaths();
|
|
475
|
+
if (remaining.length === 0)
|
|
476
|
+
return;
|
|
477
|
+
throw new Error(`Failed to stage post-hook commit-target changes: ${remaining.join(", ")}`);
|
|
478
|
+
}
|
|
479
|
+
if (staged.status !== 1) {
|
|
480
|
+
appendGitResultFailureLog(failureLogPath, "git diff post-hook worktree inspection", staged);
|
|
481
|
+
throw new Error(`Failed to inspect post-hook worktree changes: ${formatGitResultFailure(stagedArgs, staged)}`);
|
|
482
|
+
}
|
|
483
|
+
const commitArgs = ["commit", "--amend", "--no-edit", "--", ...paths];
|
|
484
|
+
const commit = gitResult(repoRoot, commitArgs);
|
|
485
|
+
if (commit.status !== 0) {
|
|
486
|
+
const output = [commit.stdout, commit.stderr]
|
|
487
|
+
.filter((part) => typeof part === "string" && part.length > 0)
|
|
488
|
+
.join("\n");
|
|
489
|
+
appendGitFailureLog(failureLogPath, [
|
|
490
|
+
`=== ${new Date().toISOString()} git commit --amend ===`,
|
|
491
|
+
`exit: ${commit.status ?? "unknown"}`,
|
|
492
|
+
"--- stdout ---",
|
|
493
|
+
typeof commit.stdout === "string" ? commit.stdout : "",
|
|
494
|
+
"--- stderr ---",
|
|
495
|
+
typeof commit.stderr === "string" ? commit.stderr : "",
|
|
496
|
+
"",
|
|
497
|
+
]);
|
|
498
|
+
throw new Error(`git commit --amend failed: ${summarizeGitHookFailure(output)}`);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const dirty = listRemainingPaths();
|
|
502
|
+
if (dirty.length > 0) {
|
|
503
|
+
throw new Error(`Pre-commit hooks kept changing commit-target files: ${dirty.join(", ")}`);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
export function zeroSeparatedPaths(repoRoot, args) {
|
|
507
|
+
return gitOutput(repoRoot, args).split("\0").filter(Boolean);
|
|
508
|
+
}
|
|
509
|
+
export function rootDirtyPaths(repoRoot) {
|
|
510
|
+
return new Set([
|
|
511
|
+
...zeroSeparatedPaths(repoRoot, ["diff", "--no-renames", "--name-only", "-z"]),
|
|
512
|
+
...zeroSeparatedPaths(repoRoot, ["diff", "--cached", "--no-renames", "--name-only", "-z"]),
|
|
513
|
+
...zeroSeparatedPaths(repoRoot, ["ls-files", "--others", "--exclude-standard", "-z"]),
|
|
514
|
+
]);
|
|
515
|
+
}
|
|
516
|
+
export const ROOT_NEW_FILES_HANDOFF_LABEL = "最上位に追加したファイル";
|
|
517
|
+
export function applyRootNewFilesHandoff(content, files) {
|
|
518
|
+
const normalized = content.replace(/\r\n/g, "\n");
|
|
519
|
+
const uniqueFiles = [...new Set(files)];
|
|
520
|
+
if (uniqueFiles.length === 0)
|
|
521
|
+
return normalized;
|
|
522
|
+
const linePattern = new RegExp(`^[ \\t]*- +${ROOT_NEW_FILES_HANDOFF_LABEL}: *(.*)$`, "m");
|
|
523
|
+
const match = linePattern.exec(normalized);
|
|
524
|
+
if (match) {
|
|
525
|
+
const existingMatches = [...match[1].matchAll(/`([^`]+)`/g)].map((m) => m[1]);
|
|
526
|
+
const merged = [...new Set([...existingMatches, ...uniqueFiles])];
|
|
527
|
+
const newLine = `- ${ROOT_NEW_FILES_HANDOFF_LABEL}: ${merged.map((f) => `\`${f}\``).join(", ")}`;
|
|
528
|
+
return normalized.replace(match[0], newLine);
|
|
529
|
+
}
|
|
530
|
+
const handoffHeading = /^## +\d+\. +申し送り[ \t]*$/m.exec(normalized);
|
|
531
|
+
if (handoffHeading) {
|
|
532
|
+
const start = handoffHeading.index + handoffHeading[0].length;
|
|
533
|
+
const rest = normalized.slice(start);
|
|
534
|
+
const nextHeading = /^##\s+/m.exec(rest);
|
|
535
|
+
const end = nextHeading ? start + nextHeading.index : normalized.length;
|
|
536
|
+
const sectionBody = normalized.slice(start, end);
|
|
537
|
+
const newLine = `- ${ROOT_NEW_FILES_HANDOFF_LABEL}: ${uniqueFiles.map((f) => `\`${f}\``).join(", ")}`;
|
|
538
|
+
const markerIndex = sectionBody.indexOf("<!-- specdojo:agent-protection-handoff -->");
|
|
539
|
+
const beforeMarker = markerIndex === -1 ? sectionBody : sectionBody.slice(0, markerIndex);
|
|
540
|
+
const afterMarker = markerIndex === -1 ? "" : sectionBody.slice(markerIndex);
|
|
541
|
+
const trimmedBefore = beforeMarker.trim();
|
|
542
|
+
let updatedBefore;
|
|
543
|
+
if (trimmedBefore === "" ||
|
|
544
|
+
trimmedBefore === "- なし" ||
|
|
545
|
+
trimmedBefore === "なし" ||
|
|
546
|
+
trimmedBefore.includes("_TODO_")) {
|
|
547
|
+
updatedBefore = newLine;
|
|
548
|
+
}
|
|
549
|
+
else {
|
|
550
|
+
updatedBefore = `${trimmedBefore}\n${newLine}`;
|
|
551
|
+
}
|
|
552
|
+
const newSectionBody = afterMarker
|
|
553
|
+
? `\n\n${updatedBefore}\n\n${afterMarker}\n\n`
|
|
554
|
+
: `\n\n${updatedBefore}\n\n`;
|
|
555
|
+
const updated = `${normalized.slice(0, start)}${newSectionBody}${normalized.slice(end)}`;
|
|
556
|
+
return updated.replace(/\n{3,}/g, "\n\n").replace(/\n*$/, "\n");
|
|
557
|
+
}
|
|
558
|
+
const numbers = [...normalized.matchAll(/^##\s+(\d+)\./gm)].map((m) => Number(m[1]));
|
|
559
|
+
const nextNum = numbers.length === 0 ? 1 : Math.max(...numbers) + 1;
|
|
560
|
+
const newLine = `- ${ROOT_NEW_FILES_HANDOFF_LABEL}: ${uniqueFiles.map((f) => `\`${f}\``).join(", ")}`;
|
|
561
|
+
return `${normalized.trimEnd()}\n\n## ${nextNum}. 申し送り\n\n${newLine}\n`;
|
|
562
|
+
}
|
|
563
|
+
export function recordRootNewFilesHandoff(resultPath, files) {
|
|
564
|
+
if (!resultPath || !existsSync(resultPath) || files.length === 0)
|
|
565
|
+
return false;
|
|
566
|
+
try {
|
|
567
|
+
const content = readFileSync(resultPath, "utf8");
|
|
568
|
+
const updated = applyRootNewFilesHandoff(content, files);
|
|
569
|
+
if (updated === content)
|
|
570
|
+
return false;
|
|
571
|
+
writeFileSync(resultPath, updated, "utf8");
|
|
572
|
+
return true;
|
|
573
|
+
}
|
|
574
|
+
catch {
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
// Commit the task result and deliverable changes inside the worktree onto its exec branch.
|
|
579
|
+
// The commit is limited to the mode-based allowlist (resolveCommitScope); out-of-scope
|
|
580
|
+
// changes stay uncommitted in the worktree and are reported. Excludes plans, events,
|
|
581
|
+
// generated files, and other tasks' results (see isCommitTargetPath).
|
|
582
|
+
export function commitWorktreeChanges(params) {
|
|
583
|
+
const { context, worktree, taskId } = params;
|
|
584
|
+
assertNoAgentProtectedConfigChanges(context, worktree, taskId);
|
|
585
|
+
if (!params.productsIntegratedByCaller)
|
|
586
|
+
assertNoPendingProductChanges(worktree);
|
|
587
|
+
let partition = partitionCommitTargets(context, worktree, taskId);
|
|
588
|
+
const scopeWarnings = [
|
|
589
|
+
...partition.unresolvedTargets.map((target) => `commit-scope: unresolved target doc id (not committable): ${target}\n`),
|
|
590
|
+
...(partition.outOfScope.length > 0
|
|
591
|
+
? [
|
|
592
|
+
`commit-scope: skipped non-target changes (left in worktree):\n${partition.outOfScope
|
|
593
|
+
.map((path) => ` ${path}`)
|
|
594
|
+
.join("\n")}\n`,
|
|
595
|
+
]
|
|
596
|
+
: []),
|
|
597
|
+
];
|
|
598
|
+
for (const warning of scopeWarnings)
|
|
599
|
+
process.stdout.write(warning);
|
|
600
|
+
if (scopeWarnings.length > 0 && params.scopeLogPath && !params.dryRun) {
|
|
601
|
+
mkdirSync(resolve(params.scopeLogPath, ".."), { recursive: true });
|
|
602
|
+
appendFileSync(params.scopeLogPath, scopeWarnings.join(""), "utf8");
|
|
603
|
+
// 追記したログ自体を commit 対象に含めるため、分類をやり直す。
|
|
604
|
+
partition = partitionCommitTargets(context, worktree, taskId);
|
|
605
|
+
}
|
|
606
|
+
const { resultRel } = taskPaths(context, taskId);
|
|
607
|
+
const trackedAtHead = pathsTrackedAtHead(worktree.path, partition.targets);
|
|
608
|
+
const projectRootNewFiles = partition.targets.filter((path) => !path.includes("/") && !trackedAtHead.has(path) && path !== resultRel);
|
|
609
|
+
if (projectRootNewFiles.length > 0) {
|
|
610
|
+
const rootNewWarning = `最上位に追加したファイル:\n` +
|
|
611
|
+
`${projectRootNewFiles.map((path) => ` ${path}`).join("\n")}\n`;
|
|
612
|
+
process.stdout.write(rootNewWarning);
|
|
613
|
+
if (params.scopeLogPath && !params.dryRun) {
|
|
614
|
+
mkdirSync(resolve(params.scopeLogPath, ".."), { recursive: true });
|
|
615
|
+
appendFileSync(params.scopeLogPath, rootNewWarning, "utf8");
|
|
616
|
+
partition = partitionCommitTargets(context, worktree, taskId);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
const allRootNewFiles = [...(params.productRootNewFiles ?? []), ...projectRootNewFiles];
|
|
620
|
+
if (allRootNewFiles.length > 0 && !params.dryRun) {
|
|
621
|
+
const resultPath = resolve(worktree.path, resultRel);
|
|
622
|
+
if (recordRootNewFilesHandoff(resultPath, allRootNewFiles)) {
|
|
623
|
+
partition = partitionCommitTargets(context, worktree, taskId);
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
const paths = partition.targets;
|
|
627
|
+
if (paths.length === 0) {
|
|
628
|
+
process.stdout.write("No commit-target changes.\n");
|
|
629
|
+
return { targets: [], committed: false };
|
|
630
|
+
}
|
|
631
|
+
assertNoAgentReadyPromotion(context, worktree, taskId, paths);
|
|
632
|
+
process.stdout.write(`commit-targets:\n${paths.map((path) => ` ${path}`).join("\n")}\n`);
|
|
633
|
+
if (params.dryRun)
|
|
634
|
+
return { targets: paths, committed: false };
|
|
635
|
+
assertResultMarkdownlint(context, worktree, taskId);
|
|
636
|
+
stageCommitTargets(worktree.path, paths);
|
|
637
|
+
const stagedArgs = ["diff", "--cached", "--quiet", "--", ...paths];
|
|
638
|
+
const staged = gitResult(worktree.path, stagedArgs);
|
|
639
|
+
if (staged.status === 0) {
|
|
640
|
+
process.stdout.write("No staged commit-target changes.\n");
|
|
641
|
+
return { targets: paths, committed: false };
|
|
642
|
+
}
|
|
643
|
+
if (staged.status !== 1) {
|
|
644
|
+
appendGitResultFailureLog(params.failureLogPath, "git diff staged worktree inspection", staged);
|
|
645
|
+
throw new Error(`Failed to inspect staged worktree changes: ${formatGitResultFailure(stagedArgs, staged)}`);
|
|
646
|
+
}
|
|
647
|
+
const commitArgs = [
|
|
648
|
+
"commit",
|
|
649
|
+
"-m",
|
|
650
|
+
params.message?.trim() || `exec(${taskId}): apply task changes`,
|
|
651
|
+
"--",
|
|
652
|
+
...paths,
|
|
653
|
+
];
|
|
654
|
+
const commit = gitResult(worktree.path, commitArgs);
|
|
655
|
+
if (commit.status !== 0) {
|
|
656
|
+
const output = [commit.stdout, commit.stderr]
|
|
657
|
+
.filter((part) => typeof part === "string" && part.length > 0)
|
|
658
|
+
.join("\n");
|
|
659
|
+
appendGitFailureLog(params.failureLogPath, [
|
|
660
|
+
`=== ${new Date().toISOString()} git commit task changes ===`,
|
|
661
|
+
`exit: ${commit.status ?? "unknown"}`,
|
|
662
|
+
"--- stdout ---",
|
|
663
|
+
typeof commit.stdout === "string" ? commit.stdout : "",
|
|
664
|
+
"--- stderr ---",
|
|
665
|
+
typeof commit.stderr === "string" ? commit.stderr : "",
|
|
666
|
+
"",
|
|
667
|
+
]);
|
|
668
|
+
throw new Error(`git commit failed: ${summarizeGitHookFailure(output)}`);
|
|
669
|
+
}
|
|
670
|
+
stabilizeCommitTargets(worktree.path, () => commitTargetPaths(context, worktree, taskId), undefined, params.failureLogPath);
|
|
671
|
+
return { targets: paths, committed: true };
|
|
672
|
+
}
|