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,693 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename, join, relative, resolve } from "node:path";
3
+ import { load } from "./yaml.js";
4
+ import { specdojoRootDir } from "./specdojo-config.js";
5
+ import { kataDirsForKinds, resolveIncludedRulebooks, resolveKataRefs } from "./kata.js";
6
+ import { resolveBasePath, resolveDeliverablePath } from "./catalog-paths.js";
7
+ import { isDctPlanFileName } from "./catalog-plan.js";
8
+ import { buildSpecdojoFrontmatter, readSpecdojoNamespace } from "./frontmatter-namespace.js";
9
+ import { qualifyPracticeId, SPECDOJO_PRACTICE_AUTHORITY } from "./practice-id.js";
10
+ import { resolveViewpointsDoc, viewpointAppliesToDocument } from "./review-plan.js";
11
+ import { listFilesRecursive, nowUtcIsoSeconds, randomHex, tsForFilenameUtc, } from "./exec-shared.js";
12
+ import { gradeFindingDisplayMessage, gradeResultPathForDocument, readGradeResultForDocument, } from "./grade-result.js";
13
+ import { resolveSpecdojoPath, resolveSpecdojoPathIfExists } from "./template-resolution.js";
14
+ import { renderReviewGradeSummary, reviewGradeFreshness } from "./review-grade.js";
15
+ export const MISSING = "_MISSING_";
16
+ export function execDocId(projectId, prefix, localBase) {
17
+ const localId = `${prefix}-${localBase.toLowerCase()}`;
18
+ return projectId ? `${projectId}:${localId}` : localId;
19
+ }
20
+ // In-place plan/result share one unique stem (`<slug>-<UTC>-<rand>`) so each run keeps a
21
+ // distinct file and id (no doc-index collision) and the result name is derivable from the
22
+ // plan. Mirrors the done/ archive naming convention (tsForFilenameUtc + randomHex).
23
+ export function buildInPlaceStem(slug) {
24
+ return `${slug}-${tsForFilenameUtc(nowUtcIsoSeconds())}-${randomHex(2)}`;
25
+ }
26
+ // Recover the shared stem from a plan path: `.../exec/plans/<stem>-plan.md` → `<stem>`.
27
+ // Used when re-running `--plan <path>` so the tied result is overwritten in place.
28
+ export function stemFromPlanPath(planPath) {
29
+ return basename(planPath).replace(/-plan\.md$/, "");
30
+ }
31
+ // ---------------------------------------------------------------------------
32
+ // Catalog helpers
33
+ // ---------------------------------------------------------------------------
34
+ function searchSections(sections, parentBase, localId) {
35
+ for (const section of sections) {
36
+ const sectionBase = resolveBasePath(parentBase, section.base_path);
37
+ for (const d of section.deliverables ?? []) {
38
+ if (d.local_id === localId) {
39
+ return {
40
+ deliverable: d,
41
+ resolvedPath: resolveDeliverablePath(sectionBase, d.path),
42
+ };
43
+ }
44
+ }
45
+ const found = searchSections(section.groups ?? [], sectionBase, localId);
46
+ if (found)
47
+ return found;
48
+ }
49
+ return null;
50
+ }
51
+ export function findDeliverableInfo(catalogPath, localId) {
52
+ if (!catalogPath || !existsSync(catalogPath))
53
+ return null;
54
+ // Catalog scans walk subdirectories, so agent judgment plans (plans/dct-plan-*.yaml)
55
+ // must be excluded; they share the dct- prefix but carry no catalog structure.
56
+ const files = listFilesRecursive(catalogPath)
57
+ .filter((f) => {
58
+ const name = f.split("/").pop() ?? "";
59
+ return /^dct-.+\.ya?ml$/i.test(name) && !isDctPlanFileName(name);
60
+ })
61
+ .sort();
62
+ for (const filePath of files) {
63
+ let doc;
64
+ try {
65
+ doc = load(readFileSync(filePath, "utf8"));
66
+ }
67
+ catch {
68
+ continue;
69
+ }
70
+ const found = searchSections(doc.groups, resolveBasePath("", doc.base_path), localId);
71
+ if (found)
72
+ return found;
73
+ }
74
+ return null;
75
+ }
76
+ export function loadCatalogDocs(catalogPath) {
77
+ if (!catalogPath || !existsSync(catalogPath))
78
+ return [];
79
+ // Catalog scans walk subdirectories, so agent judgment plans (plans/dct-plan-*.yaml)
80
+ // must be excluded; they share the dct- prefix but carry no catalog structure.
81
+ const files = listFilesRecursive(catalogPath)
82
+ .filter((f) => {
83
+ const name = f.split("/").pop() ?? "";
84
+ return /^dct-.+\.ya?ml$/i.test(name) && !isDctPlanFileName(name);
85
+ })
86
+ .sort();
87
+ const docs = [];
88
+ for (const filePath of files) {
89
+ try {
90
+ docs.push(load(readFileSync(filePath, "utf8")));
91
+ }
92
+ catch {
93
+ continue;
94
+ }
95
+ }
96
+ return docs;
97
+ }
98
+ // Resolve a `--deliverable` identifier (a bare `local_id`) to a catalog deliverable.
99
+ // `local_id` is unique project-wide (catalog validate warns otherwise); an ambiguous
100
+ // match is an error rather than a silent first match.
101
+ export function resolveDeliverableTarget(catalogPath, value) {
102
+ const localId = value.trim();
103
+ if (!localId)
104
+ throw new Error("deliverable identifier is empty");
105
+ const docs = loadCatalogDocs(catalogPath);
106
+ const matches = [];
107
+ for (const doc of docs) {
108
+ const info = searchSections(doc.groups, resolveBasePath("", doc.base_path), localId);
109
+ if (info)
110
+ matches.push({ domain: doc.domain, localId, slug: localId, info });
111
+ }
112
+ if (matches.length === 0)
113
+ throw new Error(`deliverable not found: ${localId}`);
114
+ if (matches.length > 1) {
115
+ const domains = matches.map((m) => m.domain).join(", ");
116
+ throw new Error(`ambiguous deliverable: ${localId} (defined in domains: ${domains}). ` +
117
+ `local_id must be unique project-wide; run catalog validate.`);
118
+ }
119
+ return matches[0];
120
+ }
121
+ export function loadViewpoints(viewpointsPath) {
122
+ if (!viewpointsPath || !existsSync(viewpointsPath))
123
+ return new Map();
124
+ const doc = resolveViewpointsDoc(viewpointsPath);
125
+ return new Map((doc.viewpoints ?? []).map((vp) => [vp.id, vp]));
126
+ }
127
+ export function loadRoles(rolesPath) {
128
+ if (!rolesPath || !existsSync(rolesPath))
129
+ return new Map();
130
+ try {
131
+ const doc = load(readFileSync(rolesPath, "utf8"));
132
+ return new Map((doc.roles ?? []).map((role) => [role.code, role]));
133
+ }
134
+ catch {
135
+ return new Map();
136
+ }
137
+ }
138
+ // Canonical repo-root-relative path: POSIX separators, no leading slash. Agents and
139
+ // tools resolve it from the run CWD (repo root for in-place, worktree root otherwise),
140
+ // so a leading slash (filesystem-absolute) must not be emitted.
141
+ export function repoRelativePath(absPath) {
142
+ return relative(specdojoRootDir(), absPath).replace(/\\/g, "/");
143
+ }
144
+ // ---------------------------------------------------------------------------
145
+ // Markdown builders
146
+ // ---------------------------------------------------------------------------
147
+ export function frontmatter(meta) {
148
+ const inner = [
149
+ `id: ${meta.id}`,
150
+ `type: ${meta.type}`,
151
+ `rulebook: ${meta.rulebook}`,
152
+ `task_id: ${meta.task_id}`,
153
+ ...(meta.name ? [`name: ${JSON.stringify(meta.name)}`] : []),
154
+ `mode: ${meta.mode}`,
155
+ `status: ${meta.status}`,
156
+ `project_id: ${meta.project_id}`,
157
+ ];
158
+ if (meta.origin)
159
+ inner.push(`origin: ${meta.origin}`);
160
+ if (meta.owner)
161
+ inner.push(`owner: ${meta.owner}`);
162
+ if (meta.on_critical_path)
163
+ inner.push(`on_critical_path: true`);
164
+ if (meta.approach)
165
+ inner.push(`approach: ${meta.approach}`);
166
+ if (meta.targets && meta.targets.length > 0) {
167
+ inner.push("targets:");
168
+ for (const target of meta.targets)
169
+ inner.push(` - ${target}`);
170
+ }
171
+ return buildSpecdojoFrontmatter(inner);
172
+ }
173
+ // ---------------------------------------------------------------------------
174
+ // Template-based generation (edit-plan / review-plan テンプレートの展開)
175
+ // ---------------------------------------------------------------------------
176
+ // Shared conventions (link notation など) appended to every generated plan. The plan is the
177
+ // only context guaranteed to reach the executing agent regardless of tool (it is piped via
178
+ // stdin), so cross-tool rules must travel with the plan rather than tool-specific instruction
179
+ // files. Kept as a single fragment to avoid duplicating the rule across every plan template.
180
+ const COMMON_CONVENTIONS_TEMPLATE = "xep-common-conventions-template.md";
181
+ export function execTemplatesDir() {
182
+ return resolveSpecdojoPath("docs/ja/specdojo/exec-templates");
183
+ }
184
+ export function execTemplatePath(fileName) {
185
+ return resolveSpecdojoPath(`docs/ja/specdojo/exec-templates/${fileName}`);
186
+ }
187
+ function templatePrefix(mode) {
188
+ return mode === "review" ? "xrp" : "xep";
189
+ }
190
+ function standardTemplateFileName(mode) {
191
+ return `${templatePrefix(mode)}-template.md`;
192
+ }
193
+ function approachTemplateFileName(mode, approach) {
194
+ return `${templatePrefix(mode)}-${approach}-template.md`;
195
+ }
196
+ // Selects <prefix>-<approach>-template.md when it exists, falling back
197
+ // to the standard <prefix>-template.md. Any missing variant falls through to the
198
+ // next candidate so a plan is always produced.
199
+ function resolvePlanTemplatePath(mode, approach) {
200
+ if (approach) {
201
+ const candidatePath = resolveSpecdojoPathIfExists(`docs/ja/specdojo/exec-templates/${approachTemplateFileName(mode, approach)}`);
202
+ if (candidatePath)
203
+ return candidatePath;
204
+ }
205
+ return execTemplatePath(standardTemplateFileName(mode));
206
+ }
207
+ function readTemplate(templatePath, cache) {
208
+ const cached = cache.get(templatePath);
209
+ if (cached !== undefined)
210
+ return cached;
211
+ if (!existsSync(templatePath)) {
212
+ throw new Error(`Template not found: ${templatePath}`);
213
+ }
214
+ const content = readFileSync(templatePath, "utf8");
215
+ cache.set(templatePath, content);
216
+ return content;
217
+ }
218
+ export function loadPlanTemplate(mode, approach, cache) {
219
+ return readTemplate(resolvePlanTemplatePath(mode, approach), cache);
220
+ }
221
+ // Marker a plan template places to control where the shared conventions fragment lands.
222
+ const COMMON_CONVENTIONS_PLACEHOLDER = "_COMMON_CONVENTIONS_";
223
+ // Lines delimiting the review-only block of the conventions fragment (review の判断手順). The
224
+ // block is kept, without the marker lines, in review plans and dropped from every other plan.
225
+ const REVIEW_ONLY_START = "<!-- review-only:start -->";
226
+ const REVIEW_ONLY_END = "<!-- review-only:end -->";
227
+ function selectReviewOnlyBlock(conventions, isReview) {
228
+ const kept = [];
229
+ let inside = false;
230
+ for (const line of conventions.split("\n")) {
231
+ const marker = line.trim();
232
+ if (marker === REVIEW_ONLY_START) {
233
+ inside = true;
234
+ continue;
235
+ }
236
+ if (marker === REVIEW_ONLY_END) {
237
+ inside = false;
238
+ continue;
239
+ }
240
+ if (!inside || isReview)
241
+ kept.push(line);
242
+ }
243
+ return kept
244
+ .join("\n")
245
+ .replace(/\n{3,}/g, "\n\n")
246
+ .trimEnd();
247
+ }
248
+ // Placeholder in the conventions fragment for the resolved schema path. The agent cannot derive
249
+ // the schema path on its own (it would have to hunt for it and risks burning its turn before
250
+ // filling the result), so the generator resolves it deterministically and bakes it in here.
251
+ const SCHEMA_REF_PLACEHOLDER = "_SCHEMA_REF_";
252
+ // Injects the shared conventions fragment into a built plan body so every generated plan carries
253
+ // the same rules (e.g. link notation) in its own text, independent of the executing tool. A
254
+ // template controls placement via the COMMON_CONVENTIONS_PLACEHOLDER marker; templates without the
255
+ // marker get the block appended so the rules are never silently dropped.
256
+ // schemaRef is the resolved schema path: when MISSING (non-yaml deliverable or no schema), the
257
+ // schema-validation bullet is dropped so the plan never asks for a check it cannot specify.
258
+ // mode selects whether the review-only block (review の判断手順) is kept; it defaults to edit so
259
+ // register / job plans never carry review instructions.
260
+ export function injectCommonConventions(body, schemaRef, cache, mode = "edit") {
261
+ let conventions = selectReviewOnlyBlock(readTemplate(execTemplatePath(COMMON_CONVENTIONS_TEMPLATE), cache), mode === "review");
262
+ conventions =
263
+ schemaRef === MISSING
264
+ ? conventions
265
+ .split("\n")
266
+ .filter((line) => !line.includes(SCHEMA_REF_PLACEHOLDER))
267
+ .join("\n")
268
+ : conventions.split(SCHEMA_REF_PLACEHOLDER).join(schemaRef);
269
+ if (body.includes(COMMON_CONVENTIONS_PLACEHOLDER)) {
270
+ return body.split(COMMON_CONVENTIONS_PLACEHOLDER).join(conventions);
271
+ }
272
+ return `${body.trimEnd()}\n\n${conventions}\n`;
273
+ }
274
+ export function phaseDescriptionText(task) {
275
+ if (task.description)
276
+ return task.description.trimEnd();
277
+ return task.name ?? task.id;
278
+ }
279
+ export function deliverablePath(deliverable) {
280
+ return deliverable?.resolvedPath ?? MISSING;
281
+ }
282
+ export function deliverableName(deliverable) {
283
+ return deliverable?.deliverable.name ?? MISSING;
284
+ }
285
+ export function gradeFindingsText(projectId, targetPath) {
286
+ if (!targetPath || targetPath === MISSING || !existsSync(join(specdojoRootDir(), targetPath))) {
287
+ return "- なし";
288
+ }
289
+ try {
290
+ const result = readGradeResultForDocument({ documentPath: targetPath, project: projectId });
291
+ if (!result || result.findings.length === 0)
292
+ return "- なし";
293
+ return result.findings
294
+ .map((finding) => `- ${finding.id} [${finding.severity}/${finding.rule}; line=${finding.line}; anchor=${JSON.stringify(finding.anchor)}]: ${gradeFindingDisplayMessage(finding)}`)
295
+ .join("\n");
296
+ }
297
+ catch {
298
+ return "- なし";
299
+ }
300
+ }
301
+ export function gradeFindingTargetPath(approach, deliverable, refs) {
302
+ if (approach === "rulebook-maintenance")
303
+ return refs.rulebook;
304
+ if (approach === "recipe-maintenance")
305
+ return refs.recipe;
306
+ if (approach === "sample-maintenance")
307
+ return refs.sample;
308
+ if (approach === "template-maintenance")
309
+ return refs.template;
310
+ return deliverablePath(deliverable);
311
+ }
312
+ // grade の --target。実践の型メンテナンス系は実践の型そのものを評価対象にする。
313
+ export function gradeTargetKind(approach) {
314
+ return approach === "rulebook-maintenance" ||
315
+ approach === "recipe-maintenance" ||
316
+ approach === "sample-maintenance" ||
317
+ approach === "template-maintenance"
318
+ ? "kata"
319
+ : "deliverable";
320
+ }
321
+ // review の前段で runner が grade を実行する評価対象(PJR-KCMH)。review plan の「評価結果」章と
322
+ // 同じ規則で決めるため、plan 生成と runner の実行対象が食い違わない。
323
+ export function reviewGradeSubject(catalogPath, task) {
324
+ const deliverable = task.local_id && catalogPath ? findDeliverableInfo(catalogPath, task.local_id) : null;
325
+ const refs = resolveKataRefs(deliverable?.deliverable.rulebook, deliverable?.deliverable.kind);
326
+ const path = gradeFindingTargetPath(task.approach, deliverable, refs);
327
+ if (!path || path === MISSING)
328
+ return undefined;
329
+ return { path, target: gradeTargetKind(task.approach) };
330
+ }
331
+ // review plan に提示する評価結果。runner の grade 実行結果があれば併記する。
332
+ export function reviewGradeSummaryText(projectId, subjectPath, outcome) {
333
+ return renderReviewGradeSummary(reviewGradeFreshness({
334
+ subjectPath: subjectPath === MISSING ? "" : subjectPath,
335
+ projectId,
336
+ rootDir: specdojoRootDir(),
337
+ }), outcome);
338
+ }
339
+ // 評価対象に対応する評価結果サイドカーのリポジトリ相対パス。評価対象が未作成、または
340
+ // frontmatter の id を解決できない場合は MISSING を返す(サイドカーの有無は問わない)。
341
+ export function gradeResultRef(projectId, subjectPath) {
342
+ if (!subjectPath || subjectPath === MISSING)
343
+ return MISSING;
344
+ if (!existsSync(join(specdojoRootDir(), subjectPath)))
345
+ return MISSING;
346
+ try {
347
+ return repoRelativePath(gradeResultPathForDocument({ documentPath: subjectPath, project: projectId }));
348
+ }
349
+ catch {
350
+ return MISSING;
351
+ }
352
+ }
353
+ // plan に表示する実践の型の状態。宣言からパスを解決できたがファイルが無い場合と、
354
+ // 宣言不足・対象外などでパス自体を解決できない場合を分ける。これにより executor は
355
+ // 既存文書の編集、宣言済みパスへの新規作成、前提確認が必要な状態を推測せず判別できる。
356
+ export function kataRefState(refPath) {
357
+ if (refPath === MISSING)
358
+ return "unresolved";
359
+ return existsSync(join(specdojoRootDir(), refPath)) ? "existing" : "missing";
360
+ }
361
+ // 対象成果物の depends_on を、依存先 doc の [[id]] 参照の入れ子リストで提示する。
362
+ // id は依存先の frontmatter、未作成なら配置規約から解決する。agent へ plan を渡すときに
363
+ // expandPromptRefs(src/exec-run.ts, format:'path')が
364
+ // この [[id]] を doc-index 経由でリポジトリ相対パスへ展開し、agent が先行成果物を直接開ける。
365
+ // テンプレート側はラベル直後にこの値を差し込むため、件数 0・成果物未解決時は先頭スペース付きの
366
+ // インライン値、依存ありの場合は改行始まりの入れ子リストを返す。
367
+ export function deliverableDependsOn(deliverable, projectId, catalogPath) {
368
+ if (!deliverable)
369
+ return ` ${MISSING}`;
370
+ const deps = deliverable.deliverable.depends_on ?? [];
371
+ if (deps.length === 0)
372
+ return " -";
373
+ const lines = deps.map((dep) => {
374
+ const info = findDeliverableInfo(catalogPath, dep);
375
+ return ` - [[${deliverableDocId(projectId, dep, info?.resolvedPath)}]]`;
376
+ });
377
+ return `\n${lines.join("\n")}`;
378
+ }
379
+ const PROJECT_CONTEXT_EXCLUDED_APPROACHES = new Set([
380
+ "cross-deliverable-dedup",
381
+ "rulebook-maintenance",
382
+ "recipe-maintenance",
383
+ "sample-maintenance",
384
+ "template-maintenance",
385
+ "finalize",
386
+ "bootstrap-finalize",
387
+ ]);
388
+ // Project context is project-level guidance, not an ordering/evidence edge. It is rendered only
389
+ // for deliverable edit/review work, separately from depends_on, and is deliberately omitted for
390
+ // maintenance/finalize work and when the target itself is the configured context document.
391
+ export function projectContextSection(refs, deliverable, approach, projectId) {
392
+ if (!deliverable || (approach && PROJECT_CONTEXT_EXCLUDED_APPROACHES.has(approach)))
393
+ return "";
394
+ const targetId = deliverableDocId(projectId, deliverable.deliverable.local_id, deliverable.resolvedPath);
395
+ const qualifiedRefs = [
396
+ ...new Set(refs
397
+ .map((ref) => ref.trim())
398
+ .filter(Boolean)
399
+ .map((ref) => (ref.includes(":") ? ref : qualifiedDocId(projectId, ref)))
400
+ .filter((ref) => ref !== targetId)),
401
+ ];
402
+ if (qualifiedRefs.length === 0)
403
+ return "";
404
+ return [
405
+ "### プロジェクトコンテキスト",
406
+ "",
407
+ "以下は `depends_on` とは独立したプロジェクト共通の文脈であり、実行順序・成果物間の根拠関係を表さない。作業開始前に実際に読み、プロジェクトレベルの Why、用語、判断原則と成果物の内容を整合させる。",
408
+ "",
409
+ ...qualifiedRefs.map((ref) => `- [[${ref}]]`),
410
+ "",
411
+ "プロジェクトレベルの Why は判断軸として参照し、全文を成果物へ再掲しない。対象成果物の責務に必要な結論・影響だけを反映する。",
412
+ ].join("\n");
413
+ }
414
+ export function deliverableOverview(deliverable) {
415
+ return deliverable?.deliverable.overview ?? MISSING;
416
+ }
417
+ export function implementationEvidence(deliverable) {
418
+ const refs = deliverable?.deliverable.evidence_refs ?? [];
419
+ if (refs.length === 0)
420
+ return MISSING;
421
+ return refs.map((ref) => `- \`${ref.path}\`(${ref.kind}): ${ref.purpose}`).join("\n");
422
+ }
423
+ // edit plan の「完了の狙い」用。一文書一責務のため、done_criteria を owner ロールの狙いと
424
+ // 下流ロールの入力適合に分けて提示する。owner の狙いを作成目標とし、下流は入力として最低限
425
+ // 成立させる範囲にとどめる(各ロールの内容を作り込まない)。下流の適合性検証や観点別の自己
426
+ // レビューは edit plan では行わず、多観点検証は独立した review plan に委ねる。
427
+ // owner が done_criteria に現れない場合は分割せず全件を素の箇条書きにフォールバックする。
428
+ export function doneCriteriaGoals(criteria, owner) {
429
+ if (criteria.length === 0)
430
+ return MISSING;
431
+ const ownerCriteria = owner ? criteria.filter((c) => c.roles.includes(owner)) : [];
432
+ if (ownerCriteria.length === 0) {
433
+ return criteria.map((c) => `- ${c.text}`).join("\n");
434
+ }
435
+ const downstream = criteria.filter((c) => !c.roles.includes(owner));
436
+ const lines = ["owner として達成する狙い:", ""];
437
+ for (const c of ownerCriteria)
438
+ lines.push(`- ${c.text}`);
439
+ if (downstream.length > 0) {
440
+ lines.push("");
441
+ lines.push("下流ロールの入力適合(最低ライン。各ロールの内容は作り込まず、入力として成立させる):");
442
+ lines.push("");
443
+ for (const c of downstream)
444
+ lines.push(`- [${c.roles.join(", ")}] ${c.text}`);
445
+ }
446
+ return lines.join("\n");
447
+ }
448
+ // done_criteria を人間の最終確認用チェックリストに整形する。owner/下流の分割はせず、
449
+ // 各項目を `- [ ] <text>` の素のチェック項目にする(human finalize は多観点の作り込みでは
450
+ // なく、完成版が done_criteria を満たすかの確認が目的のため)。criteria が空なら MISSING。
451
+ export function doneCriteriaChecklist(criteria) {
452
+ if (criteria.length === 0)
453
+ return MISSING;
454
+ return criteria.map((c) => `- [ ] ${c.text}`).join("\n");
455
+ }
456
+ // done_criteria を plan 提示用の素の箇条書きに整形する。チェックの記録は result 側の
457
+ // チェックリストで行うため、plan では「何を確認するか」の列挙にとどめる。
458
+ export function doneCriteriaItems(criteria) {
459
+ if (criteria.length === 0)
460
+ return MISSING;
461
+ return criteria.map((c) => `- ${c.text}`).join("\n");
462
+ }
463
+ // 主 rulebook が include する rulebook を plan へ注入する表記に整形する。
464
+ // 併せて適用する rulebook(記法など)を backtick 付きパスのカンマ区切りで示す。
465
+ // include が無い場合は他の参照と同様に MISSING を返す。
466
+ export function rulebookIncludesText(rulebookId, targetKind) {
467
+ if (targetKind === "generated")
468
+ return MISSING;
469
+ const paths = resolveIncludedRulebooks(rulebookId);
470
+ if (paths.length === 0)
471
+ return MISSING;
472
+ return paths.map((p) => `\`${p}\``).join(", ");
473
+ }
474
+ // 実践の型の doc id を正準パス(docs/ja/specdojo/<kind>s/<id>.<ext>)の basename から導出する。
475
+ // 実践の型の frontmatter id はファイル名と一致する規約(specdojo:docs-structure-guide)を前提にする。
476
+ function refDocIdFromPath(refPath) {
477
+ const localId = basename(refPath).replace(/\.(md|yaml|json)$/, "");
478
+ const parts = refPath.split("/");
479
+ const authority = parts[0] === "docs" && /^[a-z]{2}$/.test(parts[1] ?? "")
480
+ ? parts[2]
481
+ : SPECDOJO_PRACTICE_AUTHORITY;
482
+ return qualifyPracticeId(authority ?? SPECDOJO_PRACTICE_AUTHORITY, localId);
483
+ }
484
+ // approach ごとに、成果物に加えて変更・確定の対象になる実践の型の種別。
485
+ const TARGET_REF_KINDS = {
486
+ bootstrap: ["rulebook", "recipe", "sample", "template"],
487
+ "bootstrap-finalize": ["rulebook", "recipe", "sample", "template"],
488
+ "rulebook-maintenance": ["rulebook"],
489
+ "recipe-maintenance": ["recipe"],
490
+ "sample-maintenance": ["sample"],
491
+ "template-maintenance": ["template"],
492
+ };
493
+ function qualifiedDocId(projectId, localId) {
494
+ return projectId ? `${projectId}:${localId}` : localId;
495
+ }
496
+ // 成果物の doc id は、既存文書では frontmatter を正本とする。author 前など文書が
497
+ // 未作成の場合は配置規約に従い、product 配下だけをローカル ID、projects 配下を含む
498
+ // その他の配置を従来どおり project 修飾 ID とする。
499
+ export function deliverableDocId(projectId, localId, resolvedPath) {
500
+ if (resolvedPath) {
501
+ const absolutePath = resolve(specdojoRootDir(), resolvedPath);
502
+ if (existsSync(absolutePath)) {
503
+ try {
504
+ const id = readSpecdojoNamespace(readFileSync(absolutePath, "utf8")).id;
505
+ if (typeof id === "string" && id.trim())
506
+ return id.trim();
507
+ }
508
+ catch {
509
+ // 読み取り不能・不正 frontmatter は配置によるフォールバックへ進む。
510
+ }
511
+ }
512
+ const normalizedPath = resolvedPath.replaceAll("\\", "/").replace(/^\/+/, "");
513
+ if (/^docs\/[a-z]{2}\/product(?:\/|$)/.test(normalizedPath))
514
+ return localId;
515
+ }
516
+ return qualifiedDocId(projectId, localId);
517
+ }
518
+ // タスクが対象とする文書の doc id リスト。先頭は対象成果物(配置に対応する doc id)、
519
+ // 以降は approach に応じて変更・確定しうる実践の型の doc id。いずれも doc-index で
520
+ // パスへ解決できる id にし、schedule やファイル名の命名規約に依存せず対象を機械的に
521
+ // 取得できるようにする。解決できない実践の型(_MISSING_)は含めない。
522
+ // targets は frontmatter の必須項目のため、catalog で成果物を解決できない場合も
523
+ // fallbackLocalId から成果物の doc id だけは組み立てる。
524
+ export function targetDocIds(projectId, deliverable, approach, fallbackLocalId) {
525
+ if (!deliverable) {
526
+ return fallbackLocalId ? [qualifiedDocId(projectId, fallbackLocalId)] : [];
527
+ }
528
+ const ids = [
529
+ deliverableDocId(projectId, deliverable.deliverable.local_id, deliverable.resolvedPath),
530
+ ];
531
+ const kinds = approach ? (TARGET_REF_KINDS[approach] ?? []) : [];
532
+ if (kinds.length === 0)
533
+ return ids;
534
+ const refs = resolveKataRefs(deliverable.deliverable.rulebook, deliverable.deliverable.kind);
535
+ for (const kind of kinds) {
536
+ const refPath = refs[kind];
537
+ if (refPath !== MISSING)
538
+ ids.push(refDocIdFromPath(refPath));
539
+ }
540
+ return ids;
541
+ }
542
+ export function targetDocIdsForTask(projectId, task, deliverable, crossDeliverables) {
543
+ if (task.target_local_ids && task.target_local_ids.length > 0) {
544
+ return [...new Set(task.target_local_ids)].map((localId) => {
545
+ const info = crossDeliverables.get(localId);
546
+ return deliverableDocId(projectId, localId, info?.resolvedPath);
547
+ });
548
+ }
549
+ return targetDocIds(projectId, deliverable, task.approach, task.local_id);
550
+ }
551
+ // approach が実践の型の変更を伴う場合に、変更を許可するディレクトリ(repo ルート相対)。
552
+ // commit 許可リスト(exec-worktree-ops)から使う。
553
+ export function targetReferenceDirsForApproach(approach) {
554
+ const kinds = approach ? (TARGET_REF_KINDS[approach] ?? []) : [];
555
+ return kataDirsForKinds(kinds);
556
+ }
557
+ // catalog から成果物 local_id の文書パス(repo ルート相対)を解決する。
558
+ // 未作成の成果物でも catalog が宣言するパスを返せるため、doc-index に載る前の
559
+ // 新規成果物の commit 許可判定に使う。
560
+ export function deliverableDocPath(catalogPath, localId) {
561
+ return findDeliverableInfo(catalogPath, localId)?.resolvedPath;
562
+ }
563
+ // Resolve the target doc ids for a deliverable by local_id (result scaffold 用)。
564
+ // localId が不明な場合のみ undefined を返す。catalog で成果物を解決できない場合は
565
+ // 成果物の doc id 1 件へフォールバックする(targets は必須項目のため)。
566
+ export function targetDocIdsForDeliverable(catalogPath, localId, projectId, approach) {
567
+ if (!localId)
568
+ return undefined;
569
+ const info = catalogPath ? findDeliverableInfo(catalogPath, localId) : null;
570
+ const ids = targetDocIds(projectId, info, approach, localId);
571
+ return ids.length > 0 ? ids : undefined;
572
+ }
573
+ // Resolve every target of a scheduled task. Cross-deliverable tasks carry an explicit
574
+ // target_local_ids list; ordinary tasks keep the single-deliverable/reference-material behavior.
575
+ export function targetDocIdsForScheduledTask(catalogPath, task, projectId) {
576
+ if (task.target_local_ids && task.target_local_ids.length > 0) {
577
+ const ids = [...new Set(task.target_local_ids)].map((localId) => {
578
+ const info = findDeliverableInfo(catalogPath, localId);
579
+ return deliverableDocId(projectId, localId, info?.resolvedPath);
580
+ });
581
+ return ids.length > 0 ? ids : undefined;
582
+ }
583
+ return targetDocIdsForDeliverable(catalogPath, task.local_id, projectId, task.approach);
584
+ }
585
+ export function crossDeliverableTargetDetails(projectId, localIds, deliverables, catalogPath) {
586
+ const lines = [];
587
+ for (const localId of localIds) {
588
+ const info = deliverables.get(localId);
589
+ const docId = deliverableDocId(projectId, localId, info?.resolvedPath);
590
+ lines.push(`### ${docId}`);
591
+ lines.push("");
592
+ lines.push(`- document: [[${docId}]]`);
593
+ lines.push(`- name: ${deliverableName(info ?? null)}`);
594
+ lines.push(`- path: \`${deliverablePath(info ?? null)}\``);
595
+ lines.push(`- overview: ${deliverableOverview(info ?? null)}`);
596
+ lines.push(`- depends_on:${deliverableDependsOn(info ?? null, projectId, catalogPath)}`);
597
+ lines.push("- done_criteria:");
598
+ const criteria = info?.deliverable.done_criteria ?? [];
599
+ if (criteria.length === 0)
600
+ lines.push(` - ${MISSING}`);
601
+ else {
602
+ for (const criterion of criteria) {
603
+ lines.push(` - [${criterion.roles.join(", ")} / ${criterion.viewpoint}] ${criterion.text}`);
604
+ }
605
+ }
606
+ lines.push("");
607
+ }
608
+ return lines.join("\n").trimEnd();
609
+ }
610
+ // review plan の完了条件表の行。review は観点ごとに評価せず、done_criteria をタスクの
611
+ // 完了条件として照合するため、ID は DC-NNN とする。
612
+ export function reviewDoneCriteriaRows(criteria) {
613
+ if (criteria.length === 0)
614
+ return MISSING;
615
+ const lines = [];
616
+ criteria.forEach((c, i) => {
617
+ const criterionId = `DC-${String(i + 1).padStart(3, "0")}`;
618
+ lines.push(`| ${criterionId} | ${c.roles.join(", ")} | ${c.viewpoint} | ${c.text} |`);
619
+ });
620
+ return lines.join("\n");
621
+ }
622
+ export function applicableReviewCriteria(criteria, vpMap, rulebook) {
623
+ const metadata = rulebook ? { rulebook } : {};
624
+ return criteria.filter((criterion) => {
625
+ const viewpoint = vpMap.get(criterion.viewpoint);
626
+ return viewpoint === undefined || viewpointAppliesToDocument(viewpoint, metadata);
627
+ });
628
+ }
629
+ // done_criteria を確認記録用チェックボックスに整形する。各項目に roles / viewpoint
630
+ // (review-viewpoints の観点 ID)を注記し、どの観点で確認したかが result に残るようにする。
631
+ function doneCriteriaResultChecklist(criteria) {
632
+ return criteria
633
+ .map((c) => {
634
+ const annotation = [c.roles.join(", "), c.viewpoint].filter(Boolean).join(" / ");
635
+ return annotation ? `- [ ] ${c.text}(${annotation})` : `- [ ] ${c.text}`;
636
+ })
637
+ .join("\n");
638
+ }
639
+ // 確定対象(status を ready へ昇格する対象)のチェックリスト。成果物を先頭に、
640
+ // bootstrap-finalize では解決できた実践の型(_MISSING_ 以外)を続ける。
641
+ function finalizeTargetsChecklist(deliverable, approach) {
642
+ const lines = [`- [ ] 成果物: \`${deliverablePath(deliverable)}\``];
643
+ if (approach === "bootstrap-finalize") {
644
+ const refs = resolveKataRefs(deliverable.deliverable.rulebook, deliverable.deliverable.kind);
645
+ const entries = [
646
+ ["rulebook", refs.rulebook],
647
+ ["recipe", refs.recipe],
648
+ ["sample", refs.sample],
649
+ ["template", refs.template],
650
+ ];
651
+ for (const [kind, ref] of entries) {
652
+ if (ref !== MISSING)
653
+ lines.push(`- [ ] ${kind}: \`${ref}\``);
654
+ }
655
+ }
656
+ return lines.join("\n");
657
+ }
658
+ // Resolve the finalize result sections for a deliverable by local_id. Returns undefined when
659
+ // the catalog, deliverable, or its done_criteria cannot be resolved; the caller then falls
660
+ // back to a generic result body (placeholders stay _TODO_).
661
+ export function finalizeResultSectionsForDeliverable(catalogPath, localId, approach) {
662
+ if (!catalogPath || !localId)
663
+ return undefined;
664
+ const info = findDeliverableInfo(catalogPath, localId);
665
+ if (!info)
666
+ return undefined;
667
+ const criteria = info.deliverable.done_criteria ?? [];
668
+ if (criteria.length === 0)
669
+ return undefined;
670
+ return {
671
+ doneCriteriaChecklist: doneCriteriaResultChecklist(criteria),
672
+ targetsChecklist: finalizeTargetsChecklist(info, approach),
673
+ };
674
+ }
675
+ // owner の Role code から、pm-roles.yaml の責務(project_note)と
676
+ // pm-review-viewpoints.yaml の該当 role 観点を取り出す。owner 未設定や情報欠落時は
677
+ // 他のプレースホルダと同様に MISSING を返し、表示構造はテンプレート側に委ねる。
678
+ export function ownerRoleFields(owner, roleMap, vpMap, rulebook) {
679
+ if (!owner) {
680
+ return { label: MISSING, note: MISSING, viewpoints: MISSING };
681
+ }
682
+ const role = roleMap.get(owner);
683
+ const label = role?.name ? `${owner}(${role.name})` : owner;
684
+ const note = role?.project_note ?? MISSING;
685
+ const metadata = rulebook ? { rulebook } : {};
686
+ const roleViewpoints = [...vpMap.values()].filter((vp) => vp.role === owner && viewpointAppliesToDocument(vp, metadata));
687
+ const viewpoints = roleViewpoints.length > 0
688
+ ? roleViewpoints.map((vp) => `- ${vp.title}: ${vp.check}`).join("\n")
689
+ : MISSING;
690
+ return { label, note, viewpoints };
691
+ }
692
+ // edit plan は観点別の自己レビューを行わない。done_criteria は §3 の owner 視点とは別に
693
+ // 「完了の狙い」として素の箇条書きで提示し、多観点検証は独立した review plan に委ねる。