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
@@ -1,13 +1,11 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, } from "node:fs";
2
- import { spawn } from "node:child_process";
3
1
  import { join } from "node:path";
4
- import { ensureDir, nowUtcIsoSeconds, randomHex, writeJson } from "./exec-shared.js";
5
- export const EXEC_RUN_LOCK_HEARTBEAT_MS = 5_000;
6
- export const EXEC_RUN_LOCK_STALE_MS = 30_000;
2
+ import { ensureDir } from "./exec-shared.js";
3
+ import { delay, formatLockOwner, isLiveLock, LOCK_HEARTBEAT_MS, LOCK_POLL_MS, LOCK_STALE_MS, livePoolHolders, readLockOwner, releaseLock, tryAcquireLock, tryAcquirePoolSlot, } from "./exec-slot-lock.js";
4
+ export const EXEC_RUN_LOCK_HEARTBEAT_MS = LOCK_HEARTBEAT_MS;
5
+ export const EXEC_RUN_LOCK_STALE_MS = LOCK_STALE_MS;
7
6
  export const EXEC_RUN_LOCK_TOKEN_ENV = "SPECDOJO_EXEC_RUN_LOCK_TOKEN";
8
7
  export const ROUTINE_EXEC_ENV = "SPECDOJO_ROUTINE_EXEC";
9
8
  export const ROUTINE_BUSY_SKIP_EXIT_CODE = 75;
10
- const EXEC_RUN_LOCK_POLL_MS = 200;
11
9
  export class ExecRunBusyError extends Error {
12
10
  lockDir;
13
11
  owner;
@@ -18,118 +16,80 @@ export class ExecRunBusyError extends Error {
18
16
  this.name = "ExecRunBusyError";
19
17
  }
20
18
  }
19
+ export function execLocksDir(executionPath) {
20
+ return join(executionPath, "exec", ".locks");
21
+ }
21
22
  export function execRunLockPath(executionPath) {
22
- return join(executionPath, "exec", ".locks", "exec-run.lock");
23
+ return join(execLocksDir(executionPath), "exec-run.lock");
23
24
  }
24
- function readOwner(lockDir) {
25
- try {
26
- return JSON.parse(readFileSync(join(lockDir, "owner.json"), "utf8"));
27
- }
28
- catch {
29
- return null;
30
- }
25
+ // `--join` runs hold one of these slots instead of the primary exec-run.lock.
26
+ export function execRunJoinPoolPath(executionPath) {
27
+ return join(execLocksDir(executionPath), "exec-run-join");
31
28
  }
32
29
  export function inheritsExecRunLock(executionPath) {
33
30
  const inheritedToken = process.env[EXEC_RUN_LOCK_TOKEN_ENV];
34
31
  if (!inheritedToken)
35
32
  return false;
36
- return readOwner(execRunLockPath(executionPath))?.token === inheritedToken;
37
- }
38
- function formatOwner(lockDir) {
39
- const owner = readOwner(lockDir);
40
- return owner ? JSON.stringify(owner) : "(owner metadata unavailable)";
41
- }
42
- function delay(ms) {
43
- return new Promise((resolve) => setTimeout(resolve, ms));
33
+ if (readLockOwner(execRunLockPath(executionPath))?.token === inheritedToken)
34
+ return true;
35
+ return livePoolHolders(execRunJoinPoolPath(executionPath)).some((slot) => slot.owner?.token === inheritedToken);
44
36
  }
45
- const HEARTBEAT_SCRIPT = String.raw `
46
- const fs = require("node:fs");
47
- const path = require("node:path");
48
- const [lockDir, token, intervalText, parentText] = process.argv.slice(1);
49
- const ownerPath = path.join(lockDir, "owner.json");
50
- const intervalMs = Number(intervalText);
51
- const parentPid = Number(parentText);
52
- function heartbeat() {
53
- try {
54
- process.kill(parentPid, 0);
55
- const owner = JSON.parse(fs.readFileSync(ownerPath, "utf8"));
56
- if (owner.token !== token) process.exit(0);
57
- const now = new Date();
58
- fs.utimesSync(lockDir, now, now);
59
- } catch {
60
- process.exit(0);
61
- }
37
+ function describeHolders(executionPath, staleMs) {
38
+ const primary = execRunLockPath(executionPath);
39
+ const lines = [];
40
+ if (isLiveLock(primary, staleMs))
41
+ lines.push(formatLockOwner(primary));
42
+ for (const slot of livePoolHolders(execRunJoinPoolPath(executionPath), staleMs)) {
43
+ lines.push(`${slot.name}: ${slot.owner ? JSON.stringify(slot.owner) : "(owner unavailable)"}`);
44
+ }
45
+ return lines.length > 0 ? lines.join("\n") : "(owner metadata unavailable)";
62
46
  }
63
- heartbeat();
64
- setInterval(heartbeat, intervalMs);
65
- `;
66
- function startHeartbeat(lockDir, token, intervalMs) {
67
- // A separate process keeps the heartbeat alive while the runner is inside spawnSync-based
68
- // validate / refresh / git operations. It exits when the owner PID or token disappears.
69
- const heartbeat = spawn(process.execPath, ["-e", HEARTBEAT_SCRIPT, lockDir, token, String(intervalMs), String(process.pid)], { detached: true, stdio: "ignore" });
70
- heartbeat.unref();
71
- return heartbeat;
47
+ // Acquisition without `--join` keeps the historical behaviour: the primary lock is taken, and a
48
+ // live `--join` run that outlived its primary counts as busy for a non-shareable run. The check
49
+ // runs after taking the primary lock, and joiners check the primary after taking their slot, so
50
+ // a non-shareable run and a joiner can never both proceed. A shareable primary coordinates its
51
+ // shared resources across processes, so live joiners do not block it.
52
+ function tryAcquireExclusive(executionPath, opts, staleMs) {
53
+ const shareable = opts.shareable ?? false;
54
+ const handle = tryAcquireLock(execRunLockPath(executionPath), { actor: opts.actor, shareable }, { heartbeatMs: opts.heartbeatMs, staleMs });
55
+ if (!handle)
56
+ return null;
57
+ if (shareable)
58
+ return handle;
59
+ if (livePoolHolders(execRunJoinPoolPath(executionPath), staleMs).length === 0)
60
+ return handle;
61
+ releaseLock(handle);
62
+ return null;
72
63
  }
73
- function tryRemoveStaleLock(lockDir, staleMs) {
74
- let ageMs;
75
- try {
76
- ageMs = Date.now() - statSync(lockDir).mtimeMs;
77
- }
78
- catch (error) {
79
- if (error?.code === "ENOENT")
80
- return true;
81
- throw error;
82
- }
83
- if (ageMs <= staleMs)
84
- return false;
85
- const staleDir = `${lockDir}.stale-${process.pid}-${randomHex(4)}`;
86
- try {
87
- // Rename first so a competing process can never make us delete its newly acquired lock.
88
- renameSync(lockDir, staleDir);
89
- }
90
- catch (error) {
91
- if (error?.code === "ENOENT")
92
- return true;
93
- throw error;
94
- }
95
- rmSync(staleDir, { recursive: true, force: true });
96
- return true;
64
+ function tryAcquireJoin(executionPath, opts, limit, staleMs) {
65
+ if (limit < 1)
66
+ return null;
67
+ const handle = tryAcquirePoolSlot(execRunJoinPoolPath(executionPath), limit, { actor: opts.actor, shareable: true }, { heartbeatMs: opts.heartbeatMs, staleMs });
68
+ if (!handle)
69
+ return null;
70
+ const primary = execRunLockPath(executionPath);
71
+ // The primary run must tolerate joiners. Owners written by older versions carry no
72
+ // `shareable` field and are treated as exclusive.
73
+ if (!isLiveLock(primary, staleMs) || readLockOwner(primary)?.shareable === true)
74
+ return handle;
75
+ releaseLock(handle);
76
+ return null;
97
77
  }
98
78
  export async function acquireExecRunLock(executionPath, opts) {
99
- const lockDir = execRunLockPath(executionPath);
100
- ensureDir(join(executionPath, "exec", ".locks"));
101
- const heartbeatMs = opts.heartbeatMs ?? EXEC_RUN_LOCK_HEARTBEAT_MS;
79
+ ensureDir(execLocksDir(executionPath));
102
80
  const staleMs = opts.staleMs ?? EXEC_RUN_LOCK_STALE_MS;
103
- const pollMs = opts.pollMs ?? EXEC_RUN_LOCK_POLL_MS;
104
- const token = `${process.pid}-${randomHex(8)}`;
81
+ const pollMs = opts.pollMs ?? LOCK_POLL_MS;
105
82
  let waitingAnnounced = false;
106
83
  while (true) {
107
- try {
108
- mkdirSync(lockDir);
109
- writeJson(join(lockDir, "owner.json"), {
110
- actor: opts.actor,
111
- pid: process.pid,
112
- token,
113
- acquired_at_utc: nowUtcIsoSeconds(),
114
- });
115
- const now = new Date();
116
- utimesSync(lockDir, now, now);
117
- return {
118
- lockDir,
119
- token,
120
- heartbeat: startHeartbeat(lockDir, token, heartbeatMs),
121
- };
122
- }
123
- catch (error) {
124
- if (error?.code !== "EEXIST")
125
- throw error;
126
- }
127
- if (tryRemoveStaleLock(lockDir, staleMs))
128
- continue;
84
+ const handle = opts.join
85
+ ? tryAcquireJoin(executionPath, opts, opts.join.limit, staleMs)
86
+ : tryAcquireExclusive(executionPath, opts, staleMs);
87
+ if (handle)
88
+ return handle;
129
89
  if (opts.ifBusy === "skip")
130
90
  return null;
131
91
  if (opts.ifBusy === "fail") {
132
- throw new ExecRunBusyError(lockDir, formatOwner(lockDir));
92
+ throw new ExecRunBusyError(opts.join ? execRunJoinPoolPath(executionPath) : execRunLockPath(executionPath), describeHolders(executionPath, staleMs));
133
93
  }
134
94
  if (!waitingAnnounced) {
135
95
  opts.onWait?.();
@@ -139,11 +99,54 @@ export async function acquireExecRunLock(executionPath, opts) {
139
99
  }
140
100
  }
141
101
  export function releaseExecRunLock(handle) {
142
- handle.heartbeat.kill();
143
- if (!existsSync(handle.lockDir))
144
- return;
145
- const owner = readOwner(handle.lockDir);
146
- if (owner?.token !== handle.token)
147
- return;
148
- rmSync(handle.lockDir, { recursive: true, force: true });
102
+ releaseLock(handle);
103
+ }
104
+ // Serializes the register lifecycle steps that write the root worktree (start transition,
105
+ // checkpoint, merge, wait commit, view rebuild) across every exec run of the project.
106
+ export function execLifecyclePoolPath(executionPath) {
107
+ return join(execLocksDir(executionPath), "exec-lifecycle");
108
+ }
109
+ function describeSlotOwner(slot) {
110
+ if (!slot.owner)
111
+ return `${slot.name}: (owner unavailable)`;
112
+ const label = slot.owner.label ? ` ${slot.owner.label}` : "";
113
+ return `${slot.name}: ${slot.owner.actor}${label} (pid ${slot.owner.pid}, since ${slot.owner.acquired_at_utc})`;
114
+ }
115
+ /**
116
+ * Current usage of the project's cross-process locks. `pools` lists additional slot pools
117
+ * (provider caps, parent validations) with their configured limits. Stale slots whose heartbeat
118
+ * stopped are not counted.
119
+ */
120
+ export function collectExecLockUsage(executionPath, params) {
121
+ const staleMs = params.staleMs ?? EXEC_RUN_LOCK_STALE_MS;
122
+ const primary = execRunLockPath(executionPath);
123
+ const primaryOwner = isLiveLock(primary, staleMs) ? readLockOwner(primary) : null;
124
+ const primaryHolders = isLiveLock(primary, staleMs)
125
+ ? [
126
+ primaryOwner
127
+ ? `${primaryOwner.actor} (pid ${primaryOwner.pid}, since ${primaryOwner.acquired_at_utc}, ${primaryOwner.shareable === true ? "joinable" : "exclusive"})`
128
+ : "(owner unavailable)",
129
+ ]
130
+ : [];
131
+ const pool = (name, path, limit) => ({
132
+ name,
133
+ path,
134
+ limit,
135
+ holders: livePoolHolders(path, staleMs).map(describeSlotOwner),
136
+ });
137
+ return [
138
+ { name: "exec run (primary)", path: primary, limit: 1, holders: primaryHolders },
139
+ pool("exec run (--join)", execRunJoinPoolPath(executionPath), params.joinLimit),
140
+ pool("register lifecycle", execLifecyclePoolPath(executionPath), 1),
141
+ ...params.pools.map((entry) => pool(entry.name, entry.path, entry.limit)),
142
+ ];
143
+ }
144
+ export function formatExecLockUsage(entries) {
145
+ const lines = [];
146
+ for (const entry of entries) {
147
+ lines.push(`${entry.name}: ${entry.holders.length}/${entry.limit}`);
148
+ for (const holder of entry.holders)
149
+ lines.push(` ${holder}`);
150
+ }
151
+ return `${lines.join("\n")}\n`;
149
152
  }
@@ -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
+ }
@@ -0,0 +1,244 @@
1
+ import { loadExecDefaultsConfig } from "./exec-agent-config.js";
2
+ import { resolveProjectPaths } from "./exec-project.js";
3
+ import { isRegisterFailureMode } from "./exec-register.js";
4
+ import { EXCLUSIVE_EXEC_RUN, parseParallel, resolveExecDefaultsPath, resolveRegisterWorktree, withProjectExecRunLock, } from "./exec-run-shared.js";
5
+ import { runBatchMode, runManualMode } from "./exec-run-schedule-mode.js";
6
+ import { runInPlaceMode } from "./exec-run-in-place.js";
7
+ import { runJobMode } from "./exec-run-job.js";
8
+ import { spawnRefresh, spawnValidate } from "./exec-run-mode-shared.js";
9
+ import { resolveRegisterPipelineCommand } from "./exec-run-register-core.js";
10
+ import { runRegisterMode } from "./exec-run-register-mode.js";
11
+ export function registerRunCommand(exec) {
12
+ const rcmd = exec
13
+ .command("run")
14
+ .description("Run AI agent for a ready task (--auto selects next by strategy)");
15
+ rcmd.option("--project <projectId>", "Project id in .specdojo/specdojo.config.json");
16
+ rcmd.option("--by <nickname>", "Select an agent-members.yaml agent for a manual target");
17
+ rcmd.option("--auto", "Automatically select and run next ready task", false);
18
+ rcmd.option("--task <taskId>", "Task ID to run (manual selection)");
19
+ rcmd.option("--deliverable <localId>", "Catalog deliverable local_id target (unique project-wide)");
20
+ rcmd.option("--plan <path>", "Run an existing plan file (in-place; no generation)");
21
+ rcmd.option("--register <pjrIds...>", "One or more project register item IDs (PJR-XXXX) to run; execution location defaults to run.register_execution in exec-defaults (in-place when unset)");
22
+ rcmd.option("--register-filter", "Select register items deterministically with --register-types/--register-priorities/--register-statuses/--register-limit", false);
23
+ rcmd.option("--register-types <types>", "Comma-separated register item types");
24
+ rcmd.option("--register-priorities <priorities>", "Comma-separated register priorities");
25
+ rcmd.option("--register-statuses <statuses>", "Comma-separated register statuses");
26
+ rcmd.option("--register-limit <n>", "Maximum selected register items");
27
+ rcmd.option("--job <jobId>", "Materialize and run a reusable job definition");
28
+ rcmd.option("--input <key=value...>", "Job input values (repeat or provide multiple key=value pairs)");
29
+ rcmd.option("--scheduled-at <dateTime>", "Scheduled occurrence time for a Job Run");
30
+ rcmd.option("--job-trigger <source>", "Job trigger source: manual|routine|ci", "manual");
31
+ rcmd.option("--register-commit", "With in-place --register: commit each successful item's changes as a separate commit (default: leave changes in the working tree). Ignored in worktree mode, which always commits", false);
32
+ rcmd.option("--on-failure <mode>", "With --register: stop|continue remaining items after a failure (default: stop)");
33
+ rcmd.option("--resume", "With register worktree mode: resume the stage where a run stopped (executor, reporter, or integration), reusing the existing worktree and checkpoints", false);
34
+ rcmd.option("--resume-from <stage>", "With --resume: resume a reporter-stage run from executor instead (accepted value: executor)");
35
+ rcmd.option("--force-restart", "With register worktree mode: re-run the whole item even when a resumable executor result exists (discards the worktree and its uncommitted changes)", false);
36
+ rcmd.option("--worktree", "Use a git worktree and integrate back (requires --task, --register, or --job; Job runs are committed and reviewed before merge)", false);
37
+ rcmd.option("--in-place", "Run a register item in the current working tree (overrides run.register_execution; cannot be combined with --worktree)", false);
38
+ rcmd.option("--track-state", "Record claim/complete events (requires --task; --by optional, actor auto-derived from the resolved agent)", false);
39
+ rcmd.option("--archive-on-success", "Archive the generated plan to exec/plans/done/ after a successful in-place run", false);
40
+ rcmd.option("--parallel <n>", "Number of worktree instances to run in parallel", "1");
41
+ rcmd.option("--worktree-base <path>", "Override worktree base directory");
42
+ rcmd.option("--strategy <s>", "Task selection strategy: critical-first|fifo (default: critical-first)");
43
+ rcmd.option("--loop", "Repeat rounds until no ready tasks remain, rebuilding doc-index and running exec refresh between rounds", false);
44
+ rcmd.option("--max-rounds <n>", "Maximum number of rounds when using --loop (ignored without --loop)");
45
+ rcmd.option("--if-busy <policy>", "When another exec is running for the project: skip|wait|fail (default: fail)", "fail");
46
+ rcmd.option("--join", "With register worktree mode: run next to a running register worktree exec instead of waiting for it, sharing its provider caps, lifecycle serialization, and parent-validation slots (up to run.max_concurrent_runs; --if-busy applies when all join slots are taken)", false);
47
+ rcmd.option("--exec-defaults <path>", "Path to exec-defaults.yaml global config (default: .specdojo/exec-defaults.yaml)");
48
+ rcmd.option("--agent-config <path>", "Deprecated alias for --exec-defaults");
49
+ rcmd.option("--edit-by <nickname>", "agent-members.yaml nickname for edit-mode tasks in --auto batch runs");
50
+ rcmd.option("--review-by <nickname>", "agent-members.yaml nickname for review-mode tasks in --auto batch runs");
51
+ rcmd.option("--executor-by <nickname>", "Executor nickname; with --register, also accepts PJR-ID=nickname assignments separated by commas. With --plan / --deliverable, runs the executor/reporter pipeline");
52
+ rcmd.option("--reporter-by <nickname>", "agent-members.yaml reporter nickname for agent_pipeline tasks (with --plan / --deliverable, runs the executor/reporter pipeline)");
53
+ rcmd.option("--dry-run", "Print resolved command without executing", false);
54
+ rcmd.action(async (opts) => {
55
+ try {
56
+ const isAuto = !!opts.auto;
57
+ const hasTask = !!opts.task;
58
+ const hasDeliverable = !!opts.deliverable;
59
+ const hasPlan = !!opts.plan;
60
+ const hasRegisterIds = !!opts.register;
61
+ const hasRegisterFilter = !!opts.registerFilter;
62
+ const hasRegister = hasRegisterIds || hasRegisterFilter;
63
+ const hasJob = !!opts.job;
64
+ const isManual = hasTask || hasDeliverable || hasPlan || hasRegister || hasJob;
65
+ const isBatch = isAuto;
66
+ if (hasRegisterIds && hasRegisterFilter) {
67
+ process.stdout.write("Specify either --register or --register-filter, not both.\n");
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ if ((opts.registerTypes ||
72
+ opts.registerPriorities ||
73
+ opts.registerStatuses ||
74
+ opts.registerLimit) &&
75
+ !hasRegisterFilter) {
76
+ process.stdout.write("--register-types, --register-priorities, --register-statuses, and --register-limit require --register-filter.\n");
77
+ process.exitCode = 1;
78
+ return;
79
+ }
80
+ if (!isAuto && !isManual) {
81
+ process.stdout.write("Specify --auto, --by (with a manual target), --task, --deliverable, --plan, --register, or --job.\n");
82
+ process.exitCode = 1;
83
+ return;
84
+ }
85
+ if ([hasTask, hasDeliverable, hasPlan, hasRegister, hasJob].filter(Boolean).length > 1) {
86
+ process.stdout.write("Specify at most one of --task, --deliverable, --plan, --register, --job.\n");
87
+ process.exitCode = 1;
88
+ return;
89
+ }
90
+ if (hasRegister && opts.trackState) {
91
+ process.stdout.write("--track-state cannot be used with --register (state is tracked in the register itself).\n");
92
+ process.exitCode = 1;
93
+ return;
94
+ }
95
+ if (opts.worktree && opts.inPlace) {
96
+ process.stdout.write("Specify either --worktree or --in-place, not both.\n");
97
+ process.exitCode = 1;
98
+ return;
99
+ }
100
+ if (opts.inPlace && !hasRegister) {
101
+ process.stdout.write("--in-place requires --register or --register-filter.\n");
102
+ process.exitCode = 1;
103
+ return;
104
+ }
105
+ if (hasRegister) {
106
+ const { schedulePath, executionPath } = resolveProjectPaths({ project: opts.project });
107
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
108
+ opts.worktree = resolveRegisterWorktree(opts, execDefaults);
109
+ }
110
+ if (hasRegister && !opts.worktree && parseParallel(opts.parallel) !== 1) {
111
+ process.stdout.write("--parallel with --register requires worktree mode; use --worktree or configure run.register_execution: worktree.\n");
112
+ process.exitCode = 1;
113
+ return;
114
+ }
115
+ if (opts.join && !(hasRegister && opts.worktree)) {
116
+ process.stdout.write("--join requires --register (or --register-filter) in worktree mode.\n");
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ if (hasRegister && opts.worktree && opts.registerCommit) {
121
+ process.stdout.write("Note: --register-commit is ignored in worktree mode; worktree runs always commit (checkpoint + merge back).\n");
122
+ }
123
+ if ((opts.registerCommit || opts.onFailure) && !hasRegister) {
124
+ process.stdout.write("--register-commit and --on-failure require --register.\n");
125
+ process.exitCode = 1;
126
+ return;
127
+ }
128
+ if ((opts.resume || opts.forceRestart) && !hasRegister) {
129
+ process.stdout.write("--resume and --force-restart require --register.\n");
130
+ process.exitCode = 1;
131
+ return;
132
+ }
133
+ if (opts.resumeFrom && !opts.resume) {
134
+ process.stdout.write("--resume-from requires --resume.\n");
135
+ process.exitCode = 1;
136
+ return;
137
+ }
138
+ if (opts.resumeFrom && opts.resumeFrom !== "executor") {
139
+ process.stdout.write('--resume-from must be "executor".\n');
140
+ process.exitCode = 1;
141
+ return;
142
+ }
143
+ // 再開は既存 worktree の成果を再利用する操作のため、worktree 実行に限る。in-place 実行は
144
+ // executor の変更が作業ツリーに残り、再開時のID単位 commit が対象を判別できない。
145
+ if ((opts.resume || opts.forceRestart) && !opts.worktree) {
146
+ process.stdout.write("--resume and --force-restart require register worktree mode; use --worktree or configure run.register_execution: worktree.\n");
147
+ process.exitCode = 1;
148
+ return;
149
+ }
150
+ if (opts.resume && opts.forceRestart) {
151
+ process.stdout.write("Specify either --resume or --force-restart, not both.\n");
152
+ process.exitCode = 1;
153
+ return;
154
+ }
155
+ if ((opts.input || opts.scheduledAt) && !hasJob) {
156
+ process.stdout.write("--input and --scheduled-at require --job.\n");
157
+ process.exitCode = 1;
158
+ return;
159
+ }
160
+ if (opts.jobTrigger && !["manual", "routine", "ci"].includes(opts.jobTrigger)) {
161
+ process.stdout.write("--job-trigger must be manual, routine, or ci.\n");
162
+ process.exitCode = 1;
163
+ return;
164
+ }
165
+ if (opts.onFailure && !isRegisterFailureMode(opts.onFailure)) {
166
+ process.stdout.write(`--on-failure must be "stop" or "continue": ${opts.onFailure}\n`);
167
+ process.exitCode = 1;
168
+ return;
169
+ }
170
+ if (isAuto && isManual) {
171
+ process.stdout.write("Specify either --auto or a manual target, not both.\n");
172
+ process.exitCode = 1;
173
+ return;
174
+ }
175
+ if (isAuto && opts.by) {
176
+ process.stdout.write("--by requires a manual target; use --edit-by / --review-by with --auto.\n");
177
+ process.exitCode = 1;
178
+ return;
179
+ }
180
+ if (opts.by && opts.executorBy) {
181
+ process.stdout.write("Specify either --by or --executor-by, not both.\n");
182
+ process.exitCode = 1;
183
+ return;
184
+ }
185
+ if (opts.worktree && !hasTask && !hasRegister && !hasJob) {
186
+ process.stdout.write("--worktree requires --task, --register, or --job.\n");
187
+ process.exitCode = 1;
188
+ return;
189
+ }
190
+ // --parallel is allowed for register worktree runs (handled above); reject it for other
191
+ // manual targets, which run a single instance.
192
+ if (isManual && !hasRegister && parseParallel(opts.parallel) !== 1) {
193
+ process.stdout.write("--parallel cannot be used with a manual target.\n");
194
+ process.exitCode = 1;
195
+ return;
196
+ }
197
+ // register worktree 実行だけが共有資源をプロセス横断で統制するため、後から --join する
198
+ // run を受け入れる。それ以外の run は従来どおり project 全体を排他する。
199
+ const registerWorktreeLockSharing = hasRegister && opts.worktree ? { shareable: true, join: !!opts.join } : EXCLUSIVE_EXEC_RUN;
200
+ await withProjectExecRunLock(opts, "run", async () => {
201
+ // Register-item run: use the configured location or an explicit CLI override, with state tracked
202
+ // via register transitions (start → review / waiting) instead of exec events.
203
+ if (hasRegister) {
204
+ await runRegisterMode(opts);
205
+ return;
206
+ }
207
+ if (hasJob) {
208
+ await runJobMode(opts, resolveRegisterPipelineCommand);
209
+ return;
210
+ }
211
+ // In-place manual run (default): generate the plan on demand and run in the
212
+ // current repository. No validate/refresh pass — that is orchestration only.
213
+ if (isManual && !opts.worktree) {
214
+ await runInPlaceMode(opts);
215
+ return;
216
+ }
217
+ process.stdout.write("[run] validate...\n");
218
+ if (!spawnValidate(opts.project)) {
219
+ process.stdout.write("[run] validate failed — exit\n");
220
+ process.exitCode = 1;
221
+ return;
222
+ }
223
+ process.stdout.write("[run] validate: ok\n[run] refresh...\n");
224
+ if (!spawnRefresh(opts.project)) {
225
+ process.stdout.write("[run] refresh failed — exit\n");
226
+ process.exitCode = 1;
227
+ return;
228
+ }
229
+ process.stdout.write("[run] refresh: ok\n");
230
+ if (isBatch) {
231
+ await runBatchMode(opts);
232
+ }
233
+ else {
234
+ await runManualMode(opts);
235
+ }
236
+ }, registerWorktreeLockSharing);
237
+ }
238
+ catch (error) {
239
+ const message = error instanceof Error ? error.message : String(error);
240
+ process.stdout.write(message + "\n");
241
+ process.exitCode = 1;
242
+ }
243
+ });
244
+ }