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
@@ -0,0 +1,134 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { isAbsolute, resolve } from "node:path";
3
+ import { collectResolvedDeliverables, loadCatalogDocs } from "../catalog/build.js";
4
+ import { resolveBasePath } from "../catalog/paths.js";
5
+ import { collectDocIndexEntries } from "../docs/doc-index.js";
6
+ import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
7
+ import { getProjectCatalogPath, loadConfig, specdojoRootDir } from "../shared/specdojo-config.js";
8
+ import { APPROACHES } from "../shared/agent-types.js";
9
+ import { load } from "../shared/yaml.js";
10
+ const MAINTENANCE_TARGET_KIND = {
11
+ "rulebook-maintenance": "rulebook",
12
+ "recipe-maintenance": "recipe",
13
+ "sample-maintenance": "sample",
14
+ "template-maintenance": "template",
15
+ };
16
+ function resolvedIndexPath(repoRoot, indexedPath) {
17
+ const withoutLine = indexedPath.replace(/:\d+$/, "");
18
+ return resolve(isAbsolute(withoutLine) ? withoutLine : resolve(repoRoot, withoutLine));
19
+ }
20
+ function catalogDeliverableDocIds(catalogPath, repoRoot, projectId) {
21
+ const ids = new Set();
22
+ if (!existsSync(catalogPath))
23
+ return ids;
24
+ for (const loaded of loadCatalogDocs(catalogPath)) {
25
+ const deliverables = [];
26
+ collectResolvedDeliverables(loaded.doc.groups, resolveBasePath("", loaded.doc.base_path), deliverables);
27
+ for (const deliverable of deliverables) {
28
+ // register の対象指定では、PJR-H72A が定める成果物 local_id の canonical 形式も
29
+ // 受け付ける。文書が既にあれば、その frontmatter の実 ID も同じ成果物として扱う。
30
+ ids.add(`${projectId}:${deliverable.item.local_id}`);
31
+ const path = resolve(repoRoot, deliverable.resolvedPath);
32
+ if (existsSync(path)) {
33
+ try {
34
+ const id = readSpecdojoNamespace(readFileSync(path, "utf8")).id;
35
+ if (typeof id === "string" && id.trim()) {
36
+ ids.add(id.trim());
37
+ continue;
38
+ }
39
+ }
40
+ catch {
41
+ // 読み取り不能・不正 frontmatter は配置規約による ID へフォールバックする。
42
+ }
43
+ }
44
+ const normalizedPath = deliverable.resolvedPath.replaceAll("\\", "/").replace(/^\/+/, "");
45
+ if (/^docs\/[a-z]{2}\/product(?:\/|$)/.test(normalizedPath)) {
46
+ ids.add(deliverable.item.local_id);
47
+ }
48
+ }
49
+ }
50
+ return ids;
51
+ }
52
+ function targetDocumentType(path) {
53
+ if (!existsSync(path))
54
+ return undefined;
55
+ const content = readFileSync(path, "utf8");
56
+ if (path.endsWith(".md")) {
57
+ const type = readSpecdojoNamespace(content).type;
58
+ return typeof type === "string" ? type : undefined;
59
+ }
60
+ const parsed = load(content);
61
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
62
+ return undefined;
63
+ const type = parsed.type;
64
+ return typeof type === "string" ? type : undefined;
65
+ }
66
+ // register の個票に approach を書く時点で、対象が一意かつ実行方式に合うことを保証する。
67
+ // kata は都度 docs から収集した索引、成果物は DCT を正本として解決し、生成済みの
68
+ // .specdojo/doc-index.json の鮮度や成果物文書の作成済み・未作成には依存しない。
69
+ export function validateRegisterApproachTargets(opts) {
70
+ const approachText = opts.approach?.trim();
71
+ const targets = [...new Set((opts.targets ?? []).map((target) => target.trim()).filter(Boolean))];
72
+ let approach;
73
+ if (approachText !== undefined) {
74
+ if (!APPROACHES.includes(approachText)) {
75
+ throw new Error(`Invalid approach: "${approachText}". Must be one of: ${APPROACHES.join(", ")}`);
76
+ }
77
+ approach = approachText;
78
+ if (targets.length !== 1) {
79
+ throw new Error(`Approach "${approach}" requires exactly one --target doc id (received ${targets.length})`);
80
+ }
81
+ }
82
+ if (!approach && !opts.validateTargetsWithoutApproach)
83
+ return;
84
+ if (targets.length === 0)
85
+ return;
86
+ const entries = collectDocIndexEntries(resolve(opts.repoRoot, "docs"), opts.repoRoot);
87
+ if (!approach) {
88
+ for (const target of targets) {
89
+ if (!entries[target]) {
90
+ throw new Error(`Target document id is not resolvable via the document index: ${target}`);
91
+ }
92
+ }
93
+ return;
94
+ }
95
+ const expectedKind = MAINTENANCE_TARGET_KIND[approach];
96
+ const [targetId] = targets;
97
+ if (expectedKind) {
98
+ const indexedPath = entries[targetId];
99
+ if (!indexedPath) {
100
+ throw new Error(`Target document id is not resolvable via the document index: ${targetId}`);
101
+ }
102
+ const actualKind = targetDocumentType(resolvedIndexPath(opts.repoRoot, indexedPath));
103
+ if (actualKind !== expectedKind) {
104
+ throw new Error(`Approach "${approach}" requires a ${expectedKind} document target, but ${targetId} has type "${actualKind ?? "unknown"}"`);
105
+ }
106
+ return;
107
+ }
108
+ if (!opts.catalogPath) {
109
+ throw new Error(`Approach "${approach}" requires a deliverable target, but catalog_path is not configured for project ${opts.projectId}`);
110
+ }
111
+ const deliverableDocIds = catalogDeliverableDocIds(opts.catalogPath, opts.repoRoot, opts.projectId);
112
+ if (!deliverableDocIds.has(targetId)) {
113
+ throw new Error(`Approach "${approach}" requires a deliverable document from the project catalog, but ${targetId} is not a catalog deliverable`);
114
+ }
115
+ }
116
+ export function validateRegisterApproachTargetsForProject(opts) {
117
+ const repoRoot = specdojoRootDir();
118
+ const { config, configPath } = loadConfig();
119
+ const project = config?.projects[opts.projectId];
120
+ if (!project) {
121
+ throw new Error(`Unknown project: ${opts.projectId} (check ${configPath})`);
122
+ }
123
+ const catalogPath = getProjectCatalogPath(project);
124
+ validateRegisterApproachTargets({
125
+ repoRoot,
126
+ projectId: opts.projectId,
127
+ ...(catalogPath ? { catalogPath: resolve(repoRoot, catalogPath) } : {}),
128
+ ...(opts.approach !== undefined ? { approach: opts.approach } : {}),
129
+ ...(opts.targets !== undefined ? { targets: opts.targets } : {}),
130
+ ...(opts.validateTargetsWithoutApproach !== undefined
131
+ ? { validateTargetsWithoutApproach: opts.validateTargetsWithoutApproach }
132
+ : {}),
133
+ });
134
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,369 @@
1
+ import { randomInt, randomUUID } from "node:crypto";
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, } from "node:fs";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { inlineCodeAnglePlaceholders } from "../shared/text.js";
5
+ import { appendRegisterEvent, registerEventFilePath } from "./events.js";
6
+ import { REGISTER_TIMESTAMP_RE, resolveRegisterDateTimeZone, timestampFromDateInTimeZone, } from "./date.js";
7
+ import { applyRegisterItemFields, CELL_NONE, CELL_TODO, isPlaceholderCell, PJR_ID_ALPHABET, PJR_ID_RE, registerItemFieldsFromItem, setRegisterItemDescription, toCell, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, } from "./item.js";
8
+ import { getProjectExecutionPath, getProjectRegisterPath, loadConfig, loadEnv, specdojoRootDir, } from "../shared/specdojo-config.js";
9
+ import { flattenTemplateFrontmatter } from "../docs/template-frontmatter.js";
10
+ export function registerEventActor(opts) {
11
+ return opts.by?.trim() || process.env.SPECDOJO_ACTOR?.trim() || "manual";
12
+ }
13
+ export function atomicWriteFile(path, content) {
14
+ mkdirSync(dirname(path), { recursive: true });
15
+ const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
16
+ try {
17
+ writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
18
+ renameSync(temporary, path);
19
+ }
20
+ finally {
21
+ if (existsSync(temporary))
22
+ unlinkSync(temporary);
23
+ }
24
+ }
25
+ export function findMarkdownReferenceFiles(root) {
26
+ const markdownFiles = [];
27
+ const docsJaPath = join(resolve(root), "docs", "ja");
28
+ function walk(directory) {
29
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
30
+ if (entry.name.startsWith("."))
31
+ continue;
32
+ const entryPath = join(directory, entry.name);
33
+ if (entry.isDirectory()) {
34
+ if (entry.name !== "generated")
35
+ walk(entryPath);
36
+ }
37
+ else if (entry.isFile() && entry.name.endsWith(".md")) {
38
+ markdownFiles.push(entryPath);
39
+ }
40
+ }
41
+ }
42
+ if (existsSync(docsJaPath))
43
+ walk(docsJaPath);
44
+ return markdownFiles.sort((left, right) => left.localeCompare(right));
45
+ }
46
+ export function prepareRegisterEventFile(projectRegisterPath, displayId, event) {
47
+ const eventPath = registerEventFilePath(projectRegisterPath, displayId);
48
+ const content = existsSync(eventPath) ? readFileSync(eventPath, "utf8") : undefined;
49
+ return { path: eventPath, content: appendRegisterEvent(content, event) };
50
+ }
51
+ // ================================
52
+ // Constants
53
+ // ================================
54
+ // PJR-ID の乱数部分の桁数。
55
+ const PJR_ID_LENGTH = 4;
56
+ // 個票ファイル名・文書 ID の論点部分。先頭・末尾や連続ハイフンを許さない。
57
+ export const REGISTER_TOPIC_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
58
+ // 生成した ID が偶然含みうる不適切語の簡易ブロックリスト(4 文字, 大文字, 曖昧文字除外後)。
59
+ // 一致した候補は採用せず再抽選する。曖昧文字(I/L/O/U)を含む語は生成されえないため載せない。
60
+ const PJR_ID_BLOCKLIST = new Set(["CRAP", "DAMN", "TWAT", "WANK", "SHAG", "FART"]);
61
+ // 個票 Frontmatter の文書成熟度(specdojo:pjr-rulebook「個票 status の遷移基準」)。
62
+ // pjr-index の処理状態(VALID_STATUSES)とは別の状態軸として扱う。
63
+ export const VALID_TICKET_STATUSES = ["draft", "ready", "deprecated"];
64
+ // 登録項目一覧テーブルは specdojo:pjr-rulebook「本文構成」で章 1 に固定される。
65
+ // 見出し文言(言語依存)ではなく章番号でセクションを特定し、i18n 非依存にする。
66
+ export const REGISTER_SECTION_RE = /^## 1\.\s/;
67
+ // 登録項目一覧(pjr-index)の生成 template。外枠(H1・注記・章見出し)と章 1 の
68
+ // 列見出しを所有し、生成処理は行だけを差し込む。列名を定数として持たないことで、
69
+ // 一覧の言語は template 側の差し替えだけで切り替えられる。
70
+ export const REGISTER_INDEX_TEMPLATE = "pjr-index-template.md";
71
+ // ================================
72
+ // Path Resolution
73
+ // ================================
74
+ export function resolveRegisterPaths(opts) {
75
+ loadEnv();
76
+ const { config, configPath } = loadConfig();
77
+ const baseDir = specdojoRootDir();
78
+ const projectId = opts.project?.trim() ||
79
+ process.env.SPECDOJO_PROJECT?.trim() ||
80
+ (config ? Object.keys(config.projects)[0] : "");
81
+ if (!config) {
82
+ throw new Error(`register commands require specdojo.config.json.\nRun: specdojo config init`);
83
+ }
84
+ if (!projectId) {
85
+ throw new Error(`No project specified. Use --project <id> or SPECDOJO_PROJECT.`);
86
+ }
87
+ const project = config.projects[projectId];
88
+ if (!project) {
89
+ throw new Error(`Unknown project: ${projectId} (check ${configPath})`);
90
+ }
91
+ const registerPath = getProjectRegisterPath(project);
92
+ if (!registerPath) {
93
+ throw new Error(`project_register_path not set for project '${projectId}' in ${configPath}.\n` +
94
+ `Add "project_register_path": "<path>" to the project config.`);
95
+ }
96
+ const absRegisterPath = resolve(baseDir, registerPath);
97
+ return {
98
+ projectId,
99
+ projectRegisterPath: absRegisterPath,
100
+ executionPath: resolve(baseDir, getProjectExecutionPath(project)),
101
+ pjrIndexPath: join(absRegisterPath, "pjr-index.md"),
102
+ generatedPath: join(absRegisterPath, "generated"),
103
+ controlsGeneratedPath: join(dirname(absRegisterPath), "generated"),
104
+ registerDateTimeZone: resolveRegisterDateTimeZone(config, projectId),
105
+ };
106
+ }
107
+ // ================================
108
+ // Markdown Table Parsing
109
+ // ================================
110
+ export function parseTableCells(line) {
111
+ // Replace escaped pipes with placeholder before splitting
112
+ const PIPE = "\x01";
113
+ const normalized = line.replace(/\\\|/g, PIPE);
114
+ const cells = normalized.split("|").map((c) => c.replace(new RegExp(PIPE, "g"), "\\|").trim());
115
+ // Remove first and last empty elements (line starts and ends with |)
116
+ return cells.slice(1, cells.length - 1);
117
+ }
118
+ export function isTableSeparator(line) {
119
+ return line.startsWith("|") && /\|\s*---+\s*\|/.test(line);
120
+ }
121
+ export function locateRegisterTable(lines) {
122
+ let inSection = false;
123
+ let header;
124
+ for (let index = 0; index < lines.length; index++) {
125
+ const line = lines[index];
126
+ if (REGISTER_SECTION_RE.test(line)) {
127
+ inSection = true;
128
+ continue;
129
+ }
130
+ if (inSection && /^## /.test(line))
131
+ break;
132
+ if (!inSection || !line.startsWith("|"))
133
+ continue;
134
+ if (isTableSeparator(line)) {
135
+ if (header === undefined) {
136
+ throw new Error("Register table header row not found before the separator in the register list source");
137
+ }
138
+ return {
139
+ heading: { header: header.trim(), separator: line.trim() },
140
+ separatorIndex: index,
141
+ };
142
+ }
143
+ if (header === undefined)
144
+ header = line;
145
+ }
146
+ return undefined;
147
+ }
148
+ export function extractTableHeading(content) {
149
+ const located = locateRegisterTable(content.split("\n"));
150
+ if (!located) {
151
+ throw new Error("Register table header row not found in the register list source");
152
+ }
153
+ return located.heading;
154
+ }
155
+ // 章 1 の登録項目一覧テーブルの区切り行直後へ、生成した行を差し込む。
156
+ // テーブルの列見出しは template が所有するため、生成処理は行だけを注入する。
157
+ export function injectRegisterRows(content, rows) {
158
+ const lines = content.split("\n");
159
+ const located = locateRegisterTable(lines);
160
+ if (!located) {
161
+ throw new Error(`Register table not found in template: ${REGISTER_INDEX_TEMPLATE}`);
162
+ }
163
+ lines.splice(located.separatorIndex + 1, 0, ...rows);
164
+ return lines.join("\n");
165
+ }
166
+ // 旧一覧(追跡対象だった頃の pjr-index.md)の表を読む互換経路。日付セルは暦日しか持たない
167
+ // ため、移行と同じ規則でプロジェクトタイムゾーンの 21:00 を補って日時へ変換する。
168
+ export function parsePjrIndex(content, timeZone) {
169
+ const lines = content.split("\n");
170
+ const items = [];
171
+ let inSection = false;
172
+ const toTimestamp = (cell) => isPlaceholderCell(cell) ? cell.trim() : timestampFromDateInTimeZone(cell.trim(), timeZone);
173
+ for (const line of lines) {
174
+ if (REGISTER_SECTION_RE.test(line)) {
175
+ inSection = true;
176
+ continue;
177
+ }
178
+ if (inSection && /^## /.test(line))
179
+ break;
180
+ if (!inSection)
181
+ continue;
182
+ if (!line.startsWith("|") || isTableSeparator(line))
183
+ continue;
184
+ const cells = parseTableCells(line);
185
+ if (cells.length < 12)
186
+ continue;
187
+ if (!PJR_ID_RE.test(cells[0]))
188
+ continue;
189
+ items.push({
190
+ id: cells[0],
191
+ status: cells[1],
192
+ title: cells[2],
193
+ description: cells[3],
194
+ type: cells[4],
195
+ priority: cells[5],
196
+ owner: cells[6],
197
+ registeredAt: toTimestamp(cells[7]),
198
+ due: cells[8],
199
+ completedAt: toTimestamp(cells[9]),
200
+ conclusion: cells[10],
201
+ ticket: cells[11],
202
+ });
203
+ }
204
+ return items;
205
+ }
206
+ // 32 文字セットから一様乱択した 4 文字を持つ PJR-ID 候補を 1 件生成する。
207
+ function defaultPjrCandidate() {
208
+ let suffix = "";
209
+ for (let i = 0; i < PJR_ID_LENGTH; i++) {
210
+ suffix += PJR_ID_ALPHABET[randomInt(0, PJR_ID_ALPHABET.length)];
211
+ }
212
+ return `PJR-${suffix}`;
213
+ }
214
+ // 既存 ID・不適切語ブロックリストと衝突しない PJR-ID をランダムに採番する。
215
+ // 生成候補が既存 ID かブロックリストに一致した場合は再抽選する。nextCandidate は
216
+ // テストで抽選列を差し込むための注入点で、既定は 32 文字セットからの一様乱択。
217
+ export function generatePjrId(existingIds, nextCandidate = defaultPjrCandidate, maxAttempts = 256) {
218
+ const existing = new Set(existingIds);
219
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
220
+ const id = nextCandidate();
221
+ if (!PJR_ID_RE.test(id))
222
+ continue;
223
+ if (existing.has(id))
224
+ continue;
225
+ if (PJR_ID_BLOCKLIST.has(id.slice("PJR-".length)))
226
+ continue;
227
+ return id;
228
+ }
229
+ throw new Error(`Failed to generate an unused PJR-ID after ${maxAttempts} attempts`);
230
+ }
231
+ export function formatTableRow(item) {
232
+ // frontmatter・本文由来を問わず、表へ展開する全セルを同じ規則で無害化する。
233
+ // 列区切りの `|` と改行をエスケープし、山括弧プレースホルダをインラインコード化する。
234
+ // 既存コードスパンは変換処理が保持するため、再生成しても二重に囲まれない。
235
+ const cells = [
236
+ item.id,
237
+ item.status,
238
+ item.title,
239
+ item.description,
240
+ item.type,
241
+ item.priority,
242
+ item.owner,
243
+ item.registered,
244
+ item.due,
245
+ item.completed,
246
+ item.conclusion,
247
+ item.ticket,
248
+ ]
249
+ .map(toCell)
250
+ .map(inlineCodeAnglePlaceholders);
251
+ return `| ${cells.join(" | ")} |`;
252
+ }
253
+ // ================================
254
+ // Validation
255
+ // ================================
256
+ export function validateFields(opts) {
257
+ const errors = [];
258
+ if (!VALID_STATUSES.includes(opts.status)) {
259
+ errors.push(`Invalid status: "${opts.status}". Must be one of: ${VALID_STATUSES.join(", ")}`);
260
+ }
261
+ if (!VALID_TYPES.includes(opts.type)) {
262
+ errors.push(`Invalid type: "${opts.type}". Must be one of: ${VALID_TYPES.join(", ")}`);
263
+ }
264
+ if (!VALID_PRIORITIES.includes(opts.priority)) {
265
+ errors.push(`Invalid priority: "${opts.priority}". Must be one of: ${VALID_PRIORITIES.join(", ")}`);
266
+ }
267
+ if (opts.id && !PJR_ID_RE.test(opts.id)) {
268
+ errors.push(`Invalid ID: "${opts.id}". Must match PJR-XXXX (e.g., PJR-0001)`);
269
+ }
270
+ if (opts.registeredAt !== CELL_TODO && !REGISTER_TIMESTAMP_RE.test(opts.registeredAt)) {
271
+ errors.push(`Invalid registered: "${opts.registeredAt}". Must be an RFC 3339 UTC date-time (YYYY-MM-DDTHH:MM:SSZ) or _TODO_`);
272
+ }
273
+ if (!/^(\d{4}-\d{2}-\d{2}|-|_TODO_)$/.test(opts.due)) {
274
+ errors.push(`Invalid due: "${opts.due}". Must be YYYY-MM-DD, -, or _TODO_`);
275
+ }
276
+ if (opts.completedAt !== CELL_NONE && !REGISTER_TIMESTAMP_RE.test(opts.completedAt)) {
277
+ errors.push(`Invalid completed: "${opts.completedAt}". Must be an RFC 3339 UTC date-time (YYYY-MM-DDTHH:MM:SSZ) or -`);
278
+ }
279
+ if (errors.length > 0) {
280
+ throw new Error(errors.join("\n"));
281
+ }
282
+ }
283
+ // ================================
284
+ // Slug
285
+ // ================================
286
+ export function slugify(text) {
287
+ return (text
288
+ .toLowerCase()
289
+ .replace(/[^a-z0-9\s-]/g, " ")
290
+ .trim()
291
+ .replace(/[\s_]+/g, "-")
292
+ .replace(/-+/g, "-")
293
+ .replace(/^-|-$/g, "") || "item");
294
+ }
295
+ // 日本語主体のタイトルから ASCII の断片だけを topic にすると、個票名から内容を
296
+ // 推測できなくなる。区切り記号は数えず、文字・数字の過半が非 ASCII で、抽出できた
297
+ // ASCII 語が 1 語だけの場合を「意味を失う可能性がある既定 topic」とみなす。
298
+ export function derivedTopicNeedsWarning(title, topic) {
299
+ const asciiWords = title.match(/[a-z0-9]+/giu) ?? [];
300
+ if (topic === "item" && asciiWords.length === 0)
301
+ return true;
302
+ if (asciiWords.length !== 1)
303
+ return false;
304
+ const lettersAndNumbers = [...title].filter((char) => /[\p{L}\p{N}]/u.test(char));
305
+ const asciiCount = lettersAndNumbers.filter((char) => /[a-z0-9]/iu.test(char)).length;
306
+ return lettersAndNumbers.length - asciiCount > asciiCount;
307
+ }
308
+ export function printDerivedTopicWarning(topic) {
309
+ process.stdout.write(`Warning: derived topic "${topic}" may not describe the title. ` +
310
+ "Specify --topic with a lowercase, hyphen-separated English slug, or change it later " +
311
+ "with register update --topic.\n");
312
+ }
313
+ // ================================
314
+ // Ticket Generation
315
+ // ================================
316
+ function getTitlePlaceholder(type) {
317
+ return `_${type.toUpperCase().replace(/-/g, "_")}_TITLE_`;
318
+ }
319
+ function generateTicket(opts) {
320
+ if (!existsSync(opts.templatePath)) {
321
+ throw new Error(`Template not found: ${opts.templatePath}`);
322
+ }
323
+ let content = readFileSync(opts.templatePath, "utf8");
324
+ content = flattenTemplateFrontmatter(content);
325
+ const pjrLower = opts.displayId.toLowerCase();
326
+ // Keep the canonical document ID aligned with the ticket filename.
327
+ content = content.replace(/_PJR_DOCUMENT_ID_/g, `${opts.projectId}:${pjrLower}-${opts.topic}`);
328
+ // Replace remaining project id placeholder
329
+ content = content.replace(/_PROJECT_ID_/g, opts.projectId);
330
+ // Replace display id placeholder with uppercase
331
+ content = content.replace(/_PJR-XXXX_/g, opts.displayId);
332
+ // Replace type-specific title placeholder
333
+ const titlePh = getTitlePlaceholder(opts.type);
334
+ const safeTitle = inlineCodeAnglePlaceholders(opts.title);
335
+ content = content.replace(new RegExp(titlePh.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), safeTitle);
336
+ return content;
337
+ }
338
+ // 個票の完成形(テンプレート展開 + 説明の反映 + 登録項目 frontmatter)を組み立てる。
339
+ // 登録項目の構造化フィールドは frontmatter、タイトルは H1、説明は概要段落が正本になる。
340
+ export function buildRegisterItemContent(opts) {
341
+ let content = generateTicket({
342
+ projectId: opts.projectId,
343
+ displayId: opts.displayId,
344
+ topic: opts.topic,
345
+ type: opts.fields.type,
346
+ title: opts.fields.title,
347
+ templatePath: opts.templatePath,
348
+ });
349
+ if (!isPlaceholderCell(opts.fields.description)) {
350
+ content = setRegisterItemDescription(content, opts.fields.description);
351
+ }
352
+ return applyRegisterItemFields(content, registerItemFieldsFromItem({
353
+ id: opts.displayId,
354
+ status: opts.fields.status,
355
+ title: opts.fields.title,
356
+ description: opts.fields.description,
357
+ type: opts.fields.type,
358
+ priority: opts.fields.priority,
359
+ owner: opts.fields.owner,
360
+ registeredAt: opts.fields.registeredAt,
361
+ due: opts.fields.due,
362
+ completedAt: opts.fields.completedAt,
363
+ conclusion: opts.fields.conclusion,
364
+ ticket: "-",
365
+ ...(opts.fields.approach ? { approach: opts.fields.approach } : {}),
366
+ ...(opts.fields.targets ? { targets: opts.fields.targets } : {}),
367
+ ...(opts.fields.derivedFrom ? { derivedFrom: opts.fields.derivedFrom } : {}),
368
+ }));
369
+ }