specdojo 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +280 -0
  3. package/README.md +143 -30
  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/dashboard.js +140 -9
  8. package/dist/devcontainer-command.js +43 -0
  9. package/dist/devcontainer-scaffold.js +165 -0
  10. package/dist/exec-agent-config.js +107 -9
  11. package/dist/exec-agent-git-state.js +18 -0
  12. package/dist/exec-agent-protected-config.js +46 -8
  13. package/dist/exec-evidence.js +254 -11
  14. package/dist/exec-format.js +13 -4
  15. package/dist/exec-handoff.js +336 -0
  16. package/dist/exec-parent-validation.js +317 -43
  17. package/dist/exec-pipeline-state.js +74 -9
  18. package/dist/exec-plans.js +115 -113
  19. package/dist/exec-protection-handoff.js +43 -2
  20. package/dist/exec-provider-scaffold.js +247 -15
  21. package/dist/exec-register-resume.js +65 -19
  22. package/dist/exec-register.js +9 -3
  23. package/dist/exec-repo-integration.js +811 -0
  24. package/dist/exec-repo-trace.js +182 -0
  25. package/dist/exec-reporter.js +613 -132
  26. package/dist/exec-results.js +81 -56
  27. package/dist/exec-run-lock.js +110 -107
  28. package/dist/exec-run.js +1585 -356
  29. package/dist/exec-shared.js +7 -0
  30. package/dist/exec-slot-lock.js +242 -0
  31. package/dist/exec-task-repos.js +415 -0
  32. package/dist/exec-trial.js +51 -25
  33. package/dist/exec-worktree-command.js +87 -43
  34. package/dist/exec-worktree-ops.js +502 -57
  35. package/dist/exec-worktree.js +114 -27
  36. package/dist/exec.js +13 -6
  37. package/dist/grade-result.js +128 -0
  38. package/dist/grade.js +809 -72
  39. package/dist/init-command.js +443 -0
  40. package/dist/job.js +160 -10
  41. package/dist/orchestrator.js +213 -0
  42. package/dist/package-paths.js +19 -1
  43. package/dist/register-event-merge.js +169 -0
  44. package/dist/register-item.js +7 -1
  45. package/dist/register.js +294 -86
  46. package/dist/review-grade.js +252 -0
  47. package/dist/review-plan.js +111 -1
  48. package/dist/review-types.js +40 -1
  49. package/dist/routine.js +72 -5
  50. package/dist/schedule-build.js +2 -2
  51. package/dist/schedule.js +17 -4
  52. package/dist/specdojo-config.js +466 -20
  53. package/dist/specdojo-gitignore.js +135 -0
  54. package/dist/specdojo.js +8 -1
  55. package/dist/viewpoint-document-kinds-check.js +128 -0
  56. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  57. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  58. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  59. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  60. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  61. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  62. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  63. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  64. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  65. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  66. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  67. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  68. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  69. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  70. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  71. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  72. package/docs/ja/specdojo/guides/exec-config-guide.md +91 -47
  73. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  74. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  75. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  76. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +25 -4
  77. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  78. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  79. package/docs/ja/specdojo/guides/quick-start-guide.md +261 -32
  80. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  81. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  82. package/docs/ja/specdojo/guides/remote-host-development-guide.md +184 -0
  83. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  84. package/docs/ja/specdojo/guides/routine-operation-guide.md +74 -9
  85. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  86. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  87. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  88. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  89. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  90. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  91. package/docs/ja/specdojo/index.md +2 -2
  92. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  93. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  94. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  95. package/docs/ja/specdojo/references/command-reference.md +336 -93
  96. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  97. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  98. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  99. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  100. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  101. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  102. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  103. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  104. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  105. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  106. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  107. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  108. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  109. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  110. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  111. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  112. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  113. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  114. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  115. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  116. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  117. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  118. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  119. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  120. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  121. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  122. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  123. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  124. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  125. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  126. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  127. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  128. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  129. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  130. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  131. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  132. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  133. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  134. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  135. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  136. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  137. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  138. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  139. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  140. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  141. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  142. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  143. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  144. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  145. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  146. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  147. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  148. package/package.json +16 -9
  149. package/templates/antigravity/README.md +60 -0
  150. package/templates/antigravity/agent-members-snippet.yaml +61 -0
  151. package/templates/antigravity/exec-defaults-snippet.yaml +39 -0
  152. package/templates/antigravity/orchestrator.md +157 -0
  153. package/templates/antigravity/settings.global.json +55 -0
  154. package/templates/claude/agents/claude-executor.md +14 -0
  155. package/templates/claude/agents/claude-reporter.md +16 -0
  156. package/templates/claude/agents/specdojo-orchestrator.md +164 -0
  157. package/templates/claude/settings.edit.json +27 -1
  158. package/templates/codex/README.md +5 -4
  159. package/templates/codex/agents/specdojo-orchestrator.toml +165 -0
  160. package/templates/codex/orchestrator.md +157 -0
  161. package/templates/copilot/README.md +7 -5
  162. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  163. package/templates/devcontainer/devcontainer.json +27 -0
  164. package/templates/devcontainer/emacs/init.el +88 -0
  165. package/templates/devcontainer/post-create.sh +62 -0
  166. package/templates/init-agent-members.yaml +200 -0
  167. package/templates/init-exec-defaults.yaml +72 -0
  168. package/templates/opencode/agents/specdojo-orchestrator.md +204 -0
  169. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  170. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -4,7 +4,9 @@ import { isDeepStrictEqual } from "node:util";
4
4
  import { buildSpecdojoFrontmatter, parseSpecdojoDocument } from "./frontmatter-namespace.js";
5
5
  import { expandTemplate, stripTerminalControlSequences } from "./exec-shared.js";
6
6
  import { formatMarkdownFile } from "./exec-format.js";
7
+ import { deriveReporterFacts, mechanicallyNotApplicableReason, runnerOwnedValidationReason, } from "./exec-reporter.js";
7
8
  import { resolveSpecdojoPath, resolveSpecdojoPathIfExists } from "./template-resolution.js";
9
+ const MISSING_CHANGED_FILE_SUMMARY = "reporter の説明がないため、変更差分を参照。";
8
10
  // ---------------------------------------------------------------------------
9
11
  // Frontmatter helpers
10
12
  // ---------------------------------------------------------------------------
@@ -176,12 +178,6 @@ export async function scaffoldResult(opts) {
176
178
  ...(opts.targets && opts.targets.length > 0 ? { targets: opts.targets } : {}),
177
179
  };
178
180
  const values = { _FRONTMATTER_: serializeFrontmatter(meta) };
179
- // Review results pre-expand per-RVP sections (role / viewpoint_id / criterion) so the result
180
- // is self-contained. When the caller cannot resolve them, leave a language-neutral _TODO_
181
- // marker; the result template's own prose explains how to fill the sections.
182
- if (mode === "review") {
183
- values._REVIEW_RESULT_SECTIONS_ = opts.reviewSections ?? "_TODO_";
184
- }
185
181
  // Finalize results pre-expand the confirmation record (done_criteria checklist and
186
182
  // ready-promotion targets) so every finalize is verified against the same items.
187
183
  // When the caller cannot resolve them, leave _TODO_ markers for manual fill-in.
@@ -200,7 +196,9 @@ export async function scaffoldResult(opts) {
200
196
  // テンプレート文言を変えた場合はここも合わせて更新する。
201
197
  const MANDATORY_PLACEHOLDERS = {
202
198
  edit: ["_TODO_: 実施した内容", "_TODO_: 変更したファイル"],
203
- review: ["recommendation: _TODO_"],
199
+ // recommendation は review が観点ごとに評価していた時期の xrr-template.md で scaffold された
200
+ // result 用。改訂前の scaffold が未記入のまま完了扱いにならないよう検知を残す。
201
+ review: ["verdict: _TODO_", "recommendation: _TODO_"],
204
202
  };
205
203
  // runner が scaffold 時に必ず設定する識別・ライフサイクル項目。agent が frontmatter を
206
204
  // 独自形式へ置換しても本文の _TODO_ だけでは検知できないため、終了時に非空を確認する。
@@ -305,12 +303,59 @@ function reporterBulletList(values, empty) {
305
303
  return `- ${empty}`;
306
304
  return values.map((value) => `- ${reporterInlineText(value)}`).join("\n");
307
305
  }
308
- function renderEditReporterBody(output) {
309
- const changedFiles = output.changed_files.length === 0
306
+ function renderEditReporterBody(output, evidence) {
307
+ const facts = deriveReporterFacts(evidence);
308
+ const summariesByPath = new Map();
309
+ for (const file of output.changed_files) {
310
+ // The evidence path list remains authoritative. Ignore invented paths and keep the first
311
+ // description when a reporter repeats a path so rendering stays deterministic.
312
+ if (!summariesByPath.has(file.path))
313
+ summariesByPath.set(file.path, file.summary);
314
+ }
315
+ const changedFiles = facts.changed_files.length === 0
310
316
  ? "- なし"
311
- : output.changed_files
312
- .map((file) => `- \`${reporterInlineText(file.path).replace(/`/g, "'")}\`: ${reporterInlineText(file.summary)}`)
317
+ : facts.changed_files
318
+ .map((file) => `- \`${reporterInlineText(file.path).replace(/`/g, "'")}\`: ${reporterInlineText(summariesByPath.get(file.path) ?? MISSING_CHANGED_FILE_SUMMARY)}`)
313
319
  .join("\n");
320
+ const unchangedTargetNotes = (evidence?.target_coverage ?? [])
321
+ .filter((entry) => entry.status === "unchanged")
322
+ .map((entry) => {
323
+ const target = reporterInlineText(entry.target).replace(/`/g, "'");
324
+ return `対象 \`${target}\` は未変更: ${reporterInlineText(entry.reason)}`;
325
+ });
326
+ const humanValidationNotes = evidence.validations
327
+ .filter((validation) => validation.source !== "runner" && validation.status === "requires_human")
328
+ .map((validation) => {
329
+ const command = reporterInlineText(validation.command).replace(/`/g, "'");
330
+ const summary = reporterInlineText(validation.summary) || "要約なし";
331
+ return `人の確認が必要: \`${command}\`(${summary})`;
332
+ });
333
+ const notApplicableValidationNotes = evidence.validations
334
+ .filter((validation) => validation.source !== "runner" && validation.status === "not_applicable")
335
+ .map((validation) => {
336
+ const command = reporterInlineText(validation.command).replace(/`/g, "'");
337
+ const reason = reporterInlineText(validation.reason ?? "") || "理由なし";
338
+ return `適用外の検証: \`${command}\`(${reason})`;
339
+ });
340
+ const changedPaths = evidence.changes.map((change) => change.path);
341
+ const runnerOwnedValidationNotes = evidence.validations
342
+ .filter((validation) => validation.source !== "runner" && validation.status === "not_run")
343
+ .flatMap((validation) => {
344
+ const reason = runnerOwnedValidationReason(validation.command);
345
+ if (reason === undefined)
346
+ return [];
347
+ const command = reporterInlineText(validation.command).replace(/`/g, "'");
348
+ return [`runner が担う検証: \`${command}\`(${reporterInlineText(reason)})`];
349
+ });
350
+ const runnerJudgedNotApplicableNotes = evidence.validations
351
+ .filter((validation) => validation.source !== "runner" && validation.status === "not_run")
352
+ .flatMap((validation) => {
353
+ const reason = mechanicallyNotApplicableReason(validation.command, { changedPaths });
354
+ if (reason === undefined)
355
+ return [];
356
+ const command = reporterInlineText(validation.command).replace(/`/g, "'");
357
+ return [`適用外の検証(runner の判定): \`${command}\`(${reporterInlineText(reason)})`];
358
+ });
314
359
  return [
315
360
  "# Edit Result",
316
361
  "",
@@ -324,72 +369,52 @@ function renderEditReporterBody(output) {
324
369
  "",
325
370
  "## 3. 申し送り",
326
371
  "",
327
- reporterBulletList(output.handoff, "なし"),
372
+ reporterBulletList([
373
+ ...output.handoff,
374
+ ...unchangedTargetNotes,
375
+ ...notApplicableValidationNotes,
376
+ ...runnerOwnedValidationNotes,
377
+ ...runnerJudgedNotApplicableNotes,
378
+ ...humanValidationNotes,
379
+ ], "なし"),
328
380
  "",
329
381
  "## 4. 進め方と実践の型の適用",
330
382
  "",
331
383
  reporterInlineText(output.approach),
332
384
  ].join("\n");
333
385
  }
334
- function reviewViewpointContexts(body) {
335
- const contexts = [];
336
- const pattern = /^### (RVP-[0-9]{3})([^\n]*)\n\n\*\*確認基準\*\*: ([^\n]+)$/gmu;
337
- for (const match of body.matchAll(pattern)) {
338
- contexts.push({ id: match[1], suffix: match[2], criterion: match[3] });
339
- }
340
- return contexts;
341
- }
342
- function renderReviewReporterBody(output, scaffoldBody) {
343
- const contexts = reviewViewpointContexts(scaffoldBody);
344
- const expectedIds = contexts.map((context) => context.id);
345
- const actualIds = output.viewpoint_results.map((viewpoint) => viewpoint.id);
346
- if (!isDeepStrictEqual(actualIds, expectedIds)) {
347
- throw new Error(`reporter viewpoint ids must match scaffold order: expected=[${expectedIds.join(", ")}], actual=[${actualIds.join(", ")}]`);
348
- }
349
- const byId = new Map(output.viewpoint_results.map((viewpoint) => [viewpoint.id, viewpoint]));
350
- const viewpointSections = contexts.length === 0
351
- ? "- 観点別結果: 該当なし"
352
- : contexts
353
- .map((context) => {
354
- const viewpoint = byId.get(context.id);
355
- if (!viewpoint)
356
- throw new Error(`reporter viewpoint missing: ${context.id}`);
357
- return [
358
- `### ${context.id}${context.suffix}`,
359
- "",
360
- `**確認基準**: ${context.criterion}`,
361
- "",
362
- `- result: ${viewpoint.result}`,
363
- `- evidence: ${viewpoint.evidence.map(reporterInlineText).join(" / ")}`,
364
- `- notes: ${viewpoint.notes ? reporterInlineText(viewpoint.notes) : "なし"}`,
365
- ].join("\n");
366
- })
367
- .join("\n\n");
386
+ // review result の章立ては xrr-template.md と一致させる。review は成果物を再評価しないため、
387
+ // 観点別の結果ではなく評価結果の確認・判断根拠・改善指示・verdict を記録する。
388
+ function renderReviewReporterBody(output) {
368
389
  return [
369
390
  "# Review Result",
370
391
  "",
371
- "## 1. レビュー観点別結果",
392
+ "## 1. 評価結果の確認",
393
+ "",
394
+ reporterInlineText(output.grade_check),
395
+ "",
396
+ "## 2. 判断根拠",
372
397
  "",
373
- viewpointSections,
398
+ reporterBulletList(output.rationale, "なし"),
374
399
  "",
375
- "## 2. findings",
400
+ "## 3. 未充足事項・改善指示",
376
401
  "",
377
- reporterBulletList(output.findings, "なし"),
402
+ reporterBulletList(output.improvements, "なし"),
378
403
  "",
379
- "## 3. 実践の型との整合確認",
404
+ "## 4. approach に応じた確認",
380
405
  "",
381
406
  reporterInlineText(output.approach),
382
407
  "",
383
- "## 4. decision",
408
+ "## 5. decision",
384
409
  "",
385
- `- recommendation: ${output.recommendation}`,
410
+ `- verdict: ${output.verdict}`,
386
411
  ].join("\n");
387
412
  }
388
413
  /**
389
414
  * Replaces only the result body from schema-validated reporter data. The scaffolded frontmatter
390
415
  * remains byte-for-byte runner-owned until the lifecycle status update serializes it.
391
416
  */
392
- export async function renderReporterResult(resultPath, output) {
417
+ export async function renderReporterResult(resultPath, output, evidence) {
393
418
  if (!existsSync(resultPath))
394
419
  throw new Error(`Result not found: ${resultPath}`);
395
420
  const content = readFileSync(resultPath, "utf8");
@@ -401,8 +426,8 @@ export async function renderReporterResult(resultPath, output) {
401
426
  if (!frontmatter)
402
427
  throw new Error(`Result frontmatter not found: ${resultPath}`);
403
428
  const body = output.mode === "edit"
404
- ? renderEditReporterBody(output)
405
- : renderReviewReporterBody(output, parsed.body);
429
+ ? renderEditReporterBody(output, evidence)
430
+ : renderReviewReporterBody(output);
406
431
  writeFileSync(resultPath, frontmatterWithBody(frontmatter, body), "utf8");
407
432
  await formatMarkdownFile(resultPath);
408
433
  }
@@ -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
  }