specdojo 0.3.0 → 0.4.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 (245) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +77 -18
  3. package/dist/catalog/build-references.js +144 -0
  4. package/dist/catalog/build-render.js +32 -0
  5. package/dist/{catalog-build.js → catalog/build.js} +18 -295
  6. package/dist/{catalog.js → catalog/catalog.js} +11 -11
  7. package/dist/{catalog-generate.js → catalog/generate.js} +13 -16
  8. package/dist/catalog/paths.js +1 -0
  9. package/dist/{catalog-plan-generate.js → catalog/plan-generate.js} +5 -5
  10. package/dist/{catalog-plan.js → catalog/plan.js} +9 -9
  11. package/dist/{catalog-scaffold.js → catalog/scaffold.js} +6 -6
  12. package/dist/{agent.js → commands/agent.js} +11 -11
  13. package/dist/{build-command.js → commands/build.js} +2 -2
  14. package/dist/{init-command.js → commands/init.js} +103 -37
  15. package/dist/{orchestrator.js → commands/orchestrator.js} +2 -2
  16. package/dist/{watch.js → commands/watch.js} +3 -3
  17. package/dist/dashboard/dashboard-timeline.js +175 -0
  18. package/dist/{dashboard.js → dashboard/dashboard.js} +16 -549
  19. package/dist/dashboard/exec-records.js +105 -0
  20. package/dist/dashboard/routines.js +256 -0
  21. package/dist/dashboard/shared.js +14 -0
  22. package/dist/{timeline-build.js → dashboard/timeline-build.js} +2 -1
  23. package/dist/{timeline.js → dashboard/timeline.js} +1 -1
  24. package/dist/{deliverable.js → deliverable/deliverable.js} +5 -5
  25. package/dist/{deliverable-trash.js → deliverable/trash.js} +7 -7
  26. package/dist/{devcontainer-command.js → devcontainer/command.js} +5 -3
  27. package/dist/{devcontainer-scaffold.js → devcontainer/scaffold.js} +94 -2
  28. package/dist/{doc-index.js → docs/doc-index.js} +3 -3
  29. package/dist/{frontmatter-namespace.js → docs/frontmatter-namespace.js} +2 -2
  30. package/dist/{index-command.js → docs/index-command.js} +1 -1
  31. package/dist/docs/template-resolution.js +1 -0
  32. package/dist/{viewpoint-document-kinds-check.js → docs/viewpoint-document-kinds-check.js} +3 -3
  33. package/dist/{yaml-pages-command.js → docs/yaml-pages-command.js} +1 -1
  34. package/dist/{yaml-pages.js → docs/yaml-pages.js} +5 -5
  35. package/dist/{exec-agent-config.js → exec/agent-config.js} +33 -4
  36. package/dist/{exec-agent-git-state.js → exec/agent-git-state.js} +1 -1
  37. package/dist/{exec-agent-protected-config.js → exec/agent-protected-config.js} +1 -1
  38. package/dist/{exec.js → exec/commands.js} +22 -467
  39. package/dist/exec/core.js +457 -0
  40. package/dist/{exec-events.js → exec/events.js} +2 -2
  41. package/dist/{exec-evidence.js → exec/evidence.js} +11 -6
  42. package/dist/exec/exec.js +2 -0
  43. package/dist/exec/format.js +1 -0
  44. package/dist/{exec-handoff.js → exec/handoff.js} +13 -12
  45. package/dist/{exec-limit.js → exec/limit.js} +93 -12
  46. package/dist/{exec-parent-validation.js → exec/parent-validation.js} +4 -4
  47. package/dist/{exec-pipeline-state.js → exec/pipeline-state.js} +16 -2
  48. package/dist/{exec-plans.js → exec/plans-core.js} +97 -468
  49. package/dist/exec/plans-generation.js +249 -0
  50. package/dist/exec/plans-storage.js +131 -0
  51. package/dist/exec/plans.js +3 -0
  52. package/dist/{exec-project.js → exec/project.js} +1 -1
  53. package/dist/{exec-protection-handoff.js → exec/protection-handoff.js} +3 -3
  54. package/dist/{exec-register-resume.js → exec/register-resume.js} +2 -2
  55. package/dist/{exec-register.js → exec/register.js} +92 -9
  56. package/dist/exec/repo-integration-git.js +23 -0
  57. package/dist/exec/repo-integration-sync.js +264 -0
  58. package/dist/{exec-repo-integration.js → exec/repo-integration.js} +13 -287
  59. package/dist/{exec-repo-trace.js → exec/repo-trace.js} +3 -3
  60. package/dist/exec/reporter-output.js +206 -0
  61. package/dist/{exec-reporter.js → exec/reporter.js} +29 -216
  62. package/dist/{exec-results.js → exec/results.js} +277 -36
  63. package/dist/exec/run/agent-pipeline.js +276 -0
  64. package/dist/exec/run/agent.js +583 -0
  65. package/dist/exec/run/in-place.js +570 -0
  66. package/dist/exec/run/job.js +746 -0
  67. package/dist/exec/run/lifecycle-commands.js +530 -0
  68. package/dist/{exec-run-lock.js → exec/run/lock.js} +4 -3
  69. package/dist/exec/run/mode-shared.js +140 -0
  70. package/dist/exec/run/register-command.js +252 -0
  71. package/dist/exec/run/register-core.js +411 -0
  72. package/dist/exec/run/register-mode.js +210 -0
  73. package/dist/exec/run/register-resume.js +398 -0
  74. package/dist/exec/run/register-state.js +325 -0
  75. package/dist/exec/run/register-worktree.js +540 -0
  76. package/dist/exec/run/run.js +11 -0
  77. package/dist/exec/run/schedule-mode.js +294 -0
  78. package/dist/exec/run/schedule-prepare.js +366 -0
  79. package/dist/exec/run/schedule-task.js +599 -0
  80. package/dist/exec/run/shared.js +449 -0
  81. package/dist/{exec-schedule-calendar.js → exec/schedule/calendar.js} +1 -1
  82. package/dist/{exec-schedule-cpm.js → exec/schedule/cpm.js} +2 -2
  83. package/dist/{exec-schedule-gantt-chart-render.js → exec/schedule/gantt-chart-render.js} +2 -2
  84. package/dist/exec/schedule/gantt-chart.js +2 -0
  85. package/dist/{exec-schedule-hash.js → exec/schedule/hash.js} +2 -2
  86. package/dist/exec/schedule/index.js +1 -0
  87. package/dist/{exec-schedule-initial.js → exec/schedule/initial.js} +2 -2
  88. package/dist/{exec-schedule-progress.js → exec/schedule/progress.js} +2 -2
  89. package/dist/{exec-schedule-ready.js → exec/schedule/ready.js} +2 -2
  90. package/dist/{exec-schedule.js → exec/schedule/schedule.js} +11 -11
  91. package/dist/exec/shared.js +63 -0
  92. package/dist/exec/slot-lock.js +1 -0
  93. package/dist/{exec-strategy.js → exec/strategy.js} +2 -2
  94. package/dist/{exec-task-repos.js → exec/task-repos.js} +2 -2
  95. package/dist/{exec-task-view.js → exec/task-view.js} +4 -4
  96. package/dist/{exec-trial.js → exec/trial-commands.js} +23 -388
  97. package/dist/exec/trial-core.js +371 -0
  98. package/dist/exec/trial.js +2 -0
  99. package/dist/{exec-worktree-command.js → exec/worktree-command.js} +25 -23
  100. package/dist/exec/worktree-ops-commit.js +672 -0
  101. package/dist/exec/worktree-ops-lifecycle.js +297 -0
  102. package/dist/exec/worktree-ops-merge.js +344 -0
  103. package/dist/exec/worktree-ops.js +3 -0
  104. package/dist/exec/worktree.js +305 -0
  105. package/dist/grade/apply.js +734 -0
  106. package/dist/grade/command-apply.js +250 -0
  107. package/dist/grade/command-inspect.js +138 -0
  108. package/dist/grade/command-plan.js +101 -0
  109. package/dist/grade/command-shared.js +68 -0
  110. package/dist/grade/core.js +307 -0
  111. package/dist/grade/grade.js +19 -0
  112. package/dist/grade/markdown.js +274 -0
  113. package/dist/grade/pipeline-state.js +184 -0
  114. package/dist/grade/plan.js +507 -0
  115. package/dist/{grade-result.js → grade/result.js} +7 -96
  116. package/dist/grade/target-discovery.js +265 -0
  117. package/dist/grade/targets.js +435 -0
  118. package/dist/{job.js → job/definition.js} +32 -574
  119. package/dist/job/job.js +568 -0
  120. package/dist/{kata-command.js → kata/command.js} +4 -4
  121. package/dist/{kata.js → kata/kata.js} +5 -5
  122. package/dist/register/approach.js +134 -0
  123. package/dist/register/command-types.js +1 -0
  124. package/dist/register/core.js +369 -0
  125. package/dist/register/create-commands.js +352 -0
  126. package/dist/{register-date.js → register/date.js} +1 -1
  127. package/dist/register/derivation.js +163 -0
  128. package/dist/{register-event-merge.js → register/event-merge.js} +32 -3
  129. package/dist/{register-events.js → register/events.js} +12 -6
  130. package/dist/{register-history.js → register/history.js} +7 -6
  131. package/dist/{register-item.js → register/item.js} +28 -10
  132. package/dist/register/lifecycle-lock.js +5 -0
  133. package/dist/register/maintenance-commands.js +193 -0
  134. package/dist/{register-migrate-timestamps.js → register/migrate-timestamps.js} +3 -3
  135. package/dist/register/migration.js +268 -0
  136. package/dist/register/register.js +404 -0
  137. package/dist/register/renumber.js +341 -0
  138. package/dist/register/transition-commands.js +248 -0
  139. package/dist/register/update.js +230 -0
  140. package/dist/register/views.js +296 -0
  141. package/dist/{review-grade.js → review/grade.js} +2 -2
  142. package/dist/{review-plan.js → review/plan.js} +5 -5
  143. package/dist/routine/definition.js +401 -0
  144. package/dist/{routine.js → routine/routine.js} +50 -419
  145. package/dist/{schedule-approach.js → schedule/approach.js} +9 -9
  146. package/dist/{schedule-build.js → schedule/build.js} +7 -4
  147. package/dist/{schedule.js → schedule/schedule.js} +9 -9
  148. package/dist/schedule/strategy-generate-document.js +273 -0
  149. package/dist/schedule/strategy-generate-scope.js +199 -0
  150. package/dist/schedule/strategy-generate.js +348 -0
  151. package/dist/shared/agent-types.js +23 -0
  152. package/dist/shared/artifact-path.js +9 -0
  153. package/dist/{build-if-stale.js → shared/build-if-stale.js} +1 -1
  154. package/dist/shared/catalog-render.js +115 -0
  155. package/dist/{exec-slot-lock.js → shared/cross-process-lock.js} +3 -1
  156. package/dist/shared/fs.js +30 -0
  157. package/dist/shared/git.js +316 -0
  158. package/dist/shared/grade-result.js +94 -0
  159. package/dist/{package-paths.js → shared/package-paths.js} +3 -3
  160. package/dist/shared/plan-templates.js +114 -0
  161. package/dist/{exec-provider-scaffold.js → shared/provider-scaffold.js} +3 -1
  162. package/dist/shared/random.js +4 -0
  163. package/dist/{exec-schedule-index.js → shared/schedule-index.js} +3 -1
  164. package/dist/shared/schedule-paths.js +9 -0
  165. package/dist/{specdojo-config.js → shared/specdojo-config.js} +96 -9
  166. package/dist/{exec-shared.js → shared/text.js} +0 -134
  167. package/dist/shared/time.js +28 -0
  168. package/dist/shared/yaml.js +28 -0
  169. package/dist/specdojo.js +22 -22
  170. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +29 -17
  171. package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +1 -2
  172. package/docs/ja/specdojo/exec-templates/xep-register-template.md +1 -2
  173. package/docs/ja/specdojo/exec-templates/xer-template.md +1 -3
  174. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +6 -4
  175. package/docs/ja/specdojo/guides/exec-config-guide.md +97 -22
  176. package/docs/ja/specdojo/guides/exec-operation-guide.md +145 -12
  177. package/docs/ja/specdojo/guides/exec-worktree-guide.md +2 -0
  178. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +51 -18
  179. package/docs/ja/specdojo/guides/quick-start-guide.md +81 -16
  180. package/docs/ja/specdojo/guides/register-operation-guide.md +2 -1
  181. package/docs/ja/specdojo/guides/remote-host-development-guide.md +10 -1
  182. package/docs/ja/specdojo/guides/review-guide.md +1 -1
  183. package/docs/ja/specdojo/guides/routine-operation-guide.md +6 -6
  184. package/docs/ja/specdojo/guides/use-case-guide.md +1 -1
  185. package/docs/ja/specdojo/references/command-reference.md +52 -28
  186. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +17 -11
  187. package/docs/ja/specdojo/standards/job-definition-standard.md +20 -18
  188. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -2
  189. package/docs/ja/specdojo/templates/pjr-derived-items-template.md +22 -0
  190. package/docs/ja/specdojo/templates/pjr-index-template.md +1 -0
  191. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +29 -2
  192. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +20 -0
  193. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +23 -0
  194. package/docs/specdojo/schemas/v1/job-run.schema.yaml +2 -2
  195. package/docs/specdojo/schemas/v1/job.schema.yaml +7 -0
  196. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +26 -0
  197. package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
  198. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +70 -7
  199. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +1 -1
  200. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +1 -1
  201. package/package.json +4 -5
  202. package/templates/antigravity/README.md +7 -3
  203. package/templates/antigravity/agent-members-snippet.yaml +108 -12
  204. package/templates/antigravity/exec-defaults-snippet.yaml +10 -13
  205. package/templates/claude/README.md +27 -3
  206. package/templates/claude/agents/claude-executor.md +0 -1
  207. package/templates/claude/agents/claude-reporter.md +2 -1
  208. package/templates/claude/agents/claude-review-executor.md +0 -1
  209. package/templates/codex/README.md +23 -4
  210. package/templates/devcontainer/devcontainer.json +2 -2
  211. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +69 -0
  212. package/templates/devcontainer/remote-host/ssh-config.sample +16 -0
  213. package/templates/init-agent-members.yaml +75 -25
  214. package/templates/init-exec-defaults.yaml +26 -8
  215. package/templates/opencode/README.md +17 -3
  216. package/templates/opencode/agents/opencode-executor.md +0 -1
  217. package/templates/opencode/agents/opencode-reporter.md +2 -1
  218. package/templates/opencode/agents/opencode-review-executor.md +0 -1
  219. package/dist/exec-run.js +0 -6182
  220. package/dist/exec-schedule-gantt-chart.js +0 -2
  221. package/dist/exec-worktree-ops.js +0 -1292
  222. package/dist/exec-worktree.js +0 -446
  223. package/dist/grade.js +0 -3193
  224. package/dist/register.js +0 -2407
  225. package/dist/schedule-strategy-generate.js +0 -812
  226. package/templates/claude/agents/claude-expert-review-executor.md +0 -14
  227. /package/dist/{catalog-plan-prompt.js → catalog/plan-prompt.js} +0 -0
  228. /package/dist/{catalog-types.js → catalog/types.js} +0 -0
  229. /package/dist/{template-frontmatter.js → docs/template-frontmatter.js} +0 -0
  230. /package/dist/{role-types.js → exec/role-types.js} +0 -0
  231. /package/dist/{exec-schedule-gantt-chart-scope.js → exec/schedule/gantt-chart-scope.js} +0 -0
  232. /package/dist/{exec-types.js → exec/types.js} +0 -0
  233. /package/dist/{review-types.js → review/types.js} +0 -0
  234. /package/dist/{schedule-phase-sets.js → schedule/phase-sets.js} +0 -0
  235. /package/dist/{schedule-strategy-profiles.js → schedule/strategy-profiles.js} +0 -0
  236. /package/dist/{agent-response.js → shared/agent-response.js} +0 -0
  237. /package/dist/{catalog-paths.js → shared/catalog-paths.js} +0 -0
  238. /package/dist/{dist-freshness.js → shared/dist-freshness.js} +0 -0
  239. /package/dist/{git-environment.js → shared/git-environment.js} +0 -0
  240. /package/dist/{exec-format.js → shared/markdown-format.js} +0 -0
  241. /package/dist/{practice-id.js → shared/practice-id.js} +0 -0
  242. /package/dist/{spawn-self.js → shared/spawn-self.js} +0 -0
  243. /package/dist/{specdojo-gitignore.js → shared/specdojo-gitignore.js} +0 -0
  244. /package/dist/{template-resolution.js → shared/template-resolution.js} +0 -0
  245. /package/dist/{yaml-schema-modeline.js → shared/yaml-schema-modeline.js} +0 -0
@@ -5,9 +5,9 @@
5
5
  // 表示 ID・タイトル・説明は frontmatter に重複させず、`id` / H1 / 本文から導出する。
6
6
  import { existsSync, readdirSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
- import yaml from "js-yaml";
9
- import { inlineCodeAnglePlaceholders } from "./exec-shared.js";
10
- import { registerDateFromTimestamp } from "./register-date.js";
8
+ import { dump, load } from "../shared/yaml.js";
9
+ import { inlineCodeAnglePlaceholders } from "../shared/text.js";
10
+ import { registerDateFromTimestamp } from "./date.js";
11
11
  export const VALID_STATUSES = [
12
12
  "open",
13
13
  "in-progress",
@@ -64,6 +64,8 @@ const SPECDOJO_KEY_ORDER = [
64
64
  "completed_at",
65
65
  "block_reason",
66
66
  "conclusion",
67
+ "derived_from",
68
+ "approach",
67
69
  "targets",
68
70
  ];
69
71
  // ================================
@@ -92,8 +94,15 @@ export function ticketRefCell(filename) {
92
94
  return `[${filename.replace(/\.md$/, "")}](./${filename})`;
93
95
  }
94
96
  // 表セルへ埋め込むために1行化し、列区切りの `|` をエスケープする。
95
- function toCell(text) {
96
- return text.replace(/\r?\n/g, " ").replace(/\s+/g, " ").replace(/\|/g, "\\|").trim();
97
+ // すでにエスケープ済みの `\|` は再エスケープせず、複数回の呼び出しに対して冪等にする。
98
+ export function toCell(text) {
99
+ if (typeof text !== "string")
100
+ return "";
101
+ return text
102
+ .replace(/\r?\n/g, " ")
103
+ .replace(/\s+/g, " ")
104
+ .replace(/(?<!\\)((\\\\)*)\|/g, "$1\\|")
105
+ .trim();
97
106
  }
98
107
  // H1(`# PJR-XXXX タイトル`)からタイトルを導出する。表示 ID の接頭辞は取り除く。
99
108
  export function titleFromBody(body, id) {
@@ -148,7 +157,7 @@ export function readRegisterItemContent(content, filename) {
148
157
  if (match) {
149
158
  let parsed;
150
159
  try {
151
- parsed = yaml.load(match[1]);
160
+ parsed = load(match[1]);
152
161
  }
153
162
  catch {
154
163
  parsed = undefined;
@@ -159,6 +168,10 @@ export function readRegisterItemContent(content, filename) {
159
168
  const targets = Array.isArray(fields.targets)
160
169
  ? fields.targets.filter((entry) => typeof entry === "string" && entry.trim() !== "")
161
170
  : undefined;
171
+ const approach = asString(fields.approach);
172
+ const derivedFrom = Array.isArray(fields.derived_from)
173
+ ? fields.derived_from.filter((entry) => typeof entry === "string" && entry.trim() !== "")
174
+ : undefined;
162
175
  const item = {
163
176
  id,
164
177
  status: asString(fields.item_status) ?? "open",
@@ -175,7 +188,9 @@ export function readRegisterItemContent(content, filename) {
175
188
  completedAt: asString(fields.completed_at) ?? CELL_NONE,
176
189
  conclusion: asString(fields.conclusion) ?? CELL_NONE,
177
190
  ticket: ticketRefCell(filename),
191
+ ...(approach ? { approach } : {}),
178
192
  ...(targets && targets.length > 0 ? { targets } : {}),
193
+ ...(derivedFrom && derivedFrom.length > 0 ? { derivedFrom } : {}),
179
194
  };
180
195
  return {
181
196
  id,
@@ -244,7 +259,7 @@ export function validateRegisterItemDocs(projectRegisterPath) {
244
259
  let frontmatterId;
245
260
  if (match) {
246
261
  try {
247
- const parsed = yaml.load(match[1]);
262
+ const parsed = load(match[1]);
248
263
  if (isRecord(parsed) && isRecord(parsed.specdojo)) {
249
264
  frontmatterId = asString(parsed.specdojo.id);
250
265
  }
@@ -295,6 +310,9 @@ export function registerItemFieldsFromItem(item) {
295
310
  conclusion: isPlaceholderCell(item.conclusion)
296
311
  ? null
297
312
  : inlineCodeAnglePlaceholders(item.conclusion.trim()),
313
+ ...(item.approach ? { approach: item.approach } : {}),
314
+ ...(item.targets && item.targets.length > 0 ? { targets: item.targets } : {}),
315
+ ...(item.derivedFrom && item.derivedFrom.length > 0 ? { derived_from: item.derivedFrom } : {}),
298
316
  };
299
317
  }
300
318
  function orderSpecdojoKeys(fields) {
@@ -323,7 +341,7 @@ export function updateSpecdojoFields(content, mutate) {
323
341
  const fields = { ...parsed.specdojo };
324
342
  mutate(fields);
325
343
  const document = { ...parsed, specdojo: orderSpecdojoKeys(fields) };
326
- const dumped = yaml.dump(document, { lineWidth: -1, noRefs: true, quotingType: '"' });
344
+ const dumped = dump(document, { lineWidth: -1, noRefs: true, quoteStyle: "double" });
327
345
  return `---\n${dumped}---\n${match[2] ?? ""}`;
328
346
  }
329
347
  // 個票 frontmatter の `specdojo:` 名前空間を、イベント検証などの読み取り用途へ返す。
@@ -342,7 +360,7 @@ export function readSpecdojoFields(content) {
342
360
  function parseFrontmatterDocument(frontmatter) {
343
361
  let parsed;
344
362
  try {
345
- parsed = yaml.load(frontmatter);
363
+ parsed = load(frontmatter);
346
364
  }
347
365
  catch (error) {
348
366
  const detail = error instanceof Error ? error.message : String(error);
@@ -376,7 +394,7 @@ export function readRegisterItemLegacyDates(content) {
376
394
  return {};
377
395
  let parsed;
378
396
  try {
379
- parsed = yaml.load(match[1]);
397
+ parsed = load(match[1]);
380
398
  }
381
399
  catch {
382
400
  return {};
@@ -0,0 +1,5 @@
1
+ import { join } from "node:path";
2
+ // register の個票更新・view 再生成・commit を、exec run を含む全プロセス間で直列化する。
3
+ export function registerLifecyclePoolPath(executionPath) {
4
+ return join(executionPath, "exec", ".locks", "exec-lifecycle");
5
+ }
@@ -0,0 +1,193 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { collectRegisterHistoryEvents, formatRegisterHistoryEvents } from "./history.js";
3
+ import { createGitTimestampResolver, planRegisterTimestampMigration, summarizeTimestampMigration, } from "./migrate-timestamps.js";
4
+ import { registerEventFilePath, validateRegisterEventDocs } from "./events.js";
5
+ import { validateRegisterItemDocs } from "./item.js";
6
+ import { specdojoRootDir } from "../shared/specdojo-config.js";
7
+ import { validateDerivedFromDocs } from "./derivation.js";
8
+ export function registerMaintenanceCommands(reg, dependencies) {
9
+ const { addProjectOption, addRegisterCommitOptions, applyRegisterMigrationPlan, generateDerivedViewFiles, loadItemForUpdate, migrateEmbeddedRegisterEvents, migrateRegisterEventsFromGit, parseHistoryIds, planRegisterMigration, planRenumber, printCommandError, registerEventActor, renumberPjrItem, repoRelativePathspec, resolveRegisterPaths, runRegisterMutation, validBuildScopes, writeDerivedViews, } = dependencies;
10
+ // --- migrate ---
11
+ const migrateCmd = reg
12
+ .command("migrate")
13
+ .description("Migrate legacy register data (index rows, dates, and embedded register events)");
14
+ addProjectOption(migrateCmd);
15
+ migrateCmd.option("--dry-run", "Validate and print the migration summary without writing", false);
16
+ migrateCmd.action((opts) => {
17
+ try {
18
+ const paths = resolveRegisterPaths(opts);
19
+ const plan = planRegisterMigration(paths);
20
+ const summary = `items=${plan.sourceCount}, create=${plan.createdCount}, update=${plan.updatedCount}, ` +
21
+ `unchanged=${plan.unchangedCount}`;
22
+ if (opts.dryRun) {
23
+ process.stdout.write(`Would migrate register items: ${summary}\n`);
24
+ if (plan.sourceIndexPath) {
25
+ process.stdout.write(`Would remove legacy index: ${plan.sourceIndexPath}\n`);
26
+ }
27
+ }
28
+ else {
29
+ applyRegisterMigrationPlan(plan);
30
+ process.stdout.write(`Migrated register items: ${summary}\n`);
31
+ if (plan.sourceIndexPath) {
32
+ process.stdout.write(`Removed legacy index: ${plan.sourceIndexPath}\n`);
33
+ }
34
+ }
35
+ const timestampPlan = planRegisterTimestampMigration({
36
+ projectRegisterPath: paths.projectRegisterPath,
37
+ timeZone: paths.registerDateTimeZone,
38
+ resolveGitTimestamps: createGitTimestampResolver(specdojoRootDir()),
39
+ });
40
+ const timestampSummary = summarizeTimestampMigration(timestampPlan);
41
+ if (opts.dryRun) {
42
+ const embeddedMigration = migrateEmbeddedRegisterEvents(paths, true);
43
+ const eventMigration = migrateRegisterEventsFromGit(paths, true);
44
+ const eventSummary = eventMigration.available
45
+ ? `items=${eventMigration.items}, events=${eventMigration.events}, skipped=${eventMigration.skipped}`
46
+ : "unavailable (Git history not found; legacy fallback remains active)";
47
+ process.stdout.write(`Would migrate register timestamps: ${timestampSummary}\n`);
48
+ process.stdout.write(`Would separate embedded register events: items=${embeddedMigration.items}, events=${embeddedMigration.events}\n`);
49
+ process.stdout.write(`Would migrate register events: ${eventSummary}\n`);
50
+ return;
51
+ }
52
+ for (const file of timestampPlan.files) {
53
+ writeFileSync(file.path, file.content, "utf8");
54
+ }
55
+ process.stdout.write(`Migrated register timestamps: ${timestampSummary}\n`);
56
+ const embeddedMigration = migrateEmbeddedRegisterEvents(paths, false);
57
+ process.stdout.write(`Separated embedded register events: items=${embeddedMigration.items}, events=${embeddedMigration.events}\n`);
58
+ const eventMigration = migrateRegisterEventsFromGit(paths, false);
59
+ const eventSummary = eventMigration.available
60
+ ? `items=${eventMigration.items}, events=${eventMigration.events}, skipped=${eventMigration.skipped}`
61
+ : "unavailable (Git history not found; legacy fallback remains active)";
62
+ process.stdout.write(`Migrated register events: ${eventSummary}\n`);
63
+ for (const view of writeDerivedViews(paths, "all")) {
64
+ process.stdout.write(`Generated: ${view.path}\n`);
65
+ }
66
+ }
67
+ catch (error) {
68
+ printCommandError(error);
69
+ }
70
+ });
71
+ // --- build ---
72
+ const buildCmd = reg
73
+ .command("build")
74
+ .description("Generate the register list and derived views from register item files");
75
+ addProjectOption(buildCmd);
76
+ buildCmd.option("--scope <scope>", "Generation scope: register | controls | all", "all");
77
+ buildCmd.option("--dry-run", "Print generated content without writing", false);
78
+ buildCmd.action((opts) => {
79
+ try {
80
+ const paths = resolveRegisterPaths(opts);
81
+ if (!existsSync(paths.projectRegisterPath)) {
82
+ throw new Error(`Project register directory not found: ${paths.projectRegisterPath}\n` +
83
+ `Run: specdojo register scaffold --project ${opts.project || paths.projectId}`);
84
+ }
85
+ const scope = opts.scope;
86
+ if (!validBuildScopes.includes(scope)) {
87
+ throw new Error(`Invalid scope: "${opts.scope}". Must be one of: ${validBuildScopes.join(", ")}`);
88
+ }
89
+ const validation = validateRegisterItemDocs(paths.projectRegisterPath);
90
+ const derivationErrors = validateDerivedFromDocs(paths);
91
+ const eventErrors = validateRegisterEventDocs(paths.projectRegisterPath, paths.registerDateTimeZone);
92
+ if (validation.errors.length > 0 || derivationErrors.length > 0 || eventErrors.length > 0) {
93
+ throw new Error(`Invalid register item files:\n${[
94
+ ...validation.errors,
95
+ ...derivationErrors,
96
+ ...eventErrors,
97
+ ].join("\n")}`);
98
+ }
99
+ const views = generateDerivedViewFiles(paths, scope);
100
+ if (opts.dryRun) {
101
+ for (const view of views) {
102
+ process.stdout.write(`=== ${view.path} ===\n${view.content}\n\n`);
103
+ }
104
+ return;
105
+ }
106
+ for (const view of writeDerivedViews(paths, scope)) {
107
+ process.stdout.write(`Generated: ${view.path}\n`);
108
+ }
109
+ }
110
+ catch (error) {
111
+ printCommandError(error);
112
+ }
113
+ });
114
+ // --- history ---
115
+ const historyCmd = reg
116
+ .command("history")
117
+ .description("Show register item changes from append-only events and legacy Git history");
118
+ addProjectOption(historyCmd);
119
+ historyCmd.option("--since <date>", "Include commits on or after this date (YYYY-MM-DD)");
120
+ historyCmd.option("--until <date>", "Include commits on or before this date (YYYY-MM-DD)");
121
+ historyCmd.option("--id <id...>", "Limit output to these item IDs (PJR-XXXX; space/comma separated)");
122
+ historyCmd.option("--status-only", "Show only additions, removals, and status transitions", false);
123
+ historyCmd.option("--limit <count>", "Maximum number of commits to inspect");
124
+ historyCmd.option("--json", "Print events as JSON", false);
125
+ historyCmd.action((opts) => {
126
+ try {
127
+ const paths = resolveRegisterPaths(opts);
128
+ const ids = parseHistoryIds(opts.id);
129
+ const limit = opts.limit === undefined ? undefined : Number(opts.limit);
130
+ const events = collectRegisterHistoryEvents({
131
+ repoRoot: specdojoRootDir(),
132
+ registerPathspec: repoRelativePathspec(specdojoRootDir(), paths.projectRegisterPath),
133
+ since: opts.since?.trim() || undefined,
134
+ until: opts.until?.trim() || undefined,
135
+ limit,
136
+ ids,
137
+ statusOnly: Boolean(opts.statusOnly),
138
+ timeZone: paths.registerDateTimeZone,
139
+ });
140
+ if (opts.json) {
141
+ process.stdout.write(`${JSON.stringify(events, null, 2)}\n`);
142
+ return;
143
+ }
144
+ if (events.length === 0) {
145
+ process.stdout.write("No register item changes found for the given range.\n");
146
+ return;
147
+ }
148
+ process.stdout.write(`${formatRegisterHistoryEvents(events)}\n`);
149
+ const itemCount = new Set(events.map((event) => event.id)).size;
150
+ const gitCommitCount = new Set(events.filter((event) => event.source !== "event").map((event) => event.commit)).size;
151
+ const storedEventCount = events.filter((event) => event.source === "event").length;
152
+ process.stdout.write(`events=${events.length} items=${itemCount} stored=${storedEventCount} legacy_commits=${gitCommitCount}\n`);
153
+ }
154
+ catch (error) {
155
+ printCommandError(error);
156
+ }
157
+ });
158
+ // --- renumber ---
159
+ const renumberCmd = reg
160
+ .command("renumber")
161
+ .description("Resolve a random PJR-ID collision by moving one item to an unused ID");
162
+ addProjectOption(renumberCmd);
163
+ renumberCmd.requiredOption("--id <id>", "Current item ID (PJR-XXXX)");
164
+ renumberCmd.requiredOption("--to <id>", "Target unused ID (PJR-XXXX)");
165
+ renumberCmd.option("--by <actor>", "Actor recorded in the append-only register event");
166
+ renumberCmd.option("--reason <text>", "Reason recorded in the append-only register event");
167
+ renumberCmd.option("--dry-run", "Print planned changes without writing", false);
168
+ addRegisterCommitOptions(renumberCmd);
169
+ renumberCmd.action(async (opts) => {
170
+ await runRegisterMutation("renumber", opts, (context) => {
171
+ const { paths } = context;
172
+ const source = loadItemForUpdate(paths, opts.id);
173
+ const renumberPlan = planRenumber(paths, opts.id, opts.to);
174
+ context.assertCommitTargetsClean([
175
+ ...(renumberPlan.ticketRename
176
+ ? [renumberPlan.ticketRename.from, renumberPlan.ticketRename.to]
177
+ : []),
178
+ ...renumberPlan.writes.map((write) => write.path),
179
+ registerEventFilePath(paths.projectRegisterPath, opts.id),
180
+ registerEventFilePath(paths.projectRegisterPath, opts.to),
181
+ ]);
182
+ renumberPjrItem({
183
+ paths,
184
+ fromId: opts.id,
185
+ toId: opts.to,
186
+ dryRun: opts.dryRun,
187
+ actor: registerEventActor(opts),
188
+ reason: opts.reason,
189
+ });
190
+ return { id: opts.to, title: source.item.title };
191
+ });
192
+ });
193
+ }
@@ -12,9 +12,9 @@
12
12
  // 後になっている項目では、追加コミットの時刻は起票時刻ではない)。
13
13
  import { readdirSync, readFileSync } from "node:fs";
14
14
  import { join, relative, sep } from "node:path";
15
- import { applyRegisterItemTimestamps, displayIdFromTicketFilename, readRegisterItemContent, readRegisterItemLegacyDates, } from "./register-item.js";
16
- import { normalizeRegisterTimestamp, REGISTER_FALLBACK_TIME_OF_DAY, registerDateFromTimestamp, timestampFromDateInTimeZone, } from "./register-date.js";
17
- import { gitResult } from "./exec-worktree.js";
15
+ import { applyRegisterItemTimestamps, displayIdFromTicketFilename, readRegisterItemContent, readRegisterItemLegacyDates, } from "./item.js";
16
+ import { normalizeRegisterTimestamp, REGISTER_FALLBACK_TIME_OF_DAY, registerDateFromTimestamp, timestampFromDateInTimeZone, } from "./date.js";
17
+ import { gitResult } from "../shared/git.js";
18
18
  // git log の1行書式。コミットハッシュも ISO 日付も空白を含まないため、空白で分割できる。
19
19
  const COMMIT_LOG_FORMAT = "--format=%H %aI";
20
20
  // 完了日を記録する終端状態。deferred は終端だが完了日を持たないため含めない。
@@ -0,0 +1,268 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { buildRegisterItemContent, locateRegisterTable, parsePjrIndex, slugify, validateFields, } from "./core.js";
5
+ import { applyRegisterItemFields, loadRegisterItemDocs, prependRegisterItemDescription, readRegisterItemContent, registerItemFieldsFromItem, setRegisterItemTitle, } from "./item.js";
6
+ import { resolveSpecdojoTemplatePath } from "../docs/template-resolution.js";
7
+ import { loadRegisterItems } from "./views.js";
8
+ const REGISTER_ITEM_VALUE_KEYS = [
9
+ "id",
10
+ "status",
11
+ "title",
12
+ "description",
13
+ "type",
14
+ "priority",
15
+ "owner",
16
+ "registeredAt",
17
+ "due",
18
+ "completedAt",
19
+ "conclusion",
20
+ ];
21
+ // pjr-index の表セルだけで必要だった pipe のエスケープを本文へ持ち込まない。
22
+ function tableCellToBody(value) {
23
+ return value.replace(/\\\|/g, "|");
24
+ }
25
+ function migrationTopic(title) {
26
+ return slugify(tableCellToBody(title)).slice(0, 64).replace(/-+$/g, "") || "item";
27
+ }
28
+ function assertMigratedItemMatches(source, content, filename) {
29
+ const migrated = readRegisterItemContent(content, filename)?.item;
30
+ if (!migrated) {
31
+ throw new Error(`Failed to read planned register item: ${filename}`);
32
+ }
33
+ const mismatches = REGISTER_ITEM_VALUE_KEYS.filter((key) => migrated[key] !== source[key]);
34
+ if (mismatches.length > 0) {
35
+ const detail = mismatches
36
+ .map((key) => `${key}: ${JSON.stringify(source[key])} -> ${JSON.stringify(migrated[key])}`)
37
+ .join(", ");
38
+ throw new Error(`Migration verification failed for ${source.id}: ${detail}`);
39
+ }
40
+ }
41
+ // 追跡対象の旧 pjr-index と、すでに frontmatter 正本へ移った個票を統合して移行計画を作る。
42
+ // この段階では書き込みを行わず、全件の変換結果が元の項目値と一致してから計画を返す。
43
+ export function planRegisterMigration(paths) {
44
+ const docs = loadRegisterItemDocs(paths.projectRegisterPath);
45
+ const duplicateDocIds = docs
46
+ .map((doc) => doc.id)
47
+ .filter((id, index, ids) => ids.indexOf(id) !== index);
48
+ if (duplicateDocIds.length > 0) {
49
+ throw new Error(`Duplicate register item ticket IDs: ${[...new Set(duplicateDocIds)].join(", ")}`);
50
+ }
51
+ if (!existsSync(paths.pjrIndexPath)) {
52
+ const notMigrated = docs.filter((doc) => !doc.hasRegisterFields);
53
+ if (notMigrated.length > 0) {
54
+ throw new Error(`Legacy pjr-index.md is missing, but ${notMigrated.length} ticket(s) have no register item fields: ` +
55
+ notMigrated.map((doc) => doc.id).join(", "));
56
+ }
57
+ return {
58
+ sourceCount: docs.length,
59
+ createdCount: 0,
60
+ updatedCount: 0,
61
+ unchangedCount: docs.length,
62
+ files: [],
63
+ };
64
+ }
65
+ const sourceIndexContent = readFileSync(paths.pjrIndexPath, "utf8");
66
+ const timeZone = paths.registerDateTimeZone;
67
+ // 旧構成の pjr-index.md が一覧テーブルを持たない参照案内だった場合もある。
68
+ // その案内ページは、旧一覧が存在しない場合と同じ no-op として扱う。
69
+ if (!locateRegisterTable(sourceIndexContent.split("\n"))) {
70
+ const notMigrated = docs.filter((doc) => !doc.hasRegisterFields);
71
+ if (notMigrated.length > 0) {
72
+ throw new Error(`Legacy pjr-index table is missing, but ${notMigrated.length} ticket(s) have no register item fields: ` +
73
+ notMigrated.map((doc) => doc.id).join(", "));
74
+ }
75
+ return {
76
+ sourceCount: docs.length,
77
+ createdCount: 0,
78
+ updatedCount: 0,
79
+ unchangedCount: docs.length,
80
+ files: [],
81
+ };
82
+ }
83
+ const indexItems = parsePjrIndex(sourceIndexContent, timeZone);
84
+ const duplicateIndexIds = indexItems
85
+ .map((item) => item.id)
86
+ .filter((id, index, ids) => ids.indexOf(id) !== index);
87
+ if (duplicateIndexIds.length > 0) {
88
+ throw new Error(`Duplicate pjr-index IDs: ${[...new Set(duplicateIndexIds)].join(", ")}`);
89
+ }
90
+ // loadRegisterItems は移行済み個票を優先し、未移行項目だけ旧一覧を読む。これにより、
91
+ // runner がすでに遷移させた item_status を古い一覧行で巻き戻さない。
92
+ const sources = loadRegisterItems(paths);
93
+ if (sources.length !== indexItems.length) {
94
+ throw new Error(`Register item count mismatch before migration: index=${indexItems.length}, resolved=${sources.length}`);
95
+ }
96
+ const docsById = new Map(docs.map((doc) => [doc.id, doc]));
97
+ const files = [];
98
+ let createdCount = 0;
99
+ let updatedCount = 0;
100
+ let unchangedCount = 0;
101
+ for (const source of sources) {
102
+ validateFields({
103
+ type: source.item.type,
104
+ priority: source.item.priority,
105
+ status: source.item.status,
106
+ registeredAt: source.item.registeredAt,
107
+ due: source.item.due,
108
+ completedAt: source.item.completedAt,
109
+ });
110
+ const existing = docsById.get(source.id);
111
+ let filename;
112
+ let path;
113
+ let originalContent;
114
+ let content;
115
+ if (existing) {
116
+ filename = existing.filename;
117
+ path = existing.path;
118
+ originalContent = readFileSync(path, "utf8");
119
+ content = originalContent;
120
+ if (source.source === "index") {
121
+ if (existing.item.title !== source.item.title) {
122
+ content = setRegisterItemTitle(content, tableCellToBody(source.item.title));
123
+ }
124
+ if (existing.item.description !== source.item.description) {
125
+ content = prependRegisterItemDescription(content, tableCellToBody(source.item.description));
126
+ }
127
+ content = applyRegisterItemFields(content, registerItemFieldsFromItem(source.item));
128
+ }
129
+ }
130
+ else {
131
+ const topic = migrationTopic(source.item.title);
132
+ filename = `pjr-${source.id.slice("PJR-".length).toLowerCase()}-${topic}.md`;
133
+ path = join(paths.projectRegisterPath, filename);
134
+ if (existsSync(path)) {
135
+ throw new Error(`Migration target already exists: ${path}`);
136
+ }
137
+ const templatePath = resolveSpecdojoTemplatePath(`pjr-${source.item.type}-template.md`);
138
+ content = buildRegisterItemContent({
139
+ projectId: paths.projectId,
140
+ displayId: source.item.id,
141
+ topic,
142
+ fields: {
143
+ type: source.item.type,
144
+ title: tableCellToBody(source.item.title),
145
+ description: tableCellToBody(source.item.description),
146
+ priority: source.item.priority,
147
+ status: source.item.status,
148
+ owner: source.item.owner,
149
+ registeredAt: source.item.registeredAt,
150
+ due: source.item.due,
151
+ completedAt: source.item.completedAt,
152
+ conclusion: source.item.conclusion,
153
+ },
154
+ templatePath,
155
+ });
156
+ // 旧一覧のセルでは問題にならなかった `_CAPITAL_CASE_` などを本文へ移すと、
157
+ // markdownlint が underscore emphasis と解釈する。表示値を変えずに規則だけ抑止する。
158
+ if (/_[A-Z][A-Z0-9_]*_/.test(`${source.item.title}\n${source.item.description}`)) {
159
+ content = content.replace(/^(---\r?\n[\s\S]*?\r?\n---\r?\n)/, "$1\n<!-- markdownlint-disable MD049 -->\n");
160
+ }
161
+ }
162
+ assertMigratedItemMatches(source.item, content, filename);
163
+ if (content === originalContent) {
164
+ unchangedCount++;
165
+ }
166
+ else {
167
+ files.push({ path, content, originalContent });
168
+ if (originalContent === undefined)
169
+ createdCount++;
170
+ else
171
+ updatedCount++;
172
+ }
173
+ }
174
+ return {
175
+ sourceCount: sources.length,
176
+ createdCount,
177
+ updatedCount,
178
+ unchangedCount,
179
+ files,
180
+ sourceIndexPath: paths.pjrIndexPath,
181
+ sourceIndexContent,
182
+ };
183
+ }
184
+ // 全出力を同一ディレクトリ内の一時ファイルへ書いてから切り替える。切り替え途中で失敗した
185
+ // 場合は既存ファイルと旧一覧を戻し、作成途中の個票を除去して部分適用を残さない。
186
+ export function applyRegisterMigrationPlan(plan) {
187
+ if (plan.files.length === 0 && !plan.sourceIndexPath)
188
+ return;
189
+ if (plan.sourceIndexPath) {
190
+ if (!existsSync(plan.sourceIndexPath)) {
191
+ throw new Error(`Migration source changed after planning: missing ${plan.sourceIndexPath}`);
192
+ }
193
+ if (readFileSync(plan.sourceIndexPath, "utf8") !== plan.sourceIndexContent) {
194
+ throw new Error(`Migration source changed after planning: ${plan.sourceIndexPath}`);
195
+ }
196
+ }
197
+ for (const file of plan.files) {
198
+ if (file.originalContent === undefined) {
199
+ if (existsSync(file.path)) {
200
+ throw new Error(`Migration target appeared after planning: ${file.path}`);
201
+ }
202
+ }
203
+ else if (!existsSync(file.path) || readFileSync(file.path, "utf8") !== file.originalContent) {
204
+ throw new Error(`Migration target changed after planning: ${file.path}`);
205
+ }
206
+ }
207
+ const transactionId = randomUUID();
208
+ const staged = [];
209
+ let indexBackupPath;
210
+ try {
211
+ for (const file of plan.files) {
212
+ const stagedPath = join(dirname(file.path), `.specdojo-migrate-${transactionId}-${basename(file.path)}`);
213
+ staged.push({ ...file, stagedPath });
214
+ writeFileSync(stagedPath, file.content, { encoding: "utf8", flag: "wx" });
215
+ }
216
+ for (const file of staged) {
217
+ if (file.originalContent !== undefined) {
218
+ file.backupPath = `${file.stagedPath}.backup`;
219
+ renameSync(file.path, file.backupPath);
220
+ }
221
+ renameSync(file.stagedPath, file.path);
222
+ }
223
+ if (plan.sourceIndexPath) {
224
+ indexBackupPath = join(dirname(plan.sourceIndexPath), `.specdojo-migrate-${transactionId}-${basename(plan.sourceIndexPath)}.backup`);
225
+ renameSync(plan.sourceIndexPath, indexBackupPath);
226
+ }
227
+ }
228
+ catch (error) {
229
+ if (indexBackupPath && existsSync(indexBackupPath) && plan.sourceIndexPath) {
230
+ if (existsSync(plan.sourceIndexPath))
231
+ unlinkSync(plan.sourceIndexPath);
232
+ renameSync(indexBackupPath, plan.sourceIndexPath);
233
+ }
234
+ for (const file of [...staged].reverse()) {
235
+ if (existsSync(file.stagedPath))
236
+ unlinkSync(file.stagedPath);
237
+ if (file.backupPath && existsSync(file.backupPath)) {
238
+ if (existsSync(file.path))
239
+ unlinkSync(file.path);
240
+ renameSync(file.backupPath, file.path);
241
+ }
242
+ else if (file.originalContent === undefined && existsSync(file.path)) {
243
+ unlinkSync(file.path);
244
+ }
245
+ }
246
+ throw error;
247
+ }
248
+ // バックアップ除去は切り替え完了後に行う。ここで一時ファイルの除去に失敗しても、
249
+ // 正本の切り替え自体は完了しているため migration を巻き戻さない。
250
+ for (const file of staged) {
251
+ if (file.backupPath && existsSync(file.backupPath)) {
252
+ try {
253
+ unlinkSync(file.backupPath);
254
+ }
255
+ catch {
256
+ // 正本は切り替え済み。一時バックアップは次回の手動清掃対象として残す。
257
+ }
258
+ }
259
+ }
260
+ if (indexBackupPath && existsSync(indexBackupPath)) {
261
+ try {
262
+ unlinkSync(indexBackupPath);
263
+ }
264
+ catch {
265
+ // 正本は切り替え済み。一時バックアップは次回の手動清掃対象として残す。
266
+ }
267
+ }
268
+ }