specdojo 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +77 -18
  3. package/dist/catalog/build-references.js +144 -0
  4. package/dist/catalog/build-render.js +32 -0
  5. package/dist/{catalog-build.js → catalog/build.js} +18 -295
  6. package/dist/{catalog.js → catalog/catalog.js} +11 -11
  7. package/dist/{catalog-generate.js → catalog/generate.js} +13 -16
  8. package/dist/catalog/paths.js +1 -0
  9. package/dist/{catalog-plan-generate.js → catalog/plan-generate.js} +5 -5
  10. package/dist/{catalog-plan.js → catalog/plan.js} +9 -9
  11. package/dist/{catalog-scaffold.js → catalog/scaffold.js} +6 -6
  12. package/dist/{agent.js → commands/agent.js} +11 -11
  13. package/dist/{build-command.js → commands/build.js} +2 -2
  14. package/dist/{init-command.js → commands/init.js} +103 -37
  15. package/dist/{orchestrator.js → commands/orchestrator.js} +2 -2
  16. package/dist/{watch.js → commands/watch.js} +3 -3
  17. package/dist/dashboard/dashboard-timeline.js +175 -0
  18. package/dist/{dashboard.js → dashboard/dashboard.js} +16 -549
  19. package/dist/dashboard/exec-records.js +105 -0
  20. package/dist/dashboard/routines.js +256 -0
  21. package/dist/dashboard/shared.js +14 -0
  22. package/dist/{timeline-build.js → dashboard/timeline-build.js} +2 -1
  23. package/dist/{timeline.js → dashboard/timeline.js} +1 -1
  24. package/dist/{deliverable.js → deliverable/deliverable.js} +5 -5
  25. package/dist/{deliverable-trash.js → deliverable/trash.js} +7 -7
  26. package/dist/{devcontainer-command.js → devcontainer/command.js} +5 -3
  27. package/dist/{devcontainer-scaffold.js → devcontainer/scaffold.js} +94 -2
  28. package/dist/{doc-index.js → docs/doc-index.js} +3 -3
  29. package/dist/{frontmatter-namespace.js → docs/frontmatter-namespace.js} +2 -2
  30. package/dist/{index-command.js → docs/index-command.js} +1 -1
  31. package/dist/docs/template-resolution.js +1 -0
  32. package/dist/{viewpoint-document-kinds-check.js → docs/viewpoint-document-kinds-check.js} +3 -3
  33. package/dist/{yaml-pages-command.js → docs/yaml-pages-command.js} +1 -1
  34. package/dist/{yaml-pages.js → docs/yaml-pages.js} +5 -5
  35. package/dist/{exec-agent-config.js → exec/agent-config.js} +33 -4
  36. package/dist/{exec-agent-git-state.js → exec/agent-git-state.js} +1 -1
  37. package/dist/{exec-agent-protected-config.js → exec/agent-protected-config.js} +1 -1
  38. package/dist/{exec.js → exec/commands.js} +22 -467
  39. package/dist/exec/core.js +457 -0
  40. package/dist/{exec-events.js → exec/events.js} +2 -2
  41. package/dist/{exec-evidence.js → exec/evidence.js} +11 -6
  42. package/dist/exec/exec.js +2 -0
  43. package/dist/exec/format.js +1 -0
  44. package/dist/{exec-handoff.js → exec/handoff.js} +13 -12
  45. package/dist/{exec-limit.js → exec/limit.js} +93 -12
  46. package/dist/{exec-parent-validation.js → exec/parent-validation.js} +4 -4
  47. package/dist/{exec-pipeline-state.js → exec/pipeline-state.js} +16 -2
  48. package/dist/{exec-plans.js → exec/plans-core.js} +97 -468
  49. package/dist/exec/plans-generation.js +249 -0
  50. package/dist/exec/plans-storage.js +131 -0
  51. package/dist/exec/plans.js +3 -0
  52. package/dist/{exec-project.js → exec/project.js} +1 -1
  53. package/dist/{exec-protection-handoff.js → exec/protection-handoff.js} +3 -3
  54. package/dist/{exec-register-resume.js → exec/register-resume.js} +2 -2
  55. package/dist/{exec-register.js → exec/register.js} +92 -9
  56. package/dist/exec/repo-integration-git.js +23 -0
  57. package/dist/exec/repo-integration-sync.js +264 -0
  58. package/dist/{exec-repo-integration.js → exec/repo-integration.js} +13 -287
  59. package/dist/{exec-repo-trace.js → exec/repo-trace.js} +3 -3
  60. package/dist/exec/reporter-output.js +206 -0
  61. package/dist/{exec-reporter.js → exec/reporter.js} +29 -216
  62. package/dist/{exec-results.js → exec/results.js} +277 -36
  63. package/dist/exec/run/agent-pipeline.js +276 -0
  64. package/dist/exec/run/agent.js +583 -0
  65. package/dist/exec/run/in-place.js +570 -0
  66. package/dist/exec/run/job.js +746 -0
  67. package/dist/exec/run/lifecycle-commands.js +530 -0
  68. package/dist/{exec-run-lock.js → exec/run/lock.js} +4 -3
  69. package/dist/exec/run/mode-shared.js +140 -0
  70. package/dist/exec/run/register-command.js +252 -0
  71. package/dist/exec/run/register-core.js +411 -0
  72. package/dist/exec/run/register-mode.js +210 -0
  73. package/dist/exec/run/register-resume.js +398 -0
  74. package/dist/exec/run/register-state.js +325 -0
  75. package/dist/exec/run/register-worktree.js +540 -0
  76. package/dist/exec/run/run.js +11 -0
  77. package/dist/exec/run/schedule-mode.js +294 -0
  78. package/dist/exec/run/schedule-prepare.js +366 -0
  79. package/dist/exec/run/schedule-task.js +599 -0
  80. package/dist/exec/run/shared.js +449 -0
  81. package/dist/{exec-schedule-calendar.js → exec/schedule/calendar.js} +1 -1
  82. package/dist/{exec-schedule-cpm.js → exec/schedule/cpm.js} +2 -2
  83. package/dist/{exec-schedule-gantt-chart-render.js → exec/schedule/gantt-chart-render.js} +2 -2
  84. package/dist/exec/schedule/gantt-chart.js +2 -0
  85. package/dist/{exec-schedule-hash.js → exec/schedule/hash.js} +2 -2
  86. package/dist/exec/schedule/index.js +1 -0
  87. package/dist/{exec-schedule-initial.js → exec/schedule/initial.js} +2 -2
  88. package/dist/{exec-schedule-progress.js → exec/schedule/progress.js} +2 -2
  89. package/dist/{exec-schedule-ready.js → exec/schedule/ready.js} +2 -2
  90. package/dist/{exec-schedule.js → exec/schedule/schedule.js} +11 -11
  91. package/dist/exec/shared.js +63 -0
  92. package/dist/exec/slot-lock.js +1 -0
  93. package/dist/{exec-strategy.js → exec/strategy.js} +2 -2
  94. package/dist/{exec-task-repos.js → exec/task-repos.js} +2 -2
  95. package/dist/{exec-task-view.js → exec/task-view.js} +4 -4
  96. package/dist/{exec-trial.js → exec/trial-commands.js} +23 -388
  97. package/dist/exec/trial-core.js +371 -0
  98. package/dist/exec/trial.js +2 -0
  99. package/dist/{exec-worktree-command.js → exec/worktree-command.js} +25 -23
  100. package/dist/exec/worktree-ops-commit.js +672 -0
  101. package/dist/exec/worktree-ops-lifecycle.js +297 -0
  102. package/dist/exec/worktree-ops-merge.js +344 -0
  103. package/dist/exec/worktree-ops.js +3 -0
  104. package/dist/exec/worktree.js +305 -0
  105. package/dist/grade/apply.js +734 -0
  106. package/dist/grade/command-apply.js +250 -0
  107. package/dist/grade/command-inspect.js +138 -0
  108. package/dist/grade/command-plan.js +101 -0
  109. package/dist/grade/command-shared.js +68 -0
  110. package/dist/grade/core.js +307 -0
  111. package/dist/grade/grade.js +19 -0
  112. package/dist/grade/markdown.js +274 -0
  113. package/dist/grade/pipeline-state.js +184 -0
  114. package/dist/grade/plan.js +507 -0
  115. package/dist/{grade-result.js → grade/result.js} +7 -96
  116. package/dist/grade/target-discovery.js +265 -0
  117. package/dist/grade/targets.js +435 -0
  118. package/dist/{job.js → job/definition.js} +32 -574
  119. package/dist/job/job.js +568 -0
  120. package/dist/{kata-command.js → kata/command.js} +4 -4
  121. package/dist/{kata.js → kata/kata.js} +5 -5
  122. package/dist/register/approach.js +134 -0
  123. package/dist/register/command-types.js +1 -0
  124. package/dist/register/core.js +369 -0
  125. package/dist/register/create-commands.js +352 -0
  126. package/dist/{register-date.js → register/date.js} +1 -1
  127. package/dist/register/derivation.js +163 -0
  128. package/dist/{register-event-merge.js → register/event-merge.js} +32 -3
  129. package/dist/{register-events.js → register/events.js} +12 -6
  130. package/dist/{register-history.js → register/history.js} +7 -6
  131. package/dist/{register-item.js → register/item.js} +28 -10
  132. package/dist/register/lifecycle-lock.js +5 -0
  133. package/dist/register/maintenance-commands.js +193 -0
  134. package/dist/{register-migrate-timestamps.js → register/migrate-timestamps.js} +3 -3
  135. package/dist/register/migration.js +268 -0
  136. package/dist/register/register.js +404 -0
  137. package/dist/register/renumber.js +341 -0
  138. package/dist/register/transition-commands.js +248 -0
  139. package/dist/register/update.js +230 -0
  140. package/dist/register/views.js +296 -0
  141. package/dist/{review-grade.js → review/grade.js} +2 -2
  142. package/dist/{review-plan.js → review/plan.js} +5 -5
  143. package/dist/routine/definition.js +401 -0
  144. package/dist/{routine.js → routine/routine.js} +50 -419
  145. package/dist/{schedule-approach.js → schedule/approach.js} +9 -9
  146. package/dist/{schedule-build.js → schedule/build.js} +7 -4
  147. package/dist/{schedule.js → schedule/schedule.js} +9 -9
  148. package/dist/schedule/strategy-generate-document.js +273 -0
  149. package/dist/schedule/strategy-generate-scope.js +199 -0
  150. package/dist/schedule/strategy-generate.js +348 -0
  151. package/dist/shared/agent-types.js +23 -0
  152. package/dist/shared/artifact-path.js +9 -0
  153. package/dist/{build-if-stale.js → shared/build-if-stale.js} +1 -1
  154. package/dist/shared/catalog-render.js +115 -0
  155. package/dist/{exec-slot-lock.js → shared/cross-process-lock.js} +3 -1
  156. package/dist/shared/fs.js +30 -0
  157. package/dist/shared/git.js +316 -0
  158. package/dist/shared/grade-result.js +94 -0
  159. package/dist/{package-paths.js → shared/package-paths.js} +3 -3
  160. package/dist/shared/plan-templates.js +114 -0
  161. package/dist/{exec-provider-scaffold.js → shared/provider-scaffold.js} +3 -1
  162. package/dist/shared/random.js +4 -0
  163. package/dist/{exec-schedule-index.js → shared/schedule-index.js} +3 -1
  164. package/dist/shared/schedule-paths.js +9 -0
  165. package/dist/{specdojo-config.js → shared/specdojo-config.js} +96 -9
  166. package/dist/{exec-shared.js → shared/text.js} +0 -134
  167. package/dist/shared/time.js +28 -0
  168. package/dist/shared/yaml.js +28 -0
  169. package/dist/specdojo.js +22 -22
  170. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +29 -17
  171. package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +1 -2
  172. package/docs/ja/specdojo/exec-templates/xep-register-template.md +1 -2
  173. package/docs/ja/specdojo/exec-templates/xer-template.md +1 -3
  174. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +6 -4
  175. package/docs/ja/specdojo/guides/exec-config-guide.md +97 -22
  176. package/docs/ja/specdojo/guides/exec-operation-guide.md +145 -12
  177. package/docs/ja/specdojo/guides/exec-worktree-guide.md +2 -0
  178. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +51 -18
  179. package/docs/ja/specdojo/guides/quick-start-guide.md +81 -16
  180. package/docs/ja/specdojo/guides/register-operation-guide.md +2 -1
  181. package/docs/ja/specdojo/guides/remote-host-development-guide.md +10 -1
  182. package/docs/ja/specdojo/guides/review-guide.md +1 -1
  183. package/docs/ja/specdojo/guides/routine-operation-guide.md +6 -6
  184. package/docs/ja/specdojo/guides/use-case-guide.md +1 -1
  185. package/docs/ja/specdojo/references/command-reference.md +52 -28
  186. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +17 -11
  187. package/docs/ja/specdojo/standards/job-definition-standard.md +20 -18
  188. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -2
  189. package/docs/ja/specdojo/templates/pjr-derived-items-template.md +22 -0
  190. package/docs/ja/specdojo/templates/pjr-index-template.md +1 -0
  191. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +29 -2
  192. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +20 -0
  193. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +23 -0
  194. package/docs/specdojo/schemas/v1/job-run.schema.yaml +2 -2
  195. package/docs/specdojo/schemas/v1/job.schema.yaml +7 -0
  196. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +26 -0
  197. package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
  198. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +70 -7
  199. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +1 -1
  200. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +1 -1
  201. package/package.json +4 -5
  202. package/templates/antigravity/README.md +7 -3
  203. package/templates/antigravity/agent-members-snippet.yaml +108 -12
  204. package/templates/antigravity/exec-defaults-snippet.yaml +10 -13
  205. package/templates/claude/README.md +27 -3
  206. package/templates/claude/agents/claude-executor.md +0 -1
  207. package/templates/claude/agents/claude-reporter.md +2 -1
  208. package/templates/claude/agents/claude-review-executor.md +0 -1
  209. package/templates/codex/README.md +23 -4
  210. package/templates/devcontainer/devcontainer.json +2 -2
  211. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +69 -0
  212. package/templates/devcontainer/remote-host/ssh-config.sample +16 -0
  213. package/templates/init-agent-members.yaml +75 -25
  214. package/templates/init-exec-defaults.yaml +26 -8
  215. package/templates/opencode/README.md +17 -3
  216. package/templates/opencode/agents/opencode-executor.md +0 -1
  217. package/templates/opencode/agents/opencode-reporter.md +2 -1
  218. package/templates/opencode/agents/opencode-review-executor.md +0 -1
  219. package/dist/exec-run.js +0 -6182
  220. package/dist/exec-schedule-gantt-chart.js +0 -2
  221. package/dist/exec-worktree-ops.js +0 -1292
  222. package/dist/exec-worktree.js +0 -446
  223. package/dist/grade.js +0 -3193
  224. package/dist/register.js +0 -2407
  225. package/dist/schedule-strategy-generate.js +0 -812
  226. package/templates/claude/agents/claude-expert-review-executor.md +0 -14
  227. /package/dist/{catalog-plan-prompt.js → catalog/plan-prompt.js} +0 -0
  228. /package/dist/{catalog-types.js → catalog/types.js} +0 -0
  229. /package/dist/{template-frontmatter.js → docs/template-frontmatter.js} +0 -0
  230. /package/dist/{role-types.js → exec/role-types.js} +0 -0
  231. /package/dist/{exec-schedule-gantt-chart-scope.js → exec/schedule/gantt-chart-scope.js} +0 -0
  232. /package/dist/{exec-types.js → exec/types.js} +0 -0
  233. /package/dist/{review-types.js → review/types.js} +0 -0
  234. /package/dist/{schedule-phase-sets.js → schedule/phase-sets.js} +0 -0
  235. /package/dist/{schedule-strategy-profiles.js → schedule/strategy-profiles.js} +0 -0
  236. /package/dist/{agent-response.js → shared/agent-response.js} +0 -0
  237. /package/dist/{catalog-paths.js → shared/catalog-paths.js} +0 -0
  238. /package/dist/{dist-freshness.js → shared/dist-freshness.js} +0 -0
  239. /package/dist/{git-environment.js → shared/git-environment.js} +0 -0
  240. /package/dist/{exec-format.js → shared/markdown-format.js} +0 -0
  241. /package/dist/{practice-id.js → shared/practice-id.js} +0 -0
  242. /package/dist/{spawn-self.js → shared/spawn-self.js} +0 -0
  243. /package/dist/{specdojo-gitignore.js → shared/specdojo-gitignore.js} +0 -0
  244. /package/dist/{template-resolution.js → shared/template-resolution.js} +0 -0
  245. /package/dist/{yaml-schema-modeline.js → shared/yaml-schema-modeline.js} +0 -0
@@ -0,0 +1,568 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { join, relative, resolve } from "node:path";
5
+ import { buildSpecdojoFrontmatter } from "../docs/frontmatter-namespace.js";
6
+ import { listFilesRecursive, writeJson } from "../shared/fs.js";
7
+ import { gitEnvironment } from "../shared/git.js";
8
+ import { formatMarkdownFile } from "../shared/markdown-format.js";
9
+ import { execTemplatePath, injectCommonConventions, MISSING } from "../shared/plan-templates.js";
10
+ import { expandTemplate } from "../shared/text.js";
11
+ import { isJobAgentTask, isJobCommandTask, getPath, loadAllJobs, loadJobDefinition, loadJobRunRecord, parseInputValue, parseJobInputs, renderJobTemplate, resolveJobPaths, validateJobInputValue, } from "./definition.js";
12
+ import { specdojoRootDir } from "../shared/specdojo-config.js";
13
+ import { selfRunCommand } from "../shared/spawn-self.js";
14
+ export { isJobAgentTask, isJobCommandTask, jobDeclaresReview, jobRunUsesReviewedIntegration, loadAllJobs, loadJobDefinition, loadJobRunRecord, parseJobDefinition, parseJobInputs, renderJobTemplate, resolveJobPaths, resolveJobReviewAgentNominations, } from "./definition.js";
15
+ export function jobCheckpoint(paths, jobId) {
16
+ return deriveJobState(paths).jobs[jobId]?.checkpoint ?? {};
17
+ }
18
+ export function deriveJobState(paths) {
19
+ const state = { version: 1, jobs: {} };
20
+ if (!existsSync(paths.runsPath))
21
+ return state;
22
+ for (const filePath of listFilesRecursive(paths.runsPath)
23
+ .filter((path) => path.endsWith(".json"))
24
+ .sort()) {
25
+ try {
26
+ const run = loadJobRunRecord(filePath);
27
+ if (!run.checkpoint_after || (run.state !== "succeeded" && run.state !== "noop"))
28
+ continue;
29
+ const current = state.jobs[run.job_id];
30
+ if (!current || current.updated_at < run.updated_at) {
31
+ state.jobs[run.job_id] = {
32
+ checkpoint: run.checkpoint_after,
33
+ last_run_id: run.run_id,
34
+ updated_at: run.updated_at,
35
+ };
36
+ }
37
+ }
38
+ catch {
39
+ // Invalid Run files are reported by schema validation; a broken file must not erase
40
+ // checkpoints that can still be derived from other valid history entries.
41
+ }
42
+ }
43
+ return state;
44
+ }
45
+ function resolveInputs(definition, raw, checkpoint) {
46
+ const definitions = definition.inputs ?? {};
47
+ for (const key of Object.keys(raw)) {
48
+ if (!definitions[key])
49
+ throw new Error(`Unknown input for ${definition.id}: ${key}`);
50
+ }
51
+ const values = {};
52
+ for (const [key, input] of Object.entries(definitions)) {
53
+ let value = raw[key];
54
+ if (value === undefined && input.from_checkpoint)
55
+ value = getPath(checkpoint, input.from_checkpoint);
56
+ if (value === undefined && input.resolve === "git_head") {
57
+ const result = spawnSync("git", ["rev-parse", "HEAD"], {
58
+ cwd: specdojoRootDir(),
59
+ encoding: "utf8",
60
+ env: gitEnvironment(),
61
+ });
62
+ if (result.status !== 0)
63
+ throw new Error(`Unable to resolve git HEAD for input ${key}`);
64
+ value = result.stdout.trim();
65
+ }
66
+ if (value === undefined && input.default !== undefined)
67
+ value = input.default;
68
+ if (value === undefined) {
69
+ if (input.required)
70
+ throw new Error(`Missing required input for ${definition.id}: ${key}`);
71
+ continue;
72
+ }
73
+ const parsed = parseInputValue(value, input.type, key);
74
+ validateJobInputValue(parsed, input, key);
75
+ if (input.git_revision) {
76
+ if (input.type !== "string")
77
+ throw new Error(`Input ${key} with git_revision must be a string`);
78
+ const result = spawnSync("git", ["rev-parse", String(parsed)], {
79
+ cwd: specdojoRootDir(),
80
+ encoding: "utf8",
81
+ env: gitEnvironment(),
82
+ });
83
+ if (result.status !== 0)
84
+ throw new Error(`Unable to resolve git revision for input ${key}: ${parsed}`);
85
+ values[key] = result.stdout.trim();
86
+ }
87
+ else {
88
+ values[key] = parsed;
89
+ }
90
+ }
91
+ return values;
92
+ }
93
+ function qualifyTargets(projectId, targets) {
94
+ return targets.map((target) => (target.includes(":") ? target : `${projectId}:${target}`));
95
+ }
96
+ function runIdFor(definition, idempotencyKey) {
97
+ const slug = definition.id.slice(4);
98
+ const digest = createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 12);
99
+ return `JBR-${slug}-${digest}`;
100
+ }
101
+ function repoRelative(absPath) {
102
+ return relative(specdojoRootDir(), absPath).replaceAll("\\", "/");
103
+ }
104
+ const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
105
+ function appendCommandOutput(chunks, chunk, capturedBytes) {
106
+ if (capturedBytes >= MAX_COMMAND_OUTPUT_BYTES) {
107
+ return { capturedBytes, truncated: chunk.length > 0 };
108
+ }
109
+ const remaining = MAX_COMMAND_OUTPUT_BYTES - capturedBytes;
110
+ chunks.push(chunk.subarray(0, remaining));
111
+ return {
112
+ capturedBytes: capturedBytes + Math.min(chunk.length, remaining),
113
+ truncated: chunk.length > remaining,
114
+ };
115
+ }
116
+ function commandOutputText(chunks, truncated) {
117
+ const text = Buffer.concat(chunks).toString("utf8");
118
+ return truncated ? text.replace(/\uFFFD$/u, "") : text;
119
+ }
120
+ /** Executes a materialized Job command directly in the runner process, never through an agent. */
121
+ export async function executeJobCommand(command, cwd) {
122
+ const startedAt = new Date().toISOString();
123
+ return await new Promise((resolveResult) => {
124
+ const stdoutChunks = [];
125
+ const stderrChunks = [];
126
+ let stdoutBytes = 0;
127
+ let stderrBytes = 0;
128
+ let stdoutTruncated = false;
129
+ let stderrTruncated = false;
130
+ let settled = false;
131
+ const executable = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh";
132
+ const args = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-eu", "-c", command];
133
+ const child = spawn(executable, args, {
134
+ cwd,
135
+ env: gitEnvironment(),
136
+ shell: false,
137
+ stdio: ["ignore", "pipe", "pipe"],
138
+ windowsHide: true,
139
+ });
140
+ child.stdout.on("data", (chunk) => {
141
+ process.stdout.write(chunk);
142
+ const appended = appendCommandOutput(stdoutChunks, chunk, stdoutBytes);
143
+ stdoutBytes = appended.capturedBytes;
144
+ stdoutTruncated ||= appended.truncated;
145
+ });
146
+ child.stderr.on("data", (chunk) => {
147
+ process.stderr.write(chunk);
148
+ const appended = appendCommandOutput(stderrChunks, chunk, stderrBytes);
149
+ stderrBytes = appended.capturedBytes;
150
+ stderrTruncated ||= appended.truncated;
151
+ });
152
+ const finish = (exitCode, error) => {
153
+ if (settled)
154
+ return;
155
+ settled = true;
156
+ resolveResult({
157
+ command,
158
+ startedAt,
159
+ completedAt: new Date().toISOString(),
160
+ exitCode,
161
+ stdout: commandOutputText(stdoutChunks, stdoutTruncated),
162
+ stderr: commandOutputText(stderrChunks, stderrTruncated),
163
+ stdoutTruncated,
164
+ stderrTruncated,
165
+ ...(error ? { error } : {}),
166
+ });
167
+ };
168
+ child.once("error", (error) => finish(null, error.message));
169
+ child.once("close", (code) => finish(code));
170
+ });
171
+ }
172
+ export async function executeJobPrecondition(precondition, cwd) {
173
+ const result = await executeJobCommand(precondition.command, cwd);
174
+ if (result.error) {
175
+ throw new Error(`Job precondition spawn failed: ${result.error}`);
176
+ }
177
+ if (typeof precondition.skip_when === "number") {
178
+ if (result.exitCode === precondition.skip_when) {
179
+ return {
180
+ result,
181
+ skipped: true,
182
+ reason: `precondition exited with code ${precondition.skip_when}`,
183
+ };
184
+ }
185
+ if (result.exitCode !== 0) {
186
+ throw new Error(`Job precondition exited with code ${result.exitCode ?? "unknown"}`);
187
+ }
188
+ return { result, skipped: false };
189
+ }
190
+ if (result.exitCode !== 0) {
191
+ throw new Error(`Job precondition exited with code ${result.exitCode ?? "unknown"}`);
192
+ }
193
+ if (!result.stdout.trim()) {
194
+ return { result, skipped: true, reason: "empty selection" };
195
+ }
196
+ return { result, skipped: false };
197
+ }
198
+ function jobPlanFrontmatter(projectId, definition, record) {
199
+ const localId = `xep-${record.run_id.toLowerCase()}`;
200
+ const inner = [
201
+ `id: ${projectId}:${localId}`,
202
+ "type: exec-plan",
203
+ "rulebook: none",
204
+ `task_id: ${record.run_id}`,
205
+ `name: ${JSON.stringify(definition.name)}`,
206
+ // A command Run's plan is consumed only by the optional analysis reporter. Exec result
207
+ // frontmatter intentionally keeps the existing edit/review vocabulary for compatibility.
208
+ `mode: ${isJobCommandTask(record.task) ? "edit" : record.task.mode}`,
209
+ "status: ready",
210
+ `project_id: ${projectId}`,
211
+ "origin: job",
212
+ `job_id: ${definition.id}`,
213
+ `run_id: ${record.run_id}`,
214
+ ];
215
+ if (record.task.owner)
216
+ inner.push(`owner: ${record.task.owner}`);
217
+ if (record.task.targets) {
218
+ inner.push("targets:");
219
+ for (const target of record.task.targets)
220
+ inner.push(` - ${target}`);
221
+ }
222
+ if (record.task.paths) {
223
+ inner.push("paths:");
224
+ for (const path of record.task.paths)
225
+ inner.push(` - ${path}`);
226
+ }
227
+ return buildSpecdojoFrontmatter(inner);
228
+ }
229
+ export async function generateJobPlan(paths, definition, record) {
230
+ const templatePath = execTemplatePath("xep-job-template.md");
231
+ if (!existsSync(templatePath))
232
+ throw new Error(`Template not found: ${templatePath}`);
233
+ const planPath = join(paths.executionPath, "exec", "plans", `${record.run_id}-plan.md`);
234
+ mkdirSync(resolve(planPath, ".."), { recursive: true });
235
+ const commandTask = isJobCommandTask(record.task) ? record.task : undefined;
236
+ const values = {
237
+ _FRONTMATTER_: jobPlanFrontmatter(paths.projectId, definition, record),
238
+ _JOB_ID_: definition.id,
239
+ _JOB_NAME_: definition.name,
240
+ _RUN_ID_: record.run_id,
241
+ _SCHEDULED_AT_: record.scheduled_at,
242
+ _JOB_DESCRIPTION_: commandTask?.analysis?.description ??
243
+ (commandTask
244
+ ? "コマンドの終了結果を evidence として記録する。agent による判断は行わない。"
245
+ : isJobAgentTask(record.task)
246
+ ? record.task.description
247
+ : ""),
248
+ _JOB_EXECUTION_: commandTask
249
+ ? [
250
+ "### 3.1. 決定論的コマンド",
251
+ "",
252
+ "runner が次の解決済みコマンドを agent の sandbox 外で直接実行する。",
253
+ "",
254
+ "```sh",
255
+ commandTask.command,
256
+ "```",
257
+ "",
258
+ commandTask.analysis
259
+ ? "コマンドが成功または設定済みの部分成功になった場合、上記の判断を reporter agent が evidence に基づいて行う。"
260
+ : "コマンドの終了コードから Run の成否を直接決定する。",
261
+ ].join("\n")
262
+ : "",
263
+ _JOB_INPUTS_: JSON.stringify(record.inputs, null, 2),
264
+ _JOB_TARGETS_: record.task.targets?.map((target) => `- [[${target}]]`).join("\n") ?? "- -",
265
+ _JOB_PATHS_: record.task.paths?.map((path) => `- \`${path}\``).join("\n") ?? "- -",
266
+ _RESULT_REF_: repoRelative(join(paths.executionPath, "exec", "results", `${record.run_id}-result.md`)),
267
+ };
268
+ const body = expandTemplate(readFileSync(templatePath, "utf8"), values);
269
+ const content = injectCommonConventions(body, MISSING, new Map());
270
+ writeFileSync(planPath, content, "utf8");
271
+ await formatMarkdownFile(planPath);
272
+ return planPath;
273
+ }
274
+ function jobReviewPlanFrontmatter(projectId, definition, record) {
275
+ return buildSpecdojoFrontmatter([
276
+ `id: ${projectId}:xrp-${record.run_id.toLowerCase()}-review`,
277
+ "type: exec-plan",
278
+ "rulebook: none",
279
+ `task_id: ${record.run_id}-review`,
280
+ `name: ${JSON.stringify(`${definition.name} の実行結果レビュー`)}`,
281
+ "mode: review",
282
+ "status: ready",
283
+ `project_id: ${projectId}`,
284
+ "origin: job",
285
+ `job_id: ${definition.id}`,
286
+ `run_id: ${record.run_id}`,
287
+ ]);
288
+ }
289
+ export async function generateJobReviewPlan(paths, definition, record, opts) {
290
+ const templatePath = execTemplatePath("xrp-job-template.md");
291
+ if (!existsSync(templatePath))
292
+ throw new Error(`Template not found: ${templatePath}`);
293
+ const planPath = join(paths.executionPath, "exec", "plans", `${record.run_id}-review-plan.md`);
294
+ const resultPath = join(paths.executionPath, "exec", "results", `${record.run_id}-review-result.md`);
295
+ mkdirSync(resolve(planPath, ".."), { recursive: true });
296
+ const values = {
297
+ _FRONTMATTER_: jobReviewPlanFrontmatter(paths.projectId, definition, record),
298
+ _JOB_ID_: definition.id,
299
+ _JOB_NAME_: definition.name,
300
+ _RUN_ID_: record.run_id,
301
+ _RUN_STATE_: record.state,
302
+ _BRANCH_: opts.branch,
303
+ _BASE_COMMIT_: opts.baseCommit,
304
+ _OUTPUT_COMMIT_: opts.outputCommit,
305
+ _JOB_DESCRIPTION_: definition.description ?? "-",
306
+ _ANALYSIS_DESCRIPTION_: isJobCommandTask(record.task)
307
+ ? (record.task.analysis?.description ?? "コマンドの終了結果と出力を確認する。")
308
+ : record.task.description,
309
+ _RESULT_REF_: repoRelative(resultPath),
310
+ _RUN_RESULT_REF_: repoRelative(join(paths.executionPath, record.result_ref)),
311
+ };
312
+ const body = expandTemplate(readFileSync(templatePath, "utf8"), values);
313
+ const content = injectCommonConventions(body, MISSING, new Map(), "review");
314
+ writeFileSync(planPath, content, "utf8");
315
+ await formatMarkdownFile(planPath);
316
+ return { planPath, resultPath };
317
+ }
318
+ export function recordJobRunReview(runPath, review) {
319
+ const record = loadJobRunRecord(runPath);
320
+ const reviewedAt = review.reviewed_at ?? new Date().toISOString();
321
+ const updated = {
322
+ ...record,
323
+ updated_at: reviewedAt,
324
+ review: { ...review, reviewed_at: reviewedAt },
325
+ };
326
+ writeJson(runPath, updated);
327
+ return updated;
328
+ }
329
+ export async function materializeJobRun(opts) {
330
+ const paths = resolveJobPaths(opts.projectId);
331
+ const definition = loadJobDefinition(paths, opts.jobId);
332
+ const checkpoint = jobCheckpoint(paths, definition.id);
333
+ const scheduledAt = opts.scheduledAt
334
+ ? new Date(opts.scheduledAt).toISOString()
335
+ : new Date().toISOString();
336
+ const inputs = resolveInputs(definition, parseJobInputs(opts.inputs), checkpoint);
337
+ const identityContext = {
338
+ job_id: definition.id,
339
+ project_id: paths.projectId,
340
+ specdojo: selfRunCommand(),
341
+ scheduled_at: scheduledAt,
342
+ inputs,
343
+ checkpoint,
344
+ };
345
+ const idempotencyKey = renderJobTemplate(definition.run.idempotency_key, identityContext);
346
+ if (!idempotencyKey.trim())
347
+ throw new Error(`Resolved idempotency key is empty: ${definition.id}`);
348
+ const runId = runIdFor(definition, idempotencyKey);
349
+ const context = { ...identityContext, job_run_id: runId };
350
+ const runPath = join(paths.runsPath, `${runId}.json`);
351
+ const targets = definition.task.targets
352
+ ? qualifyTargets(paths.projectId, definition.task.targets)
353
+ : undefined;
354
+ const task = {
355
+ ...definition.task,
356
+ ...(targets ? { targets } : {}),
357
+ };
358
+ if (isJobCommandTask(task)) {
359
+ if (task.precondition) {
360
+ task.precondition = {
361
+ ...task.precondition,
362
+ command: renderJobTemplate(task.precondition.command, context),
363
+ };
364
+ }
365
+ task.command = renderJobTemplate(task.command, context);
366
+ if (task.analysis) {
367
+ task.analysis = {
368
+ ...task.analysis,
369
+ description: renderJobTemplate(task.analysis.description, context),
370
+ };
371
+ }
372
+ }
373
+ else {
374
+ task.description = renderJobTemplate(task.description, context);
375
+ }
376
+ const now = new Date().toISOString();
377
+ const existingRun = existsSync(runPath);
378
+ let record;
379
+ if (existingRun) {
380
+ record = loadJobRunRecord(runPath);
381
+ if (record.idempotency_key !== idempotencyKey || record.job_id !== definition.id) {
382
+ throw new Error(`Job Run identity collision: ${runId}`);
383
+ }
384
+ if (record.state === "succeeded" || record.state === "partial" || record.state === "noop") {
385
+ return {
386
+ definition,
387
+ record,
388
+ runPath,
389
+ planPath: join(paths.executionPath, record.plan_ref),
390
+ duplicateComplete: true,
391
+ };
392
+ }
393
+ }
394
+ else {
395
+ record = {
396
+ version: 1,
397
+ run_id: runId,
398
+ job_id: definition.id,
399
+ idempotency_key: idempotencyKey,
400
+ project_id: paths.projectId,
401
+ trigger: opts.trigger ?? "manual",
402
+ scheduled_at: scheduledAt,
403
+ created_at: now,
404
+ updated_at: now,
405
+ state: "running",
406
+ inputs,
407
+ task,
408
+ checkpoint_before: checkpoint,
409
+ plan_ref: `exec/plans/${runId}-plan.md`,
410
+ result_ref: `exec/results/${runId}-result.md`,
411
+ attempts: [],
412
+ };
413
+ }
414
+ if (!existingRun && !opts.dryRun && isJobCommandTask(task) && task.precondition) {
415
+ const precondition = await executeJobPrecondition(task.precondition, specdojoRootDir());
416
+ if (precondition.skipped) {
417
+ return {
418
+ definition,
419
+ record,
420
+ runPath,
421
+ planPath: join(paths.executionPath, record.plan_ref),
422
+ duplicateComplete: false,
423
+ preconditionSkipped: true,
424
+ preconditionReason: precondition.reason,
425
+ preconditionResult: precondition.result,
426
+ };
427
+ }
428
+ }
429
+ const attempt = {
430
+ attempt: record.attempts.length + 1,
431
+ started_at: now,
432
+ status: "running",
433
+ };
434
+ record = {
435
+ ...record,
436
+ updated_at: now,
437
+ state: "running",
438
+ attempts: [...record.attempts, attempt],
439
+ };
440
+ if (!opts.dryRun) {
441
+ mkdirSync(paths.runsPath, { recursive: true });
442
+ writeJson(runPath, record);
443
+ }
444
+ const planPath = opts.dryRun
445
+ ? join(paths.executionPath, record.plan_ref)
446
+ : await generateJobPlan(paths, definition, record);
447
+ return { definition, record, runPath, planPath, duplicateComplete: false };
448
+ }
449
+ export function completeJobRun(opts) {
450
+ const paths = resolveJobPaths(opts.projectId);
451
+ const record = loadJobRunRecord(opts.runPath);
452
+ const definition = loadJobDefinition(paths, record.job_id);
453
+ const completedAt = new Date().toISOString();
454
+ const attempts = [...record.attempts];
455
+ const current = attempts.at(-1);
456
+ if (!current)
457
+ throw new Error(`Job Run has no attempt: ${record.run_id}`);
458
+ attempts[attempts.length - 1] = {
459
+ ...current,
460
+ completed_at: completedAt,
461
+ status: opts.status,
462
+ result_ref: record.result_ref,
463
+ ...(opts.evidenceRef ? { evidence_ref: opts.evidenceRef } : {}),
464
+ ...(opts.exitCode !== undefined ? { exit_code: opts.exitCode } : {}),
465
+ ...(opts.reason ? { reason: opts.reason } : {}),
466
+ };
467
+ let checkpointAfter;
468
+ const advanceOn = definition.checkpoint?.advance_on ?? ["succeeded", "noop"];
469
+ if (definition.checkpoint && advanceOn.includes(opts.status)) {
470
+ const context = {
471
+ job_id: definition.id,
472
+ job_run_id: record.run_id,
473
+ project_id: record.project_id,
474
+ specdojo: selfRunCommand(),
475
+ scheduled_at: record.scheduled_at,
476
+ inputs: record.inputs,
477
+ checkpoint: record.checkpoint_before,
478
+ };
479
+ checkpointAfter = Object.fromEntries(Object.entries(definition.checkpoint.values).map(([key, value]) => [
480
+ key,
481
+ renderJobTemplate(value, context),
482
+ ]));
483
+ }
484
+ const updated = {
485
+ ...record,
486
+ updated_at: completedAt,
487
+ state: opts.status,
488
+ attempts,
489
+ ...(checkpointAfter ? { checkpoint_after: checkpointAfter } : {}),
490
+ };
491
+ writeJson(opts.runPath, updated);
492
+ if (checkpointAfter) {
493
+ const state = deriveJobState(paths);
494
+ state.jobs[record.job_id] = {
495
+ checkpoint: checkpointAfter,
496
+ last_run_id: record.run_id,
497
+ updated_at: completedAt,
498
+ };
499
+ mkdirSync(resolve(paths.statePath, ".."), { recursive: true });
500
+ writeJson(paths.statePath, state);
501
+ }
502
+ return updated;
503
+ }
504
+ export function jobRunRelativePath(runPath) {
505
+ return repoRelative(runPath);
506
+ }
507
+ export function registerJobCommands(program) {
508
+ const command = program.command("job").description("Reusable Job Definition and Run helpers");
509
+ command
510
+ .command("where")
511
+ .description("Print resolved Job paths")
512
+ .option("--project <projectId>", "Project id")
513
+ .action((opts) => {
514
+ try {
515
+ const paths = resolveJobPaths(opts.project);
516
+ process.stdout.write(`project: ${paths.projectId}\n`);
517
+ process.stdout.write(`jobs: ${paths.jobsPath}\n`);
518
+ process.stdout.write(`runs: ${paths.runsPath}\n`);
519
+ process.stdout.write(`state: ${paths.statePath}\n`);
520
+ }
521
+ catch (error) {
522
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
523
+ process.exitCode = 1;
524
+ }
525
+ });
526
+ command
527
+ .command("validate")
528
+ .description("Validate job-*.yaml definitions")
529
+ .option("--project <projectId>", "Project id")
530
+ .action((opts) => {
531
+ try {
532
+ const paths = resolveJobPaths(opts.project);
533
+ const { jobs, errors } = loadAllJobs(paths.jobsPath);
534
+ for (const error of errors)
535
+ process.stderr.write(`ERROR: ${error}\n`);
536
+ process.stdout.write(`Validated: ${jobs.length} job(s), ${errors.length} error(s)\n`);
537
+ if (errors.length)
538
+ process.exitCode = 1;
539
+ }
540
+ catch (error) {
541
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
542
+ process.exitCode = 1;
543
+ }
544
+ });
545
+ command
546
+ .command("list")
547
+ .description("List Job Definitions and latest checkpoint")
548
+ .option("--project <projectId>", "Project id")
549
+ .action((opts) => {
550
+ try {
551
+ const paths = resolveJobPaths(opts.project);
552
+ const { jobs, errors } = loadAllJobs(paths.jobsPath);
553
+ const state = deriveJobState(paths);
554
+ for (const job of jobs) {
555
+ const latest = state.jobs[job.id];
556
+ process.stdout.write(`${job.id}\t${latest?.last_run_id ?? "-"}\t${job.name}\n`);
557
+ }
558
+ for (const error of errors)
559
+ process.stderr.write(`ERROR: ${error}\n`);
560
+ if (errors.length)
561
+ process.exitCode = 1;
562
+ }
563
+ catch (error) {
564
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
565
+ process.exitCode = 1;
566
+ }
567
+ });
568
+ }
@@ -1,8 +1,8 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { basename, dirname, extname, join, relative, resolve } from "node:path";
3
- import yaml from "js-yaml";
4
- import { readSpecdojoNamespace } from "./frontmatter-namespace.js";
5
- import { specdojoResourceCandidates } from "./template-resolution.js";
3
+ import { load } from "../shared/yaml.js";
4
+ import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
5
+ import { specdojoResourceCandidates, } from "../docs/template-resolution.js";
6
6
  export const KATA_RESOURCE_KINDS = [
7
7
  "rulebook",
8
8
  "standard",
@@ -54,7 +54,7 @@ function filesBelow(root) {
54
54
  function parseDataFileId(content, extension) {
55
55
  let parsed;
56
56
  try {
57
- parsed = extension === ".json" ? JSON.parse(content) : yaml.load(content);
57
+ parsed = extension === ".json" ? JSON.parse(content) : load(content);
58
58
  }
59
59
  catch {
60
60
  return undefined;
@@ -1,9 +1,9 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { specdojoRootDir } from "./specdojo-config.js";
3
- import { readSpecdojoNamespace } from "./frontmatter-namespace.js";
4
- import { practiceLocalId } from "./practice-id.js";
5
- import { resolveSpecdojoPathIfExists, resolveSpecdojoReferencePathIfExists, specdojoResourceCandidates, } from "./template-resolution.js";
6
- import { readYamlSchemaModelineRef } from "./yaml-schema-modeline.js";
2
+ import { specdojoRootDir } from "../shared/specdojo-config.js";
3
+ import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
4
+ import { practiceLocalId } from "../shared/practice-id.js";
5
+ import { resolveSpecdojoPathIfExists, resolveSpecdojoReferencePathIfExists, specdojoResourceCandidates, } from "../docs/template-resolution.js";
6
+ import { readYamlSchemaModelineRef } from "../shared/yaml-schema-modeline.js";
7
7
  // 実践の型(rulebook / recipe / sample / template)の解決を 1 か所に集約する。
8
8
  // plan 生成(明示パスの注入)と validate(参照先の存在確認)の両方から使う。
9
9
  const MISSING = "_MISSING_";