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
@@ -1,15 +1,8 @@
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 { basename, join, relative, resolve } from "node:path";
5
- import yaml from "js-yaml";
6
- import { buildSpecdojoFrontmatter } from "./frontmatter-namespace.js";
7
- import { formatMarkdownFile } from "./exec-format.js";
8
- import { execTemplatePath, injectCommonConventions, MISSING } from "./exec-plans.js";
9
- import { expandTemplate, listFilesRecursive, readJson, writeJson } from "./exec-shared.js";
10
- import { gitEnvironment } from "./exec-worktree.js";
11
- import { getProjectJobsPath, getProjectExecutionPath, loadConfig, loadEnv, specdojoRootDir, } from "./specdojo-config.js";
12
- import { selfRunCommand } from "./spawn-self.js";
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename, join, resolve } from "node:path";
3
+ import { load } from "../shared/yaml.js";
4
+ import { listFilesRecursive, readJson } from "../shared/fs.js";
5
+ import { getProjectExecutionPath, getProjectJobsPath, loadConfig, loadEnv, specdojoRootDir, } from "../shared/specdojo-config.js";
13
6
  function isRecord(value) {
14
7
  return typeof value === "object" && value !== null && !Array.isArray(value);
15
8
  }
@@ -124,7 +117,11 @@ export function jobRunUsesReviewedIntegration(definition, opts) {
124
117
  return jobDeclaresReview(definition) || !!opts.worktree;
125
118
  }
126
119
  function isJobRunState(value) {
127
- return value === "running" || value === "succeeded" || value === "failed" || value === "noop";
120
+ return (value === "running" ||
121
+ value === "succeeded" ||
122
+ value === "partial" ||
123
+ value === "failed" ||
124
+ value === "noop");
128
125
  }
129
126
  function isJobTaskDefinition(value) {
130
127
  if (!isRecord(value))
@@ -137,6 +134,10 @@ function isJobTaskDefinition(value) {
137
134
  return false;
138
135
  if (value.mode === "command") {
139
136
  return (typeof value.command === "string" &&
137
+ (value.partial_exit_code === undefined ||
138
+ (Number.isSafeInteger(value.partial_exit_code) &&
139
+ Number(value.partial_exit_code) >= 1 &&
140
+ Number(value.partial_exit_code) <= 255)) &&
140
141
  (value.precondition === undefined ||
141
142
  (isRecord(value.precondition) &&
142
143
  typeof value.precondition.command === "string" &&
@@ -219,7 +220,7 @@ function readJobRunRecord(filePath) {
219
220
  export function loadJobRunRecord(filePath) {
220
221
  return readJobRunRecord(filePath);
221
222
  }
222
- function validateJobInputValue(value, input, key) {
223
+ export function validateJobInputValue(value, input, key) {
223
224
  const values = input.type === "list" ? value : [value];
224
225
  if (input.enum) {
225
226
  for (const item of values) {
@@ -378,6 +379,13 @@ export function parseJobDefinition(value, fileName) {
378
379
  const command = typeof value.task.command === "string" ? value.task.command.trim() : "";
379
380
  if (!command)
380
381
  errors.push("task.command is required for command mode");
382
+ const partialExitCode = value.task.partial_exit_code;
383
+ if (partialExitCode !== undefined &&
384
+ (!Number.isSafeInteger(partialExitCode) ||
385
+ Number(partialExitCode) < 1 ||
386
+ Number(partialExitCode) > 255)) {
387
+ errors.push("task.partial_exit_code must be an exit code from 1 to 255");
388
+ }
381
389
  let precondition;
382
390
  if (value.task.precondition !== undefined) {
383
391
  if (!isRecord(value.task.precondition)) {
@@ -445,6 +453,9 @@ export function parseJobDefinition(value, fileName) {
445
453
  mode: "command",
446
454
  ...(precondition ? { precondition } : {}),
447
455
  command,
456
+ ...(Number.isSafeInteger(partialExitCode)
457
+ ? { partial_exit_code: Number(partialExitCode) }
458
+ : {}),
448
459
  ...(analysis ? { analysis } : {}),
449
460
  ...common,
450
461
  };
@@ -467,8 +478,9 @@ export function parseJobDefinition(value, fileName) {
467
478
  }
468
479
  if (value.task.analysis !== undefined ||
469
480
  value.task.command !== undefined ||
470
- value.task.precondition !== undefined) {
471
- errors.push("task.command, task.precondition, and task.analysis are only allowed in command mode");
481
+ value.task.precondition !== undefined ||
482
+ value.task.partial_exit_code !== undefined) {
483
+ errors.push("task.command, task.precondition, task.partial_exit_code, and task.analysis are only allowed in command mode");
472
484
  }
473
485
  if (value.task.capabilities !== undefined && !validStringList(value.task.capabilities)) {
474
486
  errors.push("task.capabilities must be a non-empty string list");
@@ -577,7 +589,7 @@ export function loadJobDefinition(paths, jobId) {
577
589
  const filePath = candidates.find(existsSync);
578
590
  if (!filePath)
579
591
  throw new Error(`Job not found: ${normalized} (in ${paths.jobsPath})`);
580
- const parsed = parseJobDefinition(yaml.load(readFileSync(filePath, "utf8")), basename(filePath));
592
+ const parsed = parseJobDefinition(load(readFileSync(filePath, "utf8")), basename(filePath));
581
593
  if (!parsed.job)
582
594
  throw new Error(parsed.errors.join("\n"));
583
595
  return parsed.job;
@@ -591,7 +603,7 @@ export function loadAllJobs(jobsPath) {
591
603
  .filter((path) => /(?:^|\/)job-[^/]+\.ya?ml$/.test(path))
592
604
  .sort()) {
593
605
  try {
594
- const parsed = parseJobDefinition(yaml.load(readFileSync(filePath, "utf8")), basename(filePath));
606
+ const parsed = parseJobDefinition(load(readFileSync(filePath, "utf8")), basename(filePath));
595
607
  errors.push(...parsed.errors);
596
608
  if (parsed.job)
597
609
  jobs.push(parsed.job);
@@ -617,7 +629,7 @@ export function parseJobInputs(raw) {
617
629
  }
618
630
  return result;
619
631
  }
620
- function parseInputValue(value, type, key) {
632
+ export function parseInputValue(value, type, key) {
621
633
  if (type === "string")
622
634
  return String(value);
623
635
  if (type === "integer") {
@@ -640,7 +652,7 @@ function parseInputValue(value, type, key) {
640
652
  .map((item) => item.trim())
641
653
  .filter(Boolean);
642
654
  }
643
- function getPath(source, path) {
655
+ export function getPath(source, path) {
644
656
  let current = source;
645
657
  for (const part of path.split(".")) {
646
658
  if (!isRecord(current) || !Object.hasOwn(current, part))
@@ -675,557 +687,3 @@ export function renderJobTemplate(template, context) {
675
687
  throw new Error(`Unknown job template value: ${path}`);
676
688
  });
677
689
  }
678
- export function jobCheckpoint(paths, jobId) {
679
- return deriveJobState(paths).jobs[jobId]?.checkpoint ?? {};
680
- }
681
- export function deriveJobState(paths) {
682
- const state = { version: 1, jobs: {} };
683
- if (!existsSync(paths.runsPath))
684
- return state;
685
- for (const filePath of listFilesRecursive(paths.runsPath)
686
- .filter((path) => path.endsWith(".json"))
687
- .sort()) {
688
- try {
689
- const run = readJobRunRecord(filePath);
690
- if (!run.checkpoint_after || (run.state !== "succeeded" && run.state !== "noop"))
691
- continue;
692
- const current = state.jobs[run.job_id];
693
- if (!current || current.updated_at < run.updated_at) {
694
- state.jobs[run.job_id] = {
695
- checkpoint: run.checkpoint_after,
696
- last_run_id: run.run_id,
697
- updated_at: run.updated_at,
698
- };
699
- }
700
- }
701
- catch {
702
- // Invalid Run files are reported by schema validation; a broken file must not erase
703
- // checkpoints that can still be derived from other valid history entries.
704
- }
705
- }
706
- return state;
707
- }
708
- function resolveInputs(definition, raw, checkpoint) {
709
- const definitions = definition.inputs ?? {};
710
- for (const key of Object.keys(raw)) {
711
- if (!definitions[key])
712
- throw new Error(`Unknown input for ${definition.id}: ${key}`);
713
- }
714
- const values = {};
715
- for (const [key, input] of Object.entries(definitions)) {
716
- let value = raw[key];
717
- if (value === undefined && input.from_checkpoint)
718
- value = getPath(checkpoint, input.from_checkpoint);
719
- if (value === undefined && input.resolve === "git_head") {
720
- const result = spawnSync("git", ["rev-parse", "HEAD"], {
721
- cwd: specdojoRootDir(),
722
- encoding: "utf8",
723
- env: gitEnvironment(),
724
- });
725
- if (result.status !== 0)
726
- throw new Error(`Unable to resolve git HEAD for input ${key}`);
727
- value = result.stdout.trim();
728
- }
729
- if (value === undefined && input.default !== undefined)
730
- value = input.default;
731
- if (value === undefined) {
732
- if (input.required)
733
- throw new Error(`Missing required input for ${definition.id}: ${key}`);
734
- continue;
735
- }
736
- const parsed = parseInputValue(value, input.type, key);
737
- validateJobInputValue(parsed, input, key);
738
- if (input.git_revision) {
739
- if (input.type !== "string")
740
- throw new Error(`Input ${key} with git_revision must be a string`);
741
- const result = spawnSync("git", ["rev-parse", String(parsed)], {
742
- cwd: specdojoRootDir(),
743
- encoding: "utf8",
744
- env: gitEnvironment(),
745
- });
746
- if (result.status !== 0)
747
- throw new Error(`Unable to resolve git revision for input ${key}: ${parsed}`);
748
- values[key] = result.stdout.trim();
749
- }
750
- else {
751
- values[key] = parsed;
752
- }
753
- }
754
- return values;
755
- }
756
- function qualifyTargets(projectId, targets) {
757
- return targets.map((target) => (target.includes(":") ? target : `${projectId}:${target}`));
758
- }
759
- function runIdFor(definition, idempotencyKey) {
760
- const slug = definition.id.slice(4);
761
- const digest = createHash("sha256").update(idempotencyKey).digest("hex").slice(0, 12);
762
- return `JBR-${slug}-${digest}`;
763
- }
764
- function repoRelative(absPath) {
765
- return relative(specdojoRootDir(), absPath).replaceAll("\\", "/");
766
- }
767
- const MAX_COMMAND_OUTPUT_BYTES = 64 * 1024;
768
- function appendCommandOutput(chunks, chunk, capturedBytes) {
769
- if (capturedBytes >= MAX_COMMAND_OUTPUT_BYTES) {
770
- return { capturedBytes, truncated: chunk.length > 0 };
771
- }
772
- const remaining = MAX_COMMAND_OUTPUT_BYTES - capturedBytes;
773
- chunks.push(chunk.subarray(0, remaining));
774
- return {
775
- capturedBytes: capturedBytes + Math.min(chunk.length, remaining),
776
- truncated: chunk.length > remaining,
777
- };
778
- }
779
- function commandOutputText(chunks, truncated) {
780
- const text = Buffer.concat(chunks).toString("utf8");
781
- return truncated ? text.replace(/\uFFFD$/u, "") : text;
782
- }
783
- /** Executes a materialized Job command directly in the runner process, never through an agent. */
784
- export async function executeJobCommand(command, cwd) {
785
- const startedAt = new Date().toISOString();
786
- return await new Promise((resolveResult) => {
787
- const stdoutChunks = [];
788
- const stderrChunks = [];
789
- let stdoutBytes = 0;
790
- let stderrBytes = 0;
791
- let stdoutTruncated = false;
792
- let stderrTruncated = false;
793
- let settled = false;
794
- const executable = process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh";
795
- const args = process.platform === "win32" ? ["/d", "/s", "/c", command] : ["-eu", "-c", command];
796
- const child = spawn(executable, args, {
797
- cwd,
798
- env: gitEnvironment(),
799
- shell: false,
800
- stdio: ["ignore", "pipe", "pipe"],
801
- windowsHide: true,
802
- });
803
- child.stdout.on("data", (chunk) => {
804
- process.stdout.write(chunk);
805
- const appended = appendCommandOutput(stdoutChunks, chunk, stdoutBytes);
806
- stdoutBytes = appended.capturedBytes;
807
- stdoutTruncated ||= appended.truncated;
808
- });
809
- child.stderr.on("data", (chunk) => {
810
- process.stderr.write(chunk);
811
- const appended = appendCommandOutput(stderrChunks, chunk, stderrBytes);
812
- stderrBytes = appended.capturedBytes;
813
- stderrTruncated ||= appended.truncated;
814
- });
815
- const finish = (exitCode, error) => {
816
- if (settled)
817
- return;
818
- settled = true;
819
- resolveResult({
820
- command,
821
- startedAt,
822
- completedAt: new Date().toISOString(),
823
- exitCode,
824
- stdout: commandOutputText(stdoutChunks, stdoutTruncated),
825
- stderr: commandOutputText(stderrChunks, stderrTruncated),
826
- stdoutTruncated,
827
- stderrTruncated,
828
- ...(error ? { error } : {}),
829
- });
830
- };
831
- child.once("error", (error) => finish(null, error.message));
832
- child.once("close", (code) => finish(code));
833
- });
834
- }
835
- export async function executeJobPrecondition(precondition, cwd) {
836
- const result = await executeJobCommand(precondition.command, cwd);
837
- if (result.error) {
838
- throw new Error(`Job precondition spawn failed: ${result.error}`);
839
- }
840
- if (typeof precondition.skip_when === "number") {
841
- if (result.exitCode === precondition.skip_when) {
842
- return {
843
- result,
844
- skipped: true,
845
- reason: `precondition exited with code ${precondition.skip_when}`,
846
- };
847
- }
848
- if (result.exitCode !== 0) {
849
- throw new Error(`Job precondition exited with code ${result.exitCode ?? "unknown"}`);
850
- }
851
- return { result, skipped: false };
852
- }
853
- if (result.exitCode !== 0) {
854
- throw new Error(`Job precondition exited with code ${result.exitCode ?? "unknown"}`);
855
- }
856
- if (!result.stdout.trim()) {
857
- return { result, skipped: true, reason: "empty selection" };
858
- }
859
- return { result, skipped: false };
860
- }
861
- function jobPlanFrontmatter(projectId, definition, record) {
862
- const localId = `xep-${record.run_id.toLowerCase()}`;
863
- const inner = [
864
- `id: ${projectId}:${localId}`,
865
- "type: exec-plan",
866
- "rulebook: none",
867
- `task_id: ${record.run_id}`,
868
- `name: ${JSON.stringify(definition.name)}`,
869
- // A command Run's plan is consumed only by the optional analysis reporter. Exec result
870
- // frontmatter intentionally keeps the existing edit/review vocabulary for compatibility.
871
- `mode: ${isJobCommandTask(record.task) ? "edit" : record.task.mode}`,
872
- "status: ready",
873
- `project_id: ${projectId}`,
874
- "origin: job",
875
- `job_id: ${definition.id}`,
876
- `run_id: ${record.run_id}`,
877
- ];
878
- if (record.task.owner)
879
- inner.push(`owner: ${record.task.owner}`);
880
- if (record.task.targets) {
881
- inner.push("targets:");
882
- for (const target of record.task.targets)
883
- inner.push(` - ${target}`);
884
- }
885
- if (record.task.paths) {
886
- inner.push("paths:");
887
- for (const path of record.task.paths)
888
- inner.push(` - ${path}`);
889
- }
890
- return buildSpecdojoFrontmatter(inner);
891
- }
892
- export async function generateJobPlan(paths, definition, record) {
893
- const templatePath = execTemplatePath("xep-job-template.md");
894
- if (!existsSync(templatePath))
895
- throw new Error(`Template not found: ${templatePath}`);
896
- const planPath = join(paths.executionPath, "exec", "plans", `${record.run_id}-plan.md`);
897
- mkdirSync(resolve(planPath, ".."), { recursive: true });
898
- const commandTask = isJobCommandTask(record.task) ? record.task : undefined;
899
- const values = {
900
- _FRONTMATTER_: jobPlanFrontmatter(paths.projectId, definition, record),
901
- _JOB_ID_: definition.id,
902
- _JOB_NAME_: definition.name,
903
- _RUN_ID_: record.run_id,
904
- _SCHEDULED_AT_: record.scheduled_at,
905
- _JOB_DESCRIPTION_: commandTask?.analysis?.description ??
906
- (commandTask
907
- ? "コマンドの終了結果を evidence として記録する。agent による判断は行わない。"
908
- : isJobAgentTask(record.task)
909
- ? record.task.description
910
- : ""),
911
- _JOB_EXECUTION_: commandTask
912
- ? [
913
- "### 3.1. 決定論的コマンド",
914
- "",
915
- "runner が次の解決済みコマンドを agent の sandbox 外で直接実行する。",
916
- "",
917
- "```sh",
918
- commandTask.command,
919
- "```",
920
- "",
921
- commandTask.analysis
922
- ? "コマンドが成功した場合だけ、上記の判断を reporter agent が evidence に基づいて行う。"
923
- : "コマンドの終了コードから Run の成否を直接決定する。",
924
- ].join("\n")
925
- : "",
926
- _JOB_INPUTS_: JSON.stringify(record.inputs, null, 2),
927
- _JOB_TARGETS_: record.task.targets?.map((target) => `- [[${target}]]`).join("\n") ?? "- -",
928
- _JOB_PATHS_: record.task.paths?.map((path) => `- \`${path}\``).join("\n") ?? "- -",
929
- _RESULT_REF_: repoRelative(join(paths.executionPath, "exec", "results", `${record.run_id}-result.md`)),
930
- };
931
- const body = expandTemplate(readFileSync(templatePath, "utf8"), values);
932
- const content = injectCommonConventions(body, MISSING, new Map());
933
- writeFileSync(planPath, content, "utf8");
934
- await formatMarkdownFile(planPath);
935
- return planPath;
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
- }
992
- export async function materializeJobRun(opts) {
993
- const paths = resolveJobPaths(opts.projectId);
994
- const definition = loadJobDefinition(paths, opts.jobId);
995
- const checkpoint = jobCheckpoint(paths, definition.id);
996
- const scheduledAt = opts.scheduledAt
997
- ? new Date(opts.scheduledAt).toISOString()
998
- : new Date().toISOString();
999
- const inputs = resolveInputs(definition, parseJobInputs(opts.inputs), checkpoint);
1000
- const identityContext = {
1001
- job_id: definition.id,
1002
- project_id: paths.projectId,
1003
- specdojo: selfRunCommand(),
1004
- scheduled_at: scheduledAt,
1005
- inputs,
1006
- checkpoint,
1007
- };
1008
- const idempotencyKey = renderJobTemplate(definition.run.idempotency_key, identityContext);
1009
- if (!idempotencyKey.trim())
1010
- throw new Error(`Resolved idempotency key is empty: ${definition.id}`);
1011
- const runId = runIdFor(definition, idempotencyKey);
1012
- const context = { ...identityContext, job_run_id: runId };
1013
- const runPath = join(paths.runsPath, `${runId}.json`);
1014
- const targets = definition.task.targets
1015
- ? qualifyTargets(paths.projectId, definition.task.targets)
1016
- : undefined;
1017
- const task = {
1018
- ...definition.task,
1019
- ...(targets ? { targets } : {}),
1020
- };
1021
- if (isJobCommandTask(task)) {
1022
- if (task.precondition) {
1023
- task.precondition = {
1024
- ...task.precondition,
1025
- command: renderJobTemplate(task.precondition.command, context),
1026
- };
1027
- }
1028
- task.command = renderJobTemplate(task.command, context);
1029
- if (task.analysis) {
1030
- task.analysis = {
1031
- ...task.analysis,
1032
- description: renderJobTemplate(task.analysis.description, context),
1033
- };
1034
- }
1035
- }
1036
- else {
1037
- task.description = renderJobTemplate(task.description, context);
1038
- }
1039
- const now = new Date().toISOString();
1040
- const existingRun = existsSync(runPath);
1041
- let record;
1042
- if (existingRun) {
1043
- record = readJobRunRecord(runPath);
1044
- if (record.idempotency_key !== idempotencyKey || record.job_id !== definition.id) {
1045
- throw new Error(`Job Run identity collision: ${runId}`);
1046
- }
1047
- if (record.state === "succeeded" || record.state === "noop") {
1048
- return {
1049
- definition,
1050
- record,
1051
- runPath,
1052
- planPath: join(paths.executionPath, record.plan_ref),
1053
- duplicateComplete: true,
1054
- };
1055
- }
1056
- }
1057
- else {
1058
- record = {
1059
- version: 1,
1060
- run_id: runId,
1061
- job_id: definition.id,
1062
- idempotency_key: idempotencyKey,
1063
- project_id: paths.projectId,
1064
- trigger: opts.trigger ?? "manual",
1065
- scheduled_at: scheduledAt,
1066
- created_at: now,
1067
- updated_at: now,
1068
- state: "running",
1069
- inputs,
1070
- task,
1071
- checkpoint_before: checkpoint,
1072
- plan_ref: `exec/plans/${runId}-plan.md`,
1073
- result_ref: `exec/results/${runId}-result.md`,
1074
- attempts: [],
1075
- };
1076
- }
1077
- if (!existingRun && !opts.dryRun && isJobCommandTask(task) && task.precondition) {
1078
- const precondition = await executeJobPrecondition(task.precondition, specdojoRootDir());
1079
- if (precondition.skipped) {
1080
- return {
1081
- definition,
1082
- record,
1083
- runPath,
1084
- planPath: join(paths.executionPath, record.plan_ref),
1085
- duplicateComplete: false,
1086
- preconditionSkipped: true,
1087
- preconditionReason: precondition.reason,
1088
- preconditionResult: precondition.result,
1089
- };
1090
- }
1091
- }
1092
- const attempt = {
1093
- attempt: record.attempts.length + 1,
1094
- started_at: now,
1095
- status: "running",
1096
- };
1097
- record = {
1098
- ...record,
1099
- updated_at: now,
1100
- state: "running",
1101
- attempts: [...record.attempts, attempt],
1102
- };
1103
- if (!opts.dryRun) {
1104
- mkdirSync(paths.runsPath, { recursive: true });
1105
- writeJson(runPath, record);
1106
- }
1107
- const planPath = opts.dryRun
1108
- ? join(paths.executionPath, record.plan_ref)
1109
- : await generateJobPlan(paths, definition, record);
1110
- return { definition, record, runPath, planPath, duplicateComplete: false };
1111
- }
1112
- export function completeJobRun(opts) {
1113
- const paths = resolveJobPaths(opts.projectId);
1114
- const record = readJobRunRecord(opts.runPath);
1115
- const definition = loadJobDefinition(paths, record.job_id);
1116
- const completedAt = new Date().toISOString();
1117
- const attempts = [...record.attempts];
1118
- const current = attempts.at(-1);
1119
- if (!current)
1120
- throw new Error(`Job Run has no attempt: ${record.run_id}`);
1121
- attempts[attempts.length - 1] = {
1122
- ...current,
1123
- completed_at: completedAt,
1124
- status: opts.status,
1125
- result_ref: record.result_ref,
1126
- ...(opts.evidenceRef ? { evidence_ref: opts.evidenceRef } : {}),
1127
- ...(opts.exitCode !== undefined ? { exit_code: opts.exitCode } : {}),
1128
- ...(opts.reason ? { reason: opts.reason } : {}),
1129
- };
1130
- let checkpointAfter;
1131
- const advanceOn = definition.checkpoint?.advance_on ?? ["succeeded", "noop"];
1132
- if (definition.checkpoint && advanceOn.includes(opts.status)) {
1133
- const context = {
1134
- job_id: definition.id,
1135
- job_run_id: record.run_id,
1136
- project_id: record.project_id,
1137
- specdojo: selfRunCommand(),
1138
- scheduled_at: record.scheduled_at,
1139
- inputs: record.inputs,
1140
- checkpoint: record.checkpoint_before,
1141
- };
1142
- checkpointAfter = Object.fromEntries(Object.entries(definition.checkpoint.values).map(([key, value]) => [
1143
- key,
1144
- renderJobTemplate(value, context),
1145
- ]));
1146
- }
1147
- const updated = {
1148
- ...record,
1149
- updated_at: completedAt,
1150
- state: opts.status,
1151
- attempts,
1152
- ...(checkpointAfter ? { checkpoint_after: checkpointAfter } : {}),
1153
- };
1154
- writeJson(opts.runPath, updated);
1155
- if (checkpointAfter) {
1156
- const state = deriveJobState(paths);
1157
- state.jobs[record.job_id] = {
1158
- checkpoint: checkpointAfter,
1159
- last_run_id: record.run_id,
1160
- updated_at: completedAt,
1161
- };
1162
- mkdirSync(resolve(paths.statePath, ".."), { recursive: true });
1163
- writeJson(paths.statePath, state);
1164
- }
1165
- return updated;
1166
- }
1167
- export function jobRunRelativePath(runPath) {
1168
- return repoRelative(runPath);
1169
- }
1170
- export function registerJobCommands(program) {
1171
- const command = program.command("job").description("Reusable Job Definition and Run helpers");
1172
- command
1173
- .command("where")
1174
- .description("Print resolved Job paths")
1175
- .option("--project <projectId>", "Project id")
1176
- .action((opts) => {
1177
- try {
1178
- const paths = resolveJobPaths(opts.project);
1179
- process.stdout.write(`project: ${paths.projectId}\n`);
1180
- process.stdout.write(`jobs: ${paths.jobsPath}\n`);
1181
- process.stdout.write(`runs: ${paths.runsPath}\n`);
1182
- process.stdout.write(`state: ${paths.statePath}\n`);
1183
- }
1184
- catch (error) {
1185
- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
1186
- process.exitCode = 1;
1187
- }
1188
- });
1189
- command
1190
- .command("validate")
1191
- .description("Validate job-*.yaml definitions")
1192
- .option("--project <projectId>", "Project id")
1193
- .action((opts) => {
1194
- try {
1195
- const paths = resolveJobPaths(opts.project);
1196
- const { jobs, errors } = loadAllJobs(paths.jobsPath);
1197
- for (const error of errors)
1198
- process.stderr.write(`ERROR: ${error}\n`);
1199
- process.stdout.write(`Validated: ${jobs.length} job(s), ${errors.length} error(s)\n`);
1200
- if (errors.length)
1201
- process.exitCode = 1;
1202
- }
1203
- catch (error) {
1204
- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
1205
- process.exitCode = 1;
1206
- }
1207
- });
1208
- command
1209
- .command("list")
1210
- .description("List Job Definitions and latest checkpoint")
1211
- .option("--project <projectId>", "Project id")
1212
- .action((opts) => {
1213
- try {
1214
- const paths = resolveJobPaths(opts.project);
1215
- const { jobs, errors } = loadAllJobs(paths.jobsPath);
1216
- const state = deriveJobState(paths);
1217
- for (const job of jobs) {
1218
- const latest = state.jobs[job.id];
1219
- process.stdout.write(`${job.id}\t${latest?.last_run_id ?? "-"}\t${job.name}\n`);
1220
- }
1221
- for (const error of errors)
1222
- process.stderr.write(`ERROR: ${error}\n`);
1223
- if (errors.length)
1224
- process.exitCode = 1;
1225
- }
1226
- catch (error) {
1227
- process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
1228
- process.exitCode = 1;
1229
- }
1230
- });
1231
- }