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
package/dist/job.js CHANGED
@@ -24,7 +24,7 @@ function validStringList(value) {
24
24
  value.length > 0 &&
25
25
  value.every((item) => typeof item === "string" && item.trim()));
26
26
  }
27
- // Same nickname shape as pm-members.schema.yaml. The roster is not loaded here, so a
27
+ // Same nickname shape as agent-members.schema.yaml. The roster is not loaded here, so a
28
28
  // definition only guarantees the format; an unknown nickname fails when the Run resolves
29
29
  // the agent command.
30
30
  function isAgentNickname(value) {
@@ -35,21 +35,22 @@ function isJobAgentDefinition(value) {
35
35
  isAgentNickname(value.executor) &&
36
36
  (value.reporter === undefined || isAgentNickname(value.reporter)));
37
37
  }
38
- // Parses task.agent and reports why it was rejected. Unknown keys are refused so a typo
39
- // (for example `reporters`) cannot silently drop the reporter stage.
40
- function parseJobAgent(value) {
38
+ // Parses task.agent (or another nomination such as task.review.agent) and reports why it was
39
+ // rejected. Unknown keys are refused so a typo (for example `reporters`) cannot silently drop
40
+ // the reporter stage.
41
+ function parseJobAgent(value, fieldName = "task.agent") {
41
42
  if (!isRecord(value)) {
42
- return { error: "task.agent must be a mapping with executor and optional reporter" };
43
+ return { error: `${fieldName} must be a mapping with executor and optional reporter` };
43
44
  }
44
45
  const unknownKeys = Object.keys(value).filter((key) => key !== "executor" && key !== "reporter");
45
46
  if (unknownKeys.length > 0) {
46
- return { error: `task.agent has unknown key(s): ${unknownKeys.sort().join(", ")}` };
47
+ return { error: `${fieldName} has unknown key(s): ${unknownKeys.sort().join(", ")}` };
47
48
  }
48
49
  if (!isAgentNickname(value.executor)) {
49
- return { error: "task.agent.executor must be an agent nickname from pm-members.yaml" };
50
+ return { error: `${fieldName}.executor must be an agent nickname from agent-members.yaml` };
50
51
  }
51
52
  if (value.reporter !== undefined && !isAgentNickname(value.reporter)) {
52
- return { error: "task.agent.reporter must be an agent nickname from pm-members.yaml" };
53
+ return { error: `${fieldName}.reporter must be an agent nickname from agent-members.yaml` };
53
54
  }
54
55
  return {
55
56
  agent: {
@@ -58,6 +59,70 @@ function parseJobAgent(value) {
58
59
  },
59
60
  };
60
61
  }
62
+ // Parses task.review. The mapping itself is the declaration; an empty mapping declares the
63
+ // reviewed integration without pinning agents, which are then auto selected.
64
+ function parseJobReview(value) {
65
+ if (!isRecord(value)) {
66
+ return { errors: ["task.review must be a mapping with an optional agent"] };
67
+ }
68
+ const errors = [];
69
+ const unknownKeys = Object.keys(value).filter((key) => key !== "agent");
70
+ if (unknownKeys.length > 0) {
71
+ errors.push(`task.review has unknown key(s): ${unknownKeys.sort().join(", ")}`);
72
+ }
73
+ let agent;
74
+ if (value.agent !== undefined) {
75
+ const parsed = parseJobAgent(value.agent, "task.review.agent");
76
+ if (parsed.error)
77
+ errors.push(parsed.error);
78
+ agent = parsed.agent;
79
+ }
80
+ if (errors.length > 0)
81
+ return { errors };
82
+ return { review: agent ? { agent } : {}, errors };
83
+ }
84
+ function isJobReviewDefinition(value) {
85
+ return isRecord(value) && (value.agent === undefined || isJobAgentDefinition(value.agent));
86
+ }
87
+ /** True when the Job declares that its Run output is reviewed before integration. */
88
+ export function jobDeclaresReview(definition) {
89
+ return definition.task.review !== undefined;
90
+ }
91
+ /**
92
+ * Resolves the review agent nicknames of a Job Run review. The order is the CLI flag
93
+ * (`--review-by` / `--reporter-by`), then the Job's task.review.agent, then auto selection
94
+ * (an undefined entry means the caller auto selects).
95
+ */
96
+ export function resolveJobReviewAgentNominations(cli, definition) {
97
+ const nominate = (cliValue, jobValue) => {
98
+ const fromCli = cliValue?.trim();
99
+ if (fromCli)
100
+ return { nickname: fromCli, source: "cli" };
101
+ const fromJob = jobValue?.trim();
102
+ if (fromJob)
103
+ return { nickname: fromJob, source: "job" };
104
+ return undefined;
105
+ };
106
+ const agent = definition.task.review?.agent;
107
+ const executor = nominate(cli.reviewBy, agent?.executor);
108
+ const reporter = nominate(cli.reporterBy, agent?.reporter);
109
+ return {
110
+ ...(executor ? { executor } : {}),
111
+ ...(reporter ? { reporter } : {}),
112
+ };
113
+ }
114
+ /**
115
+ * Decides whether a Job Run takes the reviewed integration path (exec worktree, runner
116
+ * commit, review, merge by verdict). The Job's task.review declaration wins over the
117
+ * caller: a declared Job is always reviewed, and `--worktree` (passed by a routine with the
118
+ * legacy `action.commit: true`) still opts an undeclared Job in for compatibility. The child
119
+ * process that executes the Job inside the worktree never re-enters this path.
120
+ */
121
+ export function jobRunUsesReviewedIntegration(definition, opts) {
122
+ if (opts.isWorktreeChild)
123
+ return false;
124
+ return jobDeclaresReview(definition) || !!opts.worktree;
125
+ }
61
126
  function isJobRunState(value) {
62
127
  return value === "running" || value === "succeeded" || value === "failed" || value === "noop";
63
128
  }
@@ -68,6 +133,8 @@ function isJobTaskDefinition(value) {
68
133
  return false;
69
134
  if (!["targets", "paths"].every((field) => value[field] === undefined || validStringList(value[field])))
70
135
  return false;
136
+ if (value.review !== undefined && !isJobReviewDefinition(value.review))
137
+ return false;
71
138
  if (value.mode === "command") {
72
139
  return (typeof value.command === "string" &&
73
140
  (value.precondition === undefined ||
@@ -100,6 +167,23 @@ function isJobRunAttempt(value) {
100
167
  value.exit_code === null ||
101
168
  typeof value.exit_code === "number"));
102
169
  }
170
+ function isJobRunReview(value) {
171
+ return (isRecord(value) &&
172
+ typeof value.plan_ref === "string" &&
173
+ typeof value.result_ref === "string" &&
174
+ typeof value.reviewed_at === "string" &&
175
+ typeof value.branch === "string" &&
176
+ (value.verdict === undefined ||
177
+ [
178
+ "complete",
179
+ "complete-with-findings",
180
+ "incomplete",
181
+ "grade-stale",
182
+ "grade-unavailable",
183
+ "changed-during-review",
184
+ ].includes(String(value.verdict))) &&
185
+ (value.reason === undefined || typeof value.reason === "string"));
186
+ }
103
187
  function isJobRunRecord(value) {
104
188
  if (!isRecord(value))
105
189
  return false;
@@ -122,6 +206,7 @@ function isJobRunRecord(value) {
122
206
  isJobTaskDefinition(value.task) &&
123
207
  isRecord(value.checkpoint_before) &&
124
208
  (value.checkpoint_after === undefined || isRecord(value.checkpoint_after)) &&
209
+ (value.review === undefined || isJobRunReview(value.review)) &&
125
210
  Array.isArray(value.attempts) &&
126
211
  value.attempts.every(isJobRunAttempt));
127
212
  }
@@ -131,6 +216,9 @@ function readJobRunRecord(filePath) {
131
216
  throw new Error(`Invalid Job Run file: ${filePath}`);
132
217
  return raw;
133
218
  }
219
+ export function loadJobRunRecord(filePath) {
220
+ return readJobRunRecord(filePath);
221
+ }
134
222
  function validateJobInputValue(value, input, key) {
135
223
  const values = input.type === "list" ? value : [value];
136
224
  if (input.enum) {
@@ -274,10 +362,17 @@ export function parseJobDefinition(value, fileName) {
274
362
  errors.push("task.paths must be a non-empty string list");
275
363
  if (value.task.owner !== undefined && typeof value.task.owner !== "string")
276
364
  errors.push("task.owner must be a string");
365
+ let review;
366
+ if (value.task.review !== undefined) {
367
+ const parsedReview = parseJobReview(value.task.review);
368
+ errors.push(...parsedReview.errors);
369
+ review = parsedReview.review;
370
+ }
277
371
  const common = {
278
372
  ...(targets ? { targets: targets.map((target) => target.trim()) } : {}),
279
373
  ...(paths ? { paths: paths.map((path) => path.trim()) } : {}),
280
374
  ...(typeof value.task.owner === "string" ? { owner: value.task.owner.trim() } : {}),
375
+ ...(review ? { review } : {}),
281
376
  };
282
377
  if (mode === "command") {
283
378
  const command = typeof value.task.command === "string" ? value.task.command.trim() : "";
@@ -323,7 +418,7 @@ export function parseJobDefinition(value, fileName) {
323
418
  errors.push(`task.analysis has unknown key(s): ${unknownAnalysisKeys.sort().join(", ")}`);
324
419
  }
325
420
  if (!isAgentNickname(value.task.analysis.agent)) {
326
- errors.push("task.analysis.agent must be an agent nickname from pm-members.yaml");
421
+ errors.push("task.analysis.agent must be an agent nickname from agent-members.yaml");
327
422
  }
328
423
  const analysisDescription = typeof value.task.analysis.description === "string"
329
424
  ? value.task.analysis.description.trim()
@@ -770,7 +865,7 @@ function jobPlanFrontmatter(projectId, definition, record) {
770
865
  "type: exec-plan",
771
866
  "rulebook: none",
772
867
  `task_id: ${record.run_id}`,
773
- `name: "${definition.name.replaceAll('"', "'")}"`,
868
+ `name: ${JSON.stringify(definition.name)}`,
774
869
  // A command Run's plan is consumed only by the optional analysis reporter. Exec result
775
870
  // frontmatter intentionally keeps the existing edit/review vocabulary for compatibility.
776
871
  `mode: ${isJobCommandTask(record.task) ? "edit" : record.task.mode}`,
@@ -839,6 +934,61 @@ export async function generateJobPlan(paths, definition, record) {
839
934
  await formatMarkdownFile(planPath);
840
935
  return planPath;
841
936
  }
937
+ function jobReviewPlanFrontmatter(projectId, definition, record) {
938
+ return buildSpecdojoFrontmatter([
939
+ `id: ${projectId}:xrp-${record.run_id.toLowerCase()}-review`,
940
+ "type: exec-plan",
941
+ "rulebook: none",
942
+ `task_id: ${record.run_id}-review`,
943
+ `name: ${JSON.stringify(`${definition.name} の実行結果レビュー`)}`,
944
+ "mode: review",
945
+ "status: ready",
946
+ `project_id: ${projectId}`,
947
+ "origin: job",
948
+ `job_id: ${definition.id}`,
949
+ `run_id: ${record.run_id}`,
950
+ ]);
951
+ }
952
+ export async function generateJobReviewPlan(paths, definition, record, opts) {
953
+ const templatePath = execTemplatePath("xrp-job-template.md");
954
+ if (!existsSync(templatePath))
955
+ throw new Error(`Template not found: ${templatePath}`);
956
+ const planPath = join(paths.executionPath, "exec", "plans", `${record.run_id}-review-plan.md`);
957
+ const resultPath = join(paths.executionPath, "exec", "results", `${record.run_id}-review-result.md`);
958
+ mkdirSync(resolve(planPath, ".."), { recursive: true });
959
+ const values = {
960
+ _FRONTMATTER_: jobReviewPlanFrontmatter(paths.projectId, definition, record),
961
+ _JOB_ID_: definition.id,
962
+ _JOB_NAME_: definition.name,
963
+ _RUN_ID_: record.run_id,
964
+ _RUN_STATE_: record.state,
965
+ _BRANCH_: opts.branch,
966
+ _BASE_COMMIT_: opts.baseCommit,
967
+ _OUTPUT_COMMIT_: opts.outputCommit,
968
+ _JOB_DESCRIPTION_: definition.description ?? "-",
969
+ _ANALYSIS_DESCRIPTION_: isJobCommandTask(record.task)
970
+ ? (record.task.analysis?.description ?? "コマンドの終了結果と出力を確認する。")
971
+ : record.task.description,
972
+ _RESULT_REF_: repoRelative(resultPath),
973
+ _RUN_RESULT_REF_: repoRelative(join(paths.executionPath, record.result_ref)),
974
+ };
975
+ const body = expandTemplate(readFileSync(templatePath, "utf8"), values);
976
+ const content = injectCommonConventions(body, MISSING, new Map(), "review");
977
+ writeFileSync(planPath, content, "utf8");
978
+ await formatMarkdownFile(planPath);
979
+ return { planPath, resultPath };
980
+ }
981
+ export function recordJobRunReview(runPath, review) {
982
+ const record = readJobRunRecord(runPath);
983
+ const reviewedAt = review.reviewed_at ?? new Date().toISOString();
984
+ const updated = {
985
+ ...record,
986
+ updated_at: reviewedAt,
987
+ review: { ...review, reviewed_at: reviewedAt },
988
+ };
989
+ writeJson(runPath, updated);
990
+ return updated;
991
+ }
842
992
  export async function materializeJobRun(opts) {
843
993
  const paths = resolveJobPaths(opts.projectId);
844
994
  const definition = loadJobDefinition(paths, opts.jobId);
@@ -0,0 +1,213 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants as osConstants } from "node:os";
3
+ import { resolve } from "node:path";
4
+ import { agentExtraRootArguments, resolveProductRepos } from "./exec-task-repos.js";
5
+ import { loadConfig, specdojoRootDir, } from "./specdojo-config.js";
6
+ const ORCHESTRATOR_EXECUTABLES = {
7
+ claude: "claude",
8
+ codex: "codex",
9
+ antigravity: "agy",
10
+ copilot: "copilot",
11
+ opencode: "opencode",
12
+ };
13
+ function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function resolveOrchestratorProjectId(config, projectOption, env) {
17
+ const projectId = projectOption?.trim() ||
18
+ env.SPECDOJO_PROJECT?.trim() ||
19
+ config.current_project?.trim() ||
20
+ Object.keys(config.projects)[0];
21
+ if (!projectId) {
22
+ throw new Error("No project specified. Use --project <id>, SPECDOJO_PROJECT, current_project, or define a project.");
23
+ }
24
+ if (!config.projects[projectId]) {
25
+ throw new Error(`Unknown project: ${projectId}`);
26
+ }
27
+ return projectId;
28
+ }
29
+ function opencodeAgentName(args) {
30
+ let selected;
31
+ for (let index = 0; index < args.length; index += 1) {
32
+ const arg = args[index];
33
+ if (arg === "--agent") {
34
+ selected = args[index + 1];
35
+ index += 1;
36
+ }
37
+ else if (arg.startsWith("--agent=")) {
38
+ selected = arg.slice("--agent=".length);
39
+ }
40
+ }
41
+ if (!selected?.trim()) {
42
+ throw new Error("OpenCode orchestrator launch requires --agent <name> so repository permissions can be scoped to that agent.");
43
+ }
44
+ return selected.trim();
45
+ }
46
+ function inlineOpenCodeConfig(current, agentName, repoRoots) {
47
+ let config = {};
48
+ if (current?.trim()) {
49
+ let parsed;
50
+ try {
51
+ parsed = JSON.parse(current);
52
+ }
53
+ catch (error) {
54
+ const message = error instanceof Error ? error.message : String(error);
55
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: ${message}`);
56
+ }
57
+ if (!isRecord(parsed)) {
58
+ throw new Error("Invalid OPENCODE_CONFIG_CONTENT: top-level value must be an object");
59
+ }
60
+ config = parsed;
61
+ }
62
+ const agents = config.agent === undefined ? {} : config.agent;
63
+ if (!isRecord(agents)) {
64
+ throw new Error("Invalid OPENCODE_CONFIG_CONTENT: agent must be an object");
65
+ }
66
+ const selectedAgent = agents[agentName] === undefined ? {} : agents[agentName];
67
+ if (!isRecord(selectedAgent)) {
68
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: agent.${agentName} must be an object`);
69
+ }
70
+ const permission = selectedAgent.permission === undefined ? {} : selectedAgent.permission;
71
+ if (!isRecord(permission)) {
72
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: agent.${agentName}.permission must be an object`);
73
+ }
74
+ const externalDirectory = { "*": "deny" };
75
+ const currentEdit = permission.edit;
76
+ let edit = {};
77
+ if (isRecord(currentEdit)) {
78
+ edit = { ...currentEdit };
79
+ }
80
+ else if (typeof currentEdit === "string") {
81
+ edit = { "*": currentEdit };
82
+ }
83
+ else if (currentEdit !== undefined) {
84
+ throw new Error(`Invalid OPENCODE_CONFIG_CONTENT: agent.${agentName}.permission.edit must be a string or object`);
85
+ }
86
+ for (const repoRoot of repoRoots) {
87
+ const pattern = `${resolve(repoRoot).replaceAll("\\", "/")}/**`;
88
+ externalDirectory[pattern] = "allow";
89
+ edit[pattern] = "allow";
90
+ }
91
+ return JSON.stringify({
92
+ ...config,
93
+ agent: {
94
+ ...agents,
95
+ [agentName]: {
96
+ ...selectedAgent,
97
+ permission: {
98
+ ...permission,
99
+ external_directory: externalDirectory,
100
+ edit,
101
+ },
102
+ },
103
+ },
104
+ });
105
+ }
106
+ export function buildOrchestratorLaunch(options) {
107
+ const env = { ...(options.env ?? process.env) };
108
+ const args = [...options.providerArgs];
109
+ if (options.provider === "opencode" && options.repoRoots.length > 0) {
110
+ env.OPENCODE_CONFIG_CONTENT = inlineOpenCodeConfig(env.OPENCODE_CONFIG_CONTENT, opencodeAgentName(args), options.repoRoots);
111
+ }
112
+ else {
113
+ args.push(...agentExtraRootArguments(options.provider, options.repoRoots));
114
+ }
115
+ return {
116
+ command: ORCHESTRATOR_EXECUTABLES[options.provider],
117
+ args,
118
+ cwd: options.cwd,
119
+ env,
120
+ };
121
+ }
122
+ export function resolveOrchestratorLaunch(options) {
123
+ const env = options.env ?? process.env;
124
+ const rootDir = specdojoRootDir();
125
+ const { config, configPath } = loadConfig();
126
+ if (!config)
127
+ throw new Error(`No config found: ${configPath}`);
128
+ const projectId = resolveOrchestratorProjectId(config, options.project, env);
129
+ const repos = resolveProductRepos(rootDir, config.projects[projectId]);
130
+ return buildOrchestratorLaunch({
131
+ provider: options.provider,
132
+ providerArgs: options.providerArgs,
133
+ repoRoots: repos.map((repo) => repo.repoRoot),
134
+ cwd: rootDir,
135
+ env,
136
+ });
137
+ }
138
+ function parseProvider(value) {
139
+ if (Object.hasOwn(ORCHESTRATOR_EXECUTABLES, value)) {
140
+ return value;
141
+ }
142
+ throw new Error(`Unknown orchestrator provider: ${value}. Available: ${Object.keys(ORCHESTRATOR_EXECUTABLES).join(", ")}`);
143
+ }
144
+ export async function runOrchestratorLaunch(launch, spawnProcess = spawn, signalProcess = process) {
145
+ return await new Promise((resolveExit, reject) => {
146
+ const spawnOptions = {
147
+ cwd: launch.cwd,
148
+ env: launch.env,
149
+ stdio: "inherit",
150
+ };
151
+ const child = spawnProcess(launch.command, launch.args, spawnOptions);
152
+ const signalHandlers = [];
153
+ let settled = false;
154
+ const addSignalHandler = (signal, handler) => {
155
+ signalHandlers.push([signal, handler]);
156
+ signalProcess.on(signal, handler);
157
+ };
158
+ const cleanupSignalHandlers = () => {
159
+ for (const [signal, handler] of signalHandlers) {
160
+ signalProcess.off(signal, handler);
161
+ }
162
+ };
163
+ const settle = (callback) => {
164
+ if (settled)
165
+ return;
166
+ settled = true;
167
+ cleanupSignalHandlers();
168
+ callback();
169
+ };
170
+ addSignalHandler("SIGINT", () => undefined);
171
+ addSignalHandler("SIGQUIT", () => undefined);
172
+ for (const signal of ["SIGTERM", "SIGHUP"]) {
173
+ addSignalHandler(signal, () => {
174
+ child.kill(signal);
175
+ });
176
+ }
177
+ child.once("error", (error) => {
178
+ settle(() => reject(error));
179
+ });
180
+ child.once("exit", (code, signal) => {
181
+ settle(() => {
182
+ resolveExit(code ?? (signal ? 128 + osConstants.signals[signal] : 0));
183
+ });
184
+ });
185
+ });
186
+ }
187
+ export function registerOrchestratorCommands(program) {
188
+ const orchestrator = program
189
+ .command("orchestrator")
190
+ .description("Launch an interactive orchestrator with declared repository access");
191
+ orchestrator
192
+ .command("launch")
193
+ .description("Launch a provider CLI and allow only repositories declared by the project")
194
+ .requiredOption("--provider <name>", "Provider CLI (antigravity|claude|codex|copilot|opencode)")
195
+ .option("--project <projectId>", "Project id in specdojo.config.json")
196
+ .argument("[providerArgs...]", "Provider arguments; put them after --")
197
+ .action(async (providerArgs, opts) => {
198
+ try {
199
+ const launch = resolveOrchestratorLaunch({
200
+ provider: parseProvider(opts.provider),
201
+ providerArgs,
202
+ project: opts.project,
203
+ });
204
+ const exitCode = await runOrchestratorLaunch(launch);
205
+ if (exitCode !== 0)
206
+ process.exitCode = exitCode;
207
+ }
208
+ catch (error) {
209
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
210
+ process.exitCode = 1;
211
+ }
212
+ });
213
+ }
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs";
1
2
  import path from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  // このモジュールは開発時は src/、npm 配布時は dist/ 直下にある。
@@ -7,9 +8,26 @@ import { fileURLToPath } from "node:url";
7
8
  // 持たない構成では、モジュール位置から求めた package が自動で参照されるため、単体テストの
8
9
  // 一時ディレクトリが開発リポジトリの kata へ解決されてしまう。テストと検証では、この変数へ
9
10
  // 一時ディレクトリを指定して解決範囲を閉じる。
11
+ function moduleRelativePackageRoot() {
12
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
13
+ }
10
14
  export function specdojoPackageRootDir() {
11
15
  const override = process.env.SPECDOJO_PACKAGE_ROOT;
12
16
  if (override && override.trim() !== "")
13
17
  return path.resolve(override);
14
- return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
18
+ return moduleRelativePackageRoot();
19
+ }
20
+ function isRecord(value) {
21
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22
+ }
23
+ // CLI が報告する版。`package.json` を唯一の出所とし、`npm version` の更新へ自動で追従する。
24
+ // SPECDOJO_PACKAGE_ROOT は kata の参照先を差し替えるための変数であり、実行中の CLI 自身の
25
+ // 版とは無関係なため、ここでは参照しない。
26
+ export function specdojoPackageVersion() {
27
+ const packageJsonPath = path.join(moduleRelativePackageRoot(), "package.json");
28
+ const parsed = JSON.parse(readFileSync(packageJsonPath, "utf8"));
29
+ if (isRecord(parsed) && typeof parsed.version === "string" && parsed.version !== "") {
30
+ return parsed.version;
31
+ }
32
+ throw new Error(`version を読み取れません: ${packageJsonPath}`);
15
33
  }
@@ -0,0 +1,169 @@
1
+ // 統合 merge で登録簿の記帳ファイルが競合したときの解決処理。イベントファイルは追記型の記録なので、
2
+ // 両側のイベントの和集合(同一 id は 1 件)を時刻順に並べ、`previous_event_id` の連鎖を張り直す。
3
+ // 個票は exec branch 側を基準にし、統合先だけにあるイベントが変えたフィールドのうち、frontmatter の
4
+ // 単純な値へ写せるもの(type / priority / owner / due)だけをイベントから再構築する。
5
+ import { readRegisterEventsFromContent, serializeRegisterEvents, } from "./register-events.js";
6
+ import { applyRegisterItemFields, CELL_NONE, CELL_TODO, REMOVE_REGISTER_ITEM_FIELD, } from "./register-item.js";
7
+ function hasStatusChange(event) {
8
+ return event.changes.some((change) => change.field === "status");
9
+ }
10
+ // 両側とも古い順に並んでいる前提で、時刻順を保って 1 本にまとめる。同じ id は exec branch 側
11
+ // (theirs)の内容を採用して 1 件にする。同時刻の別イベントは、直前に出力したイベントを参照して
12
+ // いる側を優先し、判断できなければ統合先(ours)を先にする。
13
+ function interleaveEvents(ours, theirs) {
14
+ const theirsById = new Map(theirs.map((event) => [event.id, event]));
15
+ const emitted = new Set();
16
+ const merged = [];
17
+ let oursIndex = 0;
18
+ let theirsIndex = 0;
19
+ const emit = (event) => {
20
+ emitted.add(event.id);
21
+ merged.push(theirsById.get(event.id) ?? event);
22
+ };
23
+ while (oursIndex < ours.length || theirsIndex < theirs.length) {
24
+ const left = ours[oursIndex];
25
+ const right = theirs[theirsIndex];
26
+ if (left && emitted.has(left.id)) {
27
+ oursIndex += 1;
28
+ continue;
29
+ }
30
+ if (right && emitted.has(right.id)) {
31
+ theirsIndex += 1;
32
+ continue;
33
+ }
34
+ if (!left || !right) {
35
+ const next = left ?? right;
36
+ if (!next)
37
+ break;
38
+ emit(next);
39
+ if (left)
40
+ oursIndex += 1;
41
+ else
42
+ theirsIndex += 1;
43
+ continue;
44
+ }
45
+ if (left.id === right.id) {
46
+ emit(right);
47
+ oursIndex += 1;
48
+ theirsIndex += 1;
49
+ continue;
50
+ }
51
+ const lastId = merged.at(-1)?.id;
52
+ const takeRight = right.ts < left.ts ||
53
+ (right.ts === left.ts &&
54
+ right.previous_event_id === lastId &&
55
+ left.previous_event_id !== lastId);
56
+ if (takeRight) {
57
+ emit(right);
58
+ theirsIndex += 1;
59
+ }
60
+ else {
61
+ emit(left);
62
+ oursIndex += 1;
63
+ }
64
+ }
65
+ return merged;
66
+ }
67
+ // 和集合で並べたイベントの連鎖を張り直す。統合先だけにある状態を変えないイベント(`update` など)は、
68
+ // 並べ替え後の直前の状態を引き継ぐ。状態遷移の連続性が崩れる場合(統合先だけに状態遷移がある
69
+ // など)は、和集合では解決できないとして理由を返す。
70
+ function relinkEvents(events, oursOnlyIds, source) {
71
+ const relinked = [];
72
+ let previous;
73
+ for (const original of events) {
74
+ const event = { ...original };
75
+ delete event.previous_event_id;
76
+ if (previous) {
77
+ event.previous_event_id = previous.id;
78
+ if (oursOnlyIds.has(event.id) && !hasStatusChange(event)) {
79
+ event.from_status = previous.to_status;
80
+ event.to_status = previous.to_status;
81
+ }
82
+ if (event.from_status !== previous.to_status) {
83
+ return (`${source}: event ${event.id} starts at ${event.from_status ?? "null"} ` +
84
+ `but follows ${previous.to_status} after the union`);
85
+ }
86
+ }
87
+ else if (event.from_status !== null) {
88
+ return `${source}: first event ${event.id} after the union is not an add event`;
89
+ }
90
+ relinked.push(event);
91
+ previous = event;
92
+ }
93
+ return relinked;
94
+ }
95
+ // 統合先(ours)と exec branch(theirs)のイベントファイルを和集合で合わせる。
96
+ export function unionRegisterEventLogs(oursContent, theirsContent, source) {
97
+ let ours;
98
+ let theirs;
99
+ try {
100
+ ours = readRegisterEventsFromContent(oursContent, `${source} (ours)`);
101
+ theirs = readRegisterEventsFromContent(theirsContent, `${source} (theirs)`);
102
+ }
103
+ catch (error) {
104
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };
105
+ }
106
+ const theirsIds = new Set(theirs.map((event) => event.id));
107
+ const oursOnlyIds = new Set(ours.filter((event) => !theirsIds.has(event.id)).map((event) => event.id));
108
+ const relinked = relinkEvents(interleaveEvents(ours, theirs), oursOnlyIds, source);
109
+ if (typeof relinked === "string")
110
+ return { ok: false, reason: relinked };
111
+ return {
112
+ ok: true,
113
+ content: serializeRegisterEvents(relinked),
114
+ events: relinked,
115
+ oursOnlyIds,
116
+ };
117
+ }
118
+ // イベントの変更値を個票 frontmatter の値へ写す。本文(title / description)、状態遷移に伴う
119
+ // フィールド(status / block_reason / conclusion / completed)、表示用に暦日へ変換された
120
+ // registered は、イベントから元の値を復元できないため対象外とする。
121
+ function fieldUpdateFromChange(change) {
122
+ const value = change.to.trim();
123
+ const isUnset = value === "" || value === CELL_NONE || value === CELL_TODO;
124
+ switch (change.field) {
125
+ case "type":
126
+ return isUnset ? undefined : { item_type: value };
127
+ case "priority":
128
+ return isUnset ? undefined : { priority: value };
129
+ case "owner":
130
+ return { owner: isUnset ? null : value };
131
+ case "due":
132
+ return {
133
+ due_on: value === CELL_TODO
134
+ ? REMOVE_REGISTER_ITEM_FIELD
135
+ : value === CELL_NONE || value === ""
136
+ ? null
137
+ : value,
138
+ };
139
+ default:
140
+ return undefined;
141
+ }
142
+ }
143
+ // exec branch 側の個票へ、統合先だけにあるイベントの変更を反映する。同じフィールドを後から
144
+ // exec branch 側のイベントが変えている場合は、後の変更(exec branch 側)を残す。
145
+ export function rebuildRegisterTicketFromEvents(theirsTicketContent, events, oursOnlyIds) {
146
+ const lastWriter = new Map();
147
+ for (const event of events) {
148
+ for (const change of event.changes) {
149
+ lastWriter.set(change.field, { oursOnly: oursOnlyIds.has(event.id), change });
150
+ }
151
+ }
152
+ let updates = {};
153
+ const appliedFields = [];
154
+ for (const [field, writer] of lastWriter) {
155
+ if (!writer.oursOnly)
156
+ continue;
157
+ const update = fieldUpdateFromChange(writer.change);
158
+ if (!update)
159
+ continue;
160
+ updates = { ...updates, ...update };
161
+ appliedFields.push(field);
162
+ }
163
+ if (appliedFields.length === 0)
164
+ return { content: theirsTicketContent, appliedFields };
165
+ return {
166
+ content: applyRegisterItemFields(theirsTicketContent, updates),
167
+ appliedFields: appliedFields.sort(),
168
+ };
169
+ }