specdojo 0.3.0 → 0.3.1

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 (104) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/catalog-build-references.js +144 -0
  3. package/dist/catalog-build-render.js +144 -0
  4. package/dist/catalog-build.js +13 -290
  5. package/dist/catalog-generate.js +6 -9
  6. package/dist/catalog-plan-generate.js +2 -2
  7. package/dist/catalog-plan.js +6 -6
  8. package/dist/catalog-scaffold.js +4 -4
  9. package/dist/catalog.js +2 -2
  10. package/dist/dashboard-exec-records.js +105 -0
  11. package/dist/dashboard-routines.js +255 -0
  12. package/dist/dashboard-shared.js +14 -0
  13. package/dist/dashboard-timeline.js +175 -0
  14. package/dist/dashboard.js +10 -544
  15. package/dist/deliverable-trash.js +3 -3
  16. package/dist/doc-index.js +3 -3
  17. package/dist/exec-commands.js +557 -0
  18. package/dist/exec-core.js +457 -0
  19. package/dist/exec-plans-core.js +693 -0
  20. package/dist/exec-plans-generation.js +206 -0
  21. package/dist/exec-plans-storage.js +131 -0
  22. package/dist/exec-plans.js +3 -1018
  23. package/dist/exec-repo-integration-git.js +23 -0
  24. package/dist/exec-repo-integration-sync.js +264 -0
  25. package/dist/exec-repo-integration.js +4 -281
  26. package/dist/exec-reporter-output.js +206 -0
  27. package/dist/exec-reporter.js +2 -206
  28. package/dist/exec-results.js +22 -15
  29. package/dist/exec-run-agent-pipeline.js +256 -0
  30. package/dist/exec-run-agent.js +531 -0
  31. package/dist/exec-run-in-place.js +541 -0
  32. package/dist/exec-run-job.js +717 -0
  33. package/dist/exec-run-lifecycle-commands.js +522 -0
  34. package/dist/exec-run-mode-shared.js +140 -0
  35. package/dist/exec-run-register-command.js +244 -0
  36. package/dist/exec-run-register-core.js +386 -0
  37. package/dist/exec-run-register-mode.js +206 -0
  38. package/dist/exec-run-register-resume.js +393 -0
  39. package/dist/exec-run-register-state.js +322 -0
  40. package/dist/exec-run-register-worktree.js +509 -0
  41. package/dist/exec-run-schedule-mode.js +294 -0
  42. package/dist/exec-run-schedule-prepare.js +353 -0
  43. package/dist/exec-run-schedule-task.js +572 -0
  44. package/dist/exec-run-shared.js +399 -0
  45. package/dist/exec-run.js +11 -6182
  46. package/dist/exec-shared.js +2 -2
  47. package/dist/exec-trial-commands.js +558 -0
  48. package/dist/exec-trial-core.js +371 -0
  49. package/dist/exec-trial.js +2 -921
  50. package/dist/exec-worktree-ops-commit.js +707 -0
  51. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  52. package/dist/exec-worktree-ops-merge.js +303 -0
  53. package/dist/exec-worktree-ops.js +3 -1292
  54. package/dist/exec-worktree.js +32 -4
  55. package/dist/exec.js +2 -1006
  56. package/dist/frontmatter-namespace.js +2 -2
  57. package/dist/grade-apply.js +734 -0
  58. package/dist/grade-command-apply.js +250 -0
  59. package/dist/grade-command-inspect.js +138 -0
  60. package/dist/grade-command-plan.js +101 -0
  61. package/dist/grade-command-shared.js +68 -0
  62. package/dist/grade-core.js +307 -0
  63. package/dist/grade-markdown.js +274 -0
  64. package/dist/grade-pipeline-state.js +184 -0
  65. package/dist/grade-plan.js +507 -0
  66. package/dist/grade-result.js +5 -5
  67. package/dist/grade-target-discovery.js +265 -0
  68. package/dist/grade-targets.js +432 -0
  69. package/dist/grade.js +14 -3188
  70. package/dist/init-command.js +7 -7
  71. package/dist/job-definition.js +670 -0
  72. package/dist/job.js +9 -673
  73. package/dist/kata-command.js +2 -2
  74. package/dist/register-command-types.js +1 -0
  75. package/dist/register-core.js +363 -0
  76. package/dist/register-create-commands.js +245 -0
  77. package/dist/register-events.js +4 -4
  78. package/dist/register-item.js +6 -6
  79. package/dist/register-maintenance-commands.js +187 -0
  80. package/dist/register-migration.js +268 -0
  81. package/dist/register-renumber.js +314 -0
  82. package/dist/register-transition-commands.js +248 -0
  83. package/dist/register-update.js +230 -0
  84. package/dist/register-views.js +256 -0
  85. package/dist/register.js +61 -2069
  86. package/dist/review-plan.js +3 -3
  87. package/dist/routine-definition.js +401 -0
  88. package/dist/routine.js +6 -402
  89. package/dist/schedule-approach.js +2 -2
  90. package/dist/schedule-strategy-generate-document.js +273 -0
  91. package/dist/schedule-strategy-generate-scope.js +199 -0
  92. package/dist/schedule-strategy-generate.js +9 -473
  93. package/dist/schedule.js +4 -4
  94. package/dist/specdojo-config.js +3 -4
  95. package/dist/viewpoint-document-kinds-check.js +3 -3
  96. package/dist/yaml-pages.js +4 -4
  97. package/dist/yaml.js +28 -0
  98. package/docs/ja/specdojo/guides/exec-config-guide.md +6 -6
  99. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +20 -18
  100. package/docs/ja/specdojo/guides/routine-operation-guide.md +1 -1
  101. package/package.json +4 -5
  102. package/templates/antigravity/README.md +3 -3
  103. package/templates/antigravity/exec-defaults-snippet.yaml +6 -4
  104. package/templates/init-exec-defaults.yaml +3 -1
@@ -0,0 +1,717 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { relative, resolve, sep } from "node:path";
4
+ import { selfRunArgs } from "./spawn-self.js";
5
+ import { loadExecDefaultsConfig, resolveMemberCommand, } from "./exec-agent-config.js";
6
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "./exec-project.js";
7
+ import { specdojoRootDir } from "./specdojo-config.js";
8
+ import { ROUTINE_BUSY_SKIP_EXIT_CODE, ROUTINE_EXEC_ENV } from "./exec-run-lock.js";
9
+ import { isResultUnfilled, readResultFrontmatterSnapshot, renderReporterResult, scaffoldResult, updateResultStatus, } from "./exec-results.js";
10
+ import { formatMarkdownFile } from "./exec-format.js";
11
+ import { completeJobRun, executeJobCommand, generateJobReviewPlan, isJobCommandTask, jobRunUsesReviewedIntegration, loadJobDefinition, loadJobRunRecord, materializeJobRun, recordJobRunReview, resolveJobPaths, resolveJobReviewAgentNominations, } from "./job.js";
12
+ import { ensureExecWorktree, gitOutput, gitResult, resolveWorktreeBase, summarizeGitHookFailure, } from "./exec-worktree.js";
13
+ import { mergeWorktreeIntoCurrent, removeWorktree, stabilizeCommitTargets, stageCommitTargets, worktreeStatusPaths, } from "./exec-worktree-ops.js";
14
+ import { recordCommandEvidence } from "./exec-evidence.js";
15
+ import { evidenceForReporter } from "./exec-reporter.js";
16
+ import { createPipelineState, pipelineStateLocation, updatePipelineStage, writePipelineState, } from "./exec-pipeline-state.js";
17
+ import { configuredWorktreeBase, resolveAgentOverride, resolveExecDefaultsPath, selectCandidates, } from "./exec-run-shared.js";
18
+ import { executorRequirements, expandPromptRefs, loadRosterForExecutionPath, resolveReporterAgentCandidates, } from "./exec-run-agent.js";
19
+ import { runAgentPipeline, runReporterStage } from "./exec-run-agent-pipeline.js";
20
+ import { resolveInPlaceCommand, spawnAgentInPlace } from "./exec-run-in-place.js";
21
+ async function runCommandJobMode(params) {
22
+ const { opts, record, runPath, planPath, projectId, schedulePath, executionPath } = params;
23
+ if (!isJobCommandTask(record.task))
24
+ throw new Error("Expected a command Job task.");
25
+ if (opts.by || opts.executorBy) {
26
+ throw new Error("--by and --executor-by are not available for command Jobs; the runner executes command.");
27
+ }
28
+ if (opts.reporterBy && !record.task.analysis) {
29
+ throw new Error("--reporter-by requires task.analysis on a command Job.");
30
+ }
31
+ const repoRoot = specdojoRootDir();
32
+ const roster = loadRosterForExecutionPath(executionPath);
33
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
34
+ const analysisNickname = record.task.analysis
35
+ ? opts.reporterBy?.trim() || record.task.analysis.agent
36
+ : undefined;
37
+ const analysisResolution = analysisNickname
38
+ ? resolveAgentOverride("edit", analysisNickname, {}, roster, execDefaults, "reporter")
39
+ : undefined;
40
+ if (analysisResolution?.kind === "error")
41
+ throw new Error(analysisResolution.message);
42
+ if (analysisResolution && analysisResolution.kind !== "command") {
43
+ throw new Error(`Analysis agent not found: ${analysisNickname ?? ""}`);
44
+ }
45
+ const analysisCandidate = analysisResolution?.kind === "command"
46
+ ? {
47
+ command: analysisResolution.command,
48
+ actor: analysisResolution.actor ?? analysisNickname,
49
+ provider: analysisResolution.provider,
50
+ }
51
+ : undefined;
52
+ if (opts.dryRun) {
53
+ process.stdout.write(`[dry-run] execution: runner command\n`);
54
+ if (record.task.precondition) {
55
+ process.stdout.write(`[dry-run] precondition:\n${record.task.precondition.command}\n`);
56
+ process.stdout.write(`[dry-run] precondition skip_when: ${record.task.precondition.skip_when}\n`);
57
+ }
58
+ process.stdout.write(`[dry-run] command:\n${record.task.command}\n`);
59
+ if (analysisCandidate) {
60
+ process.stdout.write(`[dry-run] agent: ${analysisCandidate.actor ?? ""} (analysis reporter)\n`);
61
+ process.stdout.write(`[dry-run] reporter command: ${analysisCandidate.command}\n`);
62
+ }
63
+ process.stdout.write(`[dry-run] plan: ${planPath}\n`);
64
+ return;
65
+ }
66
+ const resultActor = analysisCandidate?.actor ?? "specdojo-runner";
67
+ const { resultPath } = await scaffoldResult({
68
+ executionPath,
69
+ taskId: record.run_id,
70
+ mode: "edit",
71
+ projectId,
72
+ origin: "job",
73
+ jobId: record.job_id,
74
+ runId: record.run_id,
75
+ planRef: record.plan_ref,
76
+ agent: resultActor,
77
+ startedAt: new Date().toISOString(),
78
+ ...(record.task.targets ? { targets: record.task.targets } : {}),
79
+ });
80
+ const evidenceRunId = `attempt-${record.attempts.length}`;
81
+ process.stdout.write(`Running Job Run ${record.run_id} command in place.\n`);
82
+ const commandOutcome = await executeJobCommand(record.task.command, repoRoot);
83
+ const recorded = recordCommandEvidence({
84
+ repoRoot,
85
+ worktreePath: repoRoot,
86
+ executionPath,
87
+ taskId: record.run_id,
88
+ runId: evidenceRunId,
89
+ actor: "specdojo-runner",
90
+ command: record.task.command,
91
+ shell: process.platform === "win32" ? process.env.ComSpec || "cmd.exe" : "/bin/sh -eu",
92
+ startedAt: commandOutcome.startedAt,
93
+ completedAt: commandOutcome.completedAt,
94
+ exitCode: commandOutcome.exitCode,
95
+ stdout: commandOutcome.stdout,
96
+ stderr: commandOutcome.stderr,
97
+ stdoutTruncated: commandOutcome.stdoutTruncated,
98
+ stderrTruncated: commandOutcome.stderrTruncated,
99
+ ...(commandOutcome.error ? { error: commandOutcome.error } : {}),
100
+ });
101
+ const evidenceRef = relative(repoRoot, recorded.evidencePath).split(sep).join("/");
102
+ process.stdout.write(`Command evidence: ${evidenceRef}\n`);
103
+ const commandSucceeded = commandOutcome.exitCode === 0 && !commandOutcome.error;
104
+ if (!commandSucceeded || !analysisCandidate) {
105
+ const reporterEvidence = evidenceForReporter(recorded.evidence, {
106
+ repoRoot,
107
+ worktreePath: repoRoot,
108
+ executionPath,
109
+ resultPath,
110
+ });
111
+ const reason = commandSucceeded
112
+ ? undefined
113
+ : commandOutcome.error
114
+ ? `command spawn failed: ${commandOutcome.error}`
115
+ : `command exited with code ${commandOutcome.exitCode ?? "unknown"}`;
116
+ await renderReporterResult(resultPath, {
117
+ schema_version: 1,
118
+ mode: "edit",
119
+ summary: [
120
+ commandSucceeded
121
+ ? "runner が解決済みコマンドを直接実行し、終了コード 0 を確認した。"
122
+ : `runner が解決済みコマンドを直接実行したが、${reason}。`,
123
+ ],
124
+ changed_files: reporterEvidence.changes.map(({ path }) => ({
125
+ path,
126
+ summary: "runner command の実行後に検出した変更",
127
+ })),
128
+ handoff: [`command evidence: ${evidenceRef}`],
129
+ approach: "Job Definition から materialize したコマンドを agent の解釈を介さず実行し、runner evidence を正本とした。",
130
+ }, reporterEvidence);
131
+ await updateResultStatus(resultPath, commandSucceeded ? "complete" : "blocked", new Date().toISOString(), reason);
132
+ completeJobRun({
133
+ projectId,
134
+ runPath,
135
+ status: commandSucceeded ? "succeeded" : "failed",
136
+ evidenceRef,
137
+ exitCode: commandOutcome.exitCode,
138
+ ...(reason ? { reason } : {}),
139
+ });
140
+ if (commandSucceeded) {
141
+ process.stdout.write(`Job Run complete: ${record.run_id}\n`);
142
+ }
143
+ else {
144
+ process.stdout.write(`Job Run failed: ${record.run_id}\n`);
145
+ process.exitCode = commandOutcome.exitCode || 1;
146
+ }
147
+ return;
148
+ }
149
+ const stateLocation = pipelineStateLocation({
150
+ repoRoot,
151
+ worktreePath: repoRoot,
152
+ executionPath,
153
+ taskId: record.run_id,
154
+ runId: evidenceRunId,
155
+ });
156
+ let state = createPipelineState({
157
+ taskId: record.run_id,
158
+ runId: evidenceRunId,
159
+ updatedAt: commandOutcome.completedAt,
160
+ executorActor: "specdojo-runner",
161
+ reporterActor: analysisCandidate.actor,
162
+ artifacts: {
163
+ plan_ref: relative(repoRoot, planPath).split(sep).join("/"),
164
+ result_ref: relative(repoRoot, resultPath).split(sep).join("/"),
165
+ },
166
+ });
167
+ state = updatePipelineStage(state, "executor", {
168
+ status: "succeeded",
169
+ attempts: 1,
170
+ started_at: commandOutcome.startedAt,
171
+ completed_at: commandOutcome.completedAt,
172
+ artifact_ref: evidenceRef,
173
+ }, commandOutcome.completedAt);
174
+ writePipelineState(stateLocation.path, state);
175
+ const reporterOutcome = await runReporterStage({
176
+ repoRoot,
177
+ cwd: repoRoot,
178
+ schedulePath,
179
+ executionPath,
180
+ reporterCandidates: [analysisCandidate],
181
+ planPrompt: expandPromptRefs(readFileSync(planPath, "utf8")),
182
+ resultPath,
183
+ execDefaults,
184
+ evidence: recorded.evidence,
185
+ evidencePath: recorded.evidencePath,
186
+ state,
187
+ statePath: stateLocation.path,
188
+ });
189
+ const reason = reporterOutcome.blockReason;
190
+ await updateResultStatus(resultPath, reporterOutcome.exitCode === 0 ? "complete" : "blocked", new Date().toISOString(), reason);
191
+ completeJobRun({
192
+ projectId,
193
+ runPath,
194
+ status: reporterOutcome.exitCode === 0 ? "succeeded" : "failed",
195
+ evidenceRef,
196
+ exitCode: commandOutcome.exitCode,
197
+ ...(reason ? { reason } : {}),
198
+ });
199
+ if (reporterOutcome.exitCode === 0) {
200
+ process.stdout.write(`Job Run complete: ${record.run_id}\n`);
201
+ }
202
+ else {
203
+ process.stdout.write(`Job Run failed: ${record.run_id}\n`);
204
+ process.exitCode = 1;
205
+ }
206
+ }
207
+ const ACCEPTED_JOB_REVIEW_VERDICTS = new Set(["complete", "complete-with-findings"]);
208
+ function jobChildArgs(opts, projectId, scheduledAt) {
209
+ const args = ["exec", "run", "--job", String(opts.job), "--project", projectId];
210
+ const inputs = Array.isArray(opts.input) ? opts.input : opts.input ? [opts.input] : [];
211
+ for (const input of inputs)
212
+ args.push("--input", input);
213
+ args.push("--scheduled-at", scheduledAt);
214
+ if (opts.jobTrigger)
215
+ args.push("--job-trigger", opts.jobTrigger);
216
+ if (opts.by)
217
+ args.push("--by", opts.by);
218
+ if (opts.reporterBy)
219
+ args.push("--reporter-by", opts.reporterBy);
220
+ if (opts.execDefaults)
221
+ args.push("--exec-defaults", opts.execDefaults);
222
+ return args;
223
+ }
224
+ function commitJobPaths(worktreePath, paths, subject, body) {
225
+ const unique = [...new Set(paths)].sort();
226
+ if (unique.length === 0)
227
+ throw new Error("Job Run produced no tracked output to commit.");
228
+ stageCommitTargets(worktreePath, unique);
229
+ const staged = gitResult(worktreePath, ["diff", "--cached", "--quiet", "--", ...unique]);
230
+ if (staged.status === 0)
231
+ throw new Error("Job Run output has no staged changes.");
232
+ if (staged.status !== 1)
233
+ throw new Error("Failed to inspect staged Job Run output.");
234
+ const commit = gitResult(worktreePath, ["commit", "-m", subject, "-m", body, "--", ...unique]);
235
+ if (commit.status !== 0) {
236
+ const output = [commit.stdout, commit.stderr]
237
+ .filter((part) => typeof part === "string" && part.length > 0)
238
+ .join("\n");
239
+ throw new Error(`git commit failed: ${summarizeGitHookFailure(output)}`);
240
+ }
241
+ stabilizeCommitTargets(worktreePath, () => worktreeStatusPaths(worktreePath).filter((path) => unique.includes(path)));
242
+ return gitOutput(worktreePath, ["rev-parse", "HEAD"]).trim();
243
+ }
244
+ function jobReviewVerdict(resultPath) {
245
+ const match = readFileSync(resultPath, "utf8").match(/^- verdict:\s*(complete|complete-with-findings|incomplete|grade-stale|grade-unavailable|changed-during-review)\s*$/m);
246
+ return match?.[1];
247
+ }
248
+ async function fillIncompleteJobReviewResult(resultPath, reason) {
249
+ const safeReason = reason.replace(/\s+/g, " ").trim();
250
+ let content = readFileSync(resultPath, "utf8");
251
+ content = content
252
+ .replace(/_TODO_: 評価結果サイドカー[^\n]*/, `Job Run の review を完了できなかった: ${safeReason}`)
253
+ .replace(/_TODO_: 変更内容[^\n]*/, `- runner が review を完了できなかったため統合不可と判断した。`)
254
+ .replace(/_TODO_: 未充足事項[^\n]*/, `- ${safeReason}`)
255
+ .replace(/_TODO_: `approach`[^\n]*/, "Job Run の出力は変更していない。")
256
+ .replace(/- verdict: _TODO_([^\n]*)/, "- verdict: incomplete");
257
+ writeFileSync(resultPath, content, "utf8");
258
+ await formatMarkdownFile(resultPath);
259
+ }
260
+ async function overrideJobReviewDecision(resultPath, verdict, reason) {
261
+ let content = readFileSync(resultPath, "utf8");
262
+ content = content.replace(/^- verdict:\s*(?:complete|complete-with-findings|incomplete|grade-stale|grade-unavailable|changed-during-review)\s*$/m, `- verdict: ${verdict}`);
263
+ const instruction = `- runner 判定: ${reason.replace(/\s+/g, " ").trim()}`;
264
+ if (!content.includes(instruction)) {
265
+ content = content.replace("\n## 4. approach に応じた確認", `\n${instruction}\n\n## 4. approach に応じた確認`);
266
+ }
267
+ writeFileSync(resultPath, content, "utf8");
268
+ await formatMarkdownFile(resultPath);
269
+ }
270
+ // Child process marker for the Job executed inside the review worktree. The child must run
271
+ // the Job in place; without it a Job that declares task.review would re-enter the worktree.
272
+ const JOB_REVIEW_WORKTREE_CHILD_ENV = "SPECDOJO_JOB_REVIEW_WORKTREE_CHILD";
273
+ function jobReviewAgentSourceLabel(nomination, cliFlag) {
274
+ return nomination.source === "cli"
275
+ ? cliFlag
276
+ : `task.review.agent.${cliFlag === "--review-by" ? "executor" : "reporter"}`;
277
+ }
278
+ function resolveJobReviewAgents(task, roster, execDefaults, opts, definition) {
279
+ // Resolution order: --review-by / --reporter-by, then the Job's task.review.agent, then
280
+ // capability based auto selection.
281
+ const nominations = resolveJobReviewAgentNominations({ reviewBy: opts.reviewBy, reporterBy: opts.reporterBy }, definition);
282
+ const override = resolveAgentOverride("review", nominations.executor?.nickname, {}, roster, execDefaults, "executor");
283
+ if (override.kind === "error") {
284
+ throw new Error(nominations.executor
285
+ ? override.message.replace(/^--by/, jobReviewAgentSourceLabel(nominations.executor, "--review-by"))
286
+ : override.message);
287
+ }
288
+ let executor;
289
+ if (override.kind === "command") {
290
+ executor = {
291
+ command: override.command,
292
+ actor: override.actor ?? String(nominations.executor?.nickname),
293
+ provider: override.provider,
294
+ };
295
+ }
296
+ else {
297
+ const requirements = executorRequirements(task);
298
+ const member = requirements
299
+ ? selectCandidates(requirements, roster, "review", undefined, execDefaults)[0]
300
+ : undefined;
301
+ const command = member ? resolveMemberCommand(execDefaults, member) : undefined;
302
+ if (!member || !command)
303
+ throw new Error("No review executor is available for Job Run review.");
304
+ executor = { command, actor: member.nickname, provider: member.provider };
305
+ }
306
+ let reporterCandidates;
307
+ try {
308
+ reporterCandidates = resolveReporterAgentCandidates(task, roster, execDefaults, undefined, nominations.reporter?.nickname);
309
+ }
310
+ catch (error) {
311
+ const message = error instanceof Error ? error.message : String(error);
312
+ if (nominations.reporter?.source !== "job")
313
+ throw error;
314
+ throw new Error(message.replace(/^--reporter-by/, jobReviewAgentSourceLabel(nominations.reporter, "--reporter-by")), { cause: error });
315
+ }
316
+ if (reporterCandidates.length === 0) {
317
+ throw new Error("No reporter is available for Job Run review.");
318
+ }
319
+ return { executor, reporterCandidates };
320
+ }
321
+ function jobReviewTaskView(runId, jobName) {
322
+ return {
323
+ id: `${runId}-review`,
324
+ local_id: runId,
325
+ name: `${jobName} の実行結果レビュー`,
326
+ mode: "review",
327
+ schedule_file: "",
328
+ fifo_rank: 0,
329
+ critical_first_rank: 0,
330
+ agent_pipeline: {
331
+ stages: [{ stage_role: "executor" }, { stage_role: "reporter" }],
332
+ },
333
+ };
334
+ }
335
+ function describeJobReviewAgent(actor, nomination, cliFlag) {
336
+ const source = nomination ? jobReviewAgentSourceLabel(nomination, cliFlag) : "auto";
337
+ return `${actor ?? "(unknown)"} (${source})`;
338
+ }
339
+ async function runJobWorktreeMode(opts) {
340
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
341
+ activateResolvedProjectPaths(resolvedPaths);
342
+ const { schedulePath, executionPath } = resolvedPaths;
343
+ const projectId = resolvedPaths.projectId ?? opts.project ?? process.env.SPECDOJO_PROJECT ?? "";
344
+ if (!projectId)
345
+ throw new Error("--job requires a project id.");
346
+ const trigger = opts.jobTrigger === "ci"
347
+ ? "ci"
348
+ : process.env[ROUTINE_EXEC_ENV] === "1" || opts.jobTrigger === "routine"
349
+ ? "routine"
350
+ : "manual";
351
+ const preview = await materializeJobRun({
352
+ projectId,
353
+ jobId: String(opts.job).trim(),
354
+ inputs: opts.input,
355
+ scheduledAt: opts.scheduledAt,
356
+ trigger,
357
+ dryRun: true,
358
+ });
359
+ if (preview.duplicateComplete) {
360
+ process.stdout.write(`Job Run already complete: ${preview.record.run_id} (${preview.record.state})\n`);
361
+ return;
362
+ }
363
+ if (opts.dryRun) {
364
+ process.stdout.write(`[dry-run] job worktree: ${projectId}-${preview.record.run_id}\n`);
365
+ process.stdout.write(`[dry-run] job: ${preview.definition.id}\n`);
366
+ process.stdout.write(`[dry-run] run: ${preview.record.run_id}\n`);
367
+ process.stdout.write("[dry-run] lifecycle: execute -> commit -> review -> merge|waiting\n");
368
+ process.stdout.write(`[dry-run] review declared by job: ${preview.definition.task.review ? "yes" : "no (--worktree)"}\n`);
369
+ const nominations = resolveJobReviewAgentNominations({ reviewBy: opts.reviewBy, reporterBy: opts.reporterBy }, preview.definition);
370
+ try {
371
+ const roster = loadRosterForExecutionPath(executionPath);
372
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
373
+ const agents = resolveJobReviewAgents(jobReviewTaskView(preview.record.run_id, preview.definition.name), roster, execDefaults, opts, preview.definition);
374
+ process.stdout.write(`[dry-run] review executor: ${describeJobReviewAgent(agents.executor.actor, nominations.executor, "--review-by")}\n`);
375
+ process.stdout.write(`[dry-run] review reporter: ${describeJobReviewAgent(agents.reporterCandidates[0]?.actor, nominations.reporter, "--reporter-by")}\n`);
376
+ }
377
+ catch (error) {
378
+ process.stdout.write(`[dry-run] review agents: unresolved (${error instanceof Error ? error.message : String(error)})\n`);
379
+ }
380
+ return;
381
+ }
382
+ const repoRoot = specdojoRootDir();
383
+ const baseCommit = gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim();
384
+ const worktreeBase = resolveWorktreeBase(repoRoot, opts.worktreeBase, configuredWorktreeBase(schedulePath));
385
+ const worktreeTaskId = `${projectId}-${preview.record.run_id}`;
386
+ const worktree = ensureExecWorktree({ repoRoot, worktreeBase, taskId: worktreeTaskId });
387
+ // materializeJobRun resolves an omitted --scheduled-at to the manual launch time. Reuse that
388
+ // exact slot in the child so the worktree writes the Job Run that the parent previewed.
389
+ const childArgs = jobChildArgs(opts, projectId, preview.record.scheduled_at);
390
+ const [executable, fullArgs] = selfRunArgs(childArgs);
391
+ process.stdout.write(`Running Job Run ${preview.record.run_id} in ${worktree.path}.\n`);
392
+ const child = spawnSync(executable, fullArgs, {
393
+ cwd: worktree.path,
394
+ env: {
395
+ ...process.env,
396
+ [ROUTINE_EXEC_ENV]: trigger === "routine" ? "1" : "0",
397
+ [JOB_REVIEW_WORKTREE_CHILD_ENV]: "1",
398
+ },
399
+ stdio: "inherit",
400
+ });
401
+ if (child.status === ROUTINE_BUSY_SKIP_EXIT_CODE) {
402
+ removeWorktree({
403
+ context: { repoRoot, schedulePath, executionPath },
404
+ worktree,
405
+ taskId: `${preview.record.run_id}-review`,
406
+ force: true,
407
+ deleteBranch: true,
408
+ });
409
+ process.exitCode = ROUTINE_BUSY_SKIP_EXIT_CODE;
410
+ return;
411
+ }
412
+ const executionRel = relative(repoRoot, executionPath);
413
+ const worktreeExecutionPath = resolve(worktree.path, executionRel);
414
+ const worktreeJobPaths = resolveJobPaths(projectId);
415
+ const runPath = resolve(worktree.path, relative(repoRoot, preview.runPath));
416
+ if (!existsSync(runPath)) {
417
+ throw new Error(`Job Run record was not created in worktree: ${preview.record.run_id}`);
418
+ }
419
+ let record = loadJobRunRecord(runPath);
420
+ const outputPaths = worktreeStatusPaths(worktree.path);
421
+ const outputCommit = commitJobPaths(worktree.path, outputPaths, `chore(routine): ${preview.definition.name}`, `Job Run: ${record.run_id}\nState: ${record.state}`);
422
+ const reviewTaskId = `${record.run_id}-review`;
423
+ const reviewTask = jobReviewTaskView(record.run_id, preview.definition.name);
424
+ const { planPath, resultPath } = await generateJobReviewPlan({
425
+ ...worktreeJobPaths,
426
+ jobsPath: resolve(worktree.path, relative(repoRoot, worktreeJobPaths.jobsPath)),
427
+ executionPath: worktreeExecutionPath,
428
+ runsPath: resolve(worktree.path, relative(repoRoot, worktreeJobPaths.runsPath)),
429
+ statePath: resolve(worktree.path, relative(repoRoot, worktreeJobPaths.statePath)),
430
+ }, preview.definition, record, { branch: worktree.branch, baseCommit, outputCommit });
431
+ const rootExecDefaultsPath = resolve(repoRoot, resolveExecDefaultsPath(opts, schedulePath));
432
+ const execDefaultsRelative = relative(repoRoot, rootExecDefaultsPath);
433
+ const execDefaultsPath = execDefaultsRelative === ".." || execDefaultsRelative.startsWith(`..${sep}`)
434
+ ? rootExecDefaultsPath
435
+ : resolve(worktree.path, execDefaultsRelative);
436
+ const execDefaults = loadExecDefaultsConfig(execDefaultsPath, worktreeExecutionPath);
437
+ const originalCwd = process.cwd();
438
+ let reviewReason;
439
+ let verdict;
440
+ try {
441
+ process.chdir(worktree.path);
442
+ const roster = loadRosterForExecutionPath(worktreeExecutionPath);
443
+ const agents = resolveJobReviewAgents(reviewTask, roster, execDefaults, opts, preview.definition);
444
+ await scaffoldResult({
445
+ executionPath: worktreeExecutionPath,
446
+ taskId: reviewTaskId,
447
+ mode: "review",
448
+ projectId,
449
+ origin: "job",
450
+ jobId: record.job_id,
451
+ runId: record.run_id,
452
+ planRef: relative(worktree.path, planPath).split(sep).join("/"),
453
+ agent: agents.executor.actor,
454
+ startedAt: new Date().toISOString(),
455
+ stem: reviewTaskId,
456
+ });
457
+ const reviewOutcome = await runAgentPipeline({
458
+ repoRoot: worktree.path,
459
+ cwd: worktree.path,
460
+ schedulePath: resolve(worktree.path, relative(repoRoot, schedulePath)),
461
+ executionPath: worktreeExecutionPath,
462
+ taskId: reviewTaskId,
463
+ executor: agents.executor,
464
+ reporterCandidates: agents.reporterCandidates,
465
+ planPath,
466
+ planPrompt: expandPromptRefs(readFileSync(planPath, "utf8")),
467
+ resultPath,
468
+ execDefaults,
469
+ mode: "review",
470
+ });
471
+ reviewReason = reviewOutcome.blockReason;
472
+ await updateResultStatus(resultPath, reviewOutcome.exitCode === 0 ? "complete" : "blocked", new Date().toISOString(), reviewReason);
473
+ verdict = reviewOutcome.exitCode === 0 ? jobReviewVerdict(resultPath) : undefined;
474
+ if (!verdict && reviewOutcome.exitCode === 0)
475
+ reviewReason = "review result has no verdict";
476
+ }
477
+ catch (error) {
478
+ reviewReason = error instanceof Error ? error.message : String(error);
479
+ if (!existsSync(resultPath)) {
480
+ await scaffoldResult({
481
+ executionPath: worktreeExecutionPath,
482
+ taskId: reviewTaskId,
483
+ mode: "review",
484
+ projectId,
485
+ origin: "job",
486
+ jobId: record.job_id,
487
+ runId: record.run_id,
488
+ planRef: relative(worktree.path, planPath).split(sep).join("/"),
489
+ agent: "specdojo-runner",
490
+ startedAt: new Date().toISOString(),
491
+ stem: reviewTaskId,
492
+ });
493
+ }
494
+ await fillIncompleteJobReviewResult(resultPath, reviewReason);
495
+ await updateResultStatus(resultPath, "blocked", new Date().toISOString(), reviewReason);
496
+ verdict = "incomplete";
497
+ }
498
+ finally {
499
+ process.chdir(originalCwd);
500
+ }
501
+ const allowedReviewPrefixes = [
502
+ `${relative(worktree.path, worktreeExecutionPath).split(sep).join("/")}/exec/evidence/${reviewTaskId}/`,
503
+ ];
504
+ const allowedReviewFiles = new Set([
505
+ relative(worktree.path, planPath).split(sep).join("/"),
506
+ relative(worktree.path, resultPath).split(sep).join("/"),
507
+ relative(worktree.path, runPath).split(sep).join("/"),
508
+ ]);
509
+ const reviewChanges = worktreeStatusPaths(worktree.path);
510
+ const unexpected = reviewChanges.filter((path) => !allowedReviewFiles.has(path) &&
511
+ !allowedReviewPrefixes.some((prefix) => path.startsWith(prefix)));
512
+ if (unexpected.length > 0) {
513
+ reviewReason = `review executor changed Job output: ${unexpected.join(", ")}`;
514
+ verdict = "changed-during-review";
515
+ await overrideJobReviewDecision(resultPath, verdict, reviewReason);
516
+ }
517
+ if (unexpected.length === 0 && record.state !== "succeeded") {
518
+ reviewReason = record.attempts.at(-1)?.reason ?? `Job Run state is ${record.state}`;
519
+ verdict = "incomplete";
520
+ await overrideJobReviewDecision(resultPath, verdict, reviewReason);
521
+ }
522
+ if (!reviewReason && verdict && !ACCEPTED_JOB_REVIEW_VERDICTS.has(verdict)) {
523
+ reviewReason = `review verdict is ${verdict}`;
524
+ }
525
+ record = recordJobRunReview(runPath, {
526
+ plan_ref: relative(worktree.path, planPath).split(sep).join("/"),
527
+ result_ref: relative(worktree.path, resultPath).split(sep).join("/"),
528
+ branch: worktree.branch,
529
+ ...(verdict ? { verdict: verdict } : {}),
530
+ ...(reviewReason ? { reason: reviewReason } : {}),
531
+ });
532
+ const committableReviewPaths = worktreeStatusPaths(worktree.path).filter((path) => allowedReviewFiles.has(path) ||
533
+ allowedReviewPrefixes.some((prefix) => path.startsWith(prefix)));
534
+ commitJobPaths(worktree.path, committableReviewPaths, `chore(routine): review ${record.run_id}`, `Job Run: ${record.run_id}\nState: ${record.state}\nVerdict: ${verdict ?? "unavailable"}`);
535
+ const accepted = record.state === "succeeded" &&
536
+ verdict !== undefined &&
537
+ ACCEPTED_JOB_REVIEW_VERDICTS.has(verdict) &&
538
+ unexpected.length === 0;
539
+ if (!accepted) {
540
+ const reason = record.state !== "succeeded"
541
+ ? `Job Run state is ${record.state}`
542
+ : (reviewReason ?? `review verdict is ${verdict ?? "unavailable"}`);
543
+ process.stdout.write(`[routine-job] waiting run_id=${record.run_id} review=${verdict ?? "unavailable"} worktree=${worktree.path} reason=${reason}\n`);
544
+ process.exitCode = child.status || 1;
545
+ return;
546
+ }
547
+ mergeWorktreeIntoCurrent({
548
+ context: { repoRoot, schedulePath, executionPath },
549
+ worktree,
550
+ taskId: reviewTaskId,
551
+ message: `chore(routine): merge ${record.run_id}`,
552
+ });
553
+ removeWorktree({
554
+ context: { repoRoot, schedulePath, executionPath },
555
+ worktree,
556
+ taskId: reviewTaskId,
557
+ deleteBranch: true,
558
+ });
559
+ process.stdout.write(`[routine-job] merged run_id=${record.run_id} review=${verdict} branch=${worktree.branch}\n`);
560
+ }
561
+ export async function runJobMode(opts, resolvePipelineAgents) {
562
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
563
+ activateResolvedProjectPaths(resolvedPaths);
564
+ const isWorktreeChild = process.env[JOB_REVIEW_WORKTREE_CHILD_ENV] === "1";
565
+ if (!isWorktreeChild) {
566
+ // A Job's task.review declaration takes precedence over the caller: it routes the Run
567
+ // through the reviewed integration path even without --worktree (routine action.commit).
568
+ const reviewProjectId = resolvedPaths.projectId ?? opts.project ?? process.env.SPECDOJO_PROJECT ?? "";
569
+ const definition = loadJobDefinition(resolveJobPaths(reviewProjectId || undefined), String(opts.job).trim());
570
+ if (jobRunUsesReviewedIntegration(definition, { worktree: opts.worktree, isWorktreeChild })) {
571
+ await runJobWorktreeMode(opts);
572
+ return;
573
+ }
574
+ }
575
+ const { schedulePath, executionPath } = resolvedPaths;
576
+ const projectId = resolvedPaths.projectId ?? opts.project ?? process.env.SPECDOJO_PROJECT ?? "";
577
+ if (!projectId)
578
+ throw new Error("--job requires a project id.");
579
+ const trigger = opts.jobTrigger === "ci"
580
+ ? "ci"
581
+ : process.env[ROUTINE_EXEC_ENV] === "1" || opts.jobTrigger === "routine"
582
+ ? "routine"
583
+ : "manual";
584
+ const materialized = await materializeJobRun({
585
+ projectId,
586
+ jobId: opts.job.trim(),
587
+ inputs: opts.input,
588
+ scheduledAt: opts.scheduledAt,
589
+ trigger,
590
+ dryRun: !!opts.dryRun,
591
+ });
592
+ const { definition, record, runPath, planPath } = materialized;
593
+ if (materialized.preconditionSkipped) {
594
+ process.stdout.write(`Job skipped: ${definition.id} (${materialized.preconditionReason ?? "precondition"})\n`);
595
+ if (trigger === "routine")
596
+ process.exitCode = ROUTINE_BUSY_SKIP_EXIT_CODE;
597
+ return;
598
+ }
599
+ if (materialized.duplicateComplete) {
600
+ process.stdout.write(`Job Run already complete: ${record.run_id} (${record.state})\n`);
601
+ return;
602
+ }
603
+ if (isJobCommandTask(record.task)) {
604
+ await runCommandJobMode({
605
+ opts,
606
+ record,
607
+ runPath,
608
+ planPath,
609
+ projectId,
610
+ schedulePath,
611
+ executionPath,
612
+ });
613
+ return;
614
+ }
615
+ const task = {
616
+ id: record.run_id,
617
+ local_id: record.task.targets?.[0] ?? record.run_id,
618
+ name: definition.name,
619
+ owner: record.task.owner,
620
+ mode: record.task.mode,
621
+ agent: record.task.agent?.executor,
622
+ capabilities: record.task.capabilities,
623
+ proficiency: record.task.proficiency,
624
+ schedule_file: "",
625
+ fifo_rank: 0,
626
+ critical_first_rank: 0,
627
+ };
628
+ const roster = loadRosterForExecutionPath(executionPath);
629
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
630
+ // Job Definition が executor と reporter の双方を指名した場合は、register 項目と同じ
631
+ // executor/reporter pipeline で実行する(result は reporter が書く)。reporter が無い
632
+ // 場合は従来どおり単一 agent 実行で、その agent が result まで記入する。
633
+ // --by は運用者による単発の差し替えとして単一 agent 実行を選ぶ。
634
+ const executorBy = opts.executorBy?.trim() || record.task.agent?.executor;
635
+ const reporterBy = opts.reporterBy?.trim() || record.task.agent?.reporter;
636
+ const pipelineAgents = !opts.by?.trim() && executorBy && reporterBy
637
+ ? resolvePipelineAgents(roster, { executorBy, reporterBy }, execDefaults)
638
+ : undefined;
639
+ const { command, actor } = pipelineAgents
640
+ ? { command: pipelineAgents.executor.command, actor: pipelineAgents.executor.actor }
641
+ : resolveInPlaceCommand(task, roster, { ...opts, executorBy: undefined, reporterBy: undefined }, execDefaults);
642
+ if (opts.dryRun) {
643
+ process.stdout.write(`[dry-run] job: ${definition.id}\n`);
644
+ process.stdout.write(`[dry-run] run: ${record.run_id}\n`);
645
+ process.stdout.write(`[dry-run] scheduled_at: ${record.scheduled_at}\n`);
646
+ process.stdout.write(`[dry-run] agent: ${actor}${pipelineAgents ? " (executor)" : ""}\n`);
647
+ process.stdout.write(`[dry-run] command: ${command}\n`);
648
+ if (pipelineAgents) {
649
+ const reporter = pipelineAgents.reporterCandidates[0];
650
+ process.stdout.write(`[dry-run] agent: ${reporter?.actor ?? ""} (reporter)\n`);
651
+ process.stdout.write(`[dry-run] reporter command: ${reporter?.command ?? ""}\n`);
652
+ }
653
+ process.stdout.write(`[dry-run] plan: ${planPath}\n`);
654
+ return;
655
+ }
656
+ const { resultPath } = await scaffoldResult({
657
+ executionPath,
658
+ taskId: record.run_id,
659
+ mode: record.task.mode,
660
+ projectId,
661
+ origin: "job",
662
+ jobId: definition.id,
663
+ runId: record.run_id,
664
+ planRef: record.plan_ref,
665
+ agent: actor,
666
+ startedAt: new Date().toISOString(),
667
+ ...(record.task.targets ? { targets: record.task.targets } : {}),
668
+ });
669
+ const resultScaffold = readResultFrontmatterSnapshot(resultPath);
670
+ const prompt = expandPromptRefs(readFileSync(planPath, "utf8"));
671
+ const repoRoot = specdojoRootDir();
672
+ let exitCode;
673
+ let reason;
674
+ if (pipelineAgents) {
675
+ process.stdout.write(`Running Job Run ${record.run_id} in place (executor/reporter pipeline): ${command}\n`);
676
+ const pipelineOutcome = await runAgentPipeline({
677
+ repoRoot,
678
+ cwd: repoRoot,
679
+ schedulePath,
680
+ executionPath,
681
+ taskId: record.run_id,
682
+ executor: pipelineAgents.executor,
683
+ reporterCandidates: pipelineAgents.reporterCandidates,
684
+ planPath,
685
+ planPrompt: prompt,
686
+ resultPath,
687
+ execDefaults,
688
+ });
689
+ exitCode = pipelineOutcome.exitCode;
690
+ reason = pipelineOutcome.blockReason;
691
+ }
692
+ else {
693
+ process.stdout.write(`Running Job Run ${record.run_id} in place: ${command}\n`);
694
+ exitCode = await spawnAgentInPlace(command, prompt, repoRoot, schedulePath, executionPath);
695
+ }
696
+ let effectiveExit = exitCode;
697
+ if (exitCode === 0 && isResultUnfilled(resultPath, record.task.mode, resultScaffold)) {
698
+ effectiveExit = 1;
699
+ reason =
700
+ "agent exited 0 but result is incomplete or its frontmatter differs from the scaffold (treated as blocked)";
701
+ }
702
+ const completedAt = new Date().toISOString();
703
+ await updateResultStatus(resultPath, effectiveExit === 0 ? "complete" : "blocked", completedAt, reason);
704
+ completeJobRun({
705
+ projectId,
706
+ runPath,
707
+ status: effectiveExit === 0 ? "succeeded" : "failed",
708
+ ...(reason ? { reason } : {}),
709
+ });
710
+ if (effectiveExit === 0) {
711
+ process.stdout.write(`Job Run complete: ${record.run_id}\n`);
712
+ }
713
+ else {
714
+ process.stdout.write(`Job Run failed: ${record.run_id}\n`);
715
+ process.exitCode = effectiveExit || 1;
716
+ }
717
+ }