specdojo 0.2.1 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/agents/specdojo-orchestrator.md +165 -0
- package/CHANGELOG.md +298 -0
- package/README.md +92 -42
- package/dist/agent-response.js +20 -0
- package/dist/agent.js +4 -4
- package/dist/build-command.js +28 -8
- package/dist/catalog-build-references.js +144 -0
- package/dist/catalog-build-render.js +144 -0
- package/dist/catalog-build.js +13 -290
- package/dist/catalog-generate.js +6 -9
- package/dist/catalog-plan-generate.js +2 -2
- package/dist/catalog-plan.js +6 -6
- package/dist/catalog-scaffold.js +4 -4
- package/dist/catalog.js +2 -2
- package/dist/dashboard-exec-records.js +105 -0
- package/dist/dashboard-routines.js +255 -0
- package/dist/dashboard-shared.js +14 -0
- package/dist/dashboard-timeline.js +175 -0
- package/dist/dashboard.js +31 -444
- package/dist/deliverable-trash.js +3 -3
- package/dist/devcontainer-command.js +43 -0
- package/dist/devcontainer-scaffold.js +165 -0
- package/dist/doc-index.js +3 -3
- package/dist/exec-agent-config.js +107 -9
- package/dist/exec-agent-git-state.js +18 -0
- package/dist/exec-agent-protected-config.js +46 -8
- package/dist/exec-commands.js +557 -0
- package/dist/exec-core.js +457 -0
- package/dist/exec-evidence.js +254 -11
- package/dist/exec-handoff.js +336 -0
- package/dist/exec-parent-validation.js +317 -43
- package/dist/exec-pipeline-state.js +74 -9
- package/dist/exec-plans-core.js +693 -0
- package/dist/exec-plans-generation.js +206 -0
- package/dist/exec-plans-storage.js +131 -0
- package/dist/exec-plans.js +3 -1016
- package/dist/exec-protection-handoff.js +43 -2
- package/dist/exec-provider-scaffold.js +247 -15
- package/dist/exec-register-resume.js +65 -19
- package/dist/exec-register.js +9 -3
- package/dist/exec-repo-integration-git.js +23 -0
- package/dist/exec-repo-integration-sync.js +264 -0
- package/dist/exec-repo-integration.js +534 -0
- package/dist/exec-repo-trace.js +182 -0
- package/dist/exec-reporter-output.js +206 -0
- package/dist/exec-reporter.js +525 -248
- package/dist/exec-results.js +103 -71
- package/dist/exec-run-agent-pipeline.js +256 -0
- package/dist/exec-run-agent.js +531 -0
- package/dist/exec-run-in-place.js +541 -0
- package/dist/exec-run-job.js +717 -0
- package/dist/exec-run-lifecycle-commands.js +522 -0
- package/dist/exec-run-lock.js +110 -107
- package/dist/exec-run-mode-shared.js +140 -0
- package/dist/exec-run-register-command.js +244 -0
- package/dist/exec-run-register-core.js +386 -0
- package/dist/exec-run-register-mode.js +206 -0
- package/dist/exec-run-register-resume.js +393 -0
- package/dist/exec-run-register-state.js +322 -0
- package/dist/exec-run-register-worktree.js +509 -0
- package/dist/exec-run-schedule-mode.js +294 -0
- package/dist/exec-run-schedule-prepare.js +353 -0
- package/dist/exec-run-schedule-task.js +572 -0
- package/dist/exec-run-shared.js +399 -0
- package/dist/exec-run.js +11 -4953
- package/dist/exec-shared.js +9 -2
- package/dist/exec-slot-lock.js +242 -0
- package/dist/exec-task-repos.js +415 -0
- package/dist/exec-trial-commands.js +558 -0
- package/dist/exec-trial-core.js +371 -0
- package/dist/exec-trial.js +2 -895
- package/dist/exec-worktree-command.js +87 -43
- package/dist/exec-worktree-ops-commit.js +707 -0
- package/dist/exec-worktree-ops-lifecycle.js +292 -0
- package/dist/exec-worktree-ops-merge.js +303 -0
- package/dist/exec-worktree-ops.js +3 -847
- package/dist/exec-worktree.js +146 -31
- package/dist/exec.js +2 -999
- package/dist/frontmatter-namespace.js +2 -2
- 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-markdown.js +274 -0
- package/dist/grade-pipeline-state.js +184 -0
- package/dist/grade-plan.js +507 -0
- package/dist/grade-result.js +133 -5
- package/dist/grade-target-discovery.js +265 -0
- package/dist/grade-targets.js +432 -0
- package/dist/grade.js +14 -2451
- package/dist/init-command.js +443 -0
- package/dist/job-definition.js +670 -0
- package/dist/job.js +64 -578
- package/dist/kata-command.js +2 -2
- package/dist/orchestrator.js +213 -0
- package/dist/register-command-types.js +1 -0
- package/dist/register-core.js +363 -0
- package/dist/register-create-commands.js +245 -0
- package/dist/register-event-merge.js +169 -0
- package/dist/register-events.js +4 -4
- package/dist/register-item.js +13 -7
- package/dist/register-maintenance-commands.js +187 -0
- package/dist/register-migration.js +268 -0
- package/dist/register-renumber.js +314 -0
- package/dist/register-transition-commands.js +248 -0
- package/dist/register-update.js +230 -0
- package/dist/register-views.js +256 -0
- package/dist/register.js +175 -1975
- package/dist/review-grade.js +252 -0
- package/dist/review-plan.js +114 -4
- package/dist/review-types.js +40 -1
- package/dist/routine-definition.js +401 -0
- package/dist/routine.js +73 -402
- package/dist/schedule-approach.js +2 -2
- package/dist/schedule-build.js +2 -2
- package/dist/schedule-strategy-generate-document.js +273 -0
- package/dist/schedule-strategy-generate-scope.js +199 -0
- package/dist/schedule-strategy-generate.js +9 -473
- package/dist/schedule.js +19 -6
- package/dist/specdojo-config.js +465 -20
- package/dist/specdojo-gitignore.js +135 -0
- package/dist/specdojo.js +6 -0
- package/dist/viewpoint-document-kinds-check.js +128 -0
- package/dist/yaml-pages.js +4 -4
- package/dist/yaml.js +28 -0
- package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
- package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
- package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
- package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
- package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
- package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
- package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
- package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
- package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
- package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
- package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
- package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
- package/docs/ja/specdojo/guides/exec-config-guide.md +93 -49
- package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
- package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
- package/docs/ja/specdojo/guides/kata-guide.md +4 -4
- package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +45 -22
- package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
- package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
- package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
- package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
- package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
- package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
- package/docs/ja/specdojo/guides/review-guide.md +195 -158
- package/docs/ja/specdojo/guides/routine-operation-guide.md +75 -10
- package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
- package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
- package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
- package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
- package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
- package/docs/ja/specdojo/guides/waza-guide.md +15 -2
- package/docs/ja/specdojo/index.md +2 -2
- package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
- package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
- package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
- package/docs/ja/specdojo/references/command-reference.md +335 -92
- package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
- package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
- package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
- package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
- package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
- package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
- package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
- package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
- package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
- package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
- package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
- package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
- package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
- package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
- package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
- package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
- package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
- package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
- package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
- package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
- package/docs/ja/specdojo/samples/bps-sample.md +74 -21
- package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
- package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
- package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
- package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
- package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
- package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
- package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
- package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
- package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
- package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
- package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
- package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
- package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
- package/docs/ja/specdojo/templates/bps-template.md +91 -0
- package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
- package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
- package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
- package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
- package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
- package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
- package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
- package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
- package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
- package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
- package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
- package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
- package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
- package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
- package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
- package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
- package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
- package/package.json +17 -12
- package/templates/antigravity/README.md +29 -4
- package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
- package/templates/antigravity/exec-defaults-snippet.yaml +10 -7
- package/templates/antigravity/orchestrator.md +18 -7
- package/templates/antigravity/settings.global.json +55 -0
- package/templates/claude/agents/claude-executor.md +14 -0
- package/templates/claude/agents/claude-reporter.md +16 -0
- package/templates/claude/agents/specdojo-orchestrator.md +18 -7
- package/templates/claude/settings.edit.json +27 -1
- package/templates/codex/README.md +5 -4
- package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
- package/templates/codex/orchestrator.md +18 -7
- package/templates/copilot/README.md +7 -5
- package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
- package/templates/devcontainer/devcontainer.json +27 -0
- package/templates/devcontainer/emacs/init.el +88 -0
- package/templates/devcontainer/post-create.sh +62 -0
- package/templates/init-agent-members.yaml +200 -0
- package/templates/init-exec-defaults.yaml +74 -0
- package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
- package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
- package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
package/dist/exec-evidence.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, join, relative, sep } from "node:path";
|
|
3
|
-
import { ensureDir, safeSlug } from "./exec-shared.js";
|
|
3
|
+
import { ensureDir, redactSensitiveText, safeSlug } from "./exec-shared.js";
|
|
4
4
|
import { gitOutput } from "./exec-worktree.js";
|
|
5
5
|
const MAX_LOG_BYTES = 64 * 1024;
|
|
6
6
|
const MAX_CHANGE_FILES = 1_000;
|
|
@@ -29,16 +29,21 @@ function boundedLog(value) {
|
|
|
29
29
|
truncated: true,
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
|
-
|
|
33
|
-
export function redactSensitiveText(value) {
|
|
34
|
-
return value
|
|
35
|
-
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/giu, "Bearer [REDACTED]")
|
|
36
|
-
.replace(/\b(sk-(?:proj-)?[A-Za-z0-9_-]{8,}|gh[opsu]_[A-Za-z0-9_]{8,})\b/gu, "[REDACTED]")
|
|
37
|
-
.replace(/\b(api[_-]?key|access[_-]?token|auth(?:orization)?|password|passwd|secret)\b(\s*[:=]\s*)([^\s,;]+)/giu, "$1$2[REDACTED]");
|
|
38
|
-
}
|
|
32
|
+
export { redactSensitiveText } from "./exec-shared.js";
|
|
39
33
|
function boundedText(value, limit) {
|
|
40
34
|
return truncate(redactSensitiveText(typeof value === "string" ? value.trim() : ""), limit);
|
|
41
35
|
}
|
|
36
|
+
function executorBlockReason(status, stderr) {
|
|
37
|
+
if (status === "rate_limited")
|
|
38
|
+
return "executor rate limit reached";
|
|
39
|
+
const lines = stderr
|
|
40
|
+
.split("\n")
|
|
41
|
+
.map((line) => line.trim())
|
|
42
|
+
.filter(Boolean);
|
|
43
|
+
const tagged = lines.find((line) => /^(blocked|review-blocked):/iu.test(line));
|
|
44
|
+
const detail = tagged ?? lines.at(-1);
|
|
45
|
+
return boundedText(detail ? `agent exited with non-zero code: ${detail}` : "agent exited with non-zero code", MAX_VALIDATION_SUMMARY_LENGTH);
|
|
46
|
+
}
|
|
42
47
|
export function parseExecutorReport(stdout) {
|
|
43
48
|
const matches = [...stdout.matchAll(REPORT_PATTERN)];
|
|
44
49
|
const raw = matches.at(-1)?.[1];
|
|
@@ -62,7 +67,12 @@ export function parseExecutorReport(stdout) {
|
|
|
62
67
|
const candidate = item;
|
|
63
68
|
const command = boundedText(candidate.command, MAX_VALIDATION_COMMAND_LENGTH);
|
|
64
69
|
const status = candidate.status;
|
|
65
|
-
if (!command ||
|
|
70
|
+
if (!command ||
|
|
71
|
+
(status !== "passed" &&
|
|
72
|
+
status !== "failed" &&
|
|
73
|
+
status !== "not_run" &&
|
|
74
|
+
status !== "not_applicable" &&
|
|
75
|
+
status !== "requires_human")) {
|
|
66
76
|
continue;
|
|
67
77
|
}
|
|
68
78
|
validations.push({
|
|
@@ -70,6 +80,29 @@ export function parseExecutorReport(stdout) {
|
|
|
70
80
|
command,
|
|
71
81
|
status,
|
|
72
82
|
summary: boundedText(candidate.summary, MAX_VALIDATION_SUMMARY_LENGTH),
|
|
83
|
+
...(status === "not_applicable"
|
|
84
|
+
? { reason: boundedText(candidate.reason, MAX_VALIDATION_SUMMARY_LENGTH) }
|
|
85
|
+
: {}),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
const targetCoverage = [];
|
|
90
|
+
if (Array.isArray(report.target_coverage)) {
|
|
91
|
+
for (const item of report.target_coverage.slice(0, MAX_CHANGE_FILES)) {
|
|
92
|
+
if (!item || typeof item !== "object" || Array.isArray(item))
|
|
93
|
+
continue;
|
|
94
|
+
const candidate = item;
|
|
95
|
+
const target = boundedText(candidate.target, 1_000);
|
|
96
|
+
const status = candidate.status;
|
|
97
|
+
const path = boundedText(candidate.path, 1_000);
|
|
98
|
+
const reason = boundedText(candidate.reason, MAX_VALIDATION_SUMMARY_LENGTH);
|
|
99
|
+
if (!target || (status !== "changed" && status !== "unchanged"))
|
|
100
|
+
continue;
|
|
101
|
+
targetCoverage.push({
|
|
102
|
+
target,
|
|
103
|
+
status,
|
|
104
|
+
...(path ? { path } : {}),
|
|
105
|
+
reason,
|
|
73
106
|
});
|
|
74
107
|
}
|
|
75
108
|
}
|
|
@@ -77,8 +110,141 @@ export function parseExecutorReport(stdout) {
|
|
|
77
110
|
return {
|
|
78
111
|
finalMessage: boundedText(report.final_message ?? fallback, MAX_FINAL_MESSAGE_LENGTH),
|
|
79
112
|
validations,
|
|
113
|
+
targetCoverage,
|
|
80
114
|
};
|
|
81
115
|
}
|
|
116
|
+
function normalizedEvidencePath(value) {
|
|
117
|
+
const normalized = value.replaceAll("\\", "/").replace(/^\.\//u, "");
|
|
118
|
+
if (!normalized ||
|
|
119
|
+
normalized.startsWith("/") ||
|
|
120
|
+
/^[A-Za-z]:\//u.test(normalized) ||
|
|
121
|
+
normalized.split("/").includes("..")) {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
return normalized;
|
|
125
|
+
}
|
|
126
|
+
function changedEvidencePaths(changes) {
|
|
127
|
+
const paths = new Set();
|
|
128
|
+
for (const change of changes) {
|
|
129
|
+
// Rename/copy entries use "old -> new". Either side is sufficient to prove that the target
|
|
130
|
+
// was handled, and both remain repository-relative paths produced by git status.
|
|
131
|
+
for (const value of change.path.split(" -> ")) {
|
|
132
|
+
const normalized = normalizedEvidencePath(value);
|
|
133
|
+
if (normalized)
|
|
134
|
+
paths.add(normalized);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return paths;
|
|
138
|
+
}
|
|
139
|
+
function changeFingerprint(worktreePath, change) {
|
|
140
|
+
const hashes = change.path.split(" -> ").map((path) => {
|
|
141
|
+
try {
|
|
142
|
+
return gitOutput(worktreePath, ["hash-object", "--", path]).trim();
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return "missing";
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
return `${change.status}\0${hashes.join("\0")}`;
|
|
149
|
+
}
|
|
150
|
+
/** Captures bounded fingerprints of the current cumulative worktree diff without storing content. */
|
|
151
|
+
export function snapshotWorktreeChanges(worktreePath, productWorktrees = []) {
|
|
152
|
+
return new Map(repoStatusChanges(worktreePath, productWorktrees)
|
|
153
|
+
.slice(0, MAX_CHANGE_FILES)
|
|
154
|
+
.map((change) => [change.path, changeFingerprint(change.root, change.local)]));
|
|
155
|
+
}
|
|
156
|
+
function qualifyEvidencePath(name, path) {
|
|
157
|
+
// Rename entries are "old -> new"; qualify each side so both stay attributable to the repository.
|
|
158
|
+
return path
|
|
159
|
+
.split(" -> ")
|
|
160
|
+
.map((side) => `${name}:${side}`)
|
|
161
|
+
.join(" -> ");
|
|
162
|
+
}
|
|
163
|
+
// PJR-98G4: プロジェクト worktree の変更は従来どおり相対パス、プロダクト worktree の変更は
|
|
164
|
+
// `<name>:<path>` で記録する。targets・paths の `<repo>:<path>` と同じ書式にそろえる。
|
|
165
|
+
function repoStatusChanges(worktreePath, productWorktrees) {
|
|
166
|
+
return [
|
|
167
|
+
...parseStatusPaths(worktreePath).map((change) => ({
|
|
168
|
+
...change,
|
|
169
|
+
root: worktreePath,
|
|
170
|
+
local: change,
|
|
171
|
+
})),
|
|
172
|
+
...productWorktrees.flatMap((product) => parseStatusPaths(product.path).map((change) => ({
|
|
173
|
+
path: qualifyEvidencePath(product.name, change.path),
|
|
174
|
+
status: change.status,
|
|
175
|
+
root: product.path,
|
|
176
|
+
local: change,
|
|
177
|
+
}))),
|
|
178
|
+
];
|
|
179
|
+
}
|
|
180
|
+
function productDiffStat(productWorktrees) {
|
|
181
|
+
return productWorktrees
|
|
182
|
+
.map((product) => {
|
|
183
|
+
const stat = gitOutput(product.path, ["diff", "--stat", "HEAD", "--"]).trim();
|
|
184
|
+
return stat ? `[${product.name}]\n${stat}` : "";
|
|
185
|
+
})
|
|
186
|
+
.filter(Boolean)
|
|
187
|
+
.join("\n");
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* Validates the stricter completion contract used when an interrupted executor is resumed.
|
|
191
|
+
* A changed target must point at a path present in the cumulative worktree diff; an unchanged
|
|
192
|
+
* target must carry a concrete reason that can be preserved in the result by the reporter path.
|
|
193
|
+
*/
|
|
194
|
+
export function validateResumedTargetCoverage(targets, evidence) {
|
|
195
|
+
const expected = [...new Set(targets.map((target) => target.trim()).filter(Boolean))];
|
|
196
|
+
if (expected.length === 0)
|
|
197
|
+
return { ok: true };
|
|
198
|
+
const coverage = evidence.target_coverage ?? [];
|
|
199
|
+
const byTarget = new Map();
|
|
200
|
+
const duplicates = new Set();
|
|
201
|
+
for (const entry of coverage) {
|
|
202
|
+
if (byTarget.has(entry.target))
|
|
203
|
+
duplicates.add(entry.target);
|
|
204
|
+
else
|
|
205
|
+
byTarget.set(entry.target, entry);
|
|
206
|
+
}
|
|
207
|
+
if (duplicates.size > 0) {
|
|
208
|
+
return {
|
|
209
|
+
ok: false,
|
|
210
|
+
reason: `resumed executor target coverage has duplicate entries: ${[...duplicates].join(", ")}`,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const missing = expected.filter((target) => !byTarget.has(target));
|
|
214
|
+
if (missing.length > 0) {
|
|
215
|
+
return {
|
|
216
|
+
ok: false,
|
|
217
|
+
reason: `resumed executor did not account for every plan target: ${missing.join(", ")}`,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
const changedPaths = changedEvidencePaths(evidence.changes);
|
|
221
|
+
for (const target of expected) {
|
|
222
|
+
const entry = byTarget.get(target);
|
|
223
|
+
if (entry.status === "unchanged") {
|
|
224
|
+
if (!entry.reason.trim()) {
|
|
225
|
+
return {
|
|
226
|
+
ok: false,
|
|
227
|
+
reason: `resumed executor reported an unchanged target without a reason: ${target}`,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
const path = entry.path ? normalizedEvidencePath(entry.path) : null;
|
|
233
|
+
if (!path) {
|
|
234
|
+
return {
|
|
235
|
+
ok: false,
|
|
236
|
+
reason: `resumed executor reported a changed target without a valid repository-relative path: ${target}`,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
if (!changedPaths.has(path)) {
|
|
240
|
+
return {
|
|
241
|
+
ok: false,
|
|
242
|
+
reason: `resumed executor target path is absent from the cumulative worktree diff: ${target} (${path})`,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
return { ok: true };
|
|
247
|
+
}
|
|
82
248
|
function parseStatusPaths(worktreePath) {
|
|
83
249
|
const output = gitOutput(worktreePath, [
|
|
84
250
|
"status",
|
|
@@ -115,6 +281,10 @@ export function buildExecutorEvidence(input) {
|
|
|
115
281
|
path: boundedText(change.path, 1_000),
|
|
116
282
|
status: boundedText(change.status, 40),
|
|
117
283
|
}));
|
|
284
|
+
const attemptChanges = (input.attemptChanges ?? []).slice(0, MAX_CHANGE_FILES).map((change) => ({
|
|
285
|
+
path: boundedText(change.path, 1_000),
|
|
286
|
+
status: boundedText(change.status, 40),
|
|
287
|
+
}));
|
|
118
288
|
const output = `${input.stdout}\n${input.stderr}`.trim();
|
|
119
289
|
const boundedOutput = boundedLog(output);
|
|
120
290
|
const logExcerpt = boundedOutput.content;
|
|
@@ -134,12 +304,17 @@ export function buildExecutorEvidence(input) {
|
|
|
134
304
|
attempts: input.attempts,
|
|
135
305
|
},
|
|
136
306
|
changes,
|
|
307
|
+
...(input.attemptChanges ? { attempt_changes: attemptChanges } : {}),
|
|
137
308
|
diff_summary: {
|
|
138
309
|
files_changed: changes.length,
|
|
139
310
|
summary: truncate(redactSensitiveText(input.diffStat.trim()), MAX_DIFF_SUMMARY_LENGTH),
|
|
140
311
|
},
|
|
141
312
|
validations,
|
|
313
|
+
...(report.targetCoverage.length > 0 ? { target_coverage: report.targetCoverage } : {}),
|
|
142
314
|
final_message: report.finalMessage,
|
|
315
|
+
...(input.status === "succeeded"
|
|
316
|
+
? {}
|
|
317
|
+
: { block_reason: executorBlockReason(input.status, input.stderr) }),
|
|
143
318
|
log_refs: [
|
|
144
319
|
{
|
|
145
320
|
kind: "agent-output-excerpt",
|
|
@@ -160,8 +335,24 @@ export function recordExecutorEvidence(input) {
|
|
|
160
335
|
`${executionRel}/exec/evidence/`,
|
|
161
336
|
`${executionRel}/generated/`,
|
|
162
337
|
];
|
|
163
|
-
const
|
|
164
|
-
const
|
|
338
|
+
const productWorktrees = input.productWorktrees ?? [];
|
|
339
|
+
const repoChanges = repoStatusChanges(input.worktreePath, productWorktrees).filter((change) => change.root !== input.worktreePath ||
|
|
340
|
+
runnerManagedPrefixes.every((prefix) => !change.path.startsWith(prefix)));
|
|
341
|
+
const changesBeforeEvidence = repoChanges.map(({ path, status }) => ({ path, status }));
|
|
342
|
+
// The attempt delta is needed both for interrupted-run target coverage and for telling the
|
|
343
|
+
// reporter which filtered runner-owned records the executor itself changed on a successful run.
|
|
344
|
+
const attemptChanges = input.changesBeforeAttempt
|
|
345
|
+
? repoChanges
|
|
346
|
+
.filter((change) => input.changesBeforeAttempt?.get(change.path) !==
|
|
347
|
+
changeFingerprint(change.root, change.local))
|
|
348
|
+
.map(({ path, status }) => ({ path, status }))
|
|
349
|
+
: undefined;
|
|
350
|
+
const diffStat = [
|
|
351
|
+
gitOutput(input.worktreePath, ["diff", "--stat", "HEAD", "--"]).trimEnd(),
|
|
352
|
+
productDiffStat(productWorktrees),
|
|
353
|
+
]
|
|
354
|
+
.filter(Boolean)
|
|
355
|
+
.join("\n");
|
|
165
356
|
const executionInWorktree = join(input.worktreePath, executionRel);
|
|
166
357
|
const evidenceDir = join(executionInWorktree, "exec", "evidence", safeSlug(input.taskId), safeSlug(input.runId));
|
|
167
358
|
ensureDir(evidenceDir);
|
|
@@ -179,6 +370,7 @@ export function recordExecutorEvidence(input) {
|
|
|
179
370
|
stdout: input.stdout,
|
|
180
371
|
stderr: input.stderr,
|
|
181
372
|
changes: changesBeforeEvidence,
|
|
373
|
+
attemptChanges,
|
|
182
374
|
diffStat,
|
|
183
375
|
logRefPath: repoRelative(input.worktreePath, logPath),
|
|
184
376
|
parentValidations: input.parentValidations,
|
|
@@ -249,6 +441,13 @@ export function recordCommandEvidence(input) {
|
|
|
249
441
|
},
|
|
250
442
|
],
|
|
251
443
|
final_message: `Runner command ${summary}.`,
|
|
444
|
+
...(!succeeded
|
|
445
|
+
? {
|
|
446
|
+
block_reason: input.error
|
|
447
|
+
? `command spawn failed: ${boundedText(input.error, MAX_VALIDATION_SUMMARY_LENGTH)}`
|
|
448
|
+
: `command exited with code ${input.exitCode ?? "unknown"}`,
|
|
449
|
+
}
|
|
450
|
+
: {}),
|
|
252
451
|
command: {
|
|
253
452
|
shell: input.shell,
|
|
254
453
|
value: safeCommand,
|
|
@@ -285,6 +484,50 @@ export function writeExecutorEvidence(path, evidence) {
|
|
|
285
484
|
writeFileSync(temporaryPath, `${JSON.stringify(evidence, null, 2)}\n`, "utf8");
|
|
286
485
|
renameSync(temporaryPath, path);
|
|
287
486
|
}
|
|
487
|
+
/**
|
|
488
|
+
* Persists failed parent-validation output beside executor evidence. A new numbered set is added
|
|
489
|
+
* for every validation batch so reporter/integration resume never overwrites the prior failure.
|
|
490
|
+
*/
|
|
491
|
+
export function recordParentValidationFailureOutput(input) {
|
|
492
|
+
if (input.failureOutputs.length === 0)
|
|
493
|
+
return input.evidence;
|
|
494
|
+
const evidenceDir = dirname(input.evidencePath);
|
|
495
|
+
ensureDir(evidenceDir);
|
|
496
|
+
const priorAttempts = input.evidence.log_refs
|
|
497
|
+
.map((ref) => /^parent-validation-attempt-(\d+)-/u.exec(ref.path.split("/").at(-1) ?? "")?.[1])
|
|
498
|
+
.filter((attempt) => attempt !== undefined)
|
|
499
|
+
.map(Number);
|
|
500
|
+
const attempt = Math.max(0, ...priorAttempts) + 1;
|
|
501
|
+
const refs = [];
|
|
502
|
+
for (const output of input.failureOutputs) {
|
|
503
|
+
const logPath = join(evidenceDir, `parent-validation-attempt-${attempt}-${safeSlug(output.label)}.log`);
|
|
504
|
+
const content = redactSensitiveText([
|
|
505
|
+
`parent validation: ${output.label}`,
|
|
506
|
+
`exit code: ${output.exitCode ?? "unknown"}`,
|
|
507
|
+
`timed out: ${output.timedOut === true ? "yes" : "no"}`,
|
|
508
|
+
...(output.error ? [`spawn error: ${output.error}`] : []),
|
|
509
|
+
"",
|
|
510
|
+
"--- stdout ---",
|
|
511
|
+
output.stdout,
|
|
512
|
+
"",
|
|
513
|
+
"--- stderr ---",
|
|
514
|
+
output.stderr,
|
|
515
|
+
].join("\n"));
|
|
516
|
+
writeFileSync(logPath, content, "utf8");
|
|
517
|
+
refs.push({
|
|
518
|
+
kind: "parent-validation-output",
|
|
519
|
+
path: repoRelative(input.worktreePath, logPath),
|
|
520
|
+
bytes: Buffer.byteLength(content, "utf8"),
|
|
521
|
+
truncated: output.stdoutTruncated === true || output.stderrTruncated === true,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
const evidence = {
|
|
525
|
+
...input.evidence,
|
|
526
|
+
log_refs: [...input.evidence.log_refs, ...refs],
|
|
527
|
+
};
|
|
528
|
+
writeExecutorEvidence(input.evidencePath, evidence);
|
|
529
|
+
return evidence;
|
|
530
|
+
}
|
|
288
531
|
/**
|
|
289
532
|
* Persists the latest failed reporter invocation streams beside executor evidence.
|
|
290
533
|
* Each stream is independently redacted and bounded so stdout/stderr remain distinguishable.
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, lstatSync, mkdtempSync, readFileSync, readdirSync, rmSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { join, posix, resolve } from "node:path";
|
|
6
|
+
import { isAgentProtectedConfigPath } from "./exec-agent-protected-config.js";
|
|
7
|
+
import { PROTECTION_HANDOFF_MARKER } from "./exec-protection-handoff.js";
|
|
8
|
+
import { normalizePjrId, resolveRegisterRunTarget } from "./exec-register.js";
|
|
9
|
+
import { refsTrailer, withCommitTrailers } from "./exec-repo-trace.js";
|
|
10
|
+
import { configuredProductReposForProject } from "./exec-task-repos.js";
|
|
11
|
+
import { parseSpecdojoDocument } from "./frontmatter-namespace.js";
|
|
12
|
+
import { qualifyTaskId } from "./exec-shared.js";
|
|
13
|
+
import { specdojoRootDir } from "./specdojo-config.js";
|
|
14
|
+
import { findExecWorktree, gitEnvironment, gitOutput, gitResult } from "./exec-worktree.js";
|
|
15
|
+
import { stageCommitTargets, stabilizeCommitTargets, unstageCommitTargets, worktreeStatusPaths, } from "./exec-worktree-ops.js";
|
|
16
|
+
const HANDOFF_MECHANISM = "agent-config-write";
|
|
17
|
+
const TRUNCATED_EVIDENCE_RE = /^\.\.\. \((?:\d+ 行を省略|文字数上限で切り詰め)\)$/m;
|
|
18
|
+
function sectionAfterMarker(content) {
|
|
19
|
+
const marker = content.lastIndexOf(PROTECTION_HANDOFF_MARKER);
|
|
20
|
+
if (marker < 0)
|
|
21
|
+
throw new Error("The latest result has no protection handoff.");
|
|
22
|
+
const rest = content.slice(marker);
|
|
23
|
+
const nextHeading = /^##\s+/m.exec(rest.slice(PROTECTION_HANDOFF_MARKER.length));
|
|
24
|
+
return nextHeading ? rest.slice(0, PROTECTION_HANDOFF_MARKER.length + nextHeading.index) : rest;
|
|
25
|
+
}
|
|
26
|
+
/** Extract the machine-recorded protected-config subjects and fenced proposed patch. */
|
|
27
|
+
export function extractProtectedConfigHandoff(content) {
|
|
28
|
+
const section = sectionAfterMarker(content);
|
|
29
|
+
if (!section.includes(`\`${HANDOFF_MECHANISM}\``)) {
|
|
30
|
+
throw new Error(`The latest protection handoff is not ${HANDOFF_MECHANISM}.`);
|
|
31
|
+
}
|
|
32
|
+
const subjectLine = section.match(/^- 対象パス:\s*(.+)$/m)?.[1] ?? "";
|
|
33
|
+
const subjects = [...subjectLine.matchAll(/`([^`]+)`/g)].map((match) => match[1].trim());
|
|
34
|
+
if (subjects.length === 0)
|
|
35
|
+
throw new Error("The protection handoff has no target paths.");
|
|
36
|
+
const lines = section.split(/\r?\n/);
|
|
37
|
+
const label = lines.findIndex((line) => line.trim() === "提案差分:");
|
|
38
|
+
if (label < 0)
|
|
39
|
+
throw new Error("The protection handoff has no proposed patch.");
|
|
40
|
+
const fenceStart = lines.findIndex((line, index) => index > label && /^`{3,}diff$/.test(line));
|
|
41
|
+
if (fenceStart < 0)
|
|
42
|
+
throw new Error("The protection handoff has no applicable proposed patch.");
|
|
43
|
+
const fence = lines[fenceStart].slice(0, -"diff".length);
|
|
44
|
+
const fenceEnd = lines.findIndex((line, index) => index > fenceStart && line === fence);
|
|
45
|
+
if (fenceEnd < 0)
|
|
46
|
+
throw new Error("The proposed patch fence is incomplete.");
|
|
47
|
+
const patch = lines
|
|
48
|
+
.slice(fenceStart + 1, fenceEnd)
|
|
49
|
+
.join("\n")
|
|
50
|
+
.trimEnd();
|
|
51
|
+
if (!patch)
|
|
52
|
+
throw new Error("The protection handoff has an empty proposed patch.");
|
|
53
|
+
if (TRUNCATED_EVIDENCE_RE.test(patch)) {
|
|
54
|
+
throw new Error("The proposed patch was truncated and cannot be applied safely.");
|
|
55
|
+
}
|
|
56
|
+
return { subjects, patch: `${patch}\n` };
|
|
57
|
+
}
|
|
58
|
+
function latestResultForTask(executionPath, taskId) {
|
|
59
|
+
const resultsDir = join(executionPath, "exec", "results");
|
|
60
|
+
if (!existsSync(resultsDir))
|
|
61
|
+
throw new Error(`Result directory not found: ${resultsDir}`);
|
|
62
|
+
const candidates = readdirSync(resultsDir)
|
|
63
|
+
.filter((name) => name.endsWith("-result.md"))
|
|
64
|
+
.flatMap((name) => {
|
|
65
|
+
const path = join(resultsDir, name);
|
|
66
|
+
const data = parseSpecdojoDocument(readFileSync(path, "utf8")).data;
|
|
67
|
+
if (data.task_id !== taskId)
|
|
68
|
+
return [];
|
|
69
|
+
return [{ path, startedAt: typeof data.started_at === "string" ? data.started_at : "" }];
|
|
70
|
+
})
|
|
71
|
+
.sort((left, right) => left.startedAt === right.startedAt
|
|
72
|
+
? left.path.localeCompare(right.path)
|
|
73
|
+
: left.startedAt.localeCompare(right.startedAt));
|
|
74
|
+
const latest = candidates.at(-1);
|
|
75
|
+
if (!latest)
|
|
76
|
+
throw new Error(`No result found for ${taskId}.`);
|
|
77
|
+
return latest.path;
|
|
78
|
+
}
|
|
79
|
+
function splitPatchByRepo(patch, knownRepos) {
|
|
80
|
+
const sections = new Map();
|
|
81
|
+
let repo = "project";
|
|
82
|
+
sections.set(repo, []);
|
|
83
|
+
for (const line of patch.split("\n")) {
|
|
84
|
+
const header = /^# repo: ([a-z0-9-]+)$/.exec(line);
|
|
85
|
+
if (header) {
|
|
86
|
+
if (!knownRepos.has(header[1])) {
|
|
87
|
+
throw new Error(`The proposed patch names an undeclared repository: ${header[1]}`);
|
|
88
|
+
}
|
|
89
|
+
repo = header[1];
|
|
90
|
+
if (!sections.has(repo))
|
|
91
|
+
sections.set(repo, []);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
sections.get(repo).push(line);
|
|
95
|
+
}
|
|
96
|
+
return new Map([...sections.entries()]
|
|
97
|
+
.map(([name, lines]) => [name, `${lines.join("\n").replace(/^\n+|\n+$/g, "")}\n`])
|
|
98
|
+
.filter(([, body]) => body.trim() !== ""));
|
|
99
|
+
}
|
|
100
|
+
function runGitApply(repoRoot, args, patch) {
|
|
101
|
+
const temporaryDir = mkdtempSync(join(tmpdir(), "specdojo-handoff-"));
|
|
102
|
+
const patchPath = join(temporaryDir, "proposed.patch");
|
|
103
|
+
try {
|
|
104
|
+
writeFileSync(patchPath, patch, "utf8");
|
|
105
|
+
return spawnSync("git", ["-C", resolve(repoRoot), "apply", ...args, patchPath], {
|
|
106
|
+
cwd: resolve(repoRoot),
|
|
107
|
+
env: gitEnvironment(),
|
|
108
|
+
encoding: "utf8",
|
|
109
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
finally {
|
|
113
|
+
rmSync(temporaryDir, { recursive: true, force: true });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function gitApplyError(result) {
|
|
117
|
+
return (result.error?.message ||
|
|
118
|
+
(typeof result.stderr === "string" ? result.stderr.trim() : "") ||
|
|
119
|
+
`git apply exited with ${result.status ?? "unknown"}`);
|
|
120
|
+
}
|
|
121
|
+
function patchPaths(repoRoot, patch) {
|
|
122
|
+
if (/^(?:rename|copy) (?:from|to) /m.test(patch)) {
|
|
123
|
+
throw new Error("Rename and copy patches are not supported by handoff apply.");
|
|
124
|
+
}
|
|
125
|
+
const result = runGitApply(repoRoot, ["--numstat", "-z"], patch);
|
|
126
|
+
if (result.error || result.status !== 0)
|
|
127
|
+
throw new Error(gitApplyError(result));
|
|
128
|
+
const stdout = typeof result.stdout === "string" ? result.stdout : "";
|
|
129
|
+
const paths = stdout
|
|
130
|
+
.split("\0")
|
|
131
|
+
.filter(Boolean)
|
|
132
|
+
.map((record) => {
|
|
133
|
+
const firstTab = record.indexOf("\t");
|
|
134
|
+
const secondTab = firstTab < 0 ? -1 : record.indexOf("\t", firstTab + 1);
|
|
135
|
+
if (secondTab < 0)
|
|
136
|
+
throw new Error("Could not read a path from the proposed patch.");
|
|
137
|
+
return record.slice(secondTab + 1);
|
|
138
|
+
});
|
|
139
|
+
if (paths.length === 0)
|
|
140
|
+
throw new Error("The proposed patch contains no file changes.");
|
|
141
|
+
for (const path of paths) {
|
|
142
|
+
const normalized = posix.normalize(path.replaceAll("\\", "/"));
|
|
143
|
+
if (path !== normalized ||
|
|
144
|
+
posix.isAbsolute(normalized) ||
|
|
145
|
+
normalized === ".." ||
|
|
146
|
+
normalized.startsWith("../")) {
|
|
147
|
+
throw new Error(`The proposed patch contains an unsafe path: ${path}`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return [...new Set(paths)].sort();
|
|
151
|
+
}
|
|
152
|
+
function qualifiedSubject(name, path) {
|
|
153
|
+
return name ? `${name}:${path}` : path;
|
|
154
|
+
}
|
|
155
|
+
function assertSubjectCoverage(handoff, patches) {
|
|
156
|
+
const subjects = [...new Set(handoff.subjects)].sort();
|
|
157
|
+
const patchSubjects = patches
|
|
158
|
+
.flatMap((repo) => repo.paths.map((path) => qualifiedSubject(repo.name, path)))
|
|
159
|
+
.sort();
|
|
160
|
+
if (subjects.join("\0") !== patchSubjects.join("\0")) {
|
|
161
|
+
throw new Error(`The proposed patch paths do not match the handoff targets (targets: ${subjects.join(", ")}; patch: ${patchSubjects.join(", ")}).`);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function assertCleanPaths(repo) {
|
|
165
|
+
const status = gitOutput(repo.root, [
|
|
166
|
+
"status",
|
|
167
|
+
"--porcelain=v1",
|
|
168
|
+
"--untracked-files=all",
|
|
169
|
+
"--",
|
|
170
|
+
...repo.paths,
|
|
171
|
+
]).trim();
|
|
172
|
+
if (status) {
|
|
173
|
+
throw new Error(`${repo.name ?? "project"} has existing changes on handoff paths; commit or restore them first: ${repo.paths.join(", ")}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function commitSubject(itemId) {
|
|
177
|
+
return `exec(handoff ${itemId}): apply protected configuration`;
|
|
178
|
+
}
|
|
179
|
+
function applyAndCommit(repo, message) {
|
|
180
|
+
const applied = runGitApply(repo.root, [], repo.patch);
|
|
181
|
+
if (applied.error || applied.status !== 0)
|
|
182
|
+
throw new Error(gitApplyError(applied));
|
|
183
|
+
try {
|
|
184
|
+
stageCommitTargets(repo.root, repo.paths);
|
|
185
|
+
const staged = gitResult(repo.root, ["diff", "--cached", "--quiet", "--", ...repo.paths]);
|
|
186
|
+
if (staged.status !== 1) {
|
|
187
|
+
if (staged.status === 0)
|
|
188
|
+
throw new Error("The proposed patch produced no staged change.");
|
|
189
|
+
throw new Error("Could not inspect the staged handoff change.");
|
|
190
|
+
}
|
|
191
|
+
const commit = gitResult(repo.root, ["commit", "-m", message, "--", ...repo.paths]);
|
|
192
|
+
if (commit.status !== 0) {
|
|
193
|
+
const output = [commit.stdout, commit.stderr]
|
|
194
|
+
.filter((value) => typeof value === "string" && value.trim() !== "")
|
|
195
|
+
.join("\n");
|
|
196
|
+
throw new Error(output || "git commit failed");
|
|
197
|
+
}
|
|
198
|
+
stabilizeCommitTargets(repo.root, () => worktreeStatusPaths(repo.root).filter((path) => repo.paths.includes(path)));
|
|
199
|
+
return gitOutput(repo.root, ["rev-parse", "--short", "HEAD"]).trim();
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
unstageCommitTargets(repo.root, repo.paths);
|
|
203
|
+
// The paths were clean before application, so restoring this exact allowlist cannot discard
|
|
204
|
+
// pre-existing user work. It also removes formatting changes made by a failed commit hook.
|
|
205
|
+
const tracked = [];
|
|
206
|
+
for (const path of repo.paths) {
|
|
207
|
+
if (gitResult(repo.root, ["cat-file", "-e", `HEAD:${path}`]).status === 0) {
|
|
208
|
+
tracked.push(path);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const absolute = resolve(repo.root, path);
|
|
212
|
+
if (lstatSync(absolute, { throwIfNoEntry: false })?.isFile())
|
|
213
|
+
unlinkSync(absolute);
|
|
214
|
+
}
|
|
215
|
+
if (tracked.length > 0) {
|
|
216
|
+
gitOutput(repo.root, [
|
|
217
|
+
"restore",
|
|
218
|
+
"--source=HEAD",
|
|
219
|
+
"--staged",
|
|
220
|
+
"--worktree",
|
|
221
|
+
"--",
|
|
222
|
+
...tracked,
|
|
223
|
+
]);
|
|
224
|
+
}
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async function confirmed(options) {
|
|
229
|
+
if (options.yes)
|
|
230
|
+
return true;
|
|
231
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
232
|
+
throw new Error("Confirmation is required; inspect the patch above and rerun with --yes.");
|
|
233
|
+
}
|
|
234
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
235
|
+
try {
|
|
236
|
+
const answer = (await prompt.question("Apply and commit this protected configuration? [y/N]: "))
|
|
237
|
+
.trim()
|
|
238
|
+
.toLowerCase();
|
|
239
|
+
return answer === "y" || answer === "yes";
|
|
240
|
+
}
|
|
241
|
+
finally {
|
|
242
|
+
prompt.close();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
export async function applyRegisterProtectionHandoff(options) {
|
|
246
|
+
const itemId = normalizePjrId(options.register);
|
|
247
|
+
const root = specdojoRootDir();
|
|
248
|
+
const projectId = options.project?.trim() || undefined;
|
|
249
|
+
const { registerPaths, item } = resolveRegisterRunTarget(projectId ?? "", itemId);
|
|
250
|
+
if (item.status !== "waiting") {
|
|
251
|
+
throw new Error(`${itemId} must be waiting before its protection handoff can be applied.`);
|
|
252
|
+
}
|
|
253
|
+
const worktree = findExecWorktree(root, qualifyTaskId(registerPaths.projectId, itemId));
|
|
254
|
+
if (!worktree)
|
|
255
|
+
throw new Error(`No blocked exec worktree found for ${itemId}.`);
|
|
256
|
+
if (resolve(worktree.path) === resolve(root)) {
|
|
257
|
+
throw new Error("Run handoff apply from the integration checkout, not the task worktree.");
|
|
258
|
+
}
|
|
259
|
+
const resultPath = latestResultForTask(registerPaths.executionPath ?? "", itemId);
|
|
260
|
+
const handoff = extractProtectedConfigHandoff(readFileSync(resultPath, "utf8"));
|
|
261
|
+
const products = configuredProductReposForProject(registerPaths.projectId);
|
|
262
|
+
const productByName = new Map(products.map((product) => [product.name, product]));
|
|
263
|
+
const sections = splitPatchByRepo(handoff.patch, new Set(productByName.keys()));
|
|
264
|
+
const patches = [];
|
|
265
|
+
for (const [name, patch] of sections) {
|
|
266
|
+
const product = name === "project" ? undefined : productByName.get(name);
|
|
267
|
+
if (name !== "project" && !product)
|
|
268
|
+
throw new Error(`Unknown repository in patch: ${name}`);
|
|
269
|
+
const repoRoot = product?.repoRoot ?? root;
|
|
270
|
+
if (product?.integrationBranch) {
|
|
271
|
+
const branch = gitOutput(repoRoot, ["branch", "--show-current"]).trim();
|
|
272
|
+
if (branch !== product.integrationBranch) {
|
|
273
|
+
throw new Error(`${name} must have integration branch ${product.integrationBranch} checked out (current: ${branch || "detached"}).`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
const paths = patchPaths(repoRoot, patch);
|
|
277
|
+
for (const path of paths) {
|
|
278
|
+
if (!isAgentProtectedConfigPath(path)) {
|
|
279
|
+
throw new Error(`The proposed patch contains a non-protected path: ${name}:${path}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
patches.push({ ...(name === "project" ? {} : { name }), root: repoRoot, patch, paths });
|
|
283
|
+
}
|
|
284
|
+
if (patches.length === 0)
|
|
285
|
+
throw new Error("The protection handoff has no applicable repository patch.");
|
|
286
|
+
assertSubjectCoverage(handoff, patches);
|
|
287
|
+
for (const repo of patches) {
|
|
288
|
+
assertCleanPaths(repo);
|
|
289
|
+
const checked = runGitApply(repo.root, ["--check"], repo.patch);
|
|
290
|
+
if (checked.error || checked.status !== 0) {
|
|
291
|
+
throw new Error(`${repo.name ?? "project"}: proposed patch does not apply: ${gitApplyError(checked)}`);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
process.stdout.write(`Protection handoff: ${itemId}\nSource: ${resultPath}\n\n${handoff.patch}`);
|
|
295
|
+
if (!(await confirmed(options))) {
|
|
296
|
+
process.stdout.write("Handoff application cancelled; no changes were made.\n");
|
|
297
|
+
return { applied: false, commits: [] };
|
|
298
|
+
}
|
|
299
|
+
const message = withCommitTrailers(commitSubject(itemId), [
|
|
300
|
+
refsTrailer(registerPaths.projectId, itemId),
|
|
301
|
+
]);
|
|
302
|
+
const commits = [];
|
|
303
|
+
// Product configuration is committed before project configuration, matching normal integration.
|
|
304
|
+
patches.sort((left, right) => (left.name ? 0 : 1) - (right.name ? 0 : 1));
|
|
305
|
+
for (const repo of patches) {
|
|
306
|
+
const sha = applyAndCommit(repo, message);
|
|
307
|
+
const name = repo.name ?? "project";
|
|
308
|
+
commits.push({ repo: name, sha });
|
|
309
|
+
process.stdout.write(`Committed ${name}: ${sha}\n`);
|
|
310
|
+
}
|
|
311
|
+
if (patches.some((repo) => repo.paths.some((path) => path.endsWith("package.json")))) {
|
|
312
|
+
process.stdout.write("If dependency declarations changed, regenerate and commit the matching lock file before resuming.\n");
|
|
313
|
+
}
|
|
314
|
+
process.stdout.write(`Resume with: specdojo exec run --project ${registerPaths.projectId} --register ${itemId} --worktree --resume\n`);
|
|
315
|
+
return { applied: true, commits };
|
|
316
|
+
}
|
|
317
|
+
export function registerExecHandoffCommands(exec) {
|
|
318
|
+
const handoff = exec
|
|
319
|
+
.command("handoff")
|
|
320
|
+
.description("Inspect and apply protected-configuration handoffs");
|
|
321
|
+
const apply = handoff
|
|
322
|
+
.command("apply")
|
|
323
|
+
.description("Apply a blocked register run's proposed protected-configuration patch");
|
|
324
|
+
apply.option("--project <projectId>", "Project id in .specdojo/specdojo.config.json");
|
|
325
|
+
apply.requiredOption("--register <pjrId>", "Project register item ID (PJR-XXXX)");
|
|
326
|
+
apply.option("--yes", "Apply and commit after printing the proposed patch", false);
|
|
327
|
+
apply.action(async (options) => {
|
|
328
|
+
try {
|
|
329
|
+
await applyRegisterProtectionHandoff(options);
|
|
330
|
+
}
|
|
331
|
+
catch (error) {
|
|
332
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
333
|
+
process.exitCode = 1;
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
}
|