@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,128 @@
1
+ import { readFile, readdir } from 'node:fs/promises';
2
+ import { join, resolve, relative, normalize } from 'node:path';
3
+ import matter from 'gray-matter';
4
+ import { marked } from 'marked';
5
+
6
+ /**
7
+ * Strip UTF-8 BOM (Byte Order Mark) if present.
8
+ * Windows editors (Notepad, older VS Code) may prepend BOM to UTF-8 files.
9
+ * gray-matter will fail to detect frontmatter delimiters if BOM is present.
10
+ * @param {string} content - Raw file content
11
+ * @returns {string} Content without BOM
12
+ */
13
+ function stripBOM(content) {
14
+ return content.replace(/^\uFEFF/, '');
15
+ }
16
+
17
+ /**
18
+ * Validate that a resolved path stays within the base directory.
19
+ * Prevents path traversal attacks (e.g., ../../etc/passwd).
20
+ *
21
+ * @param {string} basePath - Absolute base directory path
22
+ * @param {string} userPath - User-provided path (may be relative)
23
+ * @returns {string} Validated absolute path
24
+ * @throws {Error} With status 403 if path escapes base directory
25
+ */
26
+ export function validatePath(basePath, userPath) {
27
+ const resolvedBase = normalize(resolve(basePath));
28
+ const resolvedUser = normalize(resolve(basePath, userPath));
29
+
30
+ // Compute the relative path from base to target
31
+ const rel = relative(resolvedBase, resolvedUser);
32
+
33
+ // If relative path starts with '..' it escaped the base directory.
34
+ // If rel resolves to an absolute path, it was an absolute path injection.
35
+ if (rel.startsWith('..') || resolve(rel) === rel) {
36
+ const err = new Error('Path traversal attempt detected');
37
+ err.status = 403;
38
+ err.code = 'PATH_TRAVERSAL';
39
+ throw err;
40
+ }
41
+
42
+ return resolvedUser;
43
+ }
44
+
45
+ /**
46
+ * Read and parse a single markdown file with YAML frontmatter.
47
+ *
48
+ * @param {string} filePath - Absolute path to the markdown file
49
+ * @returns {Promise<{frontmatter: object, html: string, rawContent: string}>}
50
+ * @throws {Error} ENOENT if file does not exist, parse error if YAML is malformed
51
+ */
52
+ export async function readMarkdownFile(filePath) {
53
+ const fileContent = await readFile(filePath, 'utf-8');
54
+ const cleanContent = stripBOM(fileContent);
55
+
56
+ let data, content;
57
+ try {
58
+ ({ data, content } = matter(cleanContent, {
59
+ engines: {
60
+ javascript: false
61
+ }
62
+ }));
63
+ } catch (error) {
64
+ // gray-matter throws YAMLException for malformed frontmatter.
65
+ // Wrap it in a user-friendly error with status 400.
66
+ if (error.name === 'YAMLException' || (error.constructor && error.constructor.name === 'YAMLException')) {
67
+ const wrapped = new Error(`Invalid YAML frontmatter in ${filePath}: ${error.message}`);
68
+ wrapped.status = 400;
69
+ wrapped.cause = error;
70
+ throw wrapped;
71
+ }
72
+ throw error;
73
+ }
74
+
75
+ const html = marked.parse(content);
76
+
77
+ return {
78
+ frontmatter: data,
79
+ html,
80
+ rawContent: content
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Read and parse multiple markdown files in parallel (fail-fast).
86
+ * If any file fails, the entire operation rejects immediately.
87
+ *
88
+ * @param {string[]} filePaths - Array of absolute file paths
89
+ * @returns {Promise<Array<{frontmatter: object, html: string, rawContent: string}>>}
90
+ */
91
+ export async function readMarkdownFiles(filePaths) {
92
+ return Promise.all(
93
+ filePaths.map(filePath => readMarkdownFile(filePath))
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Read and parse multiple markdown files with partial failure tolerance.
99
+ * All reads complete even if some fail. Returns settled results.
100
+ *
101
+ * @param {string[]} filePaths - Array of absolute file paths
102
+ * @returns {Promise<Array<{status: 'fulfilled', value: object} | {status: 'rejected', reason: Error}>>}
103
+ */
104
+ export async function readMarkdownFilesSettled(filePaths) {
105
+ return Promise.allSettled(
106
+ filePaths.map(filePath => readMarkdownFile(filePath))
107
+ );
108
+ }
109
+
110
+ /**
111
+ * List all markdown files under the .planning/ directory recursively.
112
+ * Uses native fs.readdir with recursive option (Node.js 18.17+).
113
+ *
114
+ * @param {string} projectDir - Absolute path to the project root
115
+ * @returns {Promise<string[]>} Array of absolute file paths to .md files
116
+ * @throws {Error} ENOENT if .planning/ directory does not exist
117
+ */
118
+ export async function listPlanningFiles(projectDir) {
119
+ const planningDir = join(projectDir, '.planning');
120
+ const entries = await readdir(planningDir, {
121
+ recursive: true,
122
+ withFileTypes: true
123
+ });
124
+
125
+ return entries
126
+ .filter(entry => entry.isFile() && entry.name.endsWith('.md'))
127
+ .map(entry => join(entry.parentPath || entry.path, entry.name));
128
+ }
@@ -0,0 +1,40 @@
1
+ import { Router } from 'express';
2
+ import { addClient, removeClient } from '../services/sse.service.js';
3
+
4
+ const router = Router();
5
+
6
+ /**
7
+ * GET /stream - Server-Sent Events endpoint.
8
+ * Establishes a long-lived SSE connection. Events are pushed by the SSE service
9
+ * when the file watcher detects changes. Heartbeat comments every 30s keep the
10
+ * connection alive.
11
+ */
12
+ router.get('/stream', (req, res) => {
13
+ // Set SSE headers
14
+ res.writeHead(200, {
15
+ 'Content-Type': 'text/event-stream',
16
+ 'Cache-Control': 'no-cache',
17
+ 'Connection': 'keep-alive',
18
+ 'X-Accel-Buffering': 'no'
19
+ });
20
+ res.flushHeaders();
21
+
22
+ // Send initial connection confirmation
23
+ res.write(': connected\n\n');
24
+
25
+ // Register this client for broadcasts
26
+ addClient(res);
27
+
28
+ // Heartbeat every 30 seconds to keep connection alive
29
+ const heartbeat = setInterval(() => {
30
+ res.write(': heartbeat\n\n');
31
+ }, 30000);
32
+
33
+ // Clean up on client disconnect
34
+ req.on('close', () => {
35
+ clearInterval(heartbeat);
36
+ removeClient(res);
37
+ });
38
+ });
39
+
40
+ export default router;
@@ -0,0 +1,31 @@
1
+ import { Router } from 'express';
2
+ import { getHomepage } from '../services/project.service.js';
3
+ import { getDashboardData } from '../services/dashboard.service.js';
4
+
5
+ const router = Router();
6
+
7
+ router.get('/', async (req, res) => {
8
+ const projectDir = req.app.locals.projectDir;
9
+
10
+ const [homepageData, dashboardData] = await Promise.all([
11
+ getHomepage(projectDir),
12
+ getDashboardData(projectDir)
13
+ ]);
14
+
15
+ const templateData = {
16
+ ...homepageData,
17
+ ...dashboardData,
18
+ activePage: 'dashboard',
19
+ currentPath: '/'
20
+ };
21
+
22
+ res.setHeader('Vary', 'HX-Request');
23
+
24
+ if (req.get('HX-Request') === 'true') {
25
+ res.render('partials/dashboard-content', templateData);
26
+ } else {
27
+ res.render('index', templateData);
28
+ }
29
+ });
30
+
31
+ export default router;
@@ -0,0 +1,195 @@
1
+ import { Router } from 'express';
2
+ import { getPhaseDetail } from '../services/phase.service.js';
3
+ import { getRoadmapData } from '../services/roadmap.service.js';
4
+ import { listPendingTodos, getTodoDetail, createTodo, completeTodo } from '../services/todo.service.js';
5
+
6
+ const router = Router();
7
+
8
+ router.get('/phases', async (req, res) => {
9
+ const projectDir = req.app.locals.projectDir;
10
+ const roadmapData = await getRoadmapData(projectDir);
11
+
12
+ const templateData = {
13
+ title: 'Phases',
14
+ activePage: 'phases',
15
+ currentPath: '/phases',
16
+ phases: roadmapData.phases,
17
+ milestones: roadmapData.milestones
18
+ };
19
+
20
+ res.setHeader('Vary', 'HX-Request');
21
+
22
+ if (req.get('HX-Request') === 'true') {
23
+ res.render('partials/phases-content', templateData);
24
+ } else {
25
+ res.render('phases', templateData);
26
+ }
27
+ });
28
+
29
+ router.get('/phases/:phaseId', async (req, res) => {
30
+ const { phaseId } = req.params;
31
+
32
+ // Validate phaseId: two digits, optionally followed by decimal (e.g., 01, 05, 3.1)
33
+ if (!/^\d{1,2}(\.\d+)?$/.test(phaseId)) {
34
+ const err = new Error('Phase ID must be a number (e.g., 01, 05, 3.1)');
35
+ err.status = 404;
36
+ throw err;
37
+ }
38
+
39
+ const projectDir = req.app.locals.projectDir;
40
+ const phaseData = await getPhaseDetail(projectDir, phaseId);
41
+
42
+ const templateData = {
43
+ title: `Phase ${phaseId}: ${phaseData.phaseName}`,
44
+ activePage: 'phases',
45
+ currentPath: '/phases/' + phaseId,
46
+ ...phaseData
47
+ };
48
+
49
+ res.setHeader('Vary', 'HX-Request');
50
+
51
+ if (req.get('HX-Request') === 'true') {
52
+ res.render('partials/phase-content', templateData);
53
+ } else {
54
+ res.render('phase-detail', templateData);
55
+ }
56
+ });
57
+
58
+ router.get('/todos', async (req, res) => {
59
+ const projectDir = req.app.locals.projectDir;
60
+ const todos = await listPendingTodos(projectDir);
61
+
62
+ const templateData = {
63
+ title: 'Todos',
64
+ activePage: 'todos',
65
+ currentPath: '/todos',
66
+ todos
67
+ };
68
+
69
+ res.setHeader('Vary', 'HX-Request');
70
+
71
+ if (req.get('HX-Request') === 'true') {
72
+ res.render('partials/todos-content', templateData);
73
+ } else {
74
+ res.render('todos', templateData);
75
+ }
76
+ });
77
+
78
+ router.get('/todos/new', (req, res) => {
79
+ const templateData = {
80
+ title: 'Create Todo',
81
+ activePage: 'todos',
82
+ currentPath: '/todos/new'
83
+ };
84
+
85
+ res.setHeader('Vary', 'HX-Request');
86
+
87
+ if (req.get('HX-Request') === 'true') {
88
+ res.render('partials/todo-create-content', templateData);
89
+ } else {
90
+ res.render('todo-create', templateData);
91
+ }
92
+ });
93
+
94
+ router.get('/todos/:id', async (req, res) => {
95
+ const { id } = req.params;
96
+
97
+ // Validate ID format: must be exactly three digits
98
+ if (!/^\d{3}$/.test(id)) {
99
+ const err = new Error('Todo ID must be a three-digit number (e.g., 001, 005, 042)');
100
+ err.status = 404;
101
+ throw err;
102
+ }
103
+
104
+ const projectDir = req.app.locals.projectDir;
105
+ const todo = await getTodoDetail(projectDir, id);
106
+
107
+ const templateData = {
108
+ title: `Todo ${todo.id}: ${todo.title}`,
109
+ activePage: 'todos',
110
+ currentPath: '/todos/' + id,
111
+ ...todo
112
+ };
113
+
114
+ res.setHeader('Vary', 'HX-Request');
115
+
116
+ if (req.get('HX-Request') === 'true') {
117
+ res.render('partials/todo-detail-content', templateData);
118
+ } else {
119
+ res.render('todo-detail', templateData);
120
+ }
121
+ });
122
+
123
+ router.post('/todos', async (req, res) => {
124
+ const { title, priority, phase, description } = req.body;
125
+ const projectDir = req.app.locals.projectDir;
126
+
127
+ const todoId = await createTodo(projectDir, {
128
+ title,
129
+ priority,
130
+ phase: phase || '',
131
+ description
132
+ });
133
+
134
+ if (req.get('HX-Request') === 'true') {
135
+ // For HTMX: fetch the new todo and render its detail as a fragment
136
+ const todo = await getTodoDetail(projectDir, todoId);
137
+ res.render('partials/todo-detail-content', {
138
+ title: `Todo ${todo.id}: ${todo.title}`,
139
+ activePage: 'todos',
140
+ currentPath: '/todos/' + todoId,
141
+ ...todo
142
+ });
143
+ } else {
144
+ res.redirect(`/todos/${todoId}`);
145
+ }
146
+ });
147
+
148
+ router.post('/todos/:id/done', async (req, res) => {
149
+ const { id } = req.params;
150
+
151
+ if (!/^\d{3}$/.test(id)) {
152
+ const err = new Error('Todo ID must be a three-digit number');
153
+ err.status = 404;
154
+ throw err;
155
+ }
156
+
157
+ const projectDir = req.app.locals.projectDir;
158
+ await completeTodo(projectDir, id);
159
+
160
+ if (req.get('HX-Request') === 'true') {
161
+ // For HTMX: re-render the full todo list as a fragment
162
+ const todos = await listPendingTodos(projectDir);
163
+ res.render('partials/todos-content', {
164
+ title: 'Todos',
165
+ activePage: 'todos',
166
+ currentPath: '/todos',
167
+ todos
168
+ });
169
+ } else {
170
+ res.redirect('/todos');
171
+ }
172
+ });
173
+
174
+ router.get('/roadmap', async (req, res) => {
175
+ const projectDir = req.app.locals.projectDir;
176
+ const roadmapData = await getRoadmapData(projectDir);
177
+
178
+ const templateData = {
179
+ title: 'Roadmap',
180
+ activePage: 'roadmap',
181
+ currentPath: '/roadmap',
182
+ phases: roadmapData.phases,
183
+ milestones: roadmapData.milestones
184
+ };
185
+
186
+ res.setHeader('Vary', 'HX-Request');
187
+
188
+ if (req.get('HX-Request') === 'true') {
189
+ res.render('partials/roadmap-content', templateData);
190
+ } else {
191
+ res.render('roadmap', templateData);
192
+ }
193
+ });
194
+
195
+ export default router;
@@ -0,0 +1,42 @@
1
+ import { createApp } from './app.js';
2
+ import { createWatcher } from './services/watcher.service.js';
3
+ import { broadcast } from './services/sse.service.js';
4
+
5
+ export function startServer(config) {
6
+ const app = createApp(config);
7
+ const { port, projectDir } = config;
8
+
9
+ // Start file watcher for live updates
10
+ const watcher = createWatcher(projectDir, (event) => {
11
+ broadcast('file-change', event);
12
+ });
13
+
14
+ const server = app.listen(port, '127.0.0.1', () => {
15
+ console.log(`PBR Dashboard running at http://127.0.0.1:${port}`);
16
+ console.log(`Project directory: ${projectDir}`);
17
+ console.log('File watcher active on .planning/**/*.md');
18
+ });
19
+
20
+ const shutdown = async (signal) => {
21
+ console.log(`${signal} received. Shutting down PBR Dashboard...`);
22
+
23
+ // Close watcher first (stops generating events)
24
+ try {
25
+ await watcher.close();
26
+ console.log('File watcher closed.');
27
+ } catch (err) {
28
+ console.error('Error closing watcher:', err.message);
29
+ }
30
+
31
+ // Then close the HTTP server
32
+ server.close(() => {
33
+ console.log('Server closed.');
34
+ process.exit(0);
35
+ });
36
+ };
37
+
38
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
39
+ process.on('SIGINT', () => shutdown('SIGINT'));
40
+
41
+ return server;
42
+ }
@@ -0,0 +1,222 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ /**
5
+ * Strip UTF-8 BOM from file content.
6
+ * Duplicated from planning.repository.js intentionally --
7
+ * 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
+ * Parse STATE.md to extract project status information.
18
+ * Uses regex on raw markdown body text (not YAML frontmatter).
19
+ *
20
+ * @param {string} projectDir - Absolute path to the project root
21
+ * @returns {Promise<{projectName: string, currentPhase: object, lastActivity: object, progress: number}>}
22
+ */
23
+ export async function parseStateFile(projectDir) {
24
+ try {
25
+ const path = join(projectDir, '.planning', 'STATE.md');
26
+ const raw = await readFile(path, 'utf-8');
27
+ const content = stripBOM(raw);
28
+
29
+ // Extract project name from **Current focus:** line
30
+ let projectName = 'Unknown Project';
31
+ const focusMatch = content.match(/\*\*Current focus:\*\*\s*(.+)/);
32
+ if (focusMatch) {
33
+ projectName = focusMatch[1].trim();
34
+ } else {
35
+ // Fallback: try H1 heading
36
+ const h1Match = content.match(/^# (.+)/m);
37
+ if (h1Match) {
38
+ projectName = h1Match[1].trim();
39
+ }
40
+ }
41
+
42
+ // Extract current phase: "Phase: 3 of 12 (UI Shell)"
43
+ let currentPhaseId = 0;
44
+ let totalPhases = 0;
45
+ let phaseName = 'Not Started';
46
+ const phaseMatch = content.match(/Phase:\s*(\d+)\s*of\s*(\d+)\s*\(([^)]+)\)/);
47
+ if (phaseMatch) {
48
+ currentPhaseId = parseInt(phaseMatch[1], 10);
49
+ totalPhases = parseInt(phaseMatch[2], 10);
50
+ phaseName = phaseMatch[3].trim();
51
+ }
52
+
53
+ // Extract plan status: "Plan: 2 of 2 complete"
54
+ let planStatus = 'N/A';
55
+ const planMatch = content.match(/Plan:\s*(.+)/);
56
+ if (planMatch) {
57
+ planStatus = planMatch[1].trim();
58
+ }
59
+
60
+ // Extract last activity: "Last activity: 2026-02-08 -- Phase 3 built (...)"
61
+ let activityDate = '';
62
+ let activityDescription = 'No activity recorded';
63
+ const activityMatch = content.match(/Last activity:\s*([\d-]+)\s*--\s*(.+)/);
64
+ if (activityMatch) {
65
+ activityDate = activityMatch[1].trim();
66
+ activityDescription = activityMatch[2].trim();
67
+ }
68
+
69
+ // Extract progress percentage: "Progress: [...] 25%"
70
+ let progress = 0;
71
+ const progressMatch = content.match(/Progress:.*?(\d+)%/);
72
+ if (progressMatch) {
73
+ progress = parseInt(progressMatch[1], 10);
74
+ } else if (totalPhases > 0) {
75
+ // Calculate from phase numbers if no explicit progress
76
+ progress = Math.ceil((currentPhaseId / totalPhases) * 100);
77
+ }
78
+
79
+ return {
80
+ projectName,
81
+ currentPhase: {
82
+ id: currentPhaseId,
83
+ total: totalPhases,
84
+ name: phaseName,
85
+ planStatus
86
+ },
87
+ lastActivity: {
88
+ date: activityDate,
89
+ description: activityDescription
90
+ },
91
+ progress
92
+ };
93
+ } catch (error) {
94
+ if (error.code === 'ENOENT') {
95
+ return {
96
+ projectName: 'Unknown Project',
97
+ currentPhase: { id: 0, total: 0, name: 'Not Started', planStatus: 'N/A' },
98
+ lastActivity: { date: '', description: 'No activity recorded' },
99
+ progress: 0
100
+ };
101
+ }
102
+ throw error;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Parse ROADMAP.md to extract phase list from Progress table and checkbox list.
108
+ * Uses the Progress table as primary source (contains ALL phases including those
109
+ * added under milestone headings). Falls back to checkbox parsing for older
110
+ * roadmaps that don't have a Progress table.
111
+ *
112
+ * @param {string} projectDir - Absolute path to the project root
113
+ * @returns {Promise<{phases: Array<{id: number, name: string, description: string, status: string}>, progress: number}>}
114
+ */
115
+ export async function parseRoadmapFile(projectDir) {
116
+ try {
117
+ const filePath = join(projectDir, '.planning', 'ROADMAP.md');
118
+ const raw = await readFile(filePath, 'utf-8');
119
+ const content = stripBOM(raw).replace(/\r\n/g, '\n');
120
+
121
+ // 1. Parse descriptions from checkbox list: "- [x] Phase 01: Name -- Description"
122
+ const checkboxMap = new Map();
123
+ const checkboxRegex = /^- \[([ xX])\] Phase (\d+):\s*([^-]+?)\s*--\s*(.+)$/gm;
124
+ for (const match of content.matchAll(checkboxRegex)) {
125
+ const id = parseInt(match[2], 10);
126
+ checkboxMap.set(id, {
127
+ name: match[3].trim(),
128
+ description: match[4].trim(),
129
+ status: (match[1] === 'x' || match[1] === 'X') ? 'complete' : 'not-started'
130
+ });
131
+ }
132
+
133
+ // 2. Parse descriptions from Phase Details: "### Phase NN: Name\n**Goal**: ..."
134
+ const goalMap = new Map();
135
+ const goalRegex = /### Phase (\d+):\s*(.+)\n\*\*Goal\*\*:\s*(.+)/g;
136
+ for (const match of content.matchAll(goalRegex)) {
137
+ goalMap.set(parseInt(match[1], 10), match[3].trim());
138
+ }
139
+
140
+ // 3. Parse Progress table: "| 01. Name | 2/2 | Complete | 2026-02-08 |"
141
+ const progressRegex = /^\|\s*(\d+)\.\s+(.+?)\s*\|\s*(\d+)\/([\d?]+)\s*\|\s*(.+?)\s*\|\s*(.+?)\s*\|$/gm;
142
+ const progressPhases = [];
143
+ for (const match of content.matchAll(progressRegex)) {
144
+ const id = parseInt(match[1], 10);
145
+ const name = match[2].trim();
146
+ const statusText = match[5].trim().toLowerCase();
147
+
148
+ // Get description: prefer checkbox description, fall back to Phase Details Goal
149
+ const cbInfo = checkboxMap.get(id);
150
+ const goalDesc = goalMap.get(id);
151
+ const description = cbInfo?.description || goalDesc || '';
152
+
153
+ let status;
154
+ if (statusText === 'complete') status = 'complete';
155
+ else if (statusText === 'in progress') status = 'in-progress';
156
+ else status = 'not-started';
157
+
158
+ progressPhases.push({ id, name, description, status });
159
+ }
160
+
161
+ // Use Progress table if available, otherwise fall back to checkbox parsing
162
+ let phases;
163
+ if (progressPhases.length > 0) {
164
+ phases = progressPhases;
165
+ } else {
166
+ phases = [...checkboxMap.entries()]
167
+ .map(([id, info]) => ({
168
+ id,
169
+ name: info.name,
170
+ description: info.description,
171
+ status: info.status
172
+ }))
173
+ .sort((a, b) => a.id - b.id);
174
+ }
175
+
176
+ const completed = phases.filter(p => p.status === 'complete').length;
177
+ const total = phases.length;
178
+ const progress = total > 0 ? Math.ceil((completed / total) * 100) : 0;
179
+
180
+ return { phases, progress };
181
+ } catch (error) {
182
+ if (error.code === 'ENOENT') {
183
+ return { phases: [], progress: 0 };
184
+ }
185
+ throw error;
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Get combined dashboard data by parsing both STATE.md and ROADMAP.md.
191
+ * Orchestrates both parsers in parallel and derives in-progress status.
192
+ *
193
+ * @param {string} projectDir - Absolute path to the project root
194
+ * @returns {Promise<{projectName: string, currentPhase: object, lastActivity: object, progress: number, phases: Array}>}
195
+ */
196
+ export async function getDashboardData(projectDir) {
197
+ const [stateData, roadmapData] = await Promise.all([
198
+ parseStateFile(projectDir),
199
+ parseRoadmapFile(projectDir)
200
+ ]);
201
+
202
+ // Derive "in-progress" status for the current phase
203
+ const phases = roadmapData.phases.map(phase => ({
204
+ ...phase,
205
+ status: (phase.id === stateData.currentPhase.id && phase.status !== 'complete')
206
+ ? 'in-progress'
207
+ : phase.status
208
+ }));
209
+
210
+ // Prefer roadmap progress if phases exist, otherwise use state progress
211
+ const progress = roadmapData.phases.length > 0
212
+ ? roadmapData.progress
213
+ : stateData.progress;
214
+
215
+ return {
216
+ projectName: stateData.projectName,
217
+ currentPhase: stateData.currentPhase,
218
+ lastActivity: stateData.lastActivity,
219
+ progress,
220
+ phases
221
+ };
222
+ }