specdojo 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +280 -0
  3. package/README.md +143 -30
  4. package/dist/agent-response.js +20 -0
  5. package/dist/agent.js +4 -4
  6. package/dist/build-command.js +28 -8
  7. package/dist/dashboard.js +140 -9
  8. package/dist/devcontainer-command.js +43 -0
  9. package/dist/devcontainer-scaffold.js +165 -0
  10. package/dist/exec-agent-config.js +107 -9
  11. package/dist/exec-agent-git-state.js +18 -0
  12. package/dist/exec-agent-protected-config.js +46 -8
  13. package/dist/exec-evidence.js +254 -11
  14. package/dist/exec-format.js +13 -4
  15. package/dist/exec-handoff.js +336 -0
  16. package/dist/exec-parent-validation.js +317 -43
  17. package/dist/exec-pipeline-state.js +74 -9
  18. package/dist/exec-plans.js +115 -113
  19. package/dist/exec-protection-handoff.js +43 -2
  20. package/dist/exec-provider-scaffold.js +247 -15
  21. package/dist/exec-register-resume.js +65 -19
  22. package/dist/exec-register.js +9 -3
  23. package/dist/exec-repo-integration.js +811 -0
  24. package/dist/exec-repo-trace.js +182 -0
  25. package/dist/exec-reporter.js +613 -132
  26. package/dist/exec-results.js +81 -56
  27. package/dist/exec-run-lock.js +110 -107
  28. package/dist/exec-run.js +1585 -356
  29. package/dist/exec-shared.js +7 -0
  30. package/dist/exec-slot-lock.js +242 -0
  31. package/dist/exec-task-repos.js +415 -0
  32. package/dist/exec-trial.js +51 -25
  33. package/dist/exec-worktree-command.js +87 -43
  34. package/dist/exec-worktree-ops.js +502 -57
  35. package/dist/exec-worktree.js +114 -27
  36. package/dist/exec.js +13 -6
  37. package/dist/grade-result.js +128 -0
  38. package/dist/grade.js +809 -72
  39. package/dist/init-command.js +443 -0
  40. package/dist/job.js +160 -10
  41. package/dist/orchestrator.js +213 -0
  42. package/dist/package-paths.js +19 -1
  43. package/dist/register-event-merge.js +169 -0
  44. package/dist/register-item.js +7 -1
  45. package/dist/register.js +294 -86
  46. package/dist/review-grade.js +252 -0
  47. package/dist/review-plan.js +111 -1
  48. package/dist/review-types.js +40 -1
  49. package/dist/routine.js +72 -5
  50. package/dist/schedule-build.js +2 -2
  51. package/dist/schedule.js +17 -4
  52. package/dist/specdojo-config.js +466 -20
  53. package/dist/specdojo-gitignore.js +135 -0
  54. package/dist/specdojo.js +8 -1
  55. package/dist/viewpoint-document-kinds-check.js +128 -0
  56. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  57. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  58. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  59. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  60. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  61. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  62. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  63. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  64. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  65. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  66. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  67. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  68. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  69. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  70. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  71. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  72. package/docs/ja/specdojo/guides/exec-config-guide.md +91 -47
  73. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  74. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  75. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  76. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +25 -4
  77. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  78. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  79. package/docs/ja/specdojo/guides/quick-start-guide.md +261 -32
  80. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  81. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  82. package/docs/ja/specdojo/guides/remote-host-development-guide.md +184 -0
  83. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  84. package/docs/ja/specdojo/guides/routine-operation-guide.md +74 -9
  85. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  86. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  87. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  88. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  89. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  90. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  91. package/docs/ja/specdojo/index.md +2 -2
  92. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  93. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  94. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  95. package/docs/ja/specdojo/references/command-reference.md +336 -93
  96. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  97. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  98. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  99. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  100. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  101. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  102. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  103. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  104. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  105. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  106. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  107. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  108. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  109. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  110. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  111. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  112. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  113. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  114. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  115. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  116. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  117. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  118. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  119. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  120. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  121. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  122. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  123. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  124. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  125. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  126. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  127. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  128. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  129. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  130. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  131. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  132. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  133. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  134. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  135. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  136. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  137. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  138. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  139. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  140. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  141. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  142. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  143. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  144. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  145. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  146. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  147. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  148. package/package.json +16 -9
  149. package/templates/antigravity/README.md +60 -0
  150. package/templates/antigravity/agent-members-snippet.yaml +61 -0
  151. package/templates/antigravity/exec-defaults-snippet.yaml +39 -0
  152. package/templates/antigravity/orchestrator.md +157 -0
  153. package/templates/antigravity/settings.global.json +55 -0
  154. package/templates/claude/agents/claude-executor.md +14 -0
  155. package/templates/claude/agents/claude-reporter.md +16 -0
  156. package/templates/claude/agents/specdojo-orchestrator.md +164 -0
  157. package/templates/claude/settings.edit.json +27 -1
  158. package/templates/codex/README.md +5 -4
  159. package/templates/codex/agents/specdojo-orchestrator.toml +165 -0
  160. package/templates/codex/orchestrator.md +157 -0
  161. package/templates/copilot/README.md +7 -5
  162. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  163. package/templates/devcontainer/devcontainer.json +27 -0
  164. package/templates/devcontainer/emacs/init.el +88 -0
  165. package/templates/devcontainer/post-create.sh +62 -0
  166. package/templates/init-agent-members.yaml +200 -0
  167. package/templates/init-exec-defaults.yaml +72 -0
  168. package/templates/opencode/agents/specdojo-orchestrator.md +204 -0
  169. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  170. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -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
+ }