@sienklogic/plan-build-run 2.0.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 (221) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/CLAUDE.md +149 -0
  3. package/LICENSE +21 -0
  4. package/README.md +247 -0
  5. package/dashboard/bin/cli.js +25 -0
  6. package/dashboard/package.json +34 -0
  7. package/dashboard/public/.gitkeep +0 -0
  8. package/dashboard/public/css/layout.css +406 -0
  9. package/dashboard/public/css/status-colors.css +98 -0
  10. package/dashboard/public/js/htmx-title.js +5 -0
  11. package/dashboard/public/js/sidebar-toggle.js +20 -0
  12. package/dashboard/src/app.js +78 -0
  13. package/dashboard/src/middleware/errorHandler.js +52 -0
  14. package/dashboard/src/middleware/notFoundHandler.js +9 -0
  15. package/dashboard/src/repositories/planning.repository.js +128 -0
  16. package/dashboard/src/routes/events.routes.js +40 -0
  17. package/dashboard/src/routes/index.routes.js +31 -0
  18. package/dashboard/src/routes/pages.routes.js +195 -0
  19. package/dashboard/src/server.js +42 -0
  20. package/dashboard/src/services/dashboard.service.js +222 -0
  21. package/dashboard/src/services/phase.service.js +167 -0
  22. package/dashboard/src/services/project.service.js +57 -0
  23. package/dashboard/src/services/roadmap.service.js +171 -0
  24. package/dashboard/src/services/sse.service.js +58 -0
  25. package/dashboard/src/services/todo.service.js +254 -0
  26. package/dashboard/src/services/watcher.service.js +48 -0
  27. package/dashboard/src/views/coming-soon.ejs +11 -0
  28. package/dashboard/src/views/error.ejs +13 -0
  29. package/dashboard/src/views/index.ejs +5 -0
  30. package/dashboard/src/views/layout.ejs +1 -0
  31. package/dashboard/src/views/partials/dashboard-content.ejs +77 -0
  32. package/dashboard/src/views/partials/footer.ejs +3 -0
  33. package/dashboard/src/views/partials/head.ejs +21 -0
  34. package/dashboard/src/views/partials/header.ejs +12 -0
  35. package/dashboard/src/views/partials/layout-bottom.ejs +15 -0
  36. package/dashboard/src/views/partials/layout-top.ejs +8 -0
  37. package/dashboard/src/views/partials/phase-content.ejs +181 -0
  38. package/dashboard/src/views/partials/phases-content.ejs +117 -0
  39. package/dashboard/src/views/partials/roadmap-content.ejs +142 -0
  40. package/dashboard/src/views/partials/sidebar.ejs +38 -0
  41. package/dashboard/src/views/partials/todo-create-content.ejs +53 -0
  42. package/dashboard/src/views/partials/todo-detail-content.ejs +38 -0
  43. package/dashboard/src/views/partials/todos-content.ejs +53 -0
  44. package/dashboard/src/views/phase-detail.ejs +5 -0
  45. package/dashboard/src/views/phases.ejs +5 -0
  46. package/dashboard/src/views/roadmap.ejs +5 -0
  47. package/dashboard/src/views/todo-create.ejs +5 -0
  48. package/dashboard/src/views/todo-detail.ejs +5 -0
  49. package/dashboard/src/views/todos.ejs +5 -0
  50. package/package.json +57 -0
  51. package/plugins/pbr/.claude-plugin/plugin.json +13 -0
  52. package/plugins/pbr/UI-CONSISTENCY-GAPS.md +61 -0
  53. package/plugins/pbr/agents/codebase-mapper.md +271 -0
  54. package/plugins/pbr/agents/debugger.md +281 -0
  55. package/plugins/pbr/agents/executor.md +407 -0
  56. package/plugins/pbr/agents/general.md +164 -0
  57. package/plugins/pbr/agents/integration-checker.md +141 -0
  58. package/plugins/pbr/agents/plan-checker.md +280 -0
  59. package/plugins/pbr/agents/planner.md +358 -0
  60. package/plugins/pbr/agents/researcher.md +363 -0
  61. package/plugins/pbr/agents/synthesizer.md +230 -0
  62. package/plugins/pbr/agents/verifier.md +454 -0
  63. package/plugins/pbr/commands/begin.md +5 -0
  64. package/plugins/pbr/commands/build.md +5 -0
  65. package/plugins/pbr/commands/config.md +5 -0
  66. package/plugins/pbr/commands/continue.md +5 -0
  67. package/plugins/pbr/commands/debug.md +5 -0
  68. package/plugins/pbr/commands/discuss.md +5 -0
  69. package/plugins/pbr/commands/explore.md +5 -0
  70. package/plugins/pbr/commands/health.md +5 -0
  71. package/plugins/pbr/commands/help.md +5 -0
  72. package/plugins/pbr/commands/import.md +5 -0
  73. package/plugins/pbr/commands/milestone.md +5 -0
  74. package/plugins/pbr/commands/note.md +5 -0
  75. package/plugins/pbr/commands/pause.md +5 -0
  76. package/plugins/pbr/commands/plan.md +5 -0
  77. package/plugins/pbr/commands/quick.md +5 -0
  78. package/plugins/pbr/commands/resume.md +5 -0
  79. package/plugins/pbr/commands/review.md +5 -0
  80. package/plugins/pbr/commands/scan.md +5 -0
  81. package/plugins/pbr/commands/setup.md +5 -0
  82. package/plugins/pbr/commands/status.md +5 -0
  83. package/plugins/pbr/commands/todo.md +5 -0
  84. package/plugins/pbr/contexts/dev.md +27 -0
  85. package/plugins/pbr/contexts/research.md +28 -0
  86. package/plugins/pbr/contexts/review.md +36 -0
  87. package/plugins/pbr/hooks/hooks.json +183 -0
  88. package/plugins/pbr/references/agent-anti-patterns.md +24 -0
  89. package/plugins/pbr/references/agent-interactions.md +134 -0
  90. package/plugins/pbr/references/agent-teams.md +54 -0
  91. package/plugins/pbr/references/checkpoints.md +157 -0
  92. package/plugins/pbr/references/common-bug-patterns.md +13 -0
  93. package/plugins/pbr/references/continuation-format.md +212 -0
  94. package/plugins/pbr/references/deviation-rules.md +112 -0
  95. package/plugins/pbr/references/git-integration.md +226 -0
  96. package/plugins/pbr/references/integration-patterns.md +117 -0
  97. package/plugins/pbr/references/model-profiles.md +99 -0
  98. package/plugins/pbr/references/model-selection.md +31 -0
  99. package/plugins/pbr/references/pbr-rules.md +193 -0
  100. package/plugins/pbr/references/plan-authoring.md +181 -0
  101. package/plugins/pbr/references/plan-format.md +283 -0
  102. package/plugins/pbr/references/planning-config.md +213 -0
  103. package/plugins/pbr/references/questioning.md +214 -0
  104. package/plugins/pbr/references/reading-verification.md +127 -0
  105. package/plugins/pbr/references/stub-patterns.md +160 -0
  106. package/plugins/pbr/references/subagent-coordination.md +119 -0
  107. package/plugins/pbr/references/ui-formatting.md +399 -0
  108. package/plugins/pbr/references/verification-patterns.md +198 -0
  109. package/plugins/pbr/references/wave-execution.md +95 -0
  110. package/plugins/pbr/scripts/auto-continue.js +80 -0
  111. package/plugins/pbr/scripts/check-dangerous-commands.js +136 -0
  112. package/plugins/pbr/scripts/check-doc-sprawl.js +102 -0
  113. package/plugins/pbr/scripts/check-phase-boundary.js +196 -0
  114. package/plugins/pbr/scripts/check-plan-format.js +270 -0
  115. package/plugins/pbr/scripts/check-roadmap-sync.js +252 -0
  116. package/plugins/pbr/scripts/check-skill-workflow.js +262 -0
  117. package/plugins/pbr/scripts/check-state-sync.js +476 -0
  118. package/plugins/pbr/scripts/check-subagent-output.js +144 -0
  119. package/plugins/pbr/scripts/config-schema.json +251 -0
  120. package/plugins/pbr/scripts/context-budget-check.js +287 -0
  121. package/plugins/pbr/scripts/event-handler.js +151 -0
  122. package/plugins/pbr/scripts/event-logger.js +92 -0
  123. package/plugins/pbr/scripts/hook-logger.js +76 -0
  124. package/plugins/pbr/scripts/hooks-schema.json +79 -0
  125. package/plugins/pbr/scripts/log-subagent.js +152 -0
  126. package/plugins/pbr/scripts/log-tool-failure.js +88 -0
  127. package/plugins/pbr/scripts/pbr-tools.js +1301 -0
  128. package/plugins/pbr/scripts/post-write-dispatch.js +66 -0
  129. package/plugins/pbr/scripts/post-write-quality.js +207 -0
  130. package/plugins/pbr/scripts/pre-bash-dispatch.js +56 -0
  131. package/plugins/pbr/scripts/pre-write-dispatch.js +62 -0
  132. package/plugins/pbr/scripts/progress-tracker.js +228 -0
  133. package/plugins/pbr/scripts/session-cleanup.js +254 -0
  134. package/plugins/pbr/scripts/status-line.js +285 -0
  135. package/plugins/pbr/scripts/suggest-compact.js +119 -0
  136. package/plugins/pbr/scripts/task-completed.js +45 -0
  137. package/plugins/pbr/scripts/track-context-budget.js +119 -0
  138. package/plugins/pbr/scripts/validate-commit.js +200 -0
  139. package/plugins/pbr/scripts/validate-plugin-structure.js +172 -0
  140. package/plugins/pbr/skills/begin/SKILL.md +545 -0
  141. package/plugins/pbr/skills/begin/templates/PROJECT.md.tmpl +33 -0
  142. package/plugins/pbr/skills/begin/templates/REQUIREMENTS.md.tmpl +18 -0
  143. package/plugins/pbr/skills/begin/templates/STATE.md.tmpl +49 -0
  144. package/plugins/pbr/skills/begin/templates/config.json.tmpl +63 -0
  145. package/plugins/pbr/skills/begin/templates/researcher-prompt.md.tmpl +19 -0
  146. package/plugins/pbr/skills/begin/templates/roadmap-prompt.md.tmpl +30 -0
  147. package/plugins/pbr/skills/begin/templates/synthesis-prompt.md.tmpl +16 -0
  148. package/plugins/pbr/skills/build/SKILL.md +962 -0
  149. package/plugins/pbr/skills/config/SKILL.md +241 -0
  150. package/plugins/pbr/skills/continue/SKILL.md +127 -0
  151. package/plugins/pbr/skills/debug/SKILL.md +489 -0
  152. package/plugins/pbr/skills/debug/templates/continuation-prompt.md.tmpl +16 -0
  153. package/plugins/pbr/skills/debug/templates/initial-investigation-prompt.md.tmpl +27 -0
  154. package/plugins/pbr/skills/discuss/SKILL.md +338 -0
  155. package/plugins/pbr/skills/discuss/templates/CONTEXT.md.tmpl +61 -0
  156. package/plugins/pbr/skills/discuss/templates/decision-categories.md +9 -0
  157. package/plugins/pbr/skills/explore/SKILL.md +362 -0
  158. package/plugins/pbr/skills/health/SKILL.md +186 -0
  159. package/plugins/pbr/skills/health/templates/check-pattern.md.tmpl +30 -0
  160. package/plugins/pbr/skills/health/templates/output-format.md.tmpl +63 -0
  161. package/plugins/pbr/skills/help/SKILL.md +140 -0
  162. package/plugins/pbr/skills/import/SKILL.md +490 -0
  163. package/plugins/pbr/skills/milestone/SKILL.md +673 -0
  164. package/plugins/pbr/skills/milestone/templates/audit-report.md.tmpl +48 -0
  165. package/plugins/pbr/skills/milestone/templates/stats-file.md.tmpl +30 -0
  166. package/plugins/pbr/skills/note/SKILL.md +212 -0
  167. package/plugins/pbr/skills/pause/SKILL.md +235 -0
  168. package/plugins/pbr/skills/pause/templates/continue-here.md.tmpl +71 -0
  169. package/plugins/pbr/skills/plan/SKILL.md +628 -0
  170. package/plugins/pbr/skills/plan/decimal-phase-calc.md +98 -0
  171. package/plugins/pbr/skills/plan/templates/checker-prompt.md.tmpl +21 -0
  172. package/plugins/pbr/skills/plan/templates/gap-closure-prompt.md.tmpl +32 -0
  173. package/plugins/pbr/skills/plan/templates/planner-prompt.md.tmpl +38 -0
  174. package/plugins/pbr/skills/plan/templates/researcher-prompt.md.tmpl +19 -0
  175. package/plugins/pbr/skills/plan/templates/revision-prompt.md.tmpl +23 -0
  176. package/plugins/pbr/skills/quick/SKILL.md +335 -0
  177. package/plugins/pbr/skills/resume/SKILL.md +388 -0
  178. package/plugins/pbr/skills/review/SKILL.md +652 -0
  179. package/plugins/pbr/skills/review/templates/debugger-prompt.md.tmpl +60 -0
  180. package/plugins/pbr/skills/review/templates/gap-planner-prompt.md.tmpl +40 -0
  181. package/plugins/pbr/skills/review/templates/verifier-prompt.md.tmpl +115 -0
  182. package/plugins/pbr/skills/scan/SKILL.md +269 -0
  183. package/plugins/pbr/skills/scan/templates/mapper-prompt.md.tmpl +201 -0
  184. package/plugins/pbr/skills/setup/SKILL.md +227 -0
  185. package/plugins/pbr/skills/shared/commit-planning-docs.md +35 -0
  186. package/plugins/pbr/skills/shared/config-loading.md +102 -0
  187. package/plugins/pbr/skills/shared/context-budget.md +40 -0
  188. package/plugins/pbr/skills/shared/context-loader-task.md +86 -0
  189. package/plugins/pbr/skills/shared/digest-select.md +79 -0
  190. package/plugins/pbr/skills/shared/domain-probes.md +125 -0
  191. package/plugins/pbr/skills/shared/error-reporting.md +79 -0
  192. package/plugins/pbr/skills/shared/gate-prompts.md +388 -0
  193. package/plugins/pbr/skills/shared/phase-argument-parsing.md +45 -0
  194. package/plugins/pbr/skills/shared/progress-display.md +53 -0
  195. package/plugins/pbr/skills/shared/revision-loop.md +81 -0
  196. package/plugins/pbr/skills/shared/state-loading.md +62 -0
  197. package/plugins/pbr/skills/shared/state-update.md +161 -0
  198. package/plugins/pbr/skills/shared/universal-anti-patterns.md +33 -0
  199. package/plugins/pbr/skills/status/SKILL.md +353 -0
  200. package/plugins/pbr/skills/todo/SKILL.md +181 -0
  201. package/plugins/pbr/templates/CONTEXT.md.tmpl +52 -0
  202. package/plugins/pbr/templates/INTEGRATION-REPORT.md.tmpl +151 -0
  203. package/plugins/pbr/templates/RESEARCH-SUMMARY.md.tmpl +97 -0
  204. package/plugins/pbr/templates/ROADMAP.md.tmpl +40 -0
  205. package/plugins/pbr/templates/SUMMARY.md.tmpl +81 -0
  206. package/plugins/pbr/templates/VERIFICATION-DETAIL.md.tmpl +116 -0
  207. package/plugins/pbr/templates/codebase/ARCHITECTURE.md.tmpl +98 -0
  208. package/plugins/pbr/templates/codebase/CONCERNS.md.tmpl +93 -0
  209. package/plugins/pbr/templates/codebase/CONVENTIONS.md.tmpl +104 -0
  210. package/plugins/pbr/templates/codebase/INTEGRATIONS.md.tmpl +78 -0
  211. package/plugins/pbr/templates/codebase/STACK.md.tmpl +78 -0
  212. package/plugins/pbr/templates/codebase/STRUCTURE.md.tmpl +80 -0
  213. package/plugins/pbr/templates/codebase/TESTING.md.tmpl +107 -0
  214. package/plugins/pbr/templates/continue-here.md.tmpl +73 -0
  215. package/plugins/pbr/templates/prompt-partials/phase-project-context.md.tmpl +37 -0
  216. package/plugins/pbr/templates/research/ARCHITECTURE.md.tmpl +124 -0
  217. package/plugins/pbr/templates/research/STACK.md.tmpl +71 -0
  218. package/plugins/pbr/templates/research/SUMMARY.md.tmpl +112 -0
  219. package/plugins/pbr/templates/research-outputs/phase-research.md.tmpl +81 -0
  220. package/plugins/pbr/templates/research-outputs/project-research.md.tmpl +99 -0
  221. package/plugins/pbr/templates/research-outputs/synthesis.md.tmpl +36 -0
@@ -0,0 +1,167 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { readMarkdownFile } from '../repositories/planning.repository.js';
4
+
5
+ /**
6
+ * Format a phase directory name into a human-readable title.
7
+ * Strips the numeric prefix and title-cases each word.
8
+ *
9
+ * @param {string} dirName - Directory name like "04-dashboard-landing-page"
10
+ * @returns {string} Formatted name like "Dashboard Landing Page"
11
+ */
12
+ function formatPhaseName(dirName) {
13
+ const parts = dirName.split('-');
14
+ // Remove the numeric prefix (first element)
15
+ parts.shift();
16
+ return parts
17
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
18
+ .join(' ');
19
+ }
20
+
21
+ /**
22
+ * Parse the "Task Results" markdown table from a SUMMARY.md body.
23
+ * Returns an array of commit objects extracted from the table rows.
24
+ *
25
+ * Expected table format (produced by pbr executor):
26
+ * | Task | Status | Commit | Files | Verify |
27
+ * |------|--------|--------|-------|--------|
28
+ * | 05-01-T1: Create phase.service.js | done | 2a52581 | 1 | passed |
29
+ *
30
+ * @param {string} rawContent - The markdown body content (after frontmatter)
31
+ * @returns {Array<{task: string, status: string, hash: string, files: number, verify: string}>}
32
+ */
33
+ export function parseTaskResultsTable(rawContent) {
34
+ if (!rawContent) return [];
35
+
36
+ // Find the Task Results section. The table may be followed by another section,
37
+ // a blank line, or EOF. Use a non-greedy match to capture just the table block.
38
+ const sectionRegex = /## Task Results\s*\n([\s\S]*?)(?=\n##\s|\n\n\n|$)/;
39
+ const sectionMatch = rawContent.match(sectionRegex);
40
+ if (!sectionMatch) return [];
41
+
42
+ const tableBlock = sectionMatch[1].trim();
43
+ const lines = tableBlock.split('\n');
44
+
45
+ // Need at least header row + separator row + 1 data row = 3 lines
46
+ if (lines.length < 3) return [];
47
+
48
+ // Skip header row (index 0) and separator row (index 1)
49
+ const dataRows = lines.slice(2);
50
+ const commits = [];
51
+
52
+ for (const row of dataRows) {
53
+ // Split by pipe, trim, filter out empty strings from leading/trailing pipes
54
+ const cells = row.split('|').map(c => c.trim()).filter(c => c);
55
+ if (cells.length < 5) continue;
56
+
57
+ const hash = cells[2];
58
+ // Skip rows where commit is empty, a dash, or not a hex string
59
+ if (!hash || hash === '-' || hash === '' || !/^[0-9a-f]{5,40}$/i.test(hash)) continue;
60
+
61
+ commits.push({
62
+ task: cells[0],
63
+ status: cells[1],
64
+ hash: hash,
65
+ files: parseInt(cells[3], 10) || 0,
66
+ verify: cells[4]
67
+ });
68
+ }
69
+
70
+ return commits;
71
+ }
72
+
73
+ /**
74
+ * Get detailed information about a specific phase, including all plans,
75
+ * their summaries, and verification status.
76
+ *
77
+ * @param {string} projectDir - Absolute path to the project root
78
+ * @param {string} phaseId - Two-digit phase identifier (e.g., "04")
79
+ * @returns {Promise<{phaseId: string, phaseName: string, phaseDir: string|null, plans: Array, verification: object|null}>}
80
+ */
81
+ export async function getPhaseDetail(projectDir, phaseId) {
82
+ const emptyState = { phaseId, phaseName: 'Unknown', phaseDir: null, plans: [], verification: null };
83
+ const phasesDir = join(projectDir, '.planning', 'phases');
84
+
85
+ let phaseDirEntries;
86
+ try {
87
+ phaseDirEntries = await readdir(phasesDir, { withFileTypes: true });
88
+ } catch (error) {
89
+ if (error.code === 'ENOENT') {
90
+ return emptyState;
91
+ }
92
+ throw error;
93
+ }
94
+
95
+ // Find the directory matching this phaseId (prefer longest name to handle stale renames)
96
+ const phaseDir = phaseDirEntries
97
+ .filter(entry => entry.isDirectory() && entry.name.startsWith(`${phaseId}-`))
98
+ .sort((a, b) => b.name.length - a.name.length)
99
+ [0];
100
+
101
+ if (!phaseDir) {
102
+ return emptyState;
103
+ }
104
+
105
+ const phaseName = formatPhaseName(phaseDir.name);
106
+ const phaseFullPath = join(phasesDir, phaseDir.name);
107
+
108
+ // Read files in the phase directory
109
+ const phaseFiles = await readdir(phaseFullPath);
110
+
111
+ // Filter and sort PLAN.md files
112
+ const planRegex = /^\d{2}-\d{2}-PLAN\.md$/;
113
+ const planIdRegex = /^(\d{2}-\d{2})-PLAN\.md$/;
114
+ const planFiles = phaseFiles
115
+ .filter(f => planRegex.test(f))
116
+ .sort();
117
+
118
+ // Build summary paths and read them in parallel
119
+ const summaryPaths = planFiles.map(planFile => {
120
+ const match = planFile.match(planIdRegex);
121
+ const planId = match[1];
122
+ return { planId, planFile, summaryPath: join(phaseFullPath, `SUMMARY-${planId}.md`) };
123
+ });
124
+
125
+ const summaryResults = await Promise.allSettled(
126
+ summaryPaths.map(({ summaryPath }) => readMarkdownFile(summaryPath))
127
+ );
128
+
129
+ // Map results to plan objects
130
+ const plans = summaryPaths.map(({ planId, planFile }, index) => {
131
+ const result = summaryResults[index];
132
+ if (result.status === 'fulfilled') {
133
+ return {
134
+ planId,
135
+ planFile,
136
+ summary: result.value.frontmatter,
137
+ content: result.value.html,
138
+ commits: parseTaskResultsTable(result.value.rawContent)
139
+ };
140
+ }
141
+ if (result.reason && result.reason.code === 'ENOENT') {
142
+ return { planId, planFile, summary: null, content: null, commits: [] };
143
+ }
144
+ // Unexpected error -- re-throw
145
+ throw result.reason;
146
+ });
147
+
148
+ // Read VERIFICATION.md
149
+ let verification = null;
150
+ try {
151
+ const verDoc = await readMarkdownFile(join(phaseFullPath, 'VERIFICATION.md'));
152
+ verification = verDoc.frontmatter;
153
+ } catch (error) {
154
+ if (error.code !== 'ENOENT') {
155
+ throw error;
156
+ }
157
+ // ENOENT -> verification stays null
158
+ }
159
+
160
+ return {
161
+ phaseId,
162
+ phaseName,
163
+ phaseDir: phaseDir.name,
164
+ plans,
165
+ verification
166
+ };
167
+ }
@@ -0,0 +1,57 @@
1
+ import { join, resolve, relative } from 'node:path';
2
+ import { readMarkdownFile, listPlanningFiles } from '../repositories/planning.repository.js';
3
+
4
+ /**
5
+ * Get homepage data for the dashboard.
6
+ * Reads .planning/README.md if it exists, returns fallback data if not.
7
+ *
8
+ * @param {string} projectDir - Absolute path to the project root
9
+ * @returns {Promise<{title: string, projectDir: string, content: string}>}
10
+ */
11
+ export async function getHomepage(projectDir) {
12
+ try {
13
+ const readmePath = join(projectDir, '.planning', 'README.md');
14
+ const { frontmatter, html } = await readMarkdownFile(readmePath);
15
+
16
+ return {
17
+ title: frontmatter.title || 'PBR Dashboard',
18
+ projectDir,
19
+ content: html
20
+ };
21
+ } catch (error) {
22
+ if (error.code === 'ENOENT') {
23
+ return {
24
+ title: 'Welcome',
25
+ projectDir,
26
+ content: '<p>No project README found.</p>'
27
+ };
28
+ }
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Read a specific markdown file from within the .planning/ directory.
35
+ * Validates that the resolved path stays within .planning/ to prevent
36
+ * path traversal attacks.
37
+ *
38
+ * @param {string} projectDir - Absolute path to the project root
39
+ * @param {string} relativePath - Path relative to .planning/ (e.g., 'phases/01/PLAN.md')
40
+ * @returns {Promise<{frontmatter: object, html: string, rawContent: string}>}
41
+ * @throws {Error} If path escapes .planning/ or file not found
42
+ */
43
+ export async function getMarkdownFile(projectDir, relativePath) {
44
+ const planningDir = resolve(projectDir, '.planning');
45
+ const filePath = resolve(planningDir, relativePath);
46
+
47
+ // Path traversal protection: ensure resolved path is under .planning/
48
+ const rel = relative(planningDir, filePath);
49
+ if (rel.startsWith('..') || resolve(filePath) !== filePath && rel.startsWith('..')) {
50
+ const err = new Error('Path traversal not allowed: path escapes .planning/ directory');
51
+ err.code = 'PATH_TRAVERSAL';
52
+ err.status = 403;
53
+ throw err;
54
+ }
55
+
56
+ return readMarkdownFile(filePath);
57
+ }
@@ -0,0 +1,171 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { parseRoadmapFile } from './dashboard.service.js';
4
+
5
+ /**
6
+ * Strip UTF-8 BOM from file content.
7
+ * Duplicated intentionally -- this service reads raw text, not via the repository layer.
8
+ *
9
+ * @param {string} content - Raw file content
10
+ * @returns {string} Content without BOM
11
+ */
12
+ function stripBOM(content) {
13
+ return content.replace(/^\uFEFF/, '');
14
+ }
15
+
16
+ /**
17
+ * Count the number of PLAN.md files in a phase directory.
18
+ *
19
+ * @param {string} projectDir - Absolute path to the project root
20
+ * @param {number} phaseId - Numeric phase ID (e.g., 1, 5, 12)
21
+ * @returns {Promise<number>} Number of NN-NN-PLAN.md files found
22
+ */
23
+ async function countPlansForPhase(projectDir, phaseId) {
24
+ const phaseIdPadded = String(phaseId).padStart(2, '0');
25
+ const phasesDir = join(projectDir, '.planning', 'phases');
26
+
27
+ try {
28
+ const entries = await readdir(phasesDir, { withFileTypes: true });
29
+ // When multiple directories match (e.g. stale rename leftover), prefer the longest name
30
+ const matchingDirs = entries
31
+ .filter(e => e.isDirectory() && e.name.startsWith(`${phaseIdPadded}-`))
32
+ .sort((a, b) => b.name.length - a.name.length);
33
+ const phaseDir = matchingDirs[0];
34
+
35
+ if (!phaseDir) return 0;
36
+
37
+ const phaseFiles = await readdir(join(phasesDir, phaseDir.name));
38
+ return phaseFiles.filter(f => /^\d{2}-\d{2}-PLAN\.md$/.test(f)).length;
39
+ } catch (err) {
40
+ if (err.code === 'ENOENT') return 0;
41
+ throw err;
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Extract dependency information from all Phase Details sections in ROADMAP.md.
47
+ *
48
+ * @param {string} roadmapContent - Raw ROADMAP.md content
49
+ * @returns {Map<number, number[]>} Map of phaseId -> array of dependency phase IDs
50
+ */
51
+ function extractAllDependencies(roadmapContent) {
52
+ const dependencyMap = new Map();
53
+
54
+ // Match Phase Details sections: "### Phase NN: ..." followed by "**Depends on**: ..."
55
+ const sectionRegex = /### Phase (\d+):[\s\S]*?\*\*Depends on\*\*:\s*([^\n]+)/g;
56
+ let match;
57
+
58
+ while ((match = sectionRegex.exec(roadmapContent)) !== null) {
59
+ const phaseId = parseInt(match[1], 10);
60
+ const depText = match[2].trim();
61
+
62
+ if (depText.toLowerCase().includes('none')) {
63
+ dependencyMap.set(phaseId, []);
64
+ continue;
65
+ }
66
+
67
+ // Extract phase numbers from "Phase 01, Phase 02" format
68
+ const deps = [];
69
+ const depMatches = depText.matchAll(/Phase (\d+)/g);
70
+ for (const dm of depMatches) {
71
+ deps.push(parseInt(dm[1], 10));
72
+ }
73
+ dependencyMap.set(phaseId, deps);
74
+ }
75
+
76
+ return dependencyMap;
77
+ }
78
+
79
+ /**
80
+ * Extract milestone information from ROADMAP.md.
81
+ * Parses explicit "## Milestone:" sections and infers the implicit first milestone
82
+ * from the roadmap title (phases before the first explicit milestone).
83
+ *
84
+ * @param {string} roadmapContent - Raw ROADMAP.md content (newlines normalized)
85
+ * @returns {Array<{name: string, goal: string, startPhase: number, endPhase: number}>}
86
+ */
87
+ function extractMilestones(roadmapContent) {
88
+ const milestones = [];
89
+
90
+ // Get project title from H1: "# Roadmap: PBR Dashboard"
91
+ const titleMatch = roadmapContent.match(/^# Roadmap:\s*(.+)$/m);
92
+ const projectTitle = titleMatch ? titleMatch[1].trim() : 'Project';
93
+
94
+ // Parse explicit milestones: "## Milestone: Name\n\n**Goal:** ...\n**Phases:** N - M"
95
+ const milestoneRegex = /## Milestone:\s*(.+)\n\n\*\*Goal:\*\*\s*(.+)\n\*\*Phases:\*\*\s*(\d+)\s*-\s*(\d+)/g;
96
+ const explicit = [];
97
+ for (const match of roadmapContent.matchAll(milestoneRegex)) {
98
+ explicit.push({
99
+ name: match[1].trim(),
100
+ goal: match[2].trim(),
101
+ startPhase: parseInt(match[3], 10),
102
+ endPhase: parseInt(match[4], 10)
103
+ });
104
+ }
105
+
106
+ // Sort explicit milestones by start phase
107
+ explicit.sort((a, b) => a.startPhase - b.startPhase);
108
+
109
+ // Infer implicit first milestone (phases before first explicit milestone)
110
+ if (explicit.length > 0) {
111
+ const firstStart = explicit[0].startPhase;
112
+ if (firstStart > 1) {
113
+ milestones.push({
114
+ name: projectTitle,
115
+ goal: '',
116
+ startPhase: 1,
117
+ endPhase: firstStart - 1
118
+ });
119
+ }
120
+ } else {
121
+ // No explicit milestones — all phases belong to the project
122
+ milestones.push({
123
+ name: projectTitle,
124
+ goal: '',
125
+ startPhase: 1,
126
+ endPhase: 9999
127
+ });
128
+ }
129
+
130
+ milestones.push(...explicit);
131
+ return milestones;
132
+ }
133
+
134
+ /**
135
+ * Get enhanced roadmap data with plan counts, dependencies, and milestones.
136
+ * Combines parseRoadmapFile with raw ROADMAP.md reading for dependency
137
+ * extraction, milestone parsing, and directory scanning for plan counts.
138
+ *
139
+ * @param {string} projectDir - Absolute path to the project root
140
+ * @returns {Promise<{phases: Array, milestones: Array}>}
141
+ */
142
+ export async function getRoadmapData(projectDir) {
143
+ const { phases: basePhases } = await parseRoadmapFile(projectDir);
144
+
145
+ if (basePhases.length === 0) {
146
+ return { phases: [], milestones: [] };
147
+ }
148
+
149
+ // Read raw ROADMAP.md for dependencies and milestones
150
+ let dependencyMap = new Map();
151
+ let milestones = [];
152
+ try {
153
+ const roadmapPath = join(projectDir, '.planning', 'ROADMAP.md');
154
+ const rawContent = stripBOM(await readFile(roadmapPath, 'utf-8')).replace(/\r\n/g, '\n');
155
+ dependencyMap = extractAllDependencies(rawContent);
156
+ milestones = extractMilestones(rawContent);
157
+ } catch (err) {
158
+ if (err.code !== 'ENOENT') throw err;
159
+ }
160
+
161
+ // Enhance each phase with plan count and dependencies in parallel
162
+ const enhancedPhases = await Promise.all(
163
+ basePhases.map(async (phase) => {
164
+ const planCount = await countPlansForPhase(projectDir, phase.id);
165
+ const dependencies = dependencyMap.get(phase.id) || [];
166
+ return { ...phase, planCount, dependencies };
167
+ })
168
+ );
169
+
170
+ return { phases: enhancedPhases, milestones };
171
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * SSE (Server-Sent Events) service.
3
+ * Manages a Set of active client response objects and provides
4
+ * broadcast functionality to send events to all connected browsers.
5
+ */
6
+
7
+ /** @type {Set<import('http').ServerResponse>} */
8
+ const clients = new Set();
9
+
10
+ /**
11
+ * Register a client response object for SSE broadcasting.
12
+ * @param {import('http').ServerResponse} res
13
+ */
14
+ export function addClient(res) {
15
+ clients.add(res);
16
+ }
17
+
18
+ /**
19
+ * Remove a client response object (called on disconnect).
20
+ * @param {import('http').ServerResponse} res
21
+ */
22
+ export function removeClient(res) {
23
+ clients.delete(res);
24
+ }
25
+
26
+ /**
27
+ * Broadcast an SSE event to all connected clients.
28
+ * Clients that throw on write are automatically removed.
29
+ * @param {string} eventType - SSE event name (e.g. 'file-change')
30
+ * @param {object} data - Payload to JSON-serialize in the data field
31
+ */
32
+ export function broadcast(eventType, data) {
33
+ const id = Date.now();
34
+ const message = `event: ${eventType}\ndata: ${JSON.stringify(data)}\nid: ${id}\n\n`;
35
+
36
+ for (const client of clients) {
37
+ try {
38
+ client.write(message);
39
+ } catch {
40
+ clients.delete(client);
41
+ }
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Return the number of currently connected clients.
47
+ * @returns {number}
48
+ */
49
+ export function getClientCount() {
50
+ return clients.size;
51
+ }
52
+
53
+ /**
54
+ * Remove all clients. Used in tests to reset state between test cases.
55
+ */
56
+ export function clearClients() {
57
+ clients.clear();
58
+ }
@@ -0,0 +1,254 @@
1
+ import { readdir, readFile, writeFile, rename, mkdir } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import { readMarkdownFile } from '../repositories/planning.repository.js';
5
+
6
+ const PRIORITY_ORDER = { P0: 0, P1: 1, P2: 2, PX: 3 };
7
+
8
+ class WriteQueue {
9
+ constructor() {
10
+ this.tail = Promise.resolve();
11
+ }
12
+
13
+ enqueue(fn) {
14
+ const task = this.tail.then(fn, fn);
15
+ this.tail = task.catch(() => {});
16
+ return task;
17
+ }
18
+ }
19
+
20
+ const writeQueue = new WriteQueue();
21
+
22
+ function titleToSlug(title) {
23
+ return title
24
+ .toLowerCase()
25
+ .replace(/[^a-z0-9]+/g, '-')
26
+ .replace(/^-|-$/g, '')
27
+ .slice(0, 50);
28
+ }
29
+
30
+ async function getNextTodoId(projectDir) {
31
+ const pendingDir = join(projectDir, '.planning', 'todos', 'pending');
32
+ const doneDir = join(projectDir, '.planning', 'todos', 'done');
33
+
34
+ let highestId = 0;
35
+
36
+ for (const dir of [pendingDir, doneDir]) {
37
+ try {
38
+ const files = await readdir(dir);
39
+ for (const filename of files) {
40
+ const match = filename.match(/^(\d{3})-/);
41
+ if (match) {
42
+ const id = parseInt(match[1], 10);
43
+ if (id > highestId) highestId = id;
44
+ }
45
+ }
46
+ } catch (err) {
47
+ if (err.code !== 'ENOENT') throw err;
48
+ }
49
+ }
50
+
51
+ return String(highestId + 1).padStart(3, '0');
52
+ }
53
+
54
+ /**
55
+ * Sort todos by priority (P0 first) then alphabetically by title.
56
+ * Unknown priorities sort after PX.
57
+ * @param {Array} todos - Array of todo objects with priority and title fields
58
+ * @returns {Array} Sorted array (mutates and returns the input)
59
+ */
60
+ function sortTodosByPriority(todos) {
61
+ return todos.sort((a, b) => {
62
+ const aPriority = PRIORITY_ORDER[a.priority] ?? 99;
63
+ const bPriority = PRIORITY_ORDER[b.priority] ?? 99;
64
+ const priorityDiff = aPriority - bPriority;
65
+ if (priorityDiff !== 0) return priorityDiff;
66
+ return a.title.localeCompare(b.title);
67
+ });
68
+ }
69
+
70
+ /**
71
+ * List all pending todos from .planning/todos/pending/ directory.
72
+ * Reads each markdown file, parses frontmatter, filters invalid entries,
73
+ * and returns sorted by priority then title.
74
+ *
75
+ * @param {string} projectDir - Absolute path to the project root
76
+ * @returns {Promise<Array<{id: string, title: string, priority: string, phase: string, status: string, created: string, filename: string}>>}
77
+ */
78
+ export async function listPendingTodos(projectDir) {
79
+ const pendingDir = join(projectDir, '.planning', 'todos', 'pending');
80
+
81
+ let entries;
82
+ try {
83
+ entries = await readdir(pendingDir, { withFileTypes: true });
84
+ } catch (err) {
85
+ if (err.code === 'ENOENT') return [];
86
+ throw err;
87
+ }
88
+
89
+ // Filter for .md files and extract ID from filename prefix
90
+ const mdFiles = entries
91
+ .filter(entry => entry.isFile() && entry.name.endsWith('.md'))
92
+ .map(entry => ({
93
+ filename: entry.name,
94
+ filePath: join(pendingDir, entry.name),
95
+ fileId: entry.name.match(/^(\d{3})-/)?.[1] || null
96
+ }))
97
+ .filter(f => f.fileId !== null);
98
+
99
+ // Read all todo files in parallel with partial failure tolerance
100
+ const results = await Promise.allSettled(
101
+ mdFiles.map(f => readMarkdownFile(f.filePath))
102
+ );
103
+
104
+ const todos = [];
105
+ for (let i = 0; i < results.length; i++) {
106
+ if (results[i].status !== 'fulfilled') continue;
107
+
108
+ const { frontmatter } = results[i].value;
109
+ const { filename, fileId } = mdFiles[i];
110
+
111
+ // Skip todos missing required frontmatter fields
112
+ const title = frontmatter.title;
113
+ const priority = frontmatter.priority;
114
+ if (!title || !priority) continue;
115
+
116
+ todos.push({
117
+ id: frontmatter.id || fileId,
118
+ title,
119
+ priority,
120
+ phase: frontmatter.phase || '',
121
+ status: frontmatter.status || 'pending',
122
+ created: frontmatter.created ? String(frontmatter.created) : '',
123
+ filename
124
+ });
125
+ }
126
+
127
+ return sortTodosByPriority(todos);
128
+ }
129
+
130
+ /**
131
+ * Get a single todo by ID with full markdown content.
132
+ * Searches .planning/todos/pending/ for a file whose name starts with the given ID.
133
+ *
134
+ * @param {string} projectDir - Absolute path to the project root
135
+ * @param {string} todoId - Three-digit todo ID (e.g., "001", "042")
136
+ * @returns {Promise<{id: string, title: string, priority: string, phase: string, status: string, created: string, html: string, filename: string}>}
137
+ * @throws {Error} With status 404 if no todo matches the given ID
138
+ */
139
+ export async function getTodoDetail(projectDir, todoId) {
140
+ const pendingDir = join(projectDir, '.planning', 'todos', 'pending');
141
+
142
+ let entries;
143
+ try {
144
+ entries = await readdir(pendingDir);
145
+ } catch (err) {
146
+ if (err.code === 'ENOENT') {
147
+ const notFound = new Error(`Todo ${todoId} not found`);
148
+ notFound.status = 404;
149
+ throw notFound;
150
+ }
151
+ throw err;
152
+ }
153
+
154
+ // Find the file whose name starts with the todoId prefix
155
+ const matchingFile = entries.find(name =>
156
+ name.startsWith(`${todoId}-`) && name.endsWith('.md')
157
+ );
158
+
159
+ if (!matchingFile) {
160
+ const notFound = new Error(`Todo ${todoId} not found`);
161
+ notFound.status = 404;
162
+ throw notFound;
163
+ }
164
+
165
+ const filePath = join(pendingDir, matchingFile);
166
+ const { frontmatter, html } = await readMarkdownFile(filePath);
167
+
168
+ return {
169
+ id: frontmatter.id || todoId,
170
+ title: frontmatter.title || 'Untitled',
171
+ priority: frontmatter.priority || 'PX',
172
+ phase: frontmatter.phase || '',
173
+ status: frontmatter.status || 'pending',
174
+ created: frontmatter.created ? String(frontmatter.created) : '',
175
+ html,
176
+ filename: matchingFile
177
+ };
178
+ }
179
+
180
+ export async function createTodo(projectDir, todoData) {
181
+ const { title, priority, description } = todoData;
182
+ const phase = todoData.phase || '';
183
+
184
+ if (!title || !priority || !description) {
185
+ const err = new Error('Missing required fields: title, priority, and description are required');
186
+ err.status = 400;
187
+ throw err;
188
+ }
189
+
190
+ return writeQueue.enqueue(async () => {
191
+ const todoId = await getNextTodoId(projectDir);
192
+ const slug = titleToSlug(title);
193
+ const filename = `${todoId}-${slug}.md`;
194
+ const pendingDir = join(projectDir, '.planning', 'todos', 'pending');
195
+
196
+ await mkdir(pendingDir, { recursive: true });
197
+
198
+ const frontmatter = {
199
+ id: todoId,
200
+ title,
201
+ priority,
202
+ phase,
203
+ status: 'pending',
204
+ created: new Date().toISOString().split('T')[0]
205
+ };
206
+
207
+ const fileContent = matter.stringify(description, frontmatter);
208
+ const filePath = join(pendingDir, filename);
209
+ await writeFile(filePath, fileContent, 'utf-8');
210
+
211
+ return todoId;
212
+ });
213
+ }
214
+
215
+ export async function completeTodo(projectDir, todoId) {
216
+ return writeQueue.enqueue(async () => {
217
+ const pendingDir = join(projectDir, '.planning', 'todos', 'pending');
218
+ const doneDir = join(projectDir, '.planning', 'todos', 'done');
219
+
220
+ let entries;
221
+ try {
222
+ entries = await readdir(pendingDir);
223
+ } catch (err) {
224
+ if (err.code === 'ENOENT') {
225
+ const notFound = new Error(`Todo ${todoId} not found`);
226
+ notFound.status = 404;
227
+ throw notFound;
228
+ }
229
+ throw err;
230
+ }
231
+
232
+ const matchingFile = entries.find(name =>
233
+ name.startsWith(`${todoId}-`) && name.endsWith('.md')
234
+ );
235
+
236
+ if (!matchingFile) {
237
+ const notFound = new Error(`Todo ${todoId} not found`);
238
+ notFound.status = 404;
239
+ throw notFound;
240
+ }
241
+
242
+ const pendingPath = join(pendingDir, matchingFile);
243
+ const raw = await readFile(pendingPath, 'utf-8');
244
+ const parsed = matter(raw, { engines: { javascript: false } });
245
+
246
+ parsed.data.status = 'done';
247
+ const updatedContent = matter.stringify(parsed.content, parsed.data);
248
+ await writeFile(pendingPath, updatedContent, 'utf-8');
249
+
250
+ await mkdir(doneDir, { recursive: true });
251
+ const donePath = join(doneDir, matchingFile);
252
+ await rename(pendingPath, donePath);
253
+ });
254
+ }