specdojo 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (242) hide show
  1. package/.github/agents/specdojo-orchestrator.md +165 -0
  2. package/CHANGELOG.md +298 -0
  3. package/README.md +92 -42
  4. package/dist/agent-response.js +20 -0
  5. package/dist/agent.js +4 -4
  6. package/dist/build-command.js +28 -8
  7. package/dist/catalog-build-references.js +144 -0
  8. package/dist/catalog-build-render.js +144 -0
  9. package/dist/catalog-build.js +13 -290
  10. package/dist/catalog-generate.js +6 -9
  11. package/dist/catalog-plan-generate.js +2 -2
  12. package/dist/catalog-plan.js +6 -6
  13. package/dist/catalog-scaffold.js +4 -4
  14. package/dist/catalog.js +2 -2
  15. package/dist/dashboard-exec-records.js +105 -0
  16. package/dist/dashboard-routines.js +255 -0
  17. package/dist/dashboard-shared.js +14 -0
  18. package/dist/dashboard-timeline.js +175 -0
  19. package/dist/dashboard.js +31 -444
  20. package/dist/deliverable-trash.js +3 -3
  21. package/dist/devcontainer-command.js +43 -0
  22. package/dist/devcontainer-scaffold.js +165 -0
  23. package/dist/doc-index.js +3 -3
  24. package/dist/exec-agent-config.js +107 -9
  25. package/dist/exec-agent-git-state.js +18 -0
  26. package/dist/exec-agent-protected-config.js +46 -8
  27. package/dist/exec-commands.js +557 -0
  28. package/dist/exec-core.js +457 -0
  29. package/dist/exec-evidence.js +254 -11
  30. package/dist/exec-handoff.js +336 -0
  31. package/dist/exec-parent-validation.js +317 -43
  32. package/dist/exec-pipeline-state.js +74 -9
  33. package/dist/exec-plans-core.js +693 -0
  34. package/dist/exec-plans-generation.js +206 -0
  35. package/dist/exec-plans-storage.js +131 -0
  36. package/dist/exec-plans.js +3 -1016
  37. package/dist/exec-protection-handoff.js +43 -2
  38. package/dist/exec-provider-scaffold.js +247 -15
  39. package/dist/exec-register-resume.js +65 -19
  40. package/dist/exec-register.js +9 -3
  41. package/dist/exec-repo-integration-git.js +23 -0
  42. package/dist/exec-repo-integration-sync.js +264 -0
  43. package/dist/exec-repo-integration.js +534 -0
  44. package/dist/exec-repo-trace.js +182 -0
  45. package/dist/exec-reporter-output.js +206 -0
  46. package/dist/exec-reporter.js +525 -248
  47. package/dist/exec-results.js +103 -71
  48. package/dist/exec-run-agent-pipeline.js +256 -0
  49. package/dist/exec-run-agent.js +531 -0
  50. package/dist/exec-run-in-place.js +541 -0
  51. package/dist/exec-run-job.js +717 -0
  52. package/dist/exec-run-lifecycle-commands.js +522 -0
  53. package/dist/exec-run-lock.js +110 -107
  54. package/dist/exec-run-mode-shared.js +140 -0
  55. package/dist/exec-run-register-command.js +244 -0
  56. package/dist/exec-run-register-core.js +386 -0
  57. package/dist/exec-run-register-mode.js +206 -0
  58. package/dist/exec-run-register-resume.js +393 -0
  59. package/dist/exec-run-register-state.js +322 -0
  60. package/dist/exec-run-register-worktree.js +509 -0
  61. package/dist/exec-run-schedule-mode.js +294 -0
  62. package/dist/exec-run-schedule-prepare.js +353 -0
  63. package/dist/exec-run-schedule-task.js +572 -0
  64. package/dist/exec-run-shared.js +399 -0
  65. package/dist/exec-run.js +11 -4953
  66. package/dist/exec-shared.js +9 -2
  67. package/dist/exec-slot-lock.js +242 -0
  68. package/dist/exec-task-repos.js +415 -0
  69. package/dist/exec-trial-commands.js +558 -0
  70. package/dist/exec-trial-core.js +371 -0
  71. package/dist/exec-trial.js +2 -895
  72. package/dist/exec-worktree-command.js +87 -43
  73. package/dist/exec-worktree-ops-commit.js +707 -0
  74. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  75. package/dist/exec-worktree-ops-merge.js +303 -0
  76. package/dist/exec-worktree-ops.js +3 -847
  77. package/dist/exec-worktree.js +146 -31
  78. package/dist/exec.js +2 -999
  79. package/dist/frontmatter-namespace.js +2 -2
  80. package/dist/grade-apply.js +734 -0
  81. package/dist/grade-command-apply.js +250 -0
  82. package/dist/grade-command-inspect.js +138 -0
  83. package/dist/grade-command-plan.js +101 -0
  84. package/dist/grade-command-shared.js +68 -0
  85. package/dist/grade-core.js +307 -0
  86. package/dist/grade-markdown.js +274 -0
  87. package/dist/grade-pipeline-state.js +184 -0
  88. package/dist/grade-plan.js +507 -0
  89. package/dist/grade-result.js +133 -5
  90. package/dist/grade-target-discovery.js +265 -0
  91. package/dist/grade-targets.js +432 -0
  92. package/dist/grade.js +14 -2451
  93. package/dist/init-command.js +443 -0
  94. package/dist/job-definition.js +670 -0
  95. package/dist/job.js +64 -578
  96. package/dist/kata-command.js +2 -2
  97. package/dist/orchestrator.js +213 -0
  98. package/dist/register-command-types.js +1 -0
  99. package/dist/register-core.js +363 -0
  100. package/dist/register-create-commands.js +245 -0
  101. package/dist/register-event-merge.js +169 -0
  102. package/dist/register-events.js +4 -4
  103. package/dist/register-item.js +13 -7
  104. package/dist/register-maintenance-commands.js +187 -0
  105. package/dist/register-migration.js +268 -0
  106. package/dist/register-renumber.js +314 -0
  107. package/dist/register-transition-commands.js +248 -0
  108. package/dist/register-update.js +230 -0
  109. package/dist/register-views.js +256 -0
  110. package/dist/register.js +175 -1975
  111. package/dist/review-grade.js +252 -0
  112. package/dist/review-plan.js +114 -4
  113. package/dist/review-types.js +40 -1
  114. package/dist/routine-definition.js +401 -0
  115. package/dist/routine.js +73 -402
  116. package/dist/schedule-approach.js +2 -2
  117. package/dist/schedule-build.js +2 -2
  118. package/dist/schedule-strategy-generate-document.js +273 -0
  119. package/dist/schedule-strategy-generate-scope.js +199 -0
  120. package/dist/schedule-strategy-generate.js +9 -473
  121. package/dist/schedule.js +19 -6
  122. package/dist/specdojo-config.js +465 -20
  123. package/dist/specdojo-gitignore.js +135 -0
  124. package/dist/specdojo.js +6 -0
  125. package/dist/viewpoint-document-kinds-check.js +128 -0
  126. package/dist/yaml-pages.js +4 -4
  127. package/dist/yaml.js +28 -0
  128. package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
  129. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
  130. package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
  131. package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
  132. package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
  133. package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
  134. package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
  135. package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
  136. package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
  137. package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
  138. package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
  139. package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
  140. package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
  141. package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
  142. package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
  143. package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
  144. package/docs/ja/specdojo/guides/exec-config-guide.md +93 -49
  145. package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
  146. package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
  147. package/docs/ja/specdojo/guides/kata-guide.md +4 -4
  148. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +45 -22
  149. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  150. package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
  151. package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
  152. package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
  153. package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
  154. package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
  155. package/docs/ja/specdojo/guides/review-guide.md +195 -158
  156. package/docs/ja/specdojo/guides/routine-operation-guide.md +75 -10
  157. package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
  158. package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
  159. package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
  160. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
  161. package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
  162. package/docs/ja/specdojo/guides/waza-guide.md +15 -2
  163. package/docs/ja/specdojo/index.md +2 -2
  164. package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
  165. package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
  166. package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
  167. package/docs/ja/specdojo/references/command-reference.md +335 -92
  168. package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
  169. package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
  170. package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
  171. package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
  172. package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
  173. package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
  174. package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
  175. package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
  176. package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
  177. package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
  178. package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
  179. package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
  180. package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
  181. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
  182. package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
  183. package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
  184. package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
  185. package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
  186. package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
  187. package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
  188. package/docs/ja/specdojo/samples/bps-sample.md +74 -21
  189. package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
  190. package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
  191. package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
  192. package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
  193. package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
  194. package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
  195. package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
  196. package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
  197. package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
  198. package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
  199. package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
  200. package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
  201. package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
  202. package/docs/ja/specdojo/templates/bps-template.md +91 -0
  203. package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
  204. package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
  205. package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
  206. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
  207. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
  208. package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
  209. package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
  210. package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
  211. package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
  212. package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
  213. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
  214. package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
  215. package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
  216. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
  217. package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
  218. package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
  219. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
  220. package/package.json +17 -12
  221. package/templates/antigravity/README.md +29 -4
  222. package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
  223. package/templates/antigravity/exec-defaults-snippet.yaml +10 -7
  224. package/templates/antigravity/orchestrator.md +18 -7
  225. package/templates/antigravity/settings.global.json +55 -0
  226. package/templates/claude/agents/claude-executor.md +14 -0
  227. package/templates/claude/agents/claude-reporter.md +16 -0
  228. package/templates/claude/agents/specdojo-orchestrator.md +18 -7
  229. package/templates/claude/settings.edit.json +27 -1
  230. package/templates/codex/README.md +5 -4
  231. package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
  232. package/templates/codex/orchestrator.md +18 -7
  233. package/templates/copilot/README.md +7 -5
  234. package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
  235. package/templates/devcontainer/devcontainer.json +27 -0
  236. package/templates/devcontainer/emacs/init.el +88 -0
  237. package/templates/devcontainer/post-create.sh +62 -0
  238. package/templates/init-agent-members.yaml +200 -0
  239. package/templates/init-exec-defaults.yaml +74 -0
  240. package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
  241. package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
  242. package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
@@ -0,0 +1,314 @@
1
+ import { existsSync, readFileSync, unlinkSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { atomicWriteFile, findMarkdownReferenceFiles, formatTableRow, isTableSeparator, parsePjrIndex, parseTableCells, prepareRegisterEventFile, REGISTER_SECTION_RE, REGISTER_TOPIC_RE, } from "./register-core.js";
4
+ import { appendRegisterEvent, buildRegisterEvent, registerEventFilePath, } from "./register-events.js";
5
+ import { parseSpecdojoDocument } from "./frontmatter-namespace.js";
6
+ import { applyRegisterItemFields, PJR_ID_RE, registerItemFieldsFromItem, REMOVE_REGISTER_ITEM_FIELD, setRegisterItemDescription, setRegisterItemTitle, ticketRefCell, toDisplayItem, } from "./register-item.js";
7
+ import { specdojoRootDir } from "./specdojo-config.js";
8
+ import { loadItemForUpdate } from "./register-update.js";
9
+ import { findRegisterItem, loadRegisterItems, writeDerivedViews } from "./register-views.js";
10
+ // ================================
11
+ // Renumber (duplicate ID recovery)
12
+ // ================================
13
+ function escapeRegExp(text) {
14
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15
+ }
16
+ // 個票ファイル名 `pjr-XXXX-<topic>.md` から topic を取り出す。
17
+ // ID 接頭辞(`pjr-xxxx-`)と一致しない場合は undefined。
18
+ export function ticketTopicFromFilename(id, filename) {
19
+ const prefix = `${id.toLowerCase()}-`;
20
+ const base = filename.replace(/\.md$/, "");
21
+ if (!base.startsWith(prefix))
22
+ return undefined;
23
+ const topic = base.slice(prefix.length);
24
+ return topic.length > 0 ? topic : undefined;
25
+ }
26
+ // pjr-index の登録項目一覧テーブルで fromId の行を updated へ差し替える。
27
+ // replaceRowInContent は「同一 ID を書き戻す」用途で updated.id と一致する行を探すため、
28
+ // ID を変える再採番には fromId で行を特定する専用処理を使う。
29
+ function renumberRowInContent(content, fromId, updated) {
30
+ const newRow = formatTableRow(updated);
31
+ const lines = content.split("\n");
32
+ let inSection = false;
33
+ for (let i = 0; i < lines.length; i++) {
34
+ const line = lines[i];
35
+ if (REGISTER_SECTION_RE.test(line)) {
36
+ inSection = true;
37
+ continue;
38
+ }
39
+ if (inSection && /^## /.test(line))
40
+ break;
41
+ if (!inSection)
42
+ continue;
43
+ if (!line.startsWith("|") || isTableSeparator(line))
44
+ continue;
45
+ const cells = parseTableCells(line);
46
+ if (cells.length >= 1 && cells[0] === fromId) {
47
+ lines[i] = newRow;
48
+ return lines.join("\n");
49
+ }
50
+ }
51
+ throw new Error(`Item ${fromId} not found in table`);
52
+ }
53
+ // 個票本文の再採番。frontmatter の doc id 断片(`:pjr-XXXX-<topic>`)と
54
+ // H1 の表示 ID(`# PJR-XXXX ...`)を新しい ID へ更新する。
55
+ export function renumberTicketContent(content, fromId, toId, topic) {
56
+ const fromFragment = `:${fromId.toLowerCase()}-${topic}`;
57
+ const toFragment = `:${toId.toLowerCase()}-${topic}`;
58
+ let updated = content.split(fromFragment).join(toFragment);
59
+ updated = updated.replace(new RegExp(`^(#\\s+)${escapeRegExp(fromId)}(\\s|$)`, "m"), (_m, prefix, tail) => `${prefix}${toId}${tail}`);
60
+ return updated;
61
+ }
62
+ // 他文書からの参照リンク(wikilink `[[<docId>|...]]`)と
63
+ // exec plan / result の `targets` に含まれる doc id を新しい doc id へ置き換える。
64
+ export function renumberReferences(content, fromDocId, toDocId) {
65
+ if (!content.includes(fromDocId))
66
+ return { content, changed: false };
67
+ return { content: content.split(fromDocId).join(toDocId), changed: true };
68
+ }
69
+ // topic 変更で書き換える全ファイルを事前に算出する。参照の更新範囲は renumber と
70
+ // 同じく docs/ja 配下(生成物を除く)とし、文書 ID を含む wikilink / targets を
71
+ // 付け替える。衝突や個票 ID の不整合は、書き込み前に検出する。
72
+ export function planRetopic(paths, id, topic) {
73
+ if (!PJR_ID_RE.test(id)) {
74
+ throw new Error(`Invalid ID: "${id}". Must match PJR-XXXX (e.g., PJR-0001)`);
75
+ }
76
+ if (!REGISTER_TOPIC_RE.test(topic)) {
77
+ throw new Error(`Invalid topic: "${topic}". Must use lowercase letters, numbers, and single hyphens`);
78
+ }
79
+ const view = loadItemForUpdate(paths, id);
80
+ const oldFilename = view.ticketFilename;
81
+ if (!oldFilename || !view.ticketPath) {
82
+ throw new Error(`Item ${id} has no ticket file to change topic`);
83
+ }
84
+ const fromTopic = ticketTopicFromFilename(id, oldFilename);
85
+ if (!fromTopic) {
86
+ throw new Error(`Ticket filename "${oldFilename}" does not match ID "${id}"; fix it before changing topic.`);
87
+ }
88
+ const fromDocId = `${paths.projectId}:${oldFilename.replace(/\.md$/, "")}`;
89
+ const newFilename = `${id.toLowerCase()}-${topic}.md`;
90
+ const toDocId = `${paths.projectId}:${newFilename.replace(/\.md$/, "")}`;
91
+ const newTicketPath = join(paths.projectRegisterPath, newFilename);
92
+ const ticketContent = readFileSync(view.ticketPath, "utf8");
93
+ const currentDocId = parseSpecdojoDocument(ticketContent).data.id;
94
+ if (currentDocId !== fromDocId) {
95
+ throw new Error(`Ticket ${oldFilename} must have frontmatter id "${fromDocId}" before changing topic`);
96
+ }
97
+ if (existsSync(newTicketPath)) {
98
+ throw new Error(`Target ticket file already exists: ${newTicketPath}`);
99
+ }
100
+ const writes = [
101
+ {
102
+ path: newTicketPath,
103
+ content: renumberReferences(ticketContent, fromDocId, toDocId).content,
104
+ },
105
+ ];
106
+ const root = specdojoRootDir();
107
+ const referenceFiles = findMarkdownReferenceFiles(root);
108
+ for (const absPath of referenceFiles) {
109
+ if (absPath === view.ticketPath)
110
+ continue;
111
+ const content = readFileSync(absPath, "utf8");
112
+ const referenceUpdate = renumberReferences(content, fromDocId, toDocId);
113
+ // 旧構成の pjr-index に登録項目行が残っている場合は、文書 ID だけでなく個票リンクの
114
+ // ファイル名も追随させる。現行の generated ビューは適用後に再生成する。
115
+ const replaced = absPath === paths.pjrIndexPath
116
+ ? referenceUpdate.content.split(oldFilename).join(newFilename)
117
+ : referenceUpdate.content;
118
+ if (referenceUpdate.changed || replaced !== content) {
119
+ writes.push({ path: absPath, content: replaced });
120
+ }
121
+ }
122
+ return {
123
+ writes,
124
+ ticketRename: { from: view.ticketPath, to: newTicketPath },
125
+ fromTopic,
126
+ fromDocId,
127
+ toDocId,
128
+ };
129
+ }
130
+ export function retopicPjrItem(opts) {
131
+ const plan = planRetopic(opts.paths, opts.id, opts.topic);
132
+ const ticketWrite = plan.writes.find((write) => write.path === plan.ticketRename.to);
133
+ if (!ticketWrite)
134
+ throw new Error(`Retopiced ticket content not found: ${plan.ticketRename.to}`);
135
+ if (opts.title !== undefined)
136
+ ticketWrite.content = setRegisterItemTitle(ticketWrite.content, opts.title);
137
+ if (opts.description !== undefined) {
138
+ ticketWrite.content = setRegisterItemDescription(ticketWrite.content, opts.description);
139
+ }
140
+ ticketWrite.content = applyRegisterItemFields(ticketWrite.content, {
141
+ ...registerItemFieldsFromItem(opts.updated),
142
+ ...(opts.updated.status === "waiting" ? {} : { block_reason: REMOVE_REGISTER_ITEM_FIELD }),
143
+ ...opts.fieldUpdates,
144
+ });
145
+ if (opts.dryRun) {
146
+ process.stdout.write(`Would change topic for ${opts.id}: ${plan.fromTopic} → ${opts.topic}\n`);
147
+ process.stdout.write(` Rename: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
148
+ for (const write of plan.writes)
149
+ process.stdout.write(` Update: ${write.path}\n`);
150
+ return;
151
+ }
152
+ const beforeContent = readFileSync(plan.ticketRename.from, "utf8");
153
+ const event = buildRegisterEvent({
154
+ beforeContent,
155
+ afterContent: ticketWrite.content,
156
+ filename: basename(plan.ticketRename.to),
157
+ timeZone: opts.paths.registerDateTimeZone,
158
+ action: "update",
159
+ actor: opts.actor?.trim() || "manual",
160
+ reason: opts.reason?.trim() || `topic changed from ${plan.fromTopic} to ${opts.topic}`,
161
+ extraChanges: [{ field: "id", from: plan.fromDocId, to: plan.toDocId }],
162
+ });
163
+ if (!event)
164
+ throw new Error(`Failed to build topic update event for ${opts.id}`);
165
+ const eventWrite = prepareRegisterEventFile(opts.paths.projectRegisterPath, opts.id, event);
166
+ for (const write of plan.writes) {
167
+ atomicWriteFile(write.path, write.content);
168
+ process.stdout.write(`Updated: ${write.path}\n`);
169
+ }
170
+ unlinkSync(plan.ticketRename.from);
171
+ process.stdout.write(`Renamed: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
172
+ atomicWriteFile(eventWrite.path, eventWrite.content);
173
+ process.stdout.write(`Updated: ${eventWrite.path}\n`);
174
+ for (const view of writeDerivedViews(opts.paths, "all")) {
175
+ process.stdout.write(`Generated: ${view.path}\n`);
176
+ }
177
+ }
178
+ // 再採番で書き換える全ファイルを事前に算出する。
179
+ // 途中で衝突・不整合を検出したら例外を投げ、部分適用が起きないようにする。
180
+ export function planRenumber(paths, fromId, toId) {
181
+ const views = loadRegisterItems(paths);
182
+ const fromView = findRegisterItem(views, fromId);
183
+ if (!fromView) {
184
+ throw new Error(`Item not found: ${fromId}`);
185
+ }
186
+ if (findRegisterItem(views, toId)) {
187
+ throw new Error(`Target ID already exists: ${toId}`);
188
+ }
189
+ const fromItem = fromView.item;
190
+ const writes = [];
191
+ let ticketRename;
192
+ // pjr-index に旧 ID の行が残っている場合だけ、その行も新しい ID へ差し替える。
193
+ const hasIndexRow = existsSync(paths.pjrIndexPath) &&
194
+ parsePjrIndex(readFileSync(paths.pjrIndexPath, "utf8"), paths.registerDateTimeZone).some((it) => it.id === fromId);
195
+ let newIndexContent = hasIndexRow ? readFileSync(paths.pjrIndexPath, "utf8") : "";
196
+ const oldFilename = fromView.ticketFilename;
197
+ let fromDocId;
198
+ let toDocId;
199
+ if (oldFilename) {
200
+ const topic = ticketTopicFromFilename(fromId, oldFilename);
201
+ if (!topic) {
202
+ throw new Error(`Ticket filename "${oldFilename}" does not match ID "${fromId}"; ` +
203
+ `fix the ticket link before renumbering.`);
204
+ }
205
+ const newFilename = `${toId.toLowerCase()}-${topic}.md`;
206
+ const oldTicketPath = join(paths.projectRegisterPath, oldFilename);
207
+ const newTicketPath = join(paths.projectRegisterPath, newFilename);
208
+ if (!existsSync(oldTicketPath)) {
209
+ throw new Error(`Ticket file not found: ${oldTicketPath}`);
210
+ }
211
+ if (existsSync(newTicketPath)) {
212
+ throw new Error(`Target ticket file already exists: ${newTicketPath}`);
213
+ }
214
+ fromDocId = `${paths.projectId}:${oldFilename.replace(/\.md$/, "")}`;
215
+ toDocId = `${paths.projectId}:${newFilename.replace(/\.md$/, "")}`;
216
+ const ticketContent = readFileSync(oldTicketPath, "utf8");
217
+ writes.push({
218
+ path: newTicketPath,
219
+ content: renumberTicketContent(ticketContent, fromId, toId, topic),
220
+ });
221
+ ticketRename = { from: oldTicketPath, to: newTicketPath };
222
+ if (hasIndexRow) {
223
+ const updated = { ...fromItem, id: toId, ticket: ticketRefCell(newFilename) };
224
+ newIndexContent = renumberRowInContent(newIndexContent, fromId, toDisplayItem(updated, paths.registerDateTimeZone));
225
+ }
226
+ }
227
+ else if (hasIndexRow) {
228
+ const updated = { ...fromItem, id: toId };
229
+ newIndexContent = renumberRowInContent(newIndexContent, fromId, toDisplayItem(updated, paths.registerDateTimeZone));
230
+ }
231
+ if (hasIndexRow) {
232
+ writes.push({ path: paths.pjrIndexPath, content: newIndexContent });
233
+ }
234
+ // 参照リンク・targets の付け替え(doc id を持つ個票がある場合のみ)。
235
+ if (fromDocId && toDocId) {
236
+ const root = specdojoRootDir();
237
+ const referenceFiles = findMarkdownReferenceFiles(root);
238
+ for (const absPath of referenceFiles) {
239
+ if (absPath === paths.pjrIndexPath)
240
+ continue;
241
+ if (ticketRename && absPath === ticketRename.from)
242
+ continue;
243
+ const content = readFileSync(absPath, "utf8");
244
+ const { content: replaced, changed } = renumberReferences(content, fromDocId, toDocId);
245
+ if (changed)
246
+ writes.push({ path: absPath, content: replaced });
247
+ }
248
+ }
249
+ return { writes, ticketRename };
250
+ }
251
+ export function renumberPjrItem(opts) {
252
+ const { paths, fromId, toId, dryRun } = opts;
253
+ for (const id of [fromId, toId]) {
254
+ if (!PJR_ID_RE.test(id)) {
255
+ throw new Error(`Invalid ID: "${id}". Must match PJR-XXXX (e.g., PJR-0001)`);
256
+ }
257
+ }
258
+ if (fromId === toId) {
259
+ throw new Error(`--id and --to must differ (both are ${fromId})`);
260
+ }
261
+ const plan = planRenumber(paths, fromId, toId);
262
+ if (!dryRun && plan.ticketRename) {
263
+ const ticketWrite = plan.writes.find((write) => write.path === plan.ticketRename?.to);
264
+ if (!ticketWrite)
265
+ throw new Error(`Renumbered ticket content not found: ${plan.ticketRename.to}`);
266
+ const beforeContent = readFileSync(plan.ticketRename.from, "utf8");
267
+ const event = buildRegisterEvent({
268
+ beforeContent,
269
+ afterContent: ticketWrite.content,
270
+ filename: basename(plan.ticketRename.to),
271
+ timeZone: paths.registerDateTimeZone,
272
+ action: "renumber",
273
+ actor: opts.actor?.trim() || "manual",
274
+ reason: opts.reason?.trim() || `renumbered ${fromId} to ${toId}`,
275
+ extraChanges: [{ field: "id", from: fromId, to: toId }],
276
+ });
277
+ if (!event)
278
+ throw new Error(`Failed to build renumber event for ${fromId}`);
279
+ const oldEventPath = registerEventFilePath(paths.projectRegisterPath, fromId);
280
+ const newEventPath = registerEventFilePath(paths.projectRegisterPath, toId);
281
+ if (!existsSync(oldEventPath)) {
282
+ throw new Error(`Register event file not found: ${oldEventPath}`);
283
+ }
284
+ if (existsSync(newEventPath)) {
285
+ throw new Error(`Target register event file already exists: ${newEventPath}`);
286
+ }
287
+ const eventContent = appendRegisterEvent(readFileSync(oldEventPath, "utf8"), event);
288
+ plan.writes.push({ path: newEventPath, content: eventContent });
289
+ }
290
+ if (dryRun) {
291
+ process.stdout.write(`Would renumber ${fromId} → ${toId}:\n`);
292
+ if (plan.ticketRename) {
293
+ process.stdout.write(` Rename: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
294
+ }
295
+ for (const write of plan.writes) {
296
+ process.stdout.write(` Update: ${write.path}\n`);
297
+ }
298
+ return;
299
+ }
300
+ for (const write of plan.writes) {
301
+ atomicWriteFile(write.path, write.content);
302
+ process.stdout.write(`Updated: ${write.path}\n`);
303
+ }
304
+ if (plan.ticketRename) {
305
+ unlinkSync(plan.ticketRename.from);
306
+ process.stdout.write(`Renamed: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
307
+ const oldEventPath = registerEventFilePath(paths.projectRegisterPath, fromId);
308
+ unlinkSync(oldEventPath);
309
+ process.stdout.write(`Renamed: ${oldEventPath} → ${registerEventFilePath(paths.projectRegisterPath, toId)}\n`);
310
+ }
311
+ for (const view of writeDerivedViews(paths, "all")) {
312
+ process.stdout.write(`Generated: ${view.path}\n`);
313
+ }
314
+ }
@@ -0,0 +1,248 @@
1
+ import { inlineCodeAnglePlaceholders } from "./exec-shared.js";
2
+ import { nowUtcTimestamp } from "./register-date.js";
3
+ import { CELL_NONE } from "./register-item.js";
4
+ export function registerTransitionCommands(reg, dependencies) {
5
+ const { addProjectOption, addRegisterCommitOptions, applyItemUpdate, assertRegisterItemCommitTargetsClean, assertTerminalOperationAllowed, loadItemForUpdate, parseRegisterTimestampOption, registerEventActor, runRegisterMutation, updateTicketStatusForItem, } = dependencies;
6
+ // --- close ---
7
+ const closeCmd = reg.command("close").description("Set item status to done or decided");
8
+ addProjectOption(closeCmd);
9
+ closeCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
10
+ closeCmd.option("--status <status>", "done or decided (auto from item type if omitted)");
11
+ closeCmd.option("--conclusion <text>", "Conclusion or resolution summary");
12
+ closeCmd.option("--completed <datetime>", "Completion date-time (RFC 3339 with time zone; defaults to now in UTC)");
13
+ closeCmd.option("--by <actor>", "Actor recorded in the append-only register event");
14
+ closeCmd.option("--reason <text>", "Reason recorded in the append-only register event");
15
+ closeCmd.option("--dry-run", "Print change without writing", false);
16
+ addRegisterCommitOptions(closeCmd);
17
+ closeCmd.action(async (opts) => {
18
+ await runRegisterMutation("close", opts, (context) => {
19
+ const { paths } = context;
20
+ const view = loadItemForUpdate(paths, opts.id, "require-active");
21
+ const item = view.item;
22
+ assertTerminalOperationAllowed(item, "close");
23
+ assertRegisterItemCommitTargetsClean(context, view);
24
+ const targetStatus = opts.status ?? (["decision", "question"].includes(item.type) ? "decided" : "done");
25
+ if (targetStatus !== "done" && targetStatus !== "decided") {
26
+ throw new Error(`--status must be "done" or "decided" for the close command`);
27
+ }
28
+ const completedAt = parseRegisterTimestampOption(opts.completed, "completed", CELL_NONE) ?? nowUtcTimestamp();
29
+ if (completedAt === CELL_NONE) {
30
+ throw new Error(`Invalid completed: "${opts.completed}". A completion date-time is required`);
31
+ }
32
+ const updated = {
33
+ ...item,
34
+ status: targetStatus,
35
+ completedAt,
36
+ ...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
37
+ };
38
+ applyItemUpdate({
39
+ paths,
40
+ view,
41
+ updated,
42
+ dryRun: opts.dryRun,
43
+ eventAction: "close",
44
+ eventActor: registerEventActor(opts),
45
+ eventReason: opts.reason?.trim() || opts.conclusion?.trim() || `closed as ${targetStatus}`,
46
+ });
47
+ updateTicketStatusForItem({ paths, item, targetStatus: "ready", dryRun: opts.dryRun });
48
+ return { id: item.id, title: item.title };
49
+ });
50
+ });
51
+ // --- reject ---
52
+ const rejectCmd = reg.command("reject").description("Set item status to rejected");
53
+ addProjectOption(rejectCmd);
54
+ rejectCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
55
+ rejectCmd.option("--conclusion <text>", "Reason for rejection");
56
+ rejectCmd.option("--completed <datetime>", "Rejection date-time (RFC 3339 with time zone; defaults to now in UTC)");
57
+ rejectCmd.option("--by <actor>", "Actor recorded in the append-only register event");
58
+ rejectCmd.option("--reason <text>", "Reason recorded in the append-only register event");
59
+ rejectCmd.option("--dry-run", "Print change without writing", false);
60
+ addRegisterCommitOptions(rejectCmd);
61
+ rejectCmd.action(async (opts) => {
62
+ await runRegisterMutation("reject", opts, (context) => {
63
+ const { paths } = context;
64
+ const view = loadItemForUpdate(paths, opts.id, "require-active");
65
+ const item = view.item;
66
+ assertTerminalOperationAllowed(item, "reject");
67
+ assertRegisterItemCommitTargetsClean(context, view);
68
+ const completedAt = parseRegisterTimestampOption(opts.completed, "completed", CELL_NONE) ?? nowUtcTimestamp();
69
+ if (completedAt === CELL_NONE) {
70
+ throw new Error(`Invalid completed: "${opts.completed}". A rejection date-time is required`);
71
+ }
72
+ const updated = {
73
+ ...item,
74
+ status: "rejected",
75
+ completedAt,
76
+ ...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
77
+ };
78
+ applyItemUpdate({
79
+ paths,
80
+ view,
81
+ updated,
82
+ dryRun: opts.dryRun,
83
+ eventAction: "reject",
84
+ eventActor: registerEventActor(opts),
85
+ eventReason: opts.reason?.trim() || opts.conclusion?.trim() || "item rejected",
86
+ });
87
+ updateTicketStatusForItem({ paths, item, targetStatus: "deprecated", dryRun: opts.dryRun });
88
+ return { id: item.id, title: item.title };
89
+ });
90
+ });
91
+ // --- defer ---
92
+ const deferCmd = reg.command("defer").description("Set item status to deferred");
93
+ addProjectOption(deferCmd);
94
+ deferCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
95
+ deferCmd.option("--conclusion <text>", "Reason for deferral");
96
+ deferCmd.option("--by <actor>", "Actor recorded in the append-only register event");
97
+ deferCmd.option("--reason <text>", "Reason recorded in the append-only register event");
98
+ deferCmd.option("--dry-run", "Print change without writing", false);
99
+ addRegisterCommitOptions(deferCmd);
100
+ deferCmd.action(async (opts) => {
101
+ await runRegisterMutation("defer", opts, (context) => {
102
+ const { paths } = context;
103
+ const view = loadItemForUpdate(paths, opts.id, "require-active");
104
+ const item = view.item;
105
+ assertTerminalOperationAllowed(item, "defer");
106
+ assertRegisterItemCommitTargetsClean(context, view);
107
+ const updated = {
108
+ ...item,
109
+ status: "deferred",
110
+ ...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
111
+ };
112
+ applyItemUpdate({
113
+ paths,
114
+ view,
115
+ updated,
116
+ dryRun: opts.dryRun,
117
+ eventAction: "defer",
118
+ eventActor: registerEventActor(opts),
119
+ eventReason: opts.reason?.trim() || opts.conclusion?.trim() || "item deferred",
120
+ });
121
+ return { id: item.id, title: item.title };
122
+ });
123
+ });
124
+ // --- reopen ---
125
+ const reopenCmd = reg.command("reopen").description("Reopen a terminal-status item");
126
+ addProjectOption(reopenCmd);
127
+ reopenCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
128
+ reopenCmd.option("--status <status>", "Target status: open | in-progress | waiting | review", "open");
129
+ reopenCmd.option("--by <actor>", "Actor recorded in the append-only register event");
130
+ reopenCmd.option("--reason <text>", "Reason recorded in the append-only register event");
131
+ reopenCmd.option("--dry-run", "Print change without writing", false);
132
+ addRegisterCommitOptions(reopenCmd);
133
+ reopenCmd.action(async (opts) => {
134
+ await runRegisterMutation("reopen", opts, (context) => {
135
+ const { paths } = context;
136
+ const view = loadItemForUpdate(paths, opts.id, "require-terminal");
137
+ const item = view.item;
138
+ assertRegisterItemCommitTargetsClean(context, view);
139
+ const validReopenStatuses = ["open", "in-progress", "waiting", "review"];
140
+ if (!validReopenStatuses.includes(opts.status)) {
141
+ throw new Error(`--status must be one of: ${validReopenStatuses.join(", ")}`);
142
+ }
143
+ const updated = { ...item, status: opts.status, completedAt: CELL_NONE };
144
+ applyItemUpdate({
145
+ paths,
146
+ view,
147
+ updated,
148
+ dryRun: opts.dryRun,
149
+ eventAction: "reopen",
150
+ eventActor: registerEventActor(opts),
151
+ eventReason: opts.reason?.trim() || `reopened as ${opts.status}`,
152
+ });
153
+ return { id: item.id, title: item.title };
154
+ });
155
+ });
156
+ // --- start ---
157
+ const startCmd = reg.command("start").description("Set item status to in-progress");
158
+ addProjectOption(startCmd);
159
+ startCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
160
+ startCmd.option("--by <actor>", "Actor recorded in the append-only register event");
161
+ startCmd.option("--reason <text>", "Reason recorded in the append-only register event");
162
+ startCmd.option("--dry-run", "Print change without writing", false);
163
+ addRegisterCommitOptions(startCmd);
164
+ startCmd.action(async (opts) => {
165
+ await runRegisterMutation("start", opts, (context) => {
166
+ const { paths } = context;
167
+ const view = loadItemForUpdate(paths, opts.id, "require-active");
168
+ const item = view.item;
169
+ assertRegisterItemCommitTargetsClean(context, view);
170
+ const updated = { ...item, status: "in-progress" };
171
+ applyItemUpdate({
172
+ paths,
173
+ view,
174
+ updated,
175
+ dryRun: opts.dryRun,
176
+ eventAction: "start",
177
+ eventActor: registerEventActor(opts),
178
+ eventReason: opts.reason?.trim() || "work started",
179
+ });
180
+ return { id: item.id, title: item.title };
181
+ });
182
+ });
183
+ // --- wait ---
184
+ const waitCmd = reg.command("wait").description("Set item status to waiting");
185
+ addProjectOption(waitCmd);
186
+ waitCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
187
+ waitCmd.option("--reason <text>", "Reason for waiting");
188
+ waitCmd.option("--conclusion <text>", "Deprecated alias for --reason");
189
+ waitCmd.option("--by <actor>", "Actor recorded in the append-only register event");
190
+ waitCmd.option("--dry-run", "Print change without writing", false);
191
+ addRegisterCommitOptions(waitCmd);
192
+ waitCmd.action(async (opts) => {
193
+ await runRegisterMutation("wait", opts, (context) => {
194
+ if (opts.reason !== undefined && opts.conclusion !== undefined) {
195
+ throw new Error("Specify only one of --reason or --conclusion");
196
+ }
197
+ const { paths } = context;
198
+ const view = loadItemForUpdate(paths, opts.id, "require-active");
199
+ const item = view.item;
200
+ assertRegisterItemCommitTargetsClean(context, view);
201
+ const reason = (opts.reason ?? opts.conclusion)?.trim();
202
+ if (reason !== undefined && reason === "") {
203
+ throw new Error("Waiting reason must not be empty");
204
+ }
205
+ const updated = { ...item, status: "waiting" };
206
+ applyItemUpdate({
207
+ paths,
208
+ view,
209
+ updated,
210
+ dryRun: opts.dryRun,
211
+ ...(reason !== undefined
212
+ ? { fieldUpdates: { block_reason: inlineCodeAnglePlaceholders(reason) } }
213
+ : {}),
214
+ eventAction: "wait",
215
+ eventActor: registerEventActor(opts),
216
+ eventReason: reason || "item waiting",
217
+ });
218
+ return { id: item.id, title: item.title };
219
+ });
220
+ });
221
+ // --- review ---
222
+ const reviewCmd = reg.command("review").description("Set item status to review");
223
+ addProjectOption(reviewCmd);
224
+ reviewCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
225
+ reviewCmd.option("--by <actor>", "Actor recorded in the append-only register event");
226
+ reviewCmd.option("--reason <text>", "Reason recorded in the append-only register event");
227
+ reviewCmd.option("--dry-run", "Print change without writing", false);
228
+ addRegisterCommitOptions(reviewCmd);
229
+ reviewCmd.action(async (opts) => {
230
+ await runRegisterMutation("review", opts, (context) => {
231
+ const { paths } = context;
232
+ const view = loadItemForUpdate(paths, opts.id, "require-active");
233
+ const item = view.item;
234
+ assertRegisterItemCommitTargetsClean(context, view);
235
+ const updated = { ...item, status: "review" };
236
+ applyItemUpdate({
237
+ paths,
238
+ view,
239
+ updated,
240
+ dryRun: opts.dryRun,
241
+ eventAction: "review",
242
+ eventActor: registerEventActor(opts),
243
+ eventReason: opts.reason?.trim() || "ready for review",
244
+ });
245
+ return { id: item.id, title: item.title };
246
+ });
247
+ });
248
+ }