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,522 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { loadExecDefaultsConfig, providerSlotPoolPath, resolveMaxConcurrency, resolveMaxConcurrentRuns, } from "./exec-agent-config.js";
4
+ import { activateResolvedProjectPaths, resolveProjectPaths } from "./exec-project.js";
5
+ import { acquireSchedulerLock, buildEvent, readAllEventFiles, foldEventsToState, releaseSchedulerLock, writeEventFile, } from "./exec-events.js";
6
+ import { selectDueDeferredLimitTasks } from "./exec-limit.js";
7
+ import { buildScheduleIndex } from "./exec-schedule.js";
8
+ import { buildInitialStateFromStrategy } from "./exec-schedule-initial.js";
9
+ import { qualifyTaskId } from "./exec-shared.js";
10
+ import { specdojoRootDir } from "./specdojo-config.js";
11
+ import { collectExecLockUsage, execLocksDir, formatExecLockUsage } from "./exec-run-lock.js";
12
+ import { buildTaskView } from "./exec-task-view.js";
13
+ import { readResultFrontmatterSnapshot, updateResultStatus } from "./exec-results.js";
14
+ import { findExecWorktree, resolveWorktreeBase } from "./exec-worktree.js";
15
+ import { configuredProductRepos, withProductWorktrees } from "./exec-task-repos.js";
16
+ import { parentValidationPoolPath, resolveParentValidationConcurrency, } from "./exec-parent-validation.js";
17
+ import { loadPipelineResumeCheckpoint } from "./exec-pipeline-state.js";
18
+ import { buildTaskPhaseMap, configuredWorktreeBase, parseParallel, resolveExecDefaultsPath, withProjectExecRunLock, } from "./exec-run-shared.js";
19
+ import { loadRosterForExecutionPath, pathInsideWorktree } from "./exec-run-agent.js";
20
+ import { findClaimEventPath, prepareSingleTask, } from "./exec-run-schedule-prepare.js";
21
+ import { runPreparedTask } from "./exec-run-schedule-task.js";
22
+ import { rebuildStaleGeneratedTracksForCycle, resolveClaimingActor, runBatchMode, } from "./exec-run-schedule-mode.js";
23
+ import { spawnBlock, spawnIndexBuild, spawnRefresh, spawnValidate, } from "./exec-run-mode-shared.js";
24
+ // 同じ project の exec run が共有する枠(主 run・--join run・register lifecycle・provider の
25
+ // max_concurrency・親検証)の上限と現在の使用数を表示する。ロックは取得しない。
26
+ export function formatExecSlotsReport(executionPath, execDefaults) {
27
+ const lockRoot = execLocksDir(executionPath);
28
+ const providers = Object.keys(execDefaults.providers ?? {}).sort();
29
+ const providerPools = providers.flatMap((provider) => {
30
+ const cap = resolveMaxConcurrency(execDefaults, provider);
31
+ return cap === undefined
32
+ ? []
33
+ : [
34
+ {
35
+ name: `provider ${provider}`,
36
+ path: providerSlotPoolPath(lockRoot, provider),
37
+ limit: cap,
38
+ },
39
+ ];
40
+ });
41
+ const parentValidationPools = execDefaults.pipeline?.parent_validations?.length
42
+ ? [
43
+ {
44
+ name: "parent validations",
45
+ path: parentValidationPoolPath(lockRoot),
46
+ limit: resolveParentValidationConcurrency(execDefaults.pipeline.parent_validation_concurrency),
47
+ },
48
+ ]
49
+ : [];
50
+ const entries = collectExecLockUsage(executionPath, {
51
+ joinLimit: resolveMaxConcurrentRuns(execDefaults) - 1,
52
+ pools: [...providerPools, ...parentValidationPools],
53
+ });
54
+ return (`max concurrent runs: ${resolveMaxConcurrentRuns(execDefaults)}\n` +
55
+ formatExecLockUsage(entries));
56
+ }
57
+ export function registerSlotsCommand(exec) {
58
+ const cmd = exec
59
+ .command("slots")
60
+ .description("Show the limits and current usage of the slots shared by concurrent exec runs of a project");
61
+ cmd.option("--project <projectId>", "Project id in .specdojo/specdojo.config.json");
62
+ cmd.option("--exec-defaults <path>", "Path to exec-defaults.yaml global config (default: .specdojo/exec-defaults.yaml)");
63
+ cmd.action((opts) => {
64
+ try {
65
+ const { schedulePath, executionPath } = resolveProjectPaths({ project: opts.project });
66
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
67
+ process.stdout.write(formatExecSlotsReport(executionPath, execDefaults));
68
+ }
69
+ catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ process.stdout.write(message + "\n");
72
+ process.exitCode = 1;
73
+ }
74
+ });
75
+ }
76
+ // exec cycle: run limit-resume, doc-index rebuild, stale schedule rebuild, schedule refresh, and
77
+ // the auto loop as one
78
+ // ordered sequence while holding a single project exec-run lock for the whole run. Ordering does
79
+ // not depend on routine file order or cron time offsets, and no manual run / other routine / CI
80
+ // can interleave between the steps. The individual steps (runResumeMode, index build,
81
+ // schedule build, validate/refresh, runBatchMode) do not acquire the exec-run lock themselves, so
82
+ // the later steps never busy-skip against this run's own lock.
83
+ //
84
+ // Step failure policy (fixed and documented so results are predictable):
85
+ // - resume: a re-deferred or failed limit task must not block Ready tasks, so a resume failure
86
+ // is recorded but the cycle still proceeds to index/refresh + auto.
87
+ // - index: doc-index feeds wikilink/ID resolution for Ready task plans; if it fails, tasks may
88
+ // reference deliverables the previous cycle just created but cannot resolve them
89
+ // reliably, so the cycle aborts the remaining steps.
90
+ // - schedule: stale generated tracks must be rebuilt before validation/refresh; if any build
91
+ // fails, the cycle stops instead of selecting tasks from an old track.
92
+ // - refresh: validate/refresh feeds ready.json; if it fails the auto step cannot select tasks
93
+ // safely, so the cycle aborts the remaining step.
94
+ // - auto: failures are recorded; nothing runs after it.
95
+ // The cycle exits non-zero when any executed step failed. Busy at start is handled by the shared
96
+ // exec-run lock (--if-busy skip records a routine "skipped"; wait/fail behave as for run/resume).
97
+ export async function runCycleMode(opts) {
98
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
99
+ const projectId = resolvedPaths.projectId ?? opts.project;
100
+ const dryRun = !!opts.dryRun;
101
+ const stepOutcomes = [];
102
+ let anyFailure = false;
103
+ // runResumeMode / runBatchMode report failure via process.exitCode. Read and reset it around
104
+ // each step so one step's exit code cannot leak into the next step's outcome.
105
+ const takeStepFailure = () => {
106
+ const failed = process.exitCode !== undefined && process.exitCode !== 0;
107
+ process.exitCode = 0;
108
+ return failed;
109
+ };
110
+ // Step 1/5: resume due deferred-limit tasks.
111
+ process.stdout.write("[cycle] step 1/5: resume due deferred-limit tasks\n");
112
+ process.exitCode = 0;
113
+ await runResumeMode({ ...opts, due: true });
114
+ if (takeStepFailure()) {
115
+ anyFailure = true;
116
+ stepOutcomes.push("resume=failure");
117
+ process.stdout.write("[cycle] resume reported failures — continuing to run Ready tasks\n");
118
+ }
119
+ else {
120
+ stepOutcomes.push("resume=success");
121
+ }
122
+ // Step 2/5: rebuild doc-index before recalculating schedule state, so deliverables created by
123
+ // the resume step, or left unindexed by a prior cycle run, are resolvable before Ready
124
+ // selection instead of only becoming resolvable on a later, out-of-band index build.
125
+ process.stdout.write("[cycle] step 2/5: rebuild doc index\n");
126
+ if (dryRun) {
127
+ process.stdout.write(" [dry-run] specdojo index build\n");
128
+ stepOutcomes.push("index=success");
129
+ }
130
+ else if (!spawnIndexBuild()) {
131
+ stepOutcomes.push("index=failure");
132
+ process.stdout.write("[cycle] index build failed — aborting auto step\n");
133
+ process.stdout.write(`[cycle] summary: ${stepOutcomes.join(", ")}\n`);
134
+ process.exitCode = 1;
135
+ return;
136
+ }
137
+ else {
138
+ stepOutcomes.push("index=success");
139
+ }
140
+ // Step 3/5 is conditional: regenerate only stale/missing generated tracks. It intentionally
141
+ // emits nothing and adds nothing to the summary when no rebuild is needed.
142
+ const rebuild = await rebuildStaleGeneratedTracksForCycle(resolvedPaths.schedulePath, projectId, dryRun);
143
+ if (rebuild.status === "failure") {
144
+ stepOutcomes.push("schedule=failure");
145
+ process.stdout.write(`[cycle] summary: ${stepOutcomes.join(", ")}\n`);
146
+ process.exitCode = 1;
147
+ return;
148
+ }
149
+ if (rebuild.status === "success")
150
+ stepOutcomes.push("schedule=success");
151
+ // Step 4/5: validate + refresh schedule state before selecting Ready tasks.
152
+ process.stdout.write("[cycle] step 4/5: validate + refresh schedule state\n");
153
+ if (dryRun) {
154
+ process.stdout.write(" [dry-run] specdojo exec validate\n");
155
+ process.stdout.write(" [dry-run] specdojo exec refresh\n");
156
+ stepOutcomes.push("refresh=success");
157
+ }
158
+ else if (!spawnValidate(projectId)) {
159
+ stepOutcomes.push("refresh=failure(validate)");
160
+ process.stdout.write("[cycle] validate failed — aborting auto step\n");
161
+ process.stdout.write(`[cycle] summary: ${stepOutcomes.join(", ")}\n`);
162
+ process.exitCode = 1;
163
+ return;
164
+ }
165
+ else if (!spawnRefresh(projectId)) {
166
+ stepOutcomes.push("refresh=failure(refresh)");
167
+ process.stdout.write("[cycle] refresh failed — aborting auto step\n");
168
+ process.stdout.write(`[cycle] summary: ${stepOutcomes.join(", ")}\n`);
169
+ process.exitCode = 1;
170
+ return;
171
+ }
172
+ else {
173
+ stepOutcomes.push("refresh=success");
174
+ }
175
+ // Step 5/5: run Ready tasks (auto loop). In dry-run the refresh above is skipped, so ready.json
176
+ // may be stale/absent; preview the planned auto invocation instead of reading the cache.
177
+ process.stdout.write("[cycle] step 5/5: run Ready tasks (--auto)\n");
178
+ if (dryRun) {
179
+ const autoArgs = ["exec", "run", "--auto"];
180
+ if (projectId)
181
+ autoArgs.push("--project", projectId);
182
+ if (opts.strategy)
183
+ autoArgs.push("--strategy", opts.strategy);
184
+ if (opts.parallel)
185
+ autoArgs.push("--parallel", opts.parallel);
186
+ if (opts.executorBy)
187
+ autoArgs.push("--executor-by", opts.executorBy);
188
+ if (opts.reporterBy)
189
+ autoArgs.push("--reporter-by", opts.reporterBy);
190
+ if (opts.loop) {
191
+ autoArgs.push("--loop");
192
+ if (opts.maxRounds)
193
+ autoArgs.push("--max-rounds", opts.maxRounds);
194
+ }
195
+ process.stdout.write(` [dry-run] specdojo ${autoArgs.join(" ")}\n`);
196
+ stepOutcomes.push("auto=success");
197
+ }
198
+ else {
199
+ process.exitCode = 0;
200
+ await runBatchMode({ ...opts, auto: true, cycleRebuildStaleTracks: true });
201
+ if (takeStepFailure()) {
202
+ anyFailure = true;
203
+ stepOutcomes.push("auto=failure");
204
+ }
205
+ else {
206
+ stepOutcomes.push("auto=success");
207
+ }
208
+ }
209
+ process.stdout.write(`[cycle] summary: ${stepOutcomes.join(", ")}\n`);
210
+ if (anyFailure)
211
+ process.exitCode = 1;
212
+ }
213
+ export function registerCycleCommand(exec) {
214
+ const cmd = exec
215
+ .command("cycle")
216
+ .description("Run limit-resume, doc-index rebuild, stale track rebuild, schedule refresh, and the --auto loop as one ordered sequence under a single project lock");
217
+ cmd.option("--project <projectId>", "Project id in .specdojo/specdojo.config.json");
218
+ cmd.option("--strategy <s>", "Task selection strategy for the auto step: critical-first|fifo (default: critical-first)");
219
+ cmd.option("--parallel <n>", "Number of tasks to resume / run in parallel", "1");
220
+ cmd.option("--loop", "Repeat the auto step until no Ready tasks remain", false);
221
+ cmd.option("--max-rounds <n>", "Maximum number of auto rounds when using --loop");
222
+ cmd.option("--edit-by <nickname>", "agent-members.yaml nickname for edit-mode tasks (resume + auto)");
223
+ cmd.option("--review-by <nickname>", "agent-members.yaml nickname for review-mode tasks (resume + auto)");
224
+ cmd.option("--executor-by <nickname>", "agent-members.yaml executor nickname for pipeline tasks (resume + auto)");
225
+ cmd.option("--reporter-by <nickname>", "agent-members.yaml reporter nickname for pipeline tasks (resume + auto)");
226
+ cmd.option("--worktree-base <path>", "Override worktree base directory");
227
+ cmd.option("--exec-defaults <path>", "Path to exec-defaults.yaml global config (default: .specdojo/exec-defaults.yaml)");
228
+ cmd.option("--if-busy <policy>", "When another exec is running for the project: skip|wait|fail (default: fail)", "fail");
229
+ cmd.option("--dry-run", "Print resolved steps without executing", false);
230
+ cmd.action(async (opts) => {
231
+ try {
232
+ await withProjectExecRunLock(opts, "cycle", () => runCycleMode(opts));
233
+ }
234
+ catch (error) {
235
+ const message = error instanceof Error ? error.message : String(error);
236
+ process.stdout.write(message + "\n");
237
+ process.exitCode = 1;
238
+ }
239
+ });
240
+ }
241
+ // Restore a Schedule pipeline at its runner-owned integration stage without resolving or starting
242
+ // an agent. The block event supplies the run-scoped state reference; both agent stages must still
243
+ // be succeeded and the original worktree/result must exist before any lifecycle state is changed.
244
+ export function prepareScheduleIntegrationResume(params) {
245
+ const { task, taskState, actor, projectId, repoRoot, executionPath, schedulePath } = params;
246
+ const stateRef = typeof taskState?.meta?.pipeline_state_ref === "string"
247
+ ? taskState.meta.pipeline_state_ref
248
+ : undefined;
249
+ if (!stateRef) {
250
+ throw new Error(`integration resume has no pipeline_state_ref for ${task.id}`);
251
+ }
252
+ const worktreeTaskId = qualifyTaskId(projectId, task.id);
253
+ const foundWorktree = findExecWorktree(repoRoot, worktreeTaskId);
254
+ if (!foundWorktree)
255
+ throw new Error(`no exec worktree to resume integration for ${task.id}`);
256
+ const worktree = withProductWorktrees(foundWorktree, configuredProductRepos(schedulePath), worktreeTaskId);
257
+ const checkpoint = loadPipelineResumeCheckpoint({
258
+ worktreePath: worktree.path,
259
+ stateRef,
260
+ taskId: task.id,
261
+ });
262
+ if (!checkpoint)
263
+ throw new Error(`pipeline state is missing or invalid for ${task.id}`);
264
+ if (checkpoint.state.stages.executor.status !== "succeeded" ||
265
+ checkpoint.state.stages.reporter.status !== "succeeded") {
266
+ throw new Error(`integration resume requires succeeded executor and reporter stages for ${task.id}`);
267
+ }
268
+ const resultPath = join(executionPath, "exec", "results", `${task.id}-result.md`);
269
+ const worktreeResultPath = pathInsideWorktree(repoRoot, worktree.path, resultPath);
270
+ if (!existsSync(resultPath) || !existsSync(worktreeResultPath)) {
271
+ throw new Error(`result is missing for integration resume: ${task.id}-result.md`);
272
+ }
273
+ // 統合再開でも、root に未 commit のまま残る claim / plan / result の作業コピーを merge 前に
274
+ // 解放できるよう、通常実行と同じ checkpoint パスを持たせる。
275
+ const claimEventPath = findClaimEventPath(schedulePath, task.id);
276
+ const checkpointPaths = [
277
+ join(executionPath, "exec", "plans", `${task.id}-plan.md`),
278
+ resultPath,
279
+ ...(claimEventPath ? [claimEventPath] : []),
280
+ ];
281
+ return {
282
+ task,
283
+ actor,
284
+ agentCandidates: [],
285
+ plan: "",
286
+ prompt: "",
287
+ worktree,
288
+ resultPath,
289
+ resultScaffold: readResultFrontmatterSnapshot(resultPath),
290
+ checkpointPaths,
291
+ pipelineRunId: checkpoint.state.run_id,
292
+ pipelineResumeStage: "integrate",
293
+ pipelineStateRef: stateRef,
294
+ };
295
+ }
296
+ // Resume tasks left in "doing" state by an interrupted run. Unlike --auto (which selects from
297
+ // ready.json and provably excludes "doing"/"blocked" tasks), resume folds the event log to find
298
+ // in-flight tasks and re-runs each on its existing worktree, reusing the claiming actor and the
299
+ // partially-filled result (scaffoldResult is idempotent; the worktree is reused). No validate/build
300
+ // pass — selection comes from events, not the generated cache.
301
+ export async function runResumeMode(opts) {
302
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
303
+ activateResolvedProjectPaths(resolvedPaths);
304
+ const { schedulePath, executionPath, catalogPath, rolesPath, viewpointsPath, projectContext } = resolvedPaths;
305
+ const projectId = resolvedPaths.projectId ?? opts.project;
306
+ const planGenPaths = { catalogPath, rolesPath, viewpointsPath, projectContext };
307
+ const repoRoot = specdojoRootDir();
308
+ const worktreeBase = resolveWorktreeBase(repoRoot, opts.worktreeBase, configuredWorktreeBase(schedulePath));
309
+ const parallel = parseParallel(opts.parallel);
310
+ const dryRun = !!opts.dryRun;
311
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
312
+ const roster = loadRosterForExecutionPath(executionPath);
313
+ const { localIdToPhaseSets, phaseSetSuffixToId } = buildTaskPhaseMap(schedulePath);
314
+ // Resolve current state from the event log (not the state.json cache) so freshly claimed/blocked
315
+ // tasks within a just-interrupted run are reflected.
316
+ const schedule = buildScheduleIndex(schedulePath);
317
+ const events = readAllEventFiles(schedulePath);
318
+ const initTasks = buildInitialStateFromStrategy(schedulePath, schedule);
319
+ let snapshot = foldEventsToState(events, schedule, schedulePath, initTasks);
320
+ let doingIds;
321
+ if (opts.due) {
322
+ let lockDir = "";
323
+ try {
324
+ lockDir = acquireSchedulerLock(schedulePath, {
325
+ actor: opts.by ?? "exec-limit-resume",
326
+ lockTimeoutMs: 10_000,
327
+ lockStaleMs: 300_000,
328
+ });
329
+ // Re-fold after acquiring the scheduler lock. A concurrent routine may have already
330
+ // unblocked the task; only tasks that are still blocked and due are claimed below.
331
+ const lockedEvents = readAllEventFiles(schedulePath);
332
+ snapshot = foldEventsToState(lockedEvents, schedule, schedulePath, initTasks);
333
+ let dueTasks = selectDueDeferredLimitTasks(snapshot);
334
+ if (opts.task)
335
+ dueTasks = dueTasks.filter((task) => task.taskId === opts.task);
336
+ doingIds = dueTasks.map((task) => task.taskId);
337
+ if (!dryRun) {
338
+ for (const task of dueTasks) {
339
+ const existingMeta = snapshot.tasks[task.taskId]?.meta ?? {};
340
+ const meta = Object.entries(existingMeta).map(([key, value]) => `${key}=${String(value)}`);
341
+ meta.push("limit_resume_claimed=true");
342
+ const event = buildEvent("unblock", {
343
+ task: task.taskId,
344
+ by: task.actor || "exec-limit-resume",
345
+ msg: `automatic limit resume due at ${task.resumeAt}`,
346
+ meta,
347
+ });
348
+ writeEventFile(schedulePath, event);
349
+ }
350
+ }
351
+ // Use the post-unblock state for actor/command resolution below. In dry-run mode this is
352
+ // only an in-memory projection; otherwise it mirrors the events just written.
353
+ for (const task of dueTasks) {
354
+ snapshot.tasks[task.taskId] = {
355
+ ...snapshot.tasks[task.taskId],
356
+ state: "doing",
357
+ last_by: task.actor || "exec-limit-resume",
358
+ last_type: "unblock",
359
+ };
360
+ }
361
+ }
362
+ finally {
363
+ if (lockDir)
364
+ releaseSchedulerLock(lockDir);
365
+ }
366
+ }
367
+ else {
368
+ doingIds = Object.entries(snapshot.tasks)
369
+ .filter(([, st]) => st.state === "doing")
370
+ .map(([id]) => id)
371
+ .sort();
372
+ if (opts.task) {
373
+ const taskState = snapshot.tasks[opts.task];
374
+ const blockedPipelineStage = taskState?.meta?.pipeline_stage;
375
+ const canResumeBlockedPipeline = taskState?.state === "blocked" &&
376
+ (blockedPipelineStage === "executor" ||
377
+ blockedPipelineStage === "reporter" ||
378
+ blockedPipelineStage === "integrate") &&
379
+ typeof taskState.meta?.pipeline_state_ref === "string";
380
+ if (canResumeBlockedPipeline) {
381
+ const actor = taskState.last_by ?? opts.by ?? "exec-pipeline-resume";
382
+ if (!dryRun) {
383
+ const meta = Object.entries(taskState.meta ?? {}).map(([key, value]) => `${key}=${String(value)}`);
384
+ meta.push("pipeline_resume_claimed=true");
385
+ writeEventFile(schedulePath, buildEvent("unblock", {
386
+ task: opts.task,
387
+ by: actor,
388
+ msg: blockedPipelineStage === "integrate"
389
+ ? "resume integration from persisted pipeline state"
390
+ : blockedPipelineStage === "reporter"
391
+ ? "resume reporter from persisted pipeline state"
392
+ : "resume executor from persisted pipeline state",
393
+ meta,
394
+ }));
395
+ }
396
+ snapshot.tasks[opts.task] = {
397
+ ...taskState,
398
+ state: "doing",
399
+ last_by: actor,
400
+ last_type: "unblock",
401
+ };
402
+ }
403
+ else if (taskState?.state !== "doing") {
404
+ process.stdout.write(`[resume] ${opts.task} is not resumable (state: ${taskState?.state ?? "unknown"}) — nothing to resume.\n`);
405
+ process.exitCode = 1;
406
+ return;
407
+ }
408
+ doingIds = [opts.task];
409
+ }
410
+ }
411
+ if (doingIds.length === 0) {
412
+ process.stdout.write(opts.due
413
+ ? "[resume] no due deferred-limit tasks — exit\n"
414
+ : '[resume] no "doing" tasks to resume — exit\n');
415
+ return;
416
+ }
417
+ process.stdout.write(opts.due
418
+ ? `[resume] ${doingIds.length} due deferred-limit task(s): ${doingIds.join(", ")}\n`
419
+ : `[resume] ${doingIds.length} doing task(s): ${doingIds.join(", ")}\n`);
420
+ for (let offset = 0; offset < doingIds.length; offset += parallel) {
421
+ const batch = doingIds.slice(offset, offset + parallel);
422
+ const preparedTasks = [];
423
+ for (const taskId of batch) {
424
+ try {
425
+ const task = buildTaskView(schedulePath, executionPath, taskId);
426
+ const resolved = resolveClaimingActor(snapshot.tasks[taskId], opts.by);
427
+ const prepared = snapshot.tasks[taskId]?.meta?.pipeline_stage === "integrate"
428
+ ? prepareScheduleIntegrationResume({
429
+ task,
430
+ taskState: snapshot.tasks[taskId],
431
+ actor: resolved.actor ?? snapshot.tasks[taskId]?.last_by ?? "exec-pipeline-resume",
432
+ projectId,
433
+ repoRoot,
434
+ executionPath,
435
+ schedulePath,
436
+ })
437
+ : await prepareSingleTask(task, projectId, repoRoot, schedulePath, executionPath, roster, localIdToPhaseSets, phaseSetSuffixToId, resolved.actor, { edit: opts.editBy, review: opts.reviewBy }, { executor: opts.executorBy, reporter: opts.reporterBy }, resolved.actor, dryRun, true, // skipClaim: the task is already "doing" and remains claimed
438
+ worktreeBase, planGenPaths, execDefaults, undefined, {
439
+ stage: snapshot.tasks[taskId]?.meta?.pipeline_stage === "reporter"
440
+ ? "reporter"
441
+ : snapshot.tasks[taskId]?.meta?.pipeline_stage === "executor"
442
+ ? "executor"
443
+ : undefined,
444
+ stateRef: typeof snapshot.tasks[taskId]?.meta?.pipeline_state_ref === "string"
445
+ ? snapshot.tasks[taskId]?.meta?.pipeline_state_ref
446
+ : undefined,
447
+ });
448
+ if (typeof prepared !== "string") {
449
+ const attempts = snapshot.tasks[taskId]?.meta?.limit_attempts;
450
+ prepared.priorLimitAttempts =
451
+ typeof attempts === "string" && /^\d+$/.test(attempts)
452
+ ? Number.parseInt(attempts, 10)
453
+ : 0;
454
+ preparedTasks.push(prepared);
455
+ }
456
+ else if (prepared === "failure")
457
+ process.exitCode = 1;
458
+ }
459
+ catch (error) {
460
+ const message = error instanceof Error ? error.message : String(error);
461
+ process.stderr.write(`[resume] setup error for ${taskId}: ${message}\n`);
462
+ if (opts.due && !dryRun) {
463
+ spawnBlock(projectId, taskId, snapshot.tasks[taskId]?.last_by ?? "exec-limit-resume", `resume setup error: ${message}`);
464
+ }
465
+ process.exitCode = 1;
466
+ }
467
+ }
468
+ if (preparedTasks.length === 0)
469
+ continue;
470
+ const settled = await Promise.allSettled(preparedTasks.map((prepared) => runPreparedTask(prepared, projectId, repoRoot, schedulePath, executionPath, catalogPath, execDefaults, dryRun)));
471
+ for (const [index, result] of settled.entries()) {
472
+ if (result.status === "rejected") {
473
+ const prepared = preparedTasks[index];
474
+ const message = result.reason instanceof Error ? result.reason.message : String(result.reason);
475
+ process.stderr.write(`[resume] error: ${prepared.worktree.name}: ${message}\n`);
476
+ if (!dryRun) {
477
+ const completedAt = new Date().toISOString();
478
+ if (prepared.resultPath)
479
+ await updateResultStatus(prepared.resultPath, "blocked", completedAt);
480
+ spawnBlock(projectId, prepared.task.id, prepared.actor, `runner error: ${message}`);
481
+ }
482
+ process.exitCode = 1;
483
+ }
484
+ else if (result.value === "failure") {
485
+ process.exitCode = 1;
486
+ }
487
+ }
488
+ }
489
+ }
490
+ export function registerResumeCommand(exec) {
491
+ const cmd = exec
492
+ .command("resume")
493
+ .description("Resume in-flight tasks, blocked reporter/integration stages, or due deferred-limit tasks on existing worktrees");
494
+ cmd.option("--project <projectId>", "Project id in .specdojo/specdojo.config.json");
495
+ cmd.option("--task <taskId>", 'Resume only this task ("doing", blocked pipeline stage, or due with --due)');
496
+ cmd.option("--due", "Atomically claim and resume only retryable limit blocks whose resume time has arrived", false);
497
+ cmd.option("--by <nickname>", "Select an agent-members.yaml agent (default: the agent that claimed the task)");
498
+ cmd.option("--edit-by <nickname>", "agent-members.yaml nickname for edit-mode tasks (overrides the claiming actor)");
499
+ cmd.option("--review-by <nickname>", "agent-members.yaml nickname for review-mode tasks (overrides the claiming actor)");
500
+ cmd.option("--executor-by <nickname>", "agent-members.yaml executor nickname for pipeline tasks");
501
+ cmd.option("--reporter-by <nickname>", "agent-members.yaml reporter nickname for pipeline tasks");
502
+ cmd.option("--parallel <n>", "Number of tasks to resume in parallel", "1");
503
+ cmd.option("--worktree-base <path>", "Override worktree base directory");
504
+ cmd.option("--exec-defaults <path>", "Path to exec-defaults.yaml global config (default: .specdojo/exec-defaults.yaml)");
505
+ cmd.option("--if-busy <policy>", "When another exec is running for the project: skip|wait|fail (default: fail)", "fail");
506
+ cmd.option("--dry-run", "Print resolved commands without executing", false);
507
+ cmd.action(async (opts) => {
508
+ try {
509
+ if (opts.by && opts.executorBy) {
510
+ process.stdout.write("Specify either --by or --executor-by, not both.\n");
511
+ process.exitCode = 1;
512
+ return;
513
+ }
514
+ await withProjectExecRunLock(opts, "resume", () => runResumeMode(opts));
515
+ }
516
+ catch (error) {
517
+ const message = error instanceof Error ? error.message : String(error);
518
+ process.stdout.write(message + "\n");
519
+ process.exitCode = 1;
520
+ }
521
+ });
522
+ }
@@ -0,0 +1,140 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { dirname, join, relative, sep } from "node:path";
4
+ import { selfRunArgs } from "./spawn-self.js";
5
+ import { specdojoRootDir } from "./specdojo-config.js";
6
+ import { readPipelineState, updatePipelineRepoIntegration, updatePipelineStage, writePipelineState, } from "./exec-pipeline-state.js";
7
+ export function spawnSelf(args, cwd = specdojoRootDir()) {
8
+ const [exe, fullArgs] = selfRunArgs(args);
9
+ const result = spawnSync(exe, fullArgs, { stdio: "inherit", cwd });
10
+ return result.status === 0;
11
+ }
12
+ export function spawnValidate(projectId) {
13
+ const args = ["exec", "validate"];
14
+ if (projectId)
15
+ args.push("--project", projectId);
16
+ return spawnSelf(args);
17
+ }
18
+ export function spawnRefresh(projectId) {
19
+ const refreshArgs = ["exec", "refresh"];
20
+ if (projectId)
21
+ refreshArgs.push("--project", projectId);
22
+ return spawnSelf(refreshArgs);
23
+ }
24
+ export function spawnScheduleBuild(projectId, track) {
25
+ const args = ["schedule", "build", "--track", track, "--force"];
26
+ if (projectId)
27
+ args.push("--project", projectId);
28
+ return spawnSelf(args);
29
+ }
30
+ // doc-index is project-independent (it scans the whole docs/ tree), so no --project is passed.
31
+ // Rebuilding it before Ready selection lets tasks resolve wikilinks/IDs to deliverables that a
32
+ // prior round or a prior cycle step just created (see scheduleAvailable and runCycleMode).
33
+ export function spawnIndexBuild() {
34
+ return spawnSelf(["index", "build"]);
35
+ }
36
+ export function spawnClaim(projectId, taskId, by) {
37
+ const args = [
38
+ "exec",
39
+ "claim",
40
+ "--task",
41
+ taskId,
42
+ "--by",
43
+ by,
44
+ "--msg",
45
+ "auto-run",
46
+ "--allow-multiple-doing",
47
+ ];
48
+ if (projectId)
49
+ args.push("--project", projectId);
50
+ return spawnSelf(args);
51
+ }
52
+ export function spawnComplete(projectId, taskId, by) {
53
+ const args = ["exec", "complete", "--task", taskId, "--by", by, "--msg", "auto-complete"];
54
+ if (projectId)
55
+ args.push("--project", projectId);
56
+ spawnSelf(args);
57
+ }
58
+ // Release a just-made claim (doing → todo) when setup fails after the claim, so the task is not
59
+ // stranded in "doing" with no worktree. Uses the claiming actor, so no cross-actor override needed.
60
+ export function spawnRelease(projectId, taskId, by, reason) {
61
+ const args = [
62
+ "exec",
63
+ "release",
64
+ "--task",
65
+ taskId,
66
+ "--by",
67
+ by,
68
+ "--msg",
69
+ reason,
70
+ "--allow-multiple-doing",
71
+ ];
72
+ if (projectId)
73
+ args.push("--project", projectId);
74
+ spawnSelf(args);
75
+ }
76
+ // block 上限。block イベントログを読みやすく保つため、stderr から取り出した理由を切り詰める。
77
+ export function pipelineRecoveryMeta(input) {
78
+ return {
79
+ pipeline_stage: input.stage,
80
+ ...(input.evidenceRef ? { evidence_ref: input.evidenceRef } : {}),
81
+ ...(input.stateRef ? { pipeline_state_ref: input.stateRef } : {}),
82
+ ...(input.runId ? { pipeline_run_id: input.runId } : {}),
83
+ };
84
+ }
85
+ export function spawnBlock(projectId, taskId, by, reason, meta = { limit_deferred: "false" }) {
86
+ const args = ["exec", "block", "--task", taskId, "--by", by, "--msg", reason];
87
+ for (const [key, value] of Object.entries(meta))
88
+ args.push("--meta", `${key}=${value}`);
89
+ if (projectId)
90
+ args.push("--project", projectId);
91
+ spawnSelf(args);
92
+ }
93
+ export function repoRelativePath(repoRoot, path) {
94
+ return relative(repoRoot, path).split(sep).join("/");
95
+ }
96
+ // commitlint (config-conventional) rejects headers longer than 100 characters. Task names and
97
+ // register titles are free text, so clip the subject instead of failing the commit or merge.
98
+ const COMMIT_SUBJECT_MAX_LENGTH = 100;
99
+ export function commitSubject(prefix, title) {
100
+ const flat = title.replace(/\s+/g, " ").trim();
101
+ const subject = `${prefix}${flat}`;
102
+ if (subject.length <= COMMIT_SUBJECT_MAX_LENGTH)
103
+ return subject;
104
+ return `${subject.slice(0, COMMIT_SUBJECT_MAX_LENGTH - 1)}…`;
105
+ }
106
+ // 統合段(commit → merge → worktree 撤去)の進捗を pipeline-state へ記録する。Schedule は
107
+ // succeeded を exec branch へ commit してから merge し、register は開始と失敗を worktree に
108
+ // 記録する。記帳の失敗で統合自体を止めない。
109
+ export function recordIntegrateStage(statePath, updatedAt, buildPatch) {
110
+ if (!statePath || !existsSync(statePath))
111
+ return;
112
+ try {
113
+ const state = readPipelineState(statePath);
114
+ const patch = buildPatch(state.stages.integrate);
115
+ writePipelineState(statePath, updatePipelineStage(state, "integrate", patch, updatedAt));
116
+ }
117
+ catch (error) {
118
+ process.stderr.write(`warning: could not record the integrate stage in ${statePath}: ` +
119
+ `${error instanceof Error ? error.message : String(error)}\n`);
120
+ }
121
+ }
122
+ // 複数リポジトリ統合の進捗を同じ pipeline state へ追記する。プロダクトを統合するたびに
123
+ // project worktree 側へ書くため、途中で失敗しても `--resume` は Git の実状態とこの記録の両方を
124
+ // 手掛かりに、統合済みリポジトリを飛ばせる。
125
+ export function recordRepoIntegration(statePath, repo, patch) {
126
+ if (!statePath || !existsSync(statePath))
127
+ return;
128
+ const updatedAt = new Date().toISOString();
129
+ try {
130
+ const state = readPipelineState(statePath);
131
+ writePipelineState(statePath, updatePipelineRepoIntegration(state, repo, patch, updatedAt));
132
+ }
133
+ catch (error) {
134
+ process.stderr.write(`warning: could not record repository ${repo} in ${statePath}: ` +
135
+ `${error instanceof Error ? error.message : String(error)}\n`);
136
+ }
137
+ }
138
+ export function integrateLogPath(statePath) {
139
+ return statePath ? join(dirname(statePath), "integrate.log") : undefined;
140
+ }