specdojo 0.2.1 → 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 (242) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +298 -0
  3. package/README.md +92 -42
  4. package/dist/agent-response.js +20 -0
  5. package/dist/agent.js +4 -4
  6. package/dist/build-command.js +28 -8
  7. package/dist/catalog-build-references.js +144 -0
  8. package/dist/catalog-build-render.js +144 -0
  9. package/dist/catalog-build.js +13 -290
  10. package/dist/catalog-generate.js +6 -9
  11. package/dist/catalog-plan-generate.js +2 -2
  12. package/dist/catalog-plan.js +6 -6
  13. package/dist/catalog-scaffold.js +4 -4
  14. package/dist/catalog.js +2 -2
  15. package/dist/dashboard-exec-records.js +105 -0
  16. package/dist/dashboard-routines.js +255 -0
  17. package/dist/dashboard-shared.js +14 -0
  18. package/dist/dashboard-timeline.js +175 -0
  19. package/dist/dashboard.js +31 -444
  20. package/dist/deliverable-trash.js +3 -3
  21. package/dist/devcontainer-command.js +43 -0
  22. package/dist/devcontainer-scaffold.js +165 -0
  23. package/dist/doc-index.js +3 -3
  24. package/dist/exec-agent-config.js +107 -9
  25. package/dist/exec-agent-git-state.js +18 -0
  26. package/dist/exec-agent-protected-config.js +46 -8
  27. package/dist/exec-commands.js +557 -0
  28. package/dist/exec-core.js +457 -0
  29. package/dist/exec-evidence.js +254 -11
  30. package/dist/exec-handoff.js +336 -0
  31. package/dist/exec-parent-validation.js +317 -43
  32. package/dist/exec-pipeline-state.js +74 -9
  33. package/dist/exec-plans-core.js +693 -0
  34. package/dist/exec-plans-generation.js +206 -0
  35. package/dist/exec-plans-storage.js +131 -0
  36. package/dist/exec-plans.js +3 -1016
  37. package/dist/exec-protection-handoff.js +43 -2
  38. package/dist/exec-provider-scaffold.js +247 -15
  39. package/dist/exec-register-resume.js +65 -19
  40. package/dist/exec-register.js +9 -3
  41. package/dist/exec-repo-integration-git.js +23 -0
  42. package/dist/exec-repo-integration-sync.js +264 -0
  43. package/dist/exec-repo-integration.js +534 -0
  44. package/dist/exec-repo-trace.js +182 -0
  45. package/dist/exec-reporter-output.js +206 -0
  46. package/dist/exec-reporter.js +525 -248
  47. package/dist/exec-results.js +103 -71
  48. package/dist/exec-run-agent-pipeline.js +256 -0
  49. package/dist/exec-run-agent.js +531 -0
  50. package/dist/exec-run-in-place.js +541 -0
  51. package/dist/exec-run-job.js +717 -0
  52. package/dist/exec-run-lifecycle-commands.js +522 -0
  53. package/dist/exec-run-lock.js +110 -107
  54. package/dist/exec-run-mode-shared.js +140 -0
  55. package/dist/exec-run-register-command.js +244 -0
  56. package/dist/exec-run-register-core.js +386 -0
  57. package/dist/exec-run-register-mode.js +206 -0
  58. package/dist/exec-run-register-resume.js +393 -0
  59. package/dist/exec-run-register-state.js +322 -0
  60. package/dist/exec-run-register-worktree.js +509 -0
  61. package/dist/exec-run-schedule-mode.js +294 -0
  62. package/dist/exec-run-schedule-prepare.js +353 -0
  63. package/dist/exec-run-schedule-task.js +572 -0
  64. package/dist/exec-run-shared.js +399 -0
  65. package/dist/exec-run.js +11 -4953
  66. package/dist/exec-shared.js +9 -2
  67. package/dist/exec-slot-lock.js +242 -0
  68. package/dist/exec-task-repos.js +415 -0
  69. package/dist/exec-trial-commands.js +558 -0
  70. package/dist/exec-trial-core.js +371 -0
  71. package/dist/exec-trial.js +2 -895
  72. package/dist/exec-worktree-command.js +87 -43
  73. package/dist/exec-worktree-ops-commit.js +707 -0
  74. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  75. package/dist/exec-worktree-ops-merge.js +303 -0
  76. package/dist/exec-worktree-ops.js +3 -847
  77. package/dist/exec-worktree.js +146 -31
  78. package/dist/exec.js +2 -999
  79. package/dist/frontmatter-namespace.js +2 -2
  80. package/dist/grade-apply.js +734 -0
  81. package/dist/grade-command-apply.js +250 -0
  82. package/dist/grade-command-inspect.js +138 -0
  83. package/dist/grade-command-plan.js +101 -0
  84. package/dist/grade-command-shared.js +68 -0
  85. package/dist/grade-core.js +307 -0
  86. package/dist/grade-markdown.js +274 -0
  87. package/dist/grade-pipeline-state.js +184 -0
  88. package/dist/grade-plan.js +507 -0
  89. package/dist/grade-result.js +133 -5
  90. package/dist/grade-target-discovery.js +265 -0
  91. package/dist/grade-targets.js +432 -0
  92. package/dist/grade.js +14 -2451
  93. package/dist/init-command.js +443 -0
  94. package/dist/job-definition.js +670 -0
  95. package/dist/job.js +64 -578
  96. package/dist/kata-command.js +2 -2
  97. package/dist/orchestrator.js +213 -0
  98. package/dist/register-command-types.js +1 -0
  99. package/dist/register-core.js +363 -0
  100. package/dist/register-create-commands.js +245 -0
  101. package/dist/register-event-merge.js +169 -0
  102. package/dist/register-events.js +4 -4
  103. package/dist/register-item.js +13 -7
  104. package/dist/register-maintenance-commands.js +187 -0
  105. package/dist/register-migration.js +268 -0
  106. package/dist/register-renumber.js +314 -0
  107. package/dist/register-transition-commands.js +248 -0
  108. package/dist/register-update.js +230 -0
  109. package/dist/register-views.js +256 -0
  110. package/dist/register.js +175 -1975
  111. package/dist/review-grade.js +252 -0
  112. package/dist/review-plan.js +114 -4
  113. package/dist/review-types.js +40 -1
  114. package/dist/routine-definition.js +401 -0
  115. package/dist/routine.js +73 -402
  116. package/dist/schedule-approach.js +2 -2
  117. package/dist/schedule-build.js +2 -2
  118. package/dist/schedule-strategy-generate-document.js +273 -0
  119. package/dist/schedule-strategy-generate-scope.js +199 -0
  120. package/dist/schedule-strategy-generate.js +9 -473
  121. package/dist/schedule.js +19 -6
  122. package/dist/specdojo-config.js +465 -20
  123. package/dist/specdojo-gitignore.js +135 -0
  124. package/dist/specdojo.js +6 -0
  125. package/dist/viewpoint-document-kinds-check.js +128 -0
  126. package/dist/yaml-pages.js +4 -4
  127. package/dist/yaml.js +28 -0
  128. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  129. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  130. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  131. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  132. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  133. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  134. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  135. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  136. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  137. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  138. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  139. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  140. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  141. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  142. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  143. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  144. package/docs/ja/specdojo/guides/exec-config-guide.md +93 -49
  145. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  146. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  147. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  148. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +45 -22
  149. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  150. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  151. package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
  152. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  153. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  154. package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
  155. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  156. package/docs/ja/specdojo/guides/routine-operation-guide.md +75 -10
  157. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  158. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  159. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  160. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  161. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  162. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  163. package/docs/ja/specdojo/index.md +2 -2
  164. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  165. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  166. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  167. package/docs/ja/specdojo/references/command-reference.md +335 -92
  168. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  169. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  170. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  171. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  172. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  173. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  174. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  175. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  176. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  177. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  178. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  179. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  180. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  181. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  182. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  183. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  184. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  185. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  186. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  187. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  188. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  189. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  190. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  191. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  192. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  193. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  194. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  195. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  196. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  197. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  198. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  199. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  200. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  201. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  202. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  203. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  204. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  205. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  206. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  207. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  208. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  209. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  210. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  211. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  212. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  213. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  214. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  215. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  216. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  217. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  218. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  219. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  220. package/package.json +17 -12
  221. package/templates/antigravity/README.md +29 -4
  222. package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
  223. package/templates/antigravity/exec-defaults-snippet.yaml +10 -7
  224. package/templates/antigravity/orchestrator.md +18 -7
  225. package/templates/antigravity/settings.global.json +55 -0
  226. package/templates/claude/agents/claude-executor.md +14 -0
  227. package/templates/claude/agents/claude-reporter.md +16 -0
  228. package/templates/claude/agents/specdojo-orchestrator.md +18 -7
  229. package/templates/claude/settings.edit.json +27 -1
  230. package/templates/codex/README.md +5 -4
  231. package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
  232. package/templates/codex/orchestrator.md +18 -7
  233. package/templates/copilot/README.md +7 -5
  234. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  235. package/templates/devcontainer/devcontainer.json +27 -0
  236. package/templates/devcontainer/emacs/init.el +88 -0
  237. package/templates/devcontainer/post-create.sh +62 -0
  238. package/templates/init-agent-members.yaml +200 -0
  239. package/templates/init-exec-defaults.yaml +74 -0
  240. package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
  241. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  242. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -0,0 +1,557 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join, resolve as pathResolve } from "node:path";
3
+ import { validateCatalogLocalIds, validateRulebookKata } from "./catalog-build.js";
4
+ import { acquireSchedulerLock, canBlockTask, canCancelTask, canClaimTask, canCompleteTask, canReleaseTask, canReopenTask, canUnblockTask, computeReadyIds, readAllEventFiles, releaseSchedulerLock, schedulerLockPath, writeEventFile, } from "./exec-events.js";
5
+ import { eventsDirForProject, generatedDirForProject } from "./exec-project.js";
6
+ import { assertValidActor, getProjectViewpointsPath, loadConfig, specdojoRootDir, } from "./specdojo-config.js";
7
+ import { buildScheduleIndex, computeCpm, exitWithCode, printValidateResult, selectNextTask, validateAll, writeCpmFiles, writeGeneratedCore, writeScheduleHashAndDiff, } from "./exec-schedule.js";
8
+ import { readReadySnapshot } from "./exec-schedule-ready.js";
9
+ import { displayWidth, nowUtcIsoSeconds, padEndDisplay, requireNonEmpty } from "./exec-shared.js";
10
+ import { archivePlan, buildInPlaceStem, generateDeliverablePlan, generateSinglePlan, resolveDeliverableTarget, stemFromPlanPath, } from "./exec-plans.js";
11
+ import { runProviderScaffold, specdojoPackageRootDir } from "./exec-provider-scaffold.js";
12
+ import { generateRegisterPlan, normalizePjrId, resolveRegisterRunTarget } from "./exec-register.js";
13
+ import { scaffoldViewpoints } from "./review-plan.js";
14
+ import { registerCycleCommand, registerResumeCommand, registerRunCommand, registerSlotsCommand, } from "./exec-run.js";
15
+ import { buildTaskView } from "./exec-task-view.js";
16
+ import { registerExecWorktreeCommands } from "./exec-worktree-command.js";
17
+ import { registerExecTrialCommands } from "./exec-trial.js";
18
+ import { registerExecHandoffCommands } from "./exec-handoff.js";
19
+ import { resolveOwnerForLocalId } from "./exec-strategy.js";
20
+ import { DEFAULT_EVENT_MESSAGES, KNOWN_OWNER_LABELS, KNOWN_OWNER_LABELS_TEXT, addCommonAddOptions, addForceOption, addLockOptions, addOwnerOptions, addProjectOptions, ensureActorCanClaimNext, findRosterMember, loadRosterForOpts, loadValidatedExecState, parseApproach, parseTaskMode, printCommandError, resolveClaimOwner, resolveForceOverride, resolveProjectContext, resolveProjectId, resolveSchedulerStrategy, runLockedEventCommand, runReleaseAllBlocked, runSimpleEventCommand, scaffoldClaimResult, } from "./exec-core.js";
21
+ export function registerExecCommands(program) {
22
+ const exec = program.command("exec").description("Execution helpers");
23
+ registerExecHandoffCommands(exec);
24
+ const lockedActions = {
25
+ claim: {
26
+ type: "claim",
27
+ requireSingleDoing: true,
28
+ check: ({ schedule, snapshot }, taskId, actor, opts) => {
29
+ const taskOwner = schedule.nodes.get(taskId)?.owner;
30
+ return canClaimTask(schedule, snapshot, taskId, resolveClaimOwner(opts, actor, loadRosterForOpts(opts), taskOwner), !!opts.allowOwnerMismatch);
31
+ },
32
+ },
33
+ complete: {
34
+ type: "complete",
35
+ check: ({ schedule, snapshot }, taskId, actor, opts) => canCompleteTask(schedule, snapshot, taskId, actor, resolveForceOverride(opts, actor)),
36
+ },
37
+ reopen: {
38
+ type: "reopen",
39
+ check: ({ schedule, snapshot }, taskId, actor, opts) => canReopenTask(schedule, snapshot, taskId, findRosterMember(loadRosterForOpts(opts), actor)?.type === "human"),
40
+ },
41
+ block: {
42
+ type: "block",
43
+ check: ({ schedule, snapshot }, taskId, actor, opts) => canBlockTask(schedule, snapshot, taskId, actor, resolveForceOverride(opts, actor)),
44
+ },
45
+ unblock: {
46
+ type: "unblock",
47
+ check: ({ schedule, snapshot }, taskId) => canUnblockTask(schedule, snapshot, taskId),
48
+ },
49
+ release: {
50
+ type: "release",
51
+ check: ({ schedule, snapshot }, taskId, actor, opts) => canReleaseTask(schedule, snapshot, taskId, actor, resolveForceOverride(opts, actor)),
52
+ },
53
+ cancel: {
54
+ type: "cancel",
55
+ check: ({ schedule, snapshot }, taskId) => canCancelTask(schedule, snapshot, taskId),
56
+ },
57
+ };
58
+ const types = [
59
+ "claim",
60
+ "note",
61
+ "block",
62
+ "unblock",
63
+ "complete",
64
+ "reopen",
65
+ "release",
66
+ "cancel",
67
+ "link",
68
+ "estimate",
69
+ ];
70
+ for (const t of types) {
71
+ const cmd = exec.command(t).description(`Write ${t} event JSON into exec/events/ (UTC)`);
72
+ addCommonAddOptions(cmd, {
73
+ requireTask: t !== "release" && t !== "complete",
74
+ msgDefault: DEFAULT_EVENT_MESSAGES[t],
75
+ });
76
+ if (t in lockedActions)
77
+ addLockOptions(cmd);
78
+ if (t === "claim")
79
+ addOwnerOptions(cmd);
80
+ if (t === "complete" || t === "block" || t === "release")
81
+ addForceOption(cmd);
82
+ if (t === "release") {
83
+ cmd.option("--reset-worktree", "Discard the task's exec worktree and branch after releasing (force removal)", false);
84
+ cmd.option("--all-blocked", "Release every blocked task in the project back to todo (ignores --task)", false);
85
+ }
86
+ if (t in lockedActions) {
87
+ const action = lockedActions[t];
88
+ cmd.action(async (opts) => {
89
+ if (action.type === "release" && opts.allBlocked) {
90
+ await runReleaseAllBlocked(opts);
91
+ return;
92
+ }
93
+ await runLockedEventCommand(opts, action);
94
+ });
95
+ }
96
+ else {
97
+ cmd.action((opts) => runSimpleEventCommand(opts, t));
98
+ }
99
+ }
100
+ const vcmd = exec.command("validate").description("Validate schedule + events");
101
+ addProjectOptions(vcmd);
102
+ vcmd.action((opts) => {
103
+ try {
104
+ const { schedulePath, catalogPath } = resolveProjectContext(opts);
105
+ const res = validateAll(schedulePath);
106
+ printValidateResult(res);
107
+ // Scheduled tasks resolve their deliverable by bare local_id, so warn when a
108
+ // local_id is not unique project-wide across the catalogs.
109
+ if (catalogPath && existsSync(catalogPath)) {
110
+ for (const warn of validateCatalogLocalIds(catalogPath).warnings) {
111
+ process.stdout.write(`WARN: ${warn}\n`);
112
+ }
113
+ // Warn when a rulebook declares recipe/sample/template or includes rulebooks
114
+ // that do not exist (or self-reference / non-rulebook includes).
115
+ for (const warn of validateRulebookKata(catalogPath).warnings) {
116
+ process.stdout.write(`WARN: ${warn}\n`);
117
+ }
118
+ }
119
+ exitWithCode(res.ok);
120
+ }
121
+ catch (error) {
122
+ printCommandError(error, false);
123
+ }
124
+ });
125
+ const refreshCmd = exec
126
+ .command("refresh")
127
+ .description("Refresh derived execution state under generated/");
128
+ addProjectOptions(refreshCmd);
129
+ refreshCmd.action(async (opts) => {
130
+ try {
131
+ const { schedulePath } = resolveProjectContext(opts);
132
+ const res = validateAll(schedulePath);
133
+ printValidateResult(res);
134
+ if (!res.ok) {
135
+ exitWithCode(false);
136
+ return;
137
+ }
138
+ const schedule = buildScheduleIndex(schedulePath);
139
+ const events = readAllEventFiles(schedulePath);
140
+ const cpm = computeCpm(schedule, schedulePath);
141
+ const snapshot = writeGeneratedCore(schedulePath, events, schedule, cpm);
142
+ writeScheduleHashAndDiff(schedulePath, schedule);
143
+ writeCpmFiles(schedulePath, cpm, snapshot);
144
+ process.stdout.write(`\nGenerated: ${generatedDirForProject(schedulePath)}\n`);
145
+ exitWithCode(true);
146
+ }
147
+ catch (error) {
148
+ printCommandError(error, false);
149
+ }
150
+ });
151
+ const planCmd = exec
152
+ .command("plan")
153
+ .description("Generate a plan for an agent task or catalog deliverable (schedule-independent; does not change state or events)");
154
+ addProjectOptions(planCmd);
155
+ planCmd.option("--task <taskId>", "Scheduled task ID to generate the plan for");
156
+ planCmd.option("--deliverable <localId>", "Catalog deliverable local_id (unique project-wide)");
157
+ planCmd.option("--register <pjrId>", "Project register item ID (PJR-XXXX)");
158
+ planCmd.option("--mode <mode>", "edit|review (deliverable target)", "edit");
159
+ planCmd.option("--approach <approach>", "Approach template (deliverable target)");
160
+ planCmd.option("--track <track>", "Track to resolve the owner role from sch-strategy owner_rules (deliverable target)");
161
+ planCmd.option("--out <path>", "Override output path");
162
+ planCmd.action(async (opts) => {
163
+ try {
164
+ const { schedulePath, executionPath, catalogPath, rolesPath, viewpointsPath, projectContext, } = resolveProjectContext(opts);
165
+ const hasTask = typeof opts.task === "string" && opts.task.trim() !== "";
166
+ const hasDeliverable = typeof opts.deliverable === "string" && opts.deliverable.trim() !== "";
167
+ const hasRegister = typeof opts.register === "string" && opts.register.trim() !== "";
168
+ if ([hasTask, hasDeliverable, hasRegister].filter(Boolean).length !== 1) {
169
+ throw new Error("Specify exactly one of --task, --deliverable, or --register.");
170
+ }
171
+ const projectId = resolveProjectId(opts);
172
+ const outOverride = typeof opts.out === "string" && opts.out.trim() ? opts.out.trim() : undefined;
173
+ // Stem priority: --out → derive from the given filename (overwrite it); else --task → the
174
+ // fixed task id, so the plan/result share one canonical name with claim / run --track-state
175
+ // and an in-place run can be adopted without renaming; else --deliverable / --register → a
176
+ // new unique stem per generation (no task identity; avoids doc-index id collisions).
177
+ let outPath;
178
+ if (hasRegister) {
179
+ const pjrId = normalizePjrId(opts.register);
180
+ const { registerPaths, item } = resolveRegisterRunTarget(projectId, pjrId);
181
+ const stem = outOverride
182
+ ? stemFromPlanPath(outOverride)
183
+ : buildInPlaceStem(pjrId.toLowerCase());
184
+ const generated = await generateRegisterPlan({
185
+ executionPath,
186
+ projectId,
187
+ registerPaths,
188
+ item,
189
+ stem,
190
+ ...(outOverride ? { outPath: outOverride } : {}),
191
+ });
192
+ outPath = generated.planPath;
193
+ }
194
+ else if (hasTask) {
195
+ const task = buildTaskView(schedulePath, executionPath, opts.task.trim());
196
+ const stem = outOverride ? stemFromPlanPath(outOverride) : opts.task.trim();
197
+ outPath = await generateSinglePlan({
198
+ executionPath,
199
+ projectId,
200
+ catalogPath: catalogPath ?? "",
201
+ rolesPath,
202
+ viewpointsPath,
203
+ projectContext,
204
+ task,
205
+ stem,
206
+ ...(outOverride ? { outPath: outOverride } : {}),
207
+ });
208
+ }
209
+ else {
210
+ const target = resolveDeliverableTarget(catalogPath ?? "", opts.deliverable.trim());
211
+ const track = typeof opts.track === "string" && opts.track.trim() ? opts.track.trim() : undefined;
212
+ const owner = resolveOwnerForLocalId(schedulePath, target.localId, track);
213
+ const stem = outOverride ? stemFromPlanPath(outOverride) : buildInPlaceStem(target.slug);
214
+ outPath = await generateDeliverablePlan({
215
+ executionPath,
216
+ projectId,
217
+ catalogPath: catalogPath ?? "",
218
+ rolesPath,
219
+ viewpointsPath,
220
+ projectContext,
221
+ target,
222
+ mode: parseTaskMode(opts.mode),
223
+ ...(opts.approach ? { approach: parseApproach(opts.approach) } : {}),
224
+ ...(owner ? { owner } : {}),
225
+ stem,
226
+ ...(outOverride ? { outPath: outOverride } : {}),
227
+ });
228
+ }
229
+ process.stdout.write(`Generated: ${outPath}\n`);
230
+ exitWithCode(true);
231
+ }
232
+ catch (error) {
233
+ printCommandError(error, false);
234
+ }
235
+ });
236
+ const archiveCmd = exec
237
+ .command("archive")
238
+ .description("Archive a completed plan to exec/plans/done/ (or delete it)");
239
+ addProjectOptions(archiveCmd);
240
+ archiveCmd.option("--task <taskId>", "Scheduled task ID whose plan to archive");
241
+ archiveCmd.option("--deliverable <localId>", "Catalog deliverable local_id (unique project-wide)");
242
+ archiveCmd.option("--plan <path>", "Plan file to archive (for unique-named in-place plans)");
243
+ archiveCmd.option("--delete", "Delete the plan instead of moving it to done/", false);
244
+ archiveCmd.action((opts) => {
245
+ try {
246
+ const { executionPath, catalogPath } = resolveProjectContext(opts);
247
+ const hasTask = typeof opts.task === "string" && opts.task.trim() !== "";
248
+ const hasDeliverable = typeof opts.deliverable === "string" && opts.deliverable.trim() !== "";
249
+ const hasPlan = typeof opts.plan === "string" && opts.plan.trim() !== "";
250
+ if ([hasTask, hasDeliverable, hasPlan].filter(Boolean).length !== 1) {
251
+ throw new Error("Specify exactly one of --task, --deliverable, or --plan.");
252
+ }
253
+ // `archivePlan` rebuilds `<slug>-plan.md`; for --plan the stem recovered from the filename
254
+ // is that slug, so a unique-named in-place plan archives to done/ like a fixed-name one.
255
+ const slug = hasPlan
256
+ ? stemFromPlanPath(opts.plan.trim())
257
+ : hasTask
258
+ ? opts.task.trim()
259
+ : resolveDeliverableTarget(catalogPath ?? "", opts.deliverable.trim()).slug;
260
+ const result = archivePlan({ executionPath, slug, delete: !!opts.delete });
261
+ process.stdout.write(result.deleted ? `Deleted: ${result.from}\n` : `Archived: ${result.from} -> ${result.to}\n`);
262
+ exitWithCode(true);
263
+ }
264
+ catch (error) {
265
+ printCommandError(error, false);
266
+ }
267
+ });
268
+ const scmd = exec
269
+ .command("scheduler")
270
+ .description("Auto-claim next task safely (with project-level lock).");
271
+ addProjectOptions(scmd);
272
+ scmd.requiredOption("--by <actor>", "Actor (agent name)");
273
+ addOwnerOptions(scmd);
274
+ scmd.option("--strategy <strategy>", "critical-first|fifo (defaults to member profile or critical-first)");
275
+ scmd.option("--dry-run", "Do not write; print selected task only", false);
276
+ scmd.option("--msg <message>", "Claim message", "auto-claim");
277
+ addLockOptions(scmd);
278
+ scmd.action(async (opts) => {
279
+ let lockDir = "";
280
+ try {
281
+ const { schedulePath, executionPath, catalogPath } = resolveProjectContext(opts);
282
+ const actor = requireNonEmpty("by", opts.by);
283
+ const roster = loadRosterForOpts(opts);
284
+ assertValidActor(actor, roster);
285
+ const strategy = resolveSchedulerStrategy(opts, actor, roster);
286
+ const dryRun = !!opts.dryRun;
287
+ const msg = String(opts.msg ?? "auto-claim");
288
+ const claimOwner = resolveClaimOwner(opts, actor, roster);
289
+ const allowOwnerMismatch = !!opts.allowOwnerMismatch;
290
+ const allowMultipleDoing = !!opts.allowMultipleDoing;
291
+ const lockTimeoutMs = Number(opts.lockTimeoutMs);
292
+ const lockStaleMs = Number(opts.lockStaleMs);
293
+ lockDir = acquireSchedulerLock(schedulePath, { actor, lockTimeoutMs, lockStaleMs });
294
+ const state = loadValidatedExecState(schedulePath);
295
+ if (!state)
296
+ return;
297
+ if (!ensureActorCanClaimNext(state.snapshot, actor, allowMultipleDoing))
298
+ return;
299
+ const ready = computeReadyIds(state.schedule, state.snapshot);
300
+ let cpm = null;
301
+ try {
302
+ cpm = computeCpm(state.schedule, schedulePath);
303
+ }
304
+ catch {
305
+ cpm = null;
306
+ }
307
+ // Collect all valid owner labels for this actor.
308
+ // Single-role actors use claimOwner; multi-role actors (e.g. indie) check every role.
309
+ const actorAllRoles = findRosterMember(roster, actor)
310
+ ?.roles?.map((r) => r.trim().toUpperCase())
311
+ .filter((r) => KNOWN_OWNER_LABELS.includes(r)) ??
312
+ [];
313
+ const ownerCandidates = actorAllRoles.length > 1 ? actorAllRoles : claimOwner ? [claimOwner] : [];
314
+ const readyForOwner = ready.filter((taskId) => {
315
+ if (ownerCandidates.length === 0) {
316
+ return canClaimTask(state.schedule, state.snapshot, taskId, claimOwner, allowOwnerMismatch).ok;
317
+ }
318
+ // Pass if any of the actor's roles can claim the task
319
+ return ownerCandidates.some((role) => canClaimTask(state.schedule, state.snapshot, taskId, role, allowOwnerMismatch).ok);
320
+ });
321
+ // Filter by actor mode and execution type from ready.json.
322
+ // Agent actors (with mode set) skip tasks with wrong mode or execution: human.
323
+ const actorMember = findRosterMember(roster, actor);
324
+ const actorMode = actorMember?.mode;
325
+ const isAgent = actorMember?.type === "agent";
326
+ let readyForMode = readyForOwner;
327
+ if (actorMode || isAgent) {
328
+ const readyJsonPath = join(generatedDirForProject(schedulePath), "ready.json");
329
+ if (existsSync(readyJsonPath)) {
330
+ const readySnapshot = readReadySnapshot(readyJsonPath);
331
+ const taskInfoMap = new Map(readySnapshot.tasks.map((t) => [t.id, t]));
332
+ readyForMode = readyForOwner.filter((taskId) => {
333
+ const taskInfo = taskInfoMap.get(taskId);
334
+ if (!taskInfo)
335
+ return true;
336
+ // Agents skip manual tasks
337
+ if (isAgent && (taskInfo.execution ?? "agent") === "human")
338
+ return false;
339
+ // Mode filter: skip tasks with different mode
340
+ if (actorMode && (taskInfo.mode ?? "edit") !== actorMode)
341
+ return false;
342
+ return true;
343
+ });
344
+ }
345
+ }
346
+ const next = selectNextTask(readyForMode, cpm, strategy);
347
+ if (!next) {
348
+ if (readyForOwner.length > 0 && (actorMode || isAgent)) {
349
+ process.stdout.write(`No ready ${actorMode ?? "agent"} task for ${actor}. ` +
350
+ `${readyForOwner.length} task(s) ready but require different mode or are human-only.\n`);
351
+ }
352
+ else if (ready.length > 0 && !allowOwnerMismatch) {
353
+ process.stdout.write(`No ready task assigned to owner ${claimOwner}. Use --owner <${KNOWN_OWNER_LABELS_TEXT}>, SPECDOJO_OWNER, or --allow-owner-mismatch.\n`);
354
+ }
355
+ else {
356
+ process.stdout.write("No ready task to claim.\n");
357
+ }
358
+ exitWithCode(true);
359
+ return;
360
+ }
361
+ if (dryRun) {
362
+ process.stdout.write(next + "\n");
363
+ exitWithCode(true);
364
+ return;
365
+ }
366
+ // For multi-role actors, use the role that matches the selected task's owner.
367
+ const plannedOwner = state.schedule.nodes.get(next)?.owner ?? "";
368
+ const effectiveClaimOwner = ownerCandidates.length > 1 && ownerCandidates.includes(plannedOwner)
369
+ ? plannedOwner
370
+ : claimOwner;
371
+ const ev = {
372
+ v: 1,
373
+ ts: nowUtcIsoSeconds(),
374
+ type: "claim",
375
+ task_id: next,
376
+ by: actor,
377
+ msg,
378
+ meta: {
379
+ claim_owner: effectiveClaimOwner,
380
+ planned_owner: plannedOwner || undefined,
381
+ scheduler_strategy: strategy,
382
+ claimed_via: "dojo-exec-scheduler",
383
+ },
384
+ };
385
+ if (ev.meta?.planned_owner &&
386
+ ev.meta.claim_owner !== ev.meta.planned_owner &&
387
+ allowOwnerMismatch) {
388
+ ev.meta.owner_override = true;
389
+ }
390
+ const out = writeEventFile(schedulePath, ev);
391
+ // Await the scaffold (it formats the result with Prettier asynchronously). Firing it without
392
+ // awaiting leaks a promise that can read/write the result after the caller tears down its
393
+ // working directory, surfacing as an ENOENT unhandled rejection.
394
+ await scaffoldClaimResult({
395
+ schedulePath,
396
+ executionPath,
397
+ catalogPath,
398
+ state,
399
+ taskId: next,
400
+ projectId: resolveProjectId(opts),
401
+ actor,
402
+ startedAt: ev.ts,
403
+ });
404
+ process.stdout.write(out + "\n");
405
+ exitWithCode(true);
406
+ }
407
+ catch (error) {
408
+ printCommandError(error);
409
+ }
410
+ finally {
411
+ if (lockDir) {
412
+ try {
413
+ releaseSchedulerLock(lockDir);
414
+ }
415
+ catch {
416
+ // ignore
417
+ }
418
+ }
419
+ }
420
+ });
421
+ registerRunCommand(exec);
422
+ registerResumeCommand(exec);
423
+ registerCycleCommand(exec);
424
+ registerSlotsCommand(exec);
425
+ registerExecWorktreeCommands(exec);
426
+ registerExecTrialCommands(exec);
427
+ // exec scaffold: creates project setup files (viewpoints etc.) or provider templates
428
+ const scaffoldCmd = exec
429
+ .command("scaffold")
430
+ .description("Scaffold project setup files (pm-review-viewpoints.yaml) or provider templates (--provider)");
431
+ addProjectOptions(scaffoldCmd);
432
+ scaffoldCmd.option("--force", "Overwrite existing files", false);
433
+ scaffoldCmd.option("--provider <name>", "Copy the provider's agent/settings templates (templates/<name>) into the repository");
434
+ scaffoldCmd.option("--dry-run", "Show planned files without writing", false);
435
+ scaffoldCmd.option("--global", "Merge provider permissions into user-level settings (currently antigravity only)", false);
436
+ scaffoldCmd.action(async (opts) => {
437
+ try {
438
+ if (opts.global && !opts.provider) {
439
+ throw new Error("--global requires --provider <name>");
440
+ }
441
+ if (opts.provider) {
442
+ await runProviderScaffold(String(opts.provider), {
443
+ packageRoot: specdojoPackageRootDir(),
444
+ repoRoot: specdojoRootDir(),
445
+ force: !!opts.force,
446
+ dryRun: !!opts.dryRun,
447
+ global: !!opts.global,
448
+ });
449
+ return;
450
+ }
451
+ const { config } = loadConfig();
452
+ if (!config)
453
+ throw new Error("specdojo.config.json not found. Run: specdojo config init");
454
+ const projectId = opts.project?.trim() ||
455
+ process.env.SPECDOJO_PROJECT?.trim() ||
456
+ config.current_project?.trim() ||
457
+ Object.keys(config.projects)[0] ||
458
+ "";
459
+ if (!projectId)
460
+ throw new Error("No project specified. Use --project <id>.");
461
+ const project = config.projects[projectId];
462
+ if (!project)
463
+ throw new Error(`Unknown project: ${projectId}`);
464
+ const baseDir = specdojoRootDir();
465
+ const commonPath = join(baseDir, "docs", "ja", "specdojo", "standards", "pm-review-viewpoints.yaml");
466
+ const viewpointsRel = getProjectViewpointsPath(project);
467
+ if (viewpointsRel) {
468
+ const outputPath = pathResolve(baseDir, viewpointsRel);
469
+ const result = scaffoldViewpoints({
470
+ commonPath,
471
+ projectId,
472
+ outputPath,
473
+ force: !!opts.force,
474
+ });
475
+ if (result.written) {
476
+ process.stdout.write(`Written: ${outputPath}\n`);
477
+ }
478
+ else {
479
+ process.stdout.write(`Skipped (already exists): ${outputPath}\n`);
480
+ }
481
+ }
482
+ else {
483
+ process.stdout.write(`viewpoints_path not set for project '${projectId}'. Add it to specdojo.config.json.\n`);
484
+ }
485
+ }
486
+ catch (error) {
487
+ printCommandError(error, false);
488
+ }
489
+ });
490
+ const statusCmd = exec.command("status").description("Show tasks filtered by state and actor");
491
+ addProjectOptions(statusCmd);
492
+ statusCmd.option("--by <actor>", "Filter by actor nickname");
493
+ statusCmd.option("--state <state>", "Filter by state: todo|doing|blocked|done|cancelled (default: doing)", "doing");
494
+ statusCmd.action((opts) => {
495
+ try {
496
+ const { schedulePath } = resolveProjectContext(opts);
497
+ // Compute state directly from events (not from cached state.json)
498
+ const state = loadValidatedExecState(schedulePath);
499
+ if (!state)
500
+ return;
501
+ const snapshot = state.snapshot;
502
+ const schedule = state.schedule;
503
+ const filterState = String(opts.state ?? "doing");
504
+ const filterBy = typeof opts.by === "string" ? opts.by.trim() : undefined;
505
+ const entries = Object.entries(snapshot.tasks)
506
+ .filter(([, cs]) => cs.state === filterState)
507
+ .filter(([, cs]) => !filterBy || cs.last_by === filterBy)
508
+ .sort(([a], [b]) => a.localeCompare(b));
509
+ if (entries.length === 0) {
510
+ const byMsg = filterBy ? ` for ${filterBy}` : "";
511
+ process.stdout.write(`No ${filterState} tasks${byMsg}.\n`);
512
+ exitWithCode(true);
513
+ return;
514
+ }
515
+ const byMsg = filterBy ? ` for ${filterBy}` : "";
516
+ process.stdout.write(`${filterState} tasks${byMsg}:\n\n`);
517
+ const rows = entries.map(([taskId, cs]) => ({
518
+ taskId,
519
+ name: schedule.nodes.get(taskId)?.name ?? "-",
520
+ by: cs.last_by ?? "-",
521
+ ts: cs.last_ts ?? "-",
522
+ }));
523
+ // Size every column to its longest value (including the header) so nothing is truncated.
524
+ // displayWidth counts full-width (CJK) characters as 2 columns so the table stays aligned.
525
+ const taskWidth = Math.max("task_id".length, ...rows.map((r) => displayWidth(r.taskId)));
526
+ const nameWidth = Math.max("name".length, ...rows.map((r) => displayWidth(r.name)));
527
+ const byWidth = Math.max("by".length, ...rows.map((r) => displayWidth(r.by)));
528
+ const tsWidth = Math.max("claimed_at".length, ...rows.map((r) => displayWidth(r.ts)));
529
+ process.stdout.write(` ${padEndDisplay("task_id", taskWidth)} ${padEndDisplay("name", nameWidth)} ${padEndDisplay("by", byWidth)} claimed_at\n`);
530
+ process.stdout.write(` ${"-".repeat(taskWidth)} ${"-".repeat(nameWidth)} ${"-".repeat(byWidth)} ${"-".repeat(tsWidth)}\n`);
531
+ for (const r of rows) {
532
+ // The trailing claimed_at column is left unpadded to avoid stray trailing whitespace.
533
+ process.stdout.write(` ${padEndDisplay(r.taskId, taskWidth)} ${padEndDisplay(r.name, nameWidth)} ${padEndDisplay(r.by, byWidth)} ${r.ts}\n`);
534
+ }
535
+ exitWithCode(true);
536
+ }
537
+ catch (error) {
538
+ printCommandError(error, false);
539
+ }
540
+ });
541
+ const wcmd = exec.command("where").description("Print resolved paths");
542
+ addProjectOptions(wcmd);
543
+ wcmd.action((opts) => {
544
+ try {
545
+ const resolvedPaths = resolveProjectContext(opts);
546
+ process.stdout.write(`schedule-path: ${resolvedPaths.schedulePath}\n`);
547
+ process.stdout.write(`execution-path: ${resolvedPaths.executionPath}\n`);
548
+ const projectPath = resolvedPaths.schedulePath;
549
+ process.stdout.write(`exec/events : ${eventsDirForProject(projectPath)}\n`);
550
+ process.stdout.write(`generated : ${generatedDirForProject(projectPath)}\n`);
551
+ process.stdout.write(`scheduler-lock: ${schedulerLockPath(projectPath)}\n`);
552
+ }
553
+ catch (error) {
554
+ printCommandError(error, false);
555
+ }
556
+ });
557
+ }