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,371 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { dirname, join, relative, resolve, sep } from "node:path";
5
+ import { agentProtectedConfigViolation, captureAgentProtectedConfigSnapshot, changedAgentProtectedConfigPaths, } from "./agent-protected-config.js";
6
+ import { agentGitStateViolation, captureAgentGitStateSnapshot, changedAgentGitStateFields, } from "./agent-git-state.js";
7
+ import { ensureDir, safeSlug } from "./shared.js";
8
+ import { gitEnvironment, gitResult, worktreeNameFromTaskId } from "./worktree.js";
9
+ import { getProjectSchedulePath, loadConfig, resolveAgentMember, specdojoRootDir, } from "../shared/specdojo-config.js";
10
+ export const TRIAL_PROMPT_SUFFIX = `
11
+
12
+ ---
13
+
14
+ # Agent comparison trial instructions
15
+
16
+ This is an isolated comparison trial. Edit and validate the artifacts required by the plan, but
17
+ do not update task lifecycle state or create/update the result file. End the final response with
18
+ exactly one machine-readable executor evidence envelope as documented by SpecDojo.
19
+ `;
20
+ export function sha256(value) {
21
+ return createHash("sha256").update(value).digest("hex");
22
+ }
23
+ function normalizePlanPathCandidate(value) {
24
+ const candidate = value
25
+ .trim()
26
+ .replace(/^\.\//u, "")
27
+ .replace(/:\d+(?::\d+)?$/u, "")
28
+ .replace(/[.,;]$/u, "");
29
+ if (!candidate ||
30
+ candidate.startsWith("/") ||
31
+ candidate.includes("://") ||
32
+ /[\s<>{}*?$]/u.test(candidate) ||
33
+ candidate === ".env" ||
34
+ candidate.startsWith("secrets/")) {
35
+ return null;
36
+ }
37
+ if (/^(?:\.specdojo|docs|scripts|src|tests|tools)\//u.test(candidate) ||
38
+ /^(?:lefthook\.yml|package\.json|tsconfig[^/]*\.json|vitest[^/]*\.ts)$/u.test(candidate)) {
39
+ return candidate;
40
+ }
41
+ return null;
42
+ }
43
+ export function extractPlanRepoPaths(plan) {
44
+ const candidates = [];
45
+ for (const match of plan.matchAll(/`([^`\n]+)`/gu))
46
+ candidates.push(match[1]);
47
+ for (const match of plan.matchAll(/\]\(([^)\s]+)(?:\s+[^)]*)?\)/gu))
48
+ candidates.push(match[1]);
49
+ return [
50
+ ...new Set(candidates
51
+ .map(normalizePlanPathCandidate)
52
+ .filter((candidate) => candidate !== null)),
53
+ ].sort();
54
+ }
55
+ function objectExistsAtCommit(repoRoot, commit, path) {
56
+ return gitResult(repoRoot, ["cat-file", "-e", `${commit}:${path}`]).status === 0;
57
+ }
58
+ export function buildTrialBaseValidation(params) {
59
+ const referencedPaths = extractPlanRepoPaths(params.planContent).map((path) => ({
60
+ path,
61
+ exists_at_base: objectExistsAtCommit(params.repoRoot, params.resolvedCommit, path),
62
+ }));
63
+ const missingReferencedPaths = referencedPaths
64
+ .filter((entry) => !entry.exists_at_base)
65
+ .map((entry) => entry.path);
66
+ const planPathExistsAtBase = objectExistsAtCommit(params.repoRoot, params.resolvedCommit, params.planPath);
67
+ const warnings = [];
68
+ const baseIsAncestorOfHead = gitResult(params.repoRoot, [
69
+ "merge-base",
70
+ "--is-ancestor",
71
+ params.resolvedCommit,
72
+ params.headCommit,
73
+ ]).status === 0;
74
+ if (!baseIsAncestorOfHead) {
75
+ warnings.push("The base commit is not an ancestor of HEAD; the current HEAD cannot be used as a linear reference result.");
76
+ }
77
+ if (!planPathExistsAtBase) {
78
+ warnings.push("The plan file is not present at the base commit; the current plan content will still be supplied to every trial.");
79
+ }
80
+ if (missingReferencedPaths.length > 0) {
81
+ warnings.push(`Referenced paths missing at the base commit: ${missingReferencedPaths.join(", ")}`);
82
+ }
83
+ return {
84
+ requested_revision: params.requestedRevision,
85
+ resolved_commit: params.resolvedCommit,
86
+ head_commit_at_start: params.headCommit,
87
+ base_is_ancestor_of_head: baseIsAncestorOfHead,
88
+ defaulted_to_head: params.defaultedToHead,
89
+ plan_path_exists_at_base: planPathExistsAtBase,
90
+ compatible: baseIsAncestorOfHead && missingReferencedPaths.length === 0,
91
+ referenced_paths: referencedPaths,
92
+ missing_referenced_paths: missingReferencedPaths,
93
+ warnings,
94
+ };
95
+ }
96
+ export function classifyReporterFailure(result, reason) {
97
+ if (result === "rate_limit")
98
+ return "rate_limit";
99
+ return reason.startsWith("reporter output invalid after")
100
+ ? "invalid_output"
101
+ : "invocation_failure";
102
+ }
103
+ export function hasValidExecutorEnvelope(stdout) {
104
+ const matches = [
105
+ ...stdout.matchAll(/<specdojo_executor_evidence>\s*([\s\S]*?)\s*<\/specdojo_executor_evidence>/gu),
106
+ ];
107
+ const raw = matches.at(-1)?.[1];
108
+ if (!raw)
109
+ return false;
110
+ try {
111
+ const value = JSON.parse(raw);
112
+ if (!value || typeof value !== "object" || Array.isArray(value))
113
+ return false;
114
+ const report = value;
115
+ return typeof report.final_message === "string" && Array.isArray(report.validations);
116
+ }
117
+ catch {
118
+ return false;
119
+ }
120
+ }
121
+ export function repoRelative(repoRoot, path) {
122
+ const value = relative(repoRoot, path);
123
+ if (!value || value === ".." || value.startsWith(`..${sep}`)) {
124
+ throw new Error(`Path is outside repository root: ${path}`);
125
+ }
126
+ return value.split(sep).join("/");
127
+ }
128
+ export function comparisonDir(executionPath, comparisonId) {
129
+ return join(executionPath, "exec", "trials", safeSlug(comparisonId));
130
+ }
131
+ export function comparisonPath(executionPath, comparisonId) {
132
+ return join(comparisonDir(executionPath, comparisonId), "comparison.json");
133
+ }
134
+ export function writeComparison(path, value) {
135
+ ensureDir(dirname(path));
136
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
137
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, "utf8");
138
+ renameSync(temporary, path);
139
+ }
140
+ export function readComparison(path) {
141
+ if (!existsSync(path))
142
+ throw new Error(`Comparison not found: ${path}`);
143
+ return JSON.parse(readFileSync(path, "utf8"));
144
+ }
145
+ export function configuredWorktreeBase(schedulePath) {
146
+ const { config } = loadConfig();
147
+ if (!config)
148
+ return undefined;
149
+ const rootDir = specdojoRootDir();
150
+ for (const project of Object.values(config.projects)) {
151
+ if (resolve(rootDir, getProjectSchedulePath(project)) === schedulePath) {
152
+ return project.run?.worktree_base;
153
+ }
154
+ }
155
+ return undefined;
156
+ }
157
+ export function parsePositiveInteger(value, flag) {
158
+ if (!value || !/^\d+$/.test(value) || Number(value) < 1) {
159
+ throw new Error(`${flag} must be a positive integer: ${value ?? ""}`);
160
+ }
161
+ return Number(value);
162
+ }
163
+ export function parseRating(value, flag) {
164
+ if (value === undefined)
165
+ return undefined;
166
+ if (!/^[1-5]$/.test(value))
167
+ throw new Error(`${flag} must be an integer from 1 to 5.`);
168
+ return Number(value);
169
+ }
170
+ export function resolveMember(roster, nickname, stageRole) {
171
+ const member = resolveAgentMember(roster, nickname);
172
+ if (!member)
173
+ throw new Error(`Agent nickname not found in agent-members.yaml: ${nickname}`);
174
+ if (member.disabled)
175
+ throw new Error(`Agent is disabled in agent-members.yaml: ${nickname}`);
176
+ if ((stageRole === "reporter" && member.stage_role !== "reporter") ||
177
+ (stageRole === "executor" && member.stage_role === "reporter")) {
178
+ throw new Error(`Agent must have stage_role: ${stageRole}: ${nickname}`);
179
+ }
180
+ return member;
181
+ }
182
+ export function spawnAgent(command, prompt, cwd, env) {
183
+ return new Promise((resolveOutcome) => {
184
+ const protectedConfigBefore = captureAgentProtectedConfigSnapshot(cwd);
185
+ const gitStateBefore = captureAgentGitStateSnapshot(cwd);
186
+ const child = spawn(command, { cwd, env, shell: true, stdio: ["pipe", "pipe", "pipe"] });
187
+ let stdout = "";
188
+ let stderr = "";
189
+ let settled = false;
190
+ child.stdin.on("error", () => undefined);
191
+ child.stdout.setEncoding("utf8");
192
+ child.stderr.setEncoding("utf8");
193
+ child.stdout.on("data", (chunk) => {
194
+ stdout += chunk;
195
+ process.stdout.write(chunk);
196
+ });
197
+ child.stderr.on("data", (chunk) => {
198
+ stderr += chunk;
199
+ process.stderr.write(chunk);
200
+ });
201
+ const finish = (outcome) => {
202
+ if (settled)
203
+ return;
204
+ settled = true;
205
+ const protectedChanges = changedAgentProtectedConfigPaths(cwd, protectedConfigBefore);
206
+ if (protectedChanges.length > 0) {
207
+ outcome.stderr += `${agentProtectedConfigViolation(protectedChanges)}\n`;
208
+ outcome.exitCode = 1;
209
+ }
210
+ const gitStateChanges = changedAgentGitStateFields(cwd, gitStateBefore);
211
+ if (gitStateChanges.length > 0) {
212
+ outcome.stderr += `${agentGitStateViolation(gitStateChanges)}\n`;
213
+ outcome.exitCode = 1;
214
+ }
215
+ resolveOutcome(outcome);
216
+ };
217
+ child.once("error", (error) => {
218
+ stderr += `${error.message}\n`;
219
+ finish({ exitCode: null, stdout, stderr });
220
+ });
221
+ child.once("close", (exitCode) => finish({ exitCode, stdout, stderr }));
222
+ child.stdin.end(prompt);
223
+ });
224
+ }
225
+ export function worktreeEnvironment(repoRoot, worktreePath, schedulePath, executionPath) {
226
+ return {
227
+ ...gitEnvironment(),
228
+ SPECDOJO_SCHEDULE_PATH: resolve(worktreePath, repoRelative(repoRoot, schedulePath)),
229
+ SPECDOJO_EXECUTION_PATH: resolve(worktreePath, repoRelative(repoRoot, executionPath)),
230
+ };
231
+ }
232
+ function blankTrial(params) {
233
+ const trialId = safeSlug(params.trialId ?? params.agent);
234
+ const worktreeTaskId = `${params.projectId}:trial:${params.comparisonId}:${trialId}`;
235
+ const name = worktreeNameFromTaskId(worktreeTaskId);
236
+ return {
237
+ trial_id: trialId,
238
+ agent: params.agent,
239
+ reporter_agent: params.reporter ?? null,
240
+ worktree: resolve(params.worktreeBase, name),
241
+ branch: `exec/${name}`,
242
+ status: "pending",
243
+ started_at: null,
244
+ completed_at: null,
245
+ duration_ms: null,
246
+ executor: {
247
+ exit_code: null,
248
+ attempts: 0,
249
+ duration_ms: null,
250
+ structured_output: false,
251
+ validations_reported: 0,
252
+ validations_passed: 0,
253
+ validations_failed: 0,
254
+ validations_not_run: 0,
255
+ validations_requires_human: 0,
256
+ files_changed: 0,
257
+ evidence_ref: null,
258
+ final_message: "",
259
+ validations: [],
260
+ changes: [],
261
+ diff_summary: "",
262
+ },
263
+ parent_validation: {
264
+ configured_ids: [...(params.parentValidationIds ?? [])],
265
+ status: params.parentValidationIds?.length ? "not_run" : "not_configured",
266
+ duration_ms: null,
267
+ validations_passed: 0,
268
+ validations_failed: 0,
269
+ validations_not_run: 0,
270
+ },
271
+ reporter: {
272
+ status: "not_run",
273
+ structured_output: false,
274
+ format_attempts: 0,
275
+ format_retries: 0,
276
+ outcome: null,
277
+ output: null,
278
+ failure_category: null,
279
+ failure_reason: "",
280
+ },
281
+ subjective: {
282
+ judgment_quality: null,
283
+ writing_quality: null,
284
+ scope_adherence: null,
285
+ notes: "",
286
+ },
287
+ };
288
+ }
289
+ export function buildComparisonRecord(params) {
290
+ const reporterMode = params.pairs ? "paired" : params.reporter ? "shared" : "none";
291
+ const definitions = params.pairs ??
292
+ (params.agents ?? []).map((agent) => ({ executor: agent, reporter: params.reporter }));
293
+ const trialIds = definitions.map(({ executor, reporter }) => safeSlug(reporterMode === "paired" ? `${executor}-${reporter}` : executor));
294
+ if (new Set(trialIds).size !== trialIds.length) {
295
+ throw new Error("Trial executor/reporter selections must produce distinct trial ids.");
296
+ }
297
+ const baseValidation = params.baseValidation ??
298
+ {
299
+ requested_revision: "HEAD",
300
+ resolved_commit: params.baseCommit,
301
+ head_commit_at_start: params.baseCommit,
302
+ base_is_ancestor_of_head: true,
303
+ defaulted_to_head: true,
304
+ plan_path_exists_at_base: true,
305
+ compatible: true,
306
+ referenced_paths: [],
307
+ missing_referenced_paths: [],
308
+ warnings: [],
309
+ };
310
+ return {
311
+ schema_version: 1,
312
+ comparison_id: params.comparisonId,
313
+ project_id: params.projectId,
314
+ task_id: params.taskId,
315
+ status: "active",
316
+ created_at: params.createdAt,
317
+ completed_at: null,
318
+ base_commit: params.baseCommit,
319
+ base: baseValidation,
320
+ reporter_mode: reporterMode,
321
+ plan: {
322
+ path: params.planPath,
323
+ sha256: sha256(params.planContent),
324
+ prompt_sha256: sha256(params.prompt),
325
+ },
326
+ selected_trial_id: null,
327
+ trials: definitions.map(({ executor, reporter }, index) => blankTrial({
328
+ projectId: params.projectId,
329
+ comparisonId: params.comparisonId,
330
+ agent: executor,
331
+ trialId: trialIds[index],
332
+ reporter,
333
+ worktreeBase: params.worktreeBase,
334
+ parentValidationIds: params.parentValidationIds,
335
+ })),
336
+ agent_selection: {
337
+ policy: "manual",
338
+ target: "agent-members.yaml",
339
+ rationale: "A single comparison does not automatically change agent assignment. A human reviews objective and subjective results, then updates agent-members.yaml priority/capabilities when repeated evidence supports the change.",
340
+ },
341
+ };
342
+ }
343
+ export function updateObjectiveMetrics(trial, evidence, structuredOutput) {
344
+ trial.executor.structured_output = structuredOutput;
345
+ trial.executor.files_changed = evidence.diff_summary.files_changed;
346
+ trial.executor.final_message = evidence.final_message;
347
+ trial.executor.validations = evidence.validations;
348
+ trial.executor.changes = evidence.changes;
349
+ trial.executor.diff_summary = evidence.diff_summary.summary;
350
+ const executorValidations = evidence.validations.filter((validation) => validation.source !== "runner");
351
+ trial.executor.validations_reported = executorValidations.length;
352
+ trial.executor.validations_passed = 0;
353
+ trial.executor.validations_failed = 0;
354
+ trial.executor.validations_not_run = 0;
355
+ trial.executor.validations_requires_human = 0;
356
+ for (const validation of executorValidations) {
357
+ if (validation.status === "passed")
358
+ trial.executor.validations_passed++;
359
+ else if (validation.status === "failed")
360
+ trial.executor.validations_failed++;
361
+ else if (validation.status === "not_run")
362
+ trial.executor.validations_not_run++;
363
+ else if (validation.status === "requires_human") {
364
+ trial.executor.validations_requires_human++;
365
+ }
366
+ }
367
+ const parentValidations = evidence.validations.filter((validation) => validation.source === "runner");
368
+ trial.parent_validation.validations_passed = parentValidations.filter((validation) => validation.status === "passed").length;
369
+ trial.parent_validation.validations_failed = parentValidations.filter((validation) => validation.status === "failed").length;
370
+ trial.parent_validation.validations_not_run = parentValidations.filter((validation) => validation.status === "not_run").length;
371
+ }
@@ -0,0 +1,2 @@
1
+ export { buildComparisonRecord, buildTrialBaseValidation, classifyReporterFailure, extractPlanRepoPaths, updateObjectiveMetrics, } from "./trial-core.js";
2
+ export { registerExecTrialCommands } from "./trial-commands.js";
@@ -1,23 +1,24 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { join, resolve } from "node:path";
4
- import { acquireSchedulerLock, foldEventsToState, readAllEventFiles, releaseSchedulerLock, } from "./exec-events.js";
5
- import { hasMemberCommandSource, loadExecDefaultsConfig, resolveMemberCommand, } from "./exec-agent-config.js";
6
- import { activateResolvedProjectPaths, resolveProjectPaths } from "./exec-project.js";
7
- import { agentGitStateViolation, captureAgentGitStateAcrossRepos, changedAgentGitStateAcrossRepos, qualifiedGitStateFields, } from "./exec-agent-git-state.js";
8
- import { agentProtectedConfigViolation, captureAgentProtectedConfigAcrossRepos, changedAgentProtectedConfigAcrossRepos, qualifiedRepoPaths, } from "./exec-agent-protected-config.js";
9
- import { recordGitStateBlockAcrossRepos, recordProtectedConfigBlockAcrossRepos, } from "./exec-protection-handoff.js";
10
- import { configuredProductRepos, missingProductWorktrees, plannedProjectWorktreePath, pruneOrphanedProductExecBranches, productRepoEnvironment, withAgentExtraRoots, withoutInheritedRepoEnvironment, withProductRepoPrompt, withProductWorktrees, } from "./exec-task-repos.js";
11
- import { buildTaskPhaseMap, loadPrompt, loadRosterForExecutionPath, resolveTaskPhaseContext, selectCandidates, } from "./exec-run.js";
12
- import { buildScheduleIndex } from "./exec-schedule.js";
13
- import { buildInitialStateFromStrategy } from "./exec-schedule-initial.js";
14
- import { generateSinglePlan } from "./exec-plans.js";
15
- import { qualifyTaskId } from "./exec-shared.js";
16
- import { buildTaskView } from "./exec-task-view.js";
17
- import { findExecWorktree, gitEnvironment, gitOutput, gitResult, resolveWorktreeBase, worktreeNameFromTaskId, } from "./exec-worktree.js";
18
- import { checkpointAndEnsureWorktree, commitWorktreeChanges, mergeWorktreeIntoCurrent, pruneOrphanedExecBranches, removeWorktree, taskPaths, worktreeStatusPaths, } from "./exec-worktree-ops.js";
19
- import { getProjectSchedulePath, loadConfig, specdojoRootDir } from "./specdojo-config.js";
20
- export { isCommitTargetPath, stabilizeCommitTargets } from "./exec-worktree-ops.js";
4
+ import { acquireSchedulerLock, foldEventsToState, readAllEventFiles, releaseSchedulerLock, } from "./events.js";
5
+ import { hasMemberCommandSource, loadExecDefaultsConfig, resolveMemberCommand, } from "./agent-config.js";
6
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "./project.js";
7
+ import { agentGitStateViolation, captureAgentGitStateAcrossRepos, changedAgentGitStateAcrossRepos, qualifiedGitStateFields, } from "./agent-git-state.js";
8
+ import { agentProtectedConfigViolation, captureAgentProtectedConfigAcrossRepos, changedAgentProtectedConfigAcrossRepos, qualifiedRepoPaths, } from "./agent-protected-config.js";
9
+ import { recordGitStateBlockAcrossRepos, recordProtectedConfigBlockAcrossRepos, } from "./protection-handoff.js";
10
+ import { configuredProductRepos, missingProductWorktrees, plannedProjectWorktreePath, pruneOrphanedProductExecBranches, productRepoEnvironment, withAgentExtraRoots, withoutInheritedRepoEnvironment, withProductRepoPrompt, withProductWorktrees, } from "./task-repos.js";
11
+ import { resolveAgentMember } from "../shared/specdojo-config.js";
12
+ import { buildTaskPhaseMap, loadPrompt, loadRosterForExecutionPath, resolveTaskPhaseContext, selectCandidates, } from "./run/run.js";
13
+ import { buildScheduleIndex } from "./schedule/schedule.js";
14
+ import { buildInitialStateFromStrategy } from "./schedule/initial.js";
15
+ import { generateSinglePlan } from "./plans.js";
16
+ import { qualifyTaskId } from "./shared.js";
17
+ import { buildTaskView } from "./task-view.js";
18
+ import { findExecWorktree, gitEnvironment, gitOutput, gitResult, resolveWorktreeBase, worktreeNameFromTaskId, } from "./worktree.js";
19
+ import { checkpointAndEnsureWorktree, commitWorktreeChanges, mergeWorktreeIntoCurrent, pruneOrphanedExecBranches, removeWorktree, taskPaths, worktreeStatusPaths, } from "./worktree-ops.js";
20
+ import { getProjectSchedulePath, loadConfig, specdojoRootDir } from "../shared/specdojo-config.js";
21
+ export { isCommitTargetPath, stabilizeCommitTargets } from "./worktree-ops.js";
21
22
  const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
22
23
  const DEFAULT_LOCK_STALE_MS = 300_000;
23
24
  function commandError(error) {
@@ -97,11 +98,12 @@ function resolveAgent(context, taskId, opts) {
97
98
  if ((task.execution ?? "agent") === "human" && !opts.by) {
98
99
  throw new Error(`Task requires human execution. Use --by <nickname> to override: ${taskId}`);
99
100
  }
100
- const member = roster?.members.find((item) => item.nickname === nickname &&
101
- item.type === "agent" &&
102
- hasMemberCommandSource(execDefaults, item));
101
+ const resolvedMember = resolveAgentMember(roster, nickname);
102
+ const member = resolvedMember && hasMemberCommandSource(execDefaults, resolvedMember)
103
+ ? resolvedMember
104
+ : undefined;
103
105
  const command = member ? resolveMemberCommand(execDefaults, member) : undefined;
104
- if (!command) {
106
+ if (!member || !command) {
105
107
  throw new Error(`Agent command not found for actor: ${nickname}`);
106
108
  }
107
109
  if (!opts.by) {
@@ -110,14 +112,14 @@ function resolveAgent(context, taskId, opts) {
110
112
  throw new Error(`Cannot resolve phase context for task: ${taskId}`);
111
113
  }
112
114
  const candidates = selectCandidates({ capabilities: task.capabilities ?? [], proficiency: task.proficiency }, roster, task.mode ?? "edit", undefined, execDefaults);
113
- if (!candidates.some((candidate) => candidate.nickname === nickname)) {
115
+ if (!candidates.some((candidate) => candidate.nickname === member.nickname)) {
114
116
  throw new Error(`Claim actor does not satisfy task agent requirements: ${nickname}`);
115
117
  }
116
118
  }
117
119
  const prompt = loadPrompt(context.executionPath, taskId);
118
120
  if (!prompt)
119
121
  throw new Error(`Plan not found for task: ${taskId}`);
120
- return { actor: nickname, command, provider: member?.provider, prompt };
122
+ return { actor: member.nickname, command, provider: member.provider, prompt };
121
123
  }
122
124
  function printWorktree(worktree) {
123
125
  process.stdout.write(`worktree: ${worktree.path}\nbranch: ${worktree.branch}\n`);