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,570 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { loadExecDefaultsConfig, resolveMemberCommand, } from "../agent-config.js";
5
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "../project.js";
6
+ import { randomHex } from "../shared.js";
7
+ import { specdojoRootDir, resolveAgentMember, } from "../../shared/specdojo-config.js";
8
+ import { extractLocalId } from "../../schedule/phase-sets.js";
9
+ import { archivePlan, buildInPlaceStem, generateDeliverablePlan, generateSinglePlan, parsePlanTaskIdentity, resolveDeliverableTarget, finalizeResultSectionsForDeliverable, targetDocIdsForScheduledTask, stemFromPlanPath, } from "../plans.js";
10
+ import { buildTaskView } from "../task-view.js";
11
+ import { isResultUnfilled, readResultFrontmatterSnapshot, renderReporterResult, scaffoldResult, updateResultStatus, } from "../results.js";
12
+ import { gitEnvironment } from "../worktree.js";
13
+ import { agentProtectedConfigViolation, captureAgentProtectedConfigSnapshot, changedAgentProtectedConfigPaths, } from "../agent-protected-config.js";
14
+ import { agentGitStateViolation, captureAgentGitStateSnapshot, changedAgentGitStateFields, } from "../agent-git-state.js";
15
+ import { recordGitStateBlock, recordProtectedConfigBlock } from "../protection-handoff.js";
16
+ import { recordExecutorEvidence, recordReporterFailureOutput, writeExecutorEvidence, } from "../evidence.js";
17
+ import { deriveReporterFacts, evidenceForReporter, runReporterWithFormatRetry, } from "../reporter.js";
18
+ import { createPipelineState, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "../pipeline-state.js";
19
+ import { pinnedExecutor, pinnedReporter, resolvePinnedRateLimitRunOptions, resolveExecDefaultsPath, selectCandidates, } from "./shared.js";
20
+ import { appendParentValidationsToExecutorEvidence, buildExecutorPrompt, executorRequirements, expandPromptRefs, extractBlockReason, loadRosterForExecutionPath, reportProtectionHandoffRecord, resolveReporterAgentCandidates, runWithRetry, } from "./agent.js";
21
+ import { gradeBeforeReviewPlan } from "./schedule-prepare.js";
22
+ import { pipelineRecoveryMeta, spawnBlock, spawnClaim, spawnComplete } from "./mode-shared.js";
23
+ // Resolve the agent command and the actor for an in-place run, ignoring task state. Unlike the
24
+ // worktree flow, this never requires the task to be claimable. The actor is derived the same way
25
+ // as the worktree path (`prepareTask`): explicit --by wins, otherwise the resolved member's
26
+ // nickname. This lets --track-state record events without forcing --by.
27
+ export function resolveInPlaceCommand(task, roster, opts, execDefaults = {}) {
28
+ if (!task?.agent_pipeline && (opts.executorBy || opts.reporterBy)) {
29
+ throw new Error("--executor-by / --reporter-by require an agent_pipeline task.");
30
+ }
31
+ // A task definition can pin the delegated agent by nickname (Job `task.agent`). An explicit
32
+ // --by still wins so an operator can redirect a single run without editing the definition.
33
+ const by = (task?.agent_pipeline
34
+ ? (opts.executorBy ?? opts.by ?? pinnedExecutor(task))
35
+ : (opts.by ?? pinnedExecutor(task)))?.trim();
36
+ if (by) {
37
+ const member = resolveAgentMember(roster, by);
38
+ if (task?.agent_pipeline && member?.stage_role !== "executor") {
39
+ throw new Error(`Agent must have stage_role: executor for this pipeline stage: ${by}`);
40
+ }
41
+ const command = member ? resolveMemberCommand(execDefaults, member) : undefined;
42
+ if (!member || !command)
43
+ throw new Error(`Agent command not found for actor: ${by}`);
44
+ return {
45
+ command,
46
+ actor: member.nickname,
47
+ ...(member.provider ? { provider: member.provider } : {}),
48
+ };
49
+ }
50
+ if (task && (task.execution ?? "agent") === "human") {
51
+ throw new Error(`Task requires human execution. Use --by <nickname> to override: ${task.id}`);
52
+ }
53
+ const candidates = selectCandidates((task && executorRequirements(task)) ?? {
54
+ capabilities: task?.capabilities ?? [],
55
+ proficiency: task?.proficiency,
56
+ }, roster, task?.mode ?? "edit", undefined, execDefaults);
57
+ const candidate = candidates[0];
58
+ const command = candidate ? resolveMemberCommand(execDefaults, candidate) : undefined;
59
+ if (!candidate || !command)
60
+ throw new Error("No agent found. Specify --by <nickname>.");
61
+ return {
62
+ command,
63
+ actor: candidate.nickname,
64
+ ...(candidate.provider ? { provider: candidate.provider } : {}),
65
+ };
66
+ }
67
+ // Default two-stage pipeline for in-place runs whose task has no schedule definition (a
68
+ // bring-your-own --plan or --deliverable). Stage requirements are left open so explicit
69
+ // --executor-by / --reporter-by nicknames (or stage_role-based auto selection) decide the agents.
70
+ const DEFAULT_IN_PLACE_AGENT_PIPELINE = {
71
+ stages: [{ stage_role: "executor" }, { stage_role: "reporter" }],
72
+ };
73
+ // Decide whether an in-place run without a schedule-defined task (--plan / --deliverable) uses
74
+ // the executor/reporter pipeline. --executor-by / --reporter-by opt in to the pipeline. A --by
75
+ // nickname that names a pipeline stage agent is rejected as a configuration error: an executor
76
+ // stage agent never writes the result, so a single-agent run would always end with an unfilled
77
+ // result instead of a meaningful outcome.
78
+ export function resolveInPlaceAgentPipeline(task, roster, opts, source) {
79
+ if (task?.agent_pipeline)
80
+ return task.agent_pipeline;
81
+ const flag = source === "plan" ? "--plan" : "--deliverable";
82
+ if (opts.executorBy || opts.reporterBy) {
83
+ if (opts.by) {
84
+ throw new Error("--by cannot be combined with --executor-by / --reporter-by.");
85
+ }
86
+ if (!task) {
87
+ throw new Error(`${flag} pipeline execution requires a plan with task_id in its frontmatter (the reporter fills the scaffolded result).`);
88
+ }
89
+ return DEFAULT_IN_PLACE_AGENT_PIPELINE;
90
+ }
91
+ const by = opts.by?.trim();
92
+ if (!by)
93
+ return undefined;
94
+ const member = resolveAgentMember(roster, by);
95
+ if (member?.stage_role === "executor") {
96
+ throw new Error(`--by ${by} is a pipeline executor agent (stage_role: executor) and does not write the result. ` +
97
+ `Run ${flag} with --executor-by ${by} --reporter-by <reporter> instead.`);
98
+ }
99
+ if (member?.stage_role === "reporter") {
100
+ throw new Error(`--by ${by} is a pipeline reporter agent (stage_role: reporter) and cannot run a plan by itself. ` +
101
+ `Run ${flag} with --executor-by <executor> --reporter-by ${by} instead.`);
102
+ }
103
+ return undefined;
104
+ }
105
+ export async function spawnAgentInPlace(command, prompt, cwd, schedulePath, executionPath, resultPath) {
106
+ const protectedConfigBefore = captureAgentProtectedConfigSnapshot(cwd);
107
+ const gitStateBefore = captureAgentGitStateSnapshot(cwd);
108
+ const child = spawn(command, {
109
+ cwd,
110
+ env: {
111
+ ...gitEnvironment(),
112
+ SPECDOJO_SCHEDULE_PATH: schedulePath,
113
+ SPECDOJO_EXECUTION_PATH: executionPath,
114
+ },
115
+ shell: true,
116
+ stdio: ["pipe", "inherit", "inherit"],
117
+ });
118
+ // executeAgent と同じ理由で、stdin を読まないコマンドの EPIPE は無視する。
119
+ child.stdin.on("error", () => undefined);
120
+ child.stdin.end(prompt);
121
+ const exitCode = await new Promise((resolveExit) => {
122
+ child.once("error", () => resolveExit(1));
123
+ child.once("close", (code) => resolveExit(code ?? 1));
124
+ });
125
+ const protectedConfigChanges = changedAgentProtectedConfigPaths(cwd, protectedConfigBefore);
126
+ if (protectedConfigChanges.length > 0) {
127
+ const reason = agentProtectedConfigViolation(protectedConfigChanges);
128
+ process.stderr.write(`blocked: ${reason}\n`);
129
+ reportProtectionHandoffRecord(recordProtectedConfigBlock({
130
+ resultPath,
131
+ repoRoot: cwd,
132
+ paths: protectedConfigChanges,
133
+ reason,
134
+ }), resultPath);
135
+ return 1;
136
+ }
137
+ const gitStateChanges = changedAgentGitStateFields(cwd, gitStateBefore);
138
+ if (gitStateChanges.length > 0) {
139
+ const reason = agentGitStateViolation(gitStateChanges);
140
+ process.stderr.write(`blocked: ${reason}\n`);
141
+ reportProtectionHandoffRecord(recordGitStateBlock({
142
+ resultPath,
143
+ repoRoot: cwd,
144
+ before: gitStateBefore,
145
+ fields: gitStateChanges,
146
+ reason,
147
+ }), resultPath);
148
+ return 1;
149
+ }
150
+ return exitCode;
151
+ }
152
+ // Default run path: generate the plan on demand and run the agent in the current
153
+ // repository. No worktree, and no claim/complete events unless --track-state.
154
+ export async function runInPlaceMode(opts) {
155
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
156
+ activateResolvedProjectPaths(resolvedPaths);
157
+ const { schedulePath, executionPath, catalogPath, rolesPath, viewpointsPath, projectContext } = resolvedPaths;
158
+ const repoRoot = specdojoRootDir();
159
+ const projectId = resolvedPaths.projectId ?? opts.project ?? process.env.SPECDOJO_PROJECT ?? "";
160
+ const roster = loadRosterForExecutionPath(executionPath);
161
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
162
+ // --track-state controls whether this run records claim/complete events; it no longer affects
163
+ // file naming. Task-identity runs (--task) always use the fixed `<task-id>` stem (shared with
164
+ // claim / run --track-state), so an in-place result can be adopted by claim/complete without
165
+ // renaming; re-runs overwrite the same plan/result and git history is the audit trail. Only
166
+ // --deliverable / ad-hoc runs (no task identity) use a unique stem to avoid id collisions.
167
+ const trackState = !!opts.trackState;
168
+ const plansDir = join(executionPath, "exec", "plans");
169
+ let planPath;
170
+ let slug;
171
+ // Shared plan/result stem. For --task it is the fixed task id; for bring-your-own --plan it is
172
+ // recovered from the plan filename so re-running the same plan overwrites the tied result; for
173
+ // --deliverable it is unique per run (`<slug>-<UTC>-<rand>`).
174
+ let stem;
175
+ let task = null;
176
+ // null target = bring-your-own --plan (not generated, not archived).
177
+ let target = null;
178
+ let planProjectId = "";
179
+ // bring-your-own --plan の frontmatter から復元した targets。scaffold 時に catalog 再解決より優先する。
180
+ let planTargets;
181
+ if (opts.plan) {
182
+ planPath = resolve(opts.plan);
183
+ if (!existsSync(planPath))
184
+ throw new Error(`Plan not found: ${planPath}`);
185
+ stem = stemFromPlanPath(planPath);
186
+ // Recover task identity from the plan frontmatter so the result is scaffolded
187
+ // with complete frontmatter (id/mode/plan_ref/started_at), matching the --task
188
+ // path. Ad-hoc plans without a task_id keep the previous no-scaffold behavior.
189
+ const identity = parsePlanTaskIdentity(readFileSync(planPath, "utf8"));
190
+ if (identity) {
191
+ slug = identity.taskId;
192
+ planProjectId = identity.projectId;
193
+ planTargets = identity.targets;
194
+ task = {
195
+ id: identity.taskId,
196
+ // Derive the catalog local_id so a review result can resolve done_criteria. A scheduled
197
+ // task id (T-<track>-<local_id>-NNN) yields the local_id; a deliverable plan's task_id is
198
+ // already the local_id (slug).
199
+ local_id: extractLocalId(identity.taskId) ?? identity.taskId,
200
+ mode: identity.mode,
201
+ approach: identity.approach,
202
+ schedule_file: "",
203
+ fifo_rank: 0,
204
+ critical_first_rank: 0,
205
+ };
206
+ }
207
+ }
208
+ else if (opts.task) {
209
+ const taskId = opts.task.trim();
210
+ task = buildTaskView(schedulePath, executionPath, taskId);
211
+ slug = taskId;
212
+ stem = taskId;
213
+ planPath = join(plansDir, `${stem}-plan.md`);
214
+ }
215
+ else {
216
+ target = resolveDeliverableTarget(catalogPath ?? "", opts.deliverable.trim());
217
+ slug = target.slug;
218
+ stem = buildInPlaceStem(slug);
219
+ planPath = join(plansDir, `${stem}-plan.md`);
220
+ task = {
221
+ id: slug,
222
+ local_id: target.localId,
223
+ mode: "edit",
224
+ schedule_file: "",
225
+ fifo_rank: 0,
226
+ critical_first_rank: 0,
227
+ };
228
+ }
229
+ // --plan / --deliverable tasks carry no schedule-defined agent_pipeline. Opt in to the
230
+ // executor/reporter pipeline via --executor-by / --reporter-by, and reject a pipeline stage
231
+ // agent passed to --by before it runs (it would leave the result unfilled).
232
+ if (!opts.task) {
233
+ const pipeline = resolveInPlaceAgentPipeline(task, roster, opts, opts.plan ? "plan" : "deliverable");
234
+ if (pipeline && task)
235
+ task.agent_pipeline = pipeline;
236
+ }
237
+ const { command, actor, provider } = resolveInPlaceCommand(task, roster, opts, execDefaults);
238
+ const reporterCandidates = task?.agent_pipeline && task
239
+ ? resolveReporterAgentCandidates(task, roster, execDefaults, undefined, opts.reporterBy ?? pinnedReporter(task))
240
+ : undefined;
241
+ if (task?.agent_pipeline && !reporterCandidates?.length) {
242
+ throw new Error("No agent found for reporter pipeline stage.");
243
+ }
244
+ const label = slug ?? planPath;
245
+ if (opts.dryRun) {
246
+ process.stdout.write(`[dry-run] target: ${label} (state ignored)\n`);
247
+ process.stdout.write(`[dry-run] agent: ${actor}\n`);
248
+ process.stdout.write(`[dry-run] command: ${command}\n`);
249
+ if (reporterCandidates?.[0]) {
250
+ process.stdout.write(`[dry-run] reporter agent: ${reporterCandidates[0].actor ?? "-"}\n`);
251
+ process.stdout.write(`[dry-run] reporter command: ${reporterCandidates[0].command}\n`);
252
+ }
253
+ process.stdout.write(`[dry-run] cwd: ${repoRoot}\n`);
254
+ process.stdout.write(`[dry-run] plan: ${planPath}\n`);
255
+ return;
256
+ }
257
+ // Generate the plan on demand (skip for bring-your-own --plan).
258
+ const generatedPlan = !opts.plan;
259
+ if (opts.task && task) {
260
+ const reviewGradeOutcome = await gradeBeforeReviewPlan({
261
+ task,
262
+ projectId,
263
+ catalogPath,
264
+ repoRoot,
265
+ dryRun: false,
266
+ });
267
+ await generateSinglePlan({
268
+ executionPath,
269
+ projectId,
270
+ catalogPath: catalogPath ?? "",
271
+ rolesPath,
272
+ viewpointsPath,
273
+ projectContext,
274
+ task,
275
+ ...(stem ? { stem } : {}),
276
+ ...(reviewGradeOutcome ? { reviewGradeOutcome } : {}),
277
+ });
278
+ }
279
+ else if (target) {
280
+ await generateDeliverablePlan({
281
+ executionPath,
282
+ projectId,
283
+ catalogPath: catalogPath ?? "",
284
+ rolesPath,
285
+ viewpointsPath,
286
+ projectContext,
287
+ target,
288
+ ...(stem ? { stem } : {}),
289
+ });
290
+ }
291
+ const planPrompt = expandPromptRefs(readFileSync(planPath, "utf8"));
292
+ const prompt = task?.agent_pipeline
293
+ ? buildExecutorPrompt(planPrompt, execDefaults.pipeline?.parent_validations)
294
+ : planPrompt;
295
+ if (trackState) {
296
+ if (!opts.task)
297
+ throw new Error("--track-state requires --task.");
298
+ if (!spawnClaim(projectId, opts.task.trim(), actor)) {
299
+ throw new Error(`Claim failed for ${opts.task.trim()} (omit --track-state to run without state).`);
300
+ }
301
+ }
302
+ // Scaffold the result so the agent fills in a frontmatter-complete file (mirrors on-demand plan
303
+ // generation). Skipped for bring-your-own --plan, where no managed task identity exists.
304
+ // Idempotent: never clobbers an existing result (e.g. one created by claim above).
305
+ let resultPath;
306
+ let resultScaffold;
307
+ if (task && slug) {
308
+ const finalizeSections = task.approach === "finalize" || task.approach === "bootstrap-finalize"
309
+ ? finalizeResultSectionsForDeliverable(catalogPath ?? "", task.local_id, task.approach)
310
+ : undefined;
311
+ const targets = planTargets ??
312
+ targetDocIdsForScheduledTask(catalogPath ?? "", task, projectId || planProjectId);
313
+ resultPath = (await scaffoldResult({
314
+ executionPath,
315
+ taskId: slug,
316
+ mode: task.mode ?? "edit",
317
+ projectId: projectId || planProjectId,
318
+ planRef: `exec/plans/${stem ?? slug}-plan.md`,
319
+ agent: actor,
320
+ startedAt: new Date().toISOString(),
321
+ ...(stem ? { stem } : {}),
322
+ ...(task.approach ? { approach: task.approach } : {}),
323
+ ...(targets ? { targets } : {}),
324
+ ...(finalizeSections ? { finalizeSections } : {}),
325
+ })).resultPath;
326
+ resultScaffold = readResultFrontmatterSnapshot(resultPath);
327
+ }
328
+ process.stdout.write(`Running ${label} in place: ${command}\n`);
329
+ let exitCode;
330
+ let pipelineBlockReason;
331
+ let pipelineEvidenceRef;
332
+ let pipelineStateRef;
333
+ let pipelineRunId;
334
+ let pipelineFailureStage = "executor";
335
+ if (task?.agent_pipeline) {
336
+ const startedAt = new Date().toISOString();
337
+ pipelineRunId = `${new Date().toISOString().replace(/[-:.]/g, "")}-${randomHex(4)}`;
338
+ const stateLocation = pipelineStateLocation({
339
+ repoRoot,
340
+ worktreePath: repoRoot,
341
+ executionPath,
342
+ taskId: task.id,
343
+ runId: pipelineRunId,
344
+ });
345
+ pipelineStateRef = stateLocation.ref;
346
+ let pipelineState = createPipelineState({
347
+ taskId: task.id,
348
+ runId: pipelineRunId,
349
+ updatedAt: startedAt,
350
+ executorActor: actor,
351
+ reporterActor: reporterCandidates?.[0]?.actor,
352
+ });
353
+ pipelineState = updatePipelineStage(pipelineState, "executor", { status: "running", started_at: startedAt }, startedAt);
354
+ writePipelineState(stateLocation.path, pipelineState);
355
+ const outcome = await runWithRetry([{ command, actor, provider }], prompt, execDefaults, repoRoot, {
356
+ ...gitEnvironment(),
357
+ SPECDOJO_SCHEDULE_PATH: schedulePath,
358
+ SPECDOJO_EXECUTION_PATH: executionPath,
359
+ }, resultPath, (opts.executorBy ?? opts.by ?? pinnedExecutor(task))
360
+ ? resolvePinnedRateLimitRunOptions(opts, execDefaults, roster, "executor", {
361
+ command,
362
+ actor,
363
+ provider,
364
+ })
365
+ : undefined);
366
+ const recorded = recordExecutorEvidence({
367
+ repoRoot,
368
+ worktreePath: repoRoot,
369
+ executionPath,
370
+ taskId: task.id,
371
+ runId: pipelineRunId,
372
+ actor: outcome.actor ?? actor,
373
+ status: outcome.result === "success"
374
+ ? "succeeded"
375
+ : outcome.result === "rate_limit"
376
+ ? "rate_limited"
377
+ : "failed",
378
+ startedAt,
379
+ completedAt: new Date().toISOString(),
380
+ exitCode: outcome.exitCode,
381
+ attempts: outcome.attempts,
382
+ stdout: outcome.stdout,
383
+ stderr: outcome.stderr,
384
+ rateLimitEvents: outcome.rateLimitEvents,
385
+ });
386
+ pipelineEvidenceRef = relative(repoRoot, recorded.evidencePath).split(sep).join("/");
387
+ const executorCompletedAt = new Date().toISOString();
388
+ pipelineState = updatePipelineStage(pipelineState, "executor", {
389
+ status: outcome.result === "success"
390
+ ? "succeeded"
391
+ : outcome.protectionBlock
392
+ ? "blocked"
393
+ : outcome.result === "rate_limit"
394
+ ? "rate_limited"
395
+ : "failed",
396
+ attempts: outcome.attempts,
397
+ actor: outcome.actor ?? actor,
398
+ completed_at: executorCompletedAt,
399
+ artifact_ref: pipelineEvidenceRef,
400
+ ...(outcome.rateLimitEvents.length > 0
401
+ ? { rate_limit_events: outcome.rateLimitEvents }
402
+ : {}),
403
+ }, executorCompletedAt);
404
+ writePipelineState(stateLocation.path, pipelineState);
405
+ process.stdout.write(`Executor evidence: ${pipelineEvidenceRef}\n`);
406
+ if (outcome.result === "success") {
407
+ recorded.evidence = await appendParentValidationsToExecutorEvidence({
408
+ execDefaults,
409
+ cwd: repoRoot,
410
+ evidence: recorded.evidence,
411
+ evidencePath: recorded.evidencePath,
412
+ });
413
+ }
414
+ if (outcome.result === "success") {
415
+ pipelineFailureStage = "reporter";
416
+ const reporterEvidence = evidenceForReporter(recorded.evidence, {
417
+ repoRoot,
418
+ worktreePath: repoRoot,
419
+ executionPath,
420
+ ...(resultPath ? { resultPath } : {}),
421
+ });
422
+ const reporterStartedAt = new Date().toISOString();
423
+ pipelineState = updatePipelineStage(pipelineState, "reporter", {
424
+ status: "running",
425
+ actor: reporterCandidates?.[0]?.actor ?? null,
426
+ started_at: reporterStartedAt,
427
+ }, reporterStartedAt);
428
+ writePipelineState(stateLocation.path, pipelineState);
429
+ let reporterAttempts = 0;
430
+ let reporterActor = reporterCandidates?.[0]?.actor;
431
+ const reporterRateLimitEvents = [];
432
+ process.stdout.write(`Running reporter: ${reporterCandidates?.[0]?.command ?? ""}\n`);
433
+ const reporter = await runReporterWithFormatRetry({
434
+ plan: planPrompt,
435
+ evidence: reporterEvidence,
436
+ mode: task.mode ?? "edit",
437
+ invoke: async (reporterPrompt) => {
438
+ const reporterOutcome = await runWithRetry(reporterCandidates ?? [], reporterPrompt, execDefaults, repoRoot, {
439
+ ...gitEnvironment(),
440
+ SPECDOJO_SCHEDULE_PATH: schedulePath,
441
+ SPECDOJO_EXECUTION_PATH: executionPath,
442
+ }, resultPath, (opts.reporterBy ?? pinnedReporter(task))
443
+ ? resolvePinnedRateLimitRunOptions(opts, execDefaults, roster, "reporter", reporterCandidates[0])
444
+ : undefined);
445
+ reporterAttempts += reporterOutcome.attempts;
446
+ reporterActor = reporterOutcome.actor ?? reporterActor;
447
+ reporterRateLimitEvents.push(...reporterOutcome.rateLimitEvents);
448
+ return {
449
+ result: reporterOutcome.result,
450
+ stdout: reporterOutcome.stdout,
451
+ stderr: reporterOutcome.stderr,
452
+ };
453
+ },
454
+ });
455
+ if (reporterRateLimitEvents.length > 0) {
456
+ recorded.evidence.rate_limit_events = [
457
+ ...(recorded.evidence.rate_limit_events ?? []),
458
+ ...reporterRateLimitEvents,
459
+ ];
460
+ reporterEvidence.rate_limit_events = recorded.evidence.rate_limit_events;
461
+ writeExecutorEvidence(recorded.evidencePath, recorded.evidence);
462
+ }
463
+ if (reporter.result === "success" && resultPath) {
464
+ try {
465
+ await renderReporterResult(resultPath, reporter.output, reporterEvidence);
466
+ const facts = deriveReporterFacts(reporterEvidence, { mode: task.mode ?? "edit" });
467
+ exitCode = facts.outcome === "complete" ? 0 : 1;
468
+ pipelineBlockReason = facts.block_reason || undefined;
469
+ process.stdout.write(`Reporter complete: ${reporterCandidates?.[0]?.actor ?? "reporter"} (format attempts: ${reporter.formatAttempts})\n`);
470
+ }
471
+ catch (error) {
472
+ exitCode = 1;
473
+ pipelineBlockReason =
474
+ error instanceof Error
475
+ ? `reporter result rendering failed: ${error.message}`
476
+ : String(error);
477
+ }
478
+ }
479
+ else if (reporter.result === "success") {
480
+ exitCode = 1;
481
+ pipelineBlockReason = "reporter result path is unavailable";
482
+ }
483
+ else {
484
+ exitCode = 1;
485
+ pipelineBlockReason = reporter.reason;
486
+ recordReporterFailureOutput({
487
+ worktreePath: repoRoot,
488
+ evidencePath: recorded.evidencePath,
489
+ evidence: recorded.evidence,
490
+ invocationOutputs: reporter.invocationOutputs,
491
+ });
492
+ }
493
+ const reporterCompletedAt = new Date().toISOString();
494
+ pipelineState = updatePipelineStage(pipelineState, "reporter", {
495
+ status: exitCode === 0
496
+ ? "succeeded"
497
+ : reporter.result === "rate_limit"
498
+ ? "rate_limited"
499
+ : "failed",
500
+ attempts: reporterAttempts,
501
+ actor: reporterActor ?? null,
502
+ completed_at: reporterCompletedAt,
503
+ artifact_ref: reporter.result === "success" && resultPath
504
+ ? relative(repoRoot, resultPath).split(sep).join("/")
505
+ : null,
506
+ ...(reporterRateLimitEvents.length > 0
507
+ ? { rate_limit_events: reporterRateLimitEvents }
508
+ : {}),
509
+ }, reporterCompletedAt);
510
+ writePipelineState(stateLocation.path, pipelineState);
511
+ }
512
+ else {
513
+ pipelineBlockReason =
514
+ outcome.result === "rate_limit"
515
+ ? "executor rate limit reached"
516
+ : extractBlockReason(outcome.stderr);
517
+ exitCode = outcome.exitCode && outcome.exitCode !== 0 ? outcome.exitCode : 1;
518
+ }
519
+ }
520
+ else {
521
+ exitCode = await spawnAgentInPlace(command, prompt, repoRoot, schedulePath, executionPath, resultPath);
522
+ }
523
+ // Some agents (notably `claude -p`) exit 0 even when they conclude they are blocked: a
524
+ // permission-denied tool call is fed back as a tool error and the model ends its turn
525
+ // normally. The agent's core duty is to fill the result while preserving its scaffold
526
+ // frontmatter, so treat an incomplete or modified result as a block even on exit 0.
527
+ let effectiveExit = exitCode;
528
+ let blockReason = pipelineBlockReason;
529
+ if (exitCode === 0 &&
530
+ resultPath &&
531
+ task &&
532
+ isResultUnfilled(resultPath, task.mode ?? "edit", resultScaffold)) {
533
+ effectiveExit = 1;
534
+ blockReason =
535
+ "agent exited 0 but result is incomplete or its frontmatter differs from the scaffold (treated as blocked)";
536
+ process.stdout.write(`run blocked: ${label} (result incomplete or frontmatter changed despite exit 0)\n`);
537
+ }
538
+ // In-place runs do not write claim/complete events unless --track-state, but the result file's
539
+ // own status is a file-level field, so reflect the outcome into it regardless.
540
+ if (resultPath) {
541
+ await updateResultStatus(resultPath, effectiveExit === 0 ? "complete" : "blocked", new Date().toISOString(), blockReason);
542
+ }
543
+ if (trackState && opts.task) {
544
+ if (effectiveExit === 0)
545
+ spawnComplete(projectId, opts.task.trim(), actor);
546
+ else
547
+ spawnBlock(projectId, opts.task.trim(), actor, blockReason ?? "agent exited with non-zero code", {
548
+ limit_deferred: "false",
549
+ ...(pipelineRunId
550
+ ? pipelineRecoveryMeta({
551
+ stage: pipelineFailureStage,
552
+ evidenceRef: pipelineEvidenceRef,
553
+ stateRef: pipelineStateRef,
554
+ runId: pipelineRunId,
555
+ })
556
+ : {}),
557
+ });
558
+ }
559
+ if (effectiveExit !== 0) {
560
+ process.exitCode = effectiveExit;
561
+ process.stdout.write(`run failed: ${label} (exit ${effectiveExit})\n`);
562
+ return;
563
+ }
564
+ if (opts.archiveOnSuccess && generatedPlan && (stem ?? slug)) {
565
+ const archived = archivePlan({ executionPath, slug: stem ?? slug });
566
+ if (archived.to)
567
+ process.stdout.write(`Archived plan: ${archived.to}\n`);
568
+ }
569
+ process.stdout.write(`run done: ${label}\n`);
570
+ }