mindforge-cc 2.1.0 → 2.1.2

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 (236) hide show
  1. package/.agent/bin/lib/commands.cjs +959 -0
  2. package/.agent/bin/lib/config.cjs +421 -0
  3. package/.agent/bin/lib/core.cjs +1166 -0
  4. package/.agent/bin/lib/frontmatter.cjs +307 -0
  5. package/.agent/bin/lib/init.cjs +1336 -0
  6. package/.agent/bin/lib/milestone.cjs +252 -0
  7. package/.agent/bin/lib/model-profiles.cjs +68 -0
  8. package/.agent/bin/lib/phase.cjs +888 -0
  9. package/.agent/bin/lib/profile-output.cjs +952 -0
  10. package/.agent/bin/lib/profile-pipeline.cjs +539 -0
  11. package/.agent/bin/lib/roadmap.cjs +329 -0
  12. package/.agent/bin/lib/security.cjs +356 -0
  13. package/.agent/bin/lib/state.cjs +969 -0
  14. package/.agent/bin/lib/template.cjs +222 -0
  15. package/.agent/bin/lib/uat.cjs +189 -0
  16. package/.agent/bin/lib/verify.cjs +851 -0
  17. package/.agent/bin/lib/workstream.cjs +491 -0
  18. package/.agent/bin/mindforge-tools.cjs +897 -0
  19. package/.agent/file-manifest.json +219 -0
  20. package/.agent/hooks/mindforge-check-update.js +114 -0
  21. package/.agent/hooks/mindforge-context-monitor.js +156 -0
  22. package/.agent/hooks/mindforge-prompt-guard.js +96 -0
  23. package/.agent/hooks/mindforge-statusline.js +119 -0
  24. package/.agent/hooks/mindforge-workflow-guard.js +94 -0
  25. package/.agent/mindforge/discuss-phase.md +1 -1
  26. package/.agent/mindforge/help.md +1 -1
  27. package/.agent/mindforge/learn.md +3 -2
  28. package/.agent/mindforge/research.md +3 -2
  29. package/.agent/mindforge/steer.md +1 -1
  30. package/.agent/settings.json +38 -0
  31. package/.agent/skills/mindforge-add-backlog/SKILL.md +72 -0
  32. package/.agent/skills/mindforge-add-phase/SKILL.md +39 -0
  33. package/.agent/skills/mindforge-add-tests/SKILL.md +28 -0
  34. package/.agent/skills/mindforge-add-todo/SKILL.md +42 -0
  35. package/.agent/skills/mindforge-audit-milestone/SKILL.md +29 -0
  36. package/.agent/skills/mindforge-audit-uat/SKILL.md +20 -0
  37. package/.agent/skills/mindforge-autonomous/SKILL.md +33 -0
  38. package/.agent/skills/mindforge-check-todos/SKILL.md +40 -0
  39. package/.agent/skills/mindforge-cleanup/SKILL.md +19 -0
  40. package/.agent/skills/mindforge-complete-milestone/SKILL.md +131 -0
  41. package/.agent/skills/mindforge-debug/SKILL.md +163 -0
  42. package/.agent/skills/mindforge-discuss-phase/SKILL.md +54 -0
  43. package/.agent/skills/mindforge-do/SKILL.md +26 -0
  44. package/.agent/skills/mindforge-execute-phase/SKILL.md +49 -0
  45. package/.agent/skills/mindforge-fast/SKILL.md +23 -0
  46. package/.agent/skills/mindforge-forensics/SKILL.md +49 -0
  47. package/.agent/skills/mindforge-health/SKILL.md +17 -0
  48. package/.agent/skills/mindforge-help/SKILL.md +23 -0
  49. package/.agent/skills/mindforge-insert-phase/SKILL.md +28 -0
  50. package/.agent/skills/mindforge-join-discord/SKILL.md +19 -0
  51. package/.agent/skills/mindforge-list-phase-assumptions/SKILL.md +41 -0
  52. package/.agent/skills/mindforge-list-workspaces/SKILL.md +17 -0
  53. package/.agent/skills/mindforge-manager/SKILL.md +32 -0
  54. package/.agent/skills/mindforge-map-codebase/SKILL.md +64 -0
  55. package/.agent/skills/mindforge-milestone-summary/SKILL.md +44 -0
  56. package/.agent/skills/mindforge-new-milestone/SKILL.md +38 -0
  57. package/.agent/skills/mindforge-new-project/SKILL.md +36 -0
  58. package/.agent/skills/mindforge-new-workspace/SKILL.md +39 -0
  59. package/.agent/skills/mindforge-next/SKILL.md +19 -0
  60. package/.agent/skills/mindforge-note/SKILL.md +29 -0
  61. package/.agent/skills/mindforge-pause-work/SKILL.md +35 -0
  62. package/.agent/skills/mindforge-plan-milestone-gaps/SKILL.md +28 -0
  63. package/.agent/skills/mindforge-plan-phase/SKILL.md +37 -0
  64. package/.agent/skills/mindforge-plant-seed/SKILL.md +22 -0
  65. package/.agent/skills/mindforge-pr-branch/SKILL.md +21 -0
  66. package/.agent/skills/mindforge-profile-user/SKILL.md +38 -0
  67. package/.agent/skills/mindforge-progress/SKILL.md +19 -0
  68. package/.agent/skills/mindforge-quick/SKILL.md +38 -0
  69. package/.agent/skills/mindforge-reapply-patches/SKILL.md +124 -0
  70. package/.agent/skills/mindforge-remove-phase/SKILL.md +26 -0
  71. package/.agent/skills/mindforge-remove-workspace/SKILL.md +22 -0
  72. package/.agent/skills/mindforge-research-phase/SKILL.md +186 -0
  73. package/.agent/skills/mindforge-resume-work/SKILL.md +35 -0
  74. package/.agent/skills/mindforge-review/SKILL.md +31 -0
  75. package/.agent/skills/mindforge-review-backlog/SKILL.md +58 -0
  76. package/.agent/skills/mindforge-session-report/SKILL.md +16 -0
  77. package/.agent/skills/mindforge-set-profile/SKILL.md +9 -0
  78. package/.agent/skills/mindforge-settings/SKILL.md +32 -0
  79. package/.agent/skills/mindforge-ship/SKILL.md +16 -0
  80. package/.agent/skills/mindforge-stats/SKILL.md +16 -0
  81. package/.agent/skills/mindforge-thread/SKILL.md +123 -0
  82. package/.agent/skills/mindforge-ui-phase/SKILL.md +24 -0
  83. package/.agent/skills/mindforge-ui-review/SKILL.md +24 -0
  84. package/.agent/skills/mindforge-update/SKILL.md +35 -0
  85. package/.agent/skills/mindforge-validate-phase/SKILL.md +26 -0
  86. package/.agent/skills/mindforge-verify-work/SKILL.md +30 -0
  87. package/.agent/skills/mindforge-workstreams/SKILL.md +65 -0
  88. package/.agent/workflows/mindforge-add-phase.md +112 -0
  89. package/.agent/workflows/mindforge-add-tests.md +351 -0
  90. package/.agent/workflows/mindforge-add-todo.md +158 -0
  91. package/.agent/workflows/mindforge-audit-milestone.md +332 -0
  92. package/.agent/workflows/mindforge-audit-uat.md +109 -0
  93. package/.agent/workflows/mindforge-autonomous.md +815 -0
  94. package/.agent/workflows/mindforge-check-todos.md +177 -0
  95. package/.agent/workflows/mindforge-cleanup.md +152 -0
  96. package/.agent/workflows/mindforge-complete-milestone.md +766 -0
  97. package/.agent/workflows/mindforge-diagnose-issues.md +220 -0
  98. package/.agent/workflows/mindforge-discovery-phase.md +289 -0
  99. package/.agent/workflows/mindforge-discuss-phase-assumptions.md +645 -0
  100. package/.agent/workflows/mindforge-discuss-phase.md +1047 -0
  101. package/.agent/workflows/mindforge-do.md +104 -0
  102. package/.agent/workflows/mindforge-execute-phase.md +838 -0
  103. package/.agent/workflows/mindforge-execute-plan.md +509 -0
  104. package/.agent/workflows/mindforge-fast.md +105 -0
  105. package/.agent/workflows/mindforge-forensics.md +265 -0
  106. package/.agent/workflows/mindforge-health.md +181 -0
  107. package/.agent/workflows/mindforge-help.md +606 -0
  108. package/.agent/workflows/mindforge-insert-phase.md +130 -0
  109. package/.agent/workflows/mindforge-list-phase-assumptions.md +178 -0
  110. package/.agent/workflows/mindforge-list-workspaces.md +56 -0
  111. package/.agent/workflows/mindforge-manager.md +360 -0
  112. package/.agent/workflows/mindforge-map-codebase.md +370 -0
  113. package/.agent/workflows/mindforge-milestone-summary.md +223 -0
  114. package/.agent/workflows/mindforge-new-milestone.md +469 -0
  115. package/.agent/workflows/mindforge-new-project.md +1226 -0
  116. package/.agent/workflows/mindforge-new-workspace.md +237 -0
  117. package/.agent/workflows/mindforge-next.md +97 -0
  118. package/.agent/workflows/mindforge-node-repair.md +92 -0
  119. package/.agent/workflows/mindforge-note.md +156 -0
  120. package/.agent/workflows/mindforge-pause-work.md +176 -0
  121. package/.agent/workflows/mindforge-plan-milestone-gaps.md +273 -0
  122. package/.agent/workflows/mindforge-plan-phase.md +848 -0
  123. package/.agent/workflows/mindforge-plant-seed.md +169 -0
  124. package/.agent/workflows/mindforge-pr-branch.md +129 -0
  125. package/.agent/workflows/mindforge-profile-user.md +450 -0
  126. package/.agent/workflows/mindforge-progress.md +507 -0
  127. package/.agent/workflows/mindforge-quick.md +732 -0
  128. package/.agent/workflows/mindforge-remove-phase.md +155 -0
  129. package/.agent/workflows/mindforge-remove-workspace.md +90 -0
  130. package/.agent/workflows/mindforge-research-phase.md +74 -0
  131. package/.agent/workflows/mindforge-resume-project.md +325 -0
  132. package/.agent/workflows/mindforge-review.md +228 -0
  133. package/.agent/workflows/mindforge-session-report.md +146 -0
  134. package/.agent/workflows/mindforge-settings.md +283 -0
  135. package/.agent/workflows/mindforge-ship.md +228 -0
  136. package/.agent/workflows/mindforge-stats.md +60 -0
  137. package/.agent/workflows/mindforge-transition.md +671 -0
  138. package/.agent/workflows/mindforge-ui-phase.md +290 -0
  139. package/.agent/workflows/mindforge-ui-review.md +157 -0
  140. package/.agent/workflows/mindforge-update.md +323 -0
  141. package/.agent/workflows/mindforge-validate-phase.md +167 -0
  142. package/.agent/workflows/mindforge-verify-phase.md +254 -0
  143. package/.agent/workflows/mindforge-verify-work.md +623 -0
  144. package/.mindforge/personas/advisor-researcher.md +3 -3
  145. package/.mindforge/personas/debug-specialist.md +1 -1
  146. package/.mindforge/personas/debugger.md +1 -1
  147. package/.mindforge/personas/developer.md +1 -1
  148. package/.mindforge/personas/phase-researcher.md +4 -4
  149. package/.mindforge/personas/project-researcher.md +3 -3
  150. package/.mindforge/personas/research-agent.md +4 -3
  151. package/.mindforge/personas/tech-writer.md +1 -1
  152. package/.mindforge/personas/ui-researcher.md +1 -1
  153. package/.planning/ROADMAP.md +10 -0
  154. package/CHANGELOG.md +34 -0
  155. package/README.md +70 -45
  156. package/RELEASENOTES.md +26 -26
  157. package/bin/install.js +41 -41
  158. package/bin/installer-core.js +67 -26
  159. package/bin/wizard/setup-wizard.js +11 -24
  160. package/bin/wizard/theme.js +141 -0
  161. package/docs/PERSONAS.md +119 -87
  162. package/docs/References/checkpoints.md +778 -0
  163. package/docs/References/config-reference.md +81 -0
  164. package/docs/References/continuation-format.md +249 -0
  165. package/docs/References/decimal-phase-calculation.md +64 -0
  166. package/docs/References/git-integration.md +295 -0
  167. package/docs/References/git-planning-commit.md +38 -0
  168. package/docs/References/model-profile-resolution.md +36 -0
  169. package/docs/References/model-profiles.md +139 -0
  170. package/docs/References/phase-argument-parsing.md +61 -0
  171. package/docs/References/planning-config.md +202 -0
  172. package/docs/References/questioning.md +162 -0
  173. package/docs/References/tdd.md +263 -0
  174. package/docs/References/ui-brand.md +160 -0
  175. package/docs/References/user-profiling.md +681 -0
  176. package/docs/References/verification-patterns.md +612 -0
  177. package/docs/References/workstream-flag.md +58 -0
  178. package/docs/Templates/Agents/CLAUDE-MD.md +122 -0
  179. package/docs/Templates/Agents/COPILOT-INSTRUCTIONS.md +7 -0
  180. package/docs/Templates/Agents/DEBUGGER-PROMPT.md +91 -0
  181. package/docs/Templates/Agents/PLANNER-PROMPT.md +117 -0
  182. package/docs/Templates/Codebase/architecture.md +255 -0
  183. package/docs/Templates/Codebase/concerns.md +310 -0
  184. package/docs/Templates/Codebase/conventions.md +307 -0
  185. package/docs/Templates/Codebase/integrations.md +280 -0
  186. package/docs/Templates/Codebase/stack.md +186 -0
  187. package/docs/Templates/Codebase/structure.md +285 -0
  188. package/docs/Templates/Codebase/testing.md +480 -0
  189. package/docs/Templates/Execution/CONTINUE-HERE.md +78 -0
  190. package/docs/Templates/Execution/DISCUSSION-LOG.md +63 -0
  191. package/docs/Templates/Execution/PHASE-PROMPT.md +610 -0
  192. package/docs/Templates/Execution/STATE.md +176 -0
  193. package/docs/Templates/Execution/SUMMARY-COMPLEX.md +59 -0
  194. package/docs/Templates/Execution/SUMMARY-MINIMAL.md +41 -0
  195. package/docs/Templates/Execution/SUMMARY-STANDARD.md +48 -0
  196. package/docs/Templates/Execution/SUMMARY.md +248 -0
  197. package/docs/Templates/Profile/DEV-PREFERENCES.md +21 -0
  198. package/docs/Templates/Profile/USER-PROFILE.md +146 -0
  199. package/docs/Templates/Profile/USER-SETUP.md +311 -0
  200. package/docs/Templates/Project/DISCOVERY.md +146 -0
  201. package/docs/Templates/Project/MILESTONE-ARCHIVE.md +123 -0
  202. package/docs/Templates/Project/MILESTONE.md +115 -0
  203. package/docs/Templates/Project/PROJECT.md +206 -0
  204. package/docs/Templates/Project/REQUIREMENTS.md +231 -0
  205. package/docs/Templates/Project/RETROSPECTIVE.md +54 -0
  206. package/docs/Templates/Project/ROADMAP.md +202 -0
  207. package/docs/Templates/Quality/DEBUG.md +164 -0
  208. package/docs/Templates/Quality/UAT.md +280 -0
  209. package/docs/Templates/Quality/UI-SPEC.md +100 -0
  210. package/docs/Templates/Quality/VALIDATION.md +76 -0
  211. package/docs/Templates/Quality/VERIFICATION-REPORT.md +322 -0
  212. package/docs/Templates/Research/ARCHITECTURE.md +204 -0
  213. package/docs/Templates/Research/FEATURES.md +147 -0
  214. package/docs/Templates/Research/PITFALLS.md +200 -0
  215. package/docs/Templates/Research/STACK.md +120 -0
  216. package/docs/Templates/Research/SUMMARY.md +170 -0
  217. package/docs/Templates/System/CONFIG.json +43 -0
  218. package/docs/Templates/System/CONTEXT.md +352 -0
  219. package/docs/architecture/README.md +54 -42
  220. package/docs/commands-reference.md +62 -14
  221. package/docs/getting-started.md +26 -18
  222. package/docs/skills-authoring-guide.md +40 -12
  223. package/docs/tutorial.md +83 -116
  224. package/docs/user-guide.md +72 -198
  225. package/package.json +7 -2
  226. package/.mindforge/memory/knowledge-base.jsonl +0 -7
  227. package/.mindforge/memory/pattern-library.jsonl +0 -1
  228. package/.mindforge/memory/team-preferences.jsonl +0 -4
  229. package/.planning/browser-daemon.log +0 -32
  230. package/docs/mindforge-md-reference.md +0 -57
  231. package/docs/reference/config-reference.md +0 -64
  232. /package/{.mindforge/memory/decision-library.jsonl → .planning/phases/01-migrate-gsd-to-mindforge/.gitkeep} +0 -0
  233. /package/docs/{reference → References}/audit-events.md +0 -0
  234. /package/docs/{reference → References}/commands.md +0 -0
  235. /package/docs/{reference → References}/sdk-api.md +0 -0
  236. /package/docs/{reference → References}/skills-api.md +0 -0
@@ -0,0 +1,329 @@
1
+ /**
2
+ * Roadmap — Roadmap parsing and update operations
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { escapeRegex, normalizePhaseName, planningPaths, output, error, findPhaseInternal, stripShippedMilestones, extractCurrentMilestone, replaceInCurrentMilestone } = require('./core.cjs');
8
+
9
+ function cmdRoadmapGetPhase(cwd, phaseNum, raw) {
10
+ const roadmapPath = planningPaths(cwd).roadmap;
11
+
12
+ if (!fs.existsSync(roadmapPath)) {
13
+ output({ found: false, error: 'ROADMAP.md not found' }, raw, '');
14
+ return;
15
+ }
16
+
17
+ try {
18
+ const content = extractCurrentMilestone(fs.readFileSync(roadmapPath, 'utf-8'), cwd);
19
+
20
+ // Escape special regex chars in phase number, handle decimal
21
+ const escapedPhase = escapeRegex(phaseNum);
22
+
23
+ // Match "## Phase X:", "### Phase X:", or "#### Phase X:" with optional name
24
+ const phasePattern = new RegExp(
25
+ `#{2,4}\\s*Phase\\s+${escapedPhase}:\\s*([^\\n]+)`,
26
+ 'i'
27
+ );
28
+ const headerMatch = content.match(phasePattern);
29
+
30
+ if (!headerMatch) {
31
+ // Fallback: check if phase exists in summary list but missing detail section
32
+ const checklistPattern = new RegExp(
33
+ `-\\s*\\[[ x]\\]\\s*\\*\\*Phase\\s+${escapedPhase}:\\s*([^*]+)\\*\\*`,
34
+ 'i'
35
+ );
36
+ const checklistMatch = content.match(checklistPattern);
37
+
38
+ if (checklistMatch) {
39
+ // Phase exists in summary but missing detail section - malformed ROADMAP
40
+ output({
41
+ found: false,
42
+ phase_number: phaseNum,
43
+ phase_name: checklistMatch[1].trim(),
44
+ error: 'malformed_roadmap',
45
+ message: `Phase ${phaseNum} exists in summary list but missing "### Phase ${phaseNum}:" detail section. ROADMAP.md needs both formats.`
46
+ }, raw, '');
47
+ return;
48
+ }
49
+
50
+ output({ found: false, phase_number: phaseNum }, raw, '');
51
+ return;
52
+ }
53
+
54
+ const phaseName = headerMatch[1].trim();
55
+ const headerIndex = headerMatch.index;
56
+
57
+ // Find the end of this section (next ## or ### phase header, or end of file)
58
+ const restOfContent = content.slice(headerIndex);
59
+ const nextHeaderMatch = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
60
+ const sectionEnd = nextHeaderMatch
61
+ ? headerIndex + nextHeaderMatch.index
62
+ : content.length;
63
+
64
+ const section = content.slice(headerIndex, sectionEnd).trim();
65
+
66
+ // Extract goal if present (supports both **Goal:** and **Goal**: formats)
67
+ const goalMatch = section.match(/\*\*Goal(?::\*\*|\*\*:)\s*([^\n]+)/i);
68
+ const goal = goalMatch ? goalMatch[1].trim() : null;
69
+
70
+ // Extract success criteria as structured array
71
+ const criteriaMatch = section.match(/\*\*Success Criteria\*\*[^\n]*:\s*\n((?:\s*\d+\.\s*[^\n]+\n?)+)/i);
72
+ const success_criteria = criteriaMatch
73
+ ? criteriaMatch[1].trim().split('\n').map(line => line.replace(/^\s*\d+\.\s*/, '').trim()).filter(Boolean)
74
+ : [];
75
+
76
+ output(
77
+ {
78
+ found: true,
79
+ phase_number: phaseNum,
80
+ phase_name: phaseName,
81
+ goal,
82
+ success_criteria,
83
+ section,
84
+ },
85
+ raw,
86
+ section
87
+ );
88
+ } catch (e) {
89
+ error('Failed to read ROADMAP.md: ' + e.message);
90
+ }
91
+ }
92
+
93
+ function cmdRoadmapAnalyze(cwd, raw) {
94
+ const roadmapPath = planningPaths(cwd).roadmap;
95
+
96
+ if (!fs.existsSync(roadmapPath)) {
97
+ output({ error: 'ROADMAP.md not found', milestones: [], phases: [], current_phase: null }, raw);
98
+ return;
99
+ }
100
+
101
+ const rawContent = fs.readFileSync(roadmapPath, 'utf-8');
102
+ const content = extractCurrentMilestone(rawContent, cwd);
103
+ const phasesDir = planningPaths(cwd).phases;
104
+
105
+ // Extract all phase headings: ## Phase N: Name or ### Phase N: Name
106
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
107
+ const phases = [];
108
+ let match;
109
+
110
+ while ((match = phasePattern.exec(content)) !== null) {
111
+ const phaseNum = match[1];
112
+ const phaseName = match[2].replace(/\(INSERTED\)/i, '').trim();
113
+
114
+ // Extract goal from the section
115
+ const sectionStart = match.index;
116
+ const restOfContent = content.slice(sectionStart);
117
+ const nextHeader = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
118
+ const sectionEnd = nextHeader ? sectionStart + nextHeader.index : content.length;
119
+ const section = content.slice(sectionStart, sectionEnd);
120
+
121
+ const goalMatch = section.match(/\*\*Goal(?::\*\*|\*\*:)\s*([^\n]+)/i);
122
+ const goal = goalMatch ? goalMatch[1].trim() : null;
123
+
124
+ const dependsMatch = section.match(/\*\*Depends on(?::\*\*|\*\*:)\s*([^\n]+)/i);
125
+ const depends_on = dependsMatch ? dependsMatch[1].trim() : null;
126
+
127
+ // Check completion on disk
128
+ const normalized = normalizePhaseName(phaseNum);
129
+ let diskStatus = 'no_directory';
130
+ let planCount = 0;
131
+ let summaryCount = 0;
132
+ let hasContext = false;
133
+ let hasResearch = false;
134
+
135
+ try {
136
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
137
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
138
+ const dirMatch = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);
139
+
140
+ if (dirMatch) {
141
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dirMatch));
142
+ planCount = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
143
+ summaryCount = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
144
+ hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
145
+ hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
146
+
147
+ if (summaryCount >= planCount && planCount > 0) diskStatus = 'complete';
148
+ else if (summaryCount > 0) diskStatus = 'partial';
149
+ else if (planCount > 0) diskStatus = 'planned';
150
+ else if (hasResearch) diskStatus = 'researched';
151
+ else if (hasContext) diskStatus = 'discussed';
152
+ else diskStatus = 'empty';
153
+ }
154
+ } catch { /* intentionally empty */ }
155
+
156
+ // Check ROADMAP checkbox status
157
+ const checkboxPattern = new RegExp(`-\\s*\\[(x| )\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}[:\\s]`, 'i');
158
+ const checkboxMatch = content.match(checkboxPattern);
159
+ const roadmapComplete = checkboxMatch ? checkboxMatch[1] === 'x' : false;
160
+
161
+ // If roadmap marks phase complete, trust that over disk file structure.
162
+ // Phases completed before MindForge tracking (or via external tools) may lack
163
+ // the standard PLAN/SUMMARY pairs but are still done.
164
+ if (roadmapComplete && diskStatus !== 'complete') {
165
+ diskStatus = 'complete';
166
+ }
167
+
168
+ phases.push({
169
+ number: phaseNum,
170
+ name: phaseName,
171
+ goal,
172
+ depends_on,
173
+ plan_count: planCount,
174
+ summary_count: summaryCount,
175
+ has_context: hasContext,
176
+ has_research: hasResearch,
177
+ disk_status: diskStatus,
178
+ roadmap_complete: roadmapComplete,
179
+ });
180
+ }
181
+
182
+ // Extract milestone info
183
+ const milestones = [];
184
+ const milestonePattern = /##\s*(.*v(\d+(?:\.\d+)+)[^(\n]*)/gi;
185
+ let mMatch;
186
+ while ((mMatch = milestonePattern.exec(content)) !== null) {
187
+ milestones.push({
188
+ heading: mMatch[1].trim(),
189
+ version: 'v' + mMatch[2],
190
+ });
191
+ }
192
+
193
+ // Find current and next phase
194
+ const currentPhase = phases.find(p => p.disk_status === 'planned' || p.disk_status === 'partial') || null;
195
+ const nextPhase = phases.find(p => p.disk_status === 'empty' || p.disk_status === 'no_directory' || p.disk_status === 'discussed' || p.disk_status === 'researched') || null;
196
+
197
+ // Aggregated stats
198
+ const totalPlans = phases.reduce((sum, p) => sum + p.plan_count, 0);
199
+ const totalSummaries = phases.reduce((sum, p) => sum + p.summary_count, 0);
200
+ const completedPhases = phases.filter(p => p.disk_status === 'complete').length;
201
+
202
+ // Detect phases in summary list without detail sections (malformed ROADMAP)
203
+ const checklistPattern = /-\s*\[[ x]\]\s*\*\*Phase\s+(\d+[A-Z]?(?:\.\d+)*)/gi;
204
+ const checklistPhases = new Set();
205
+ let checklistMatch;
206
+ while ((checklistMatch = checklistPattern.exec(content)) !== null) {
207
+ checklistPhases.add(checklistMatch[1]);
208
+ }
209
+ const detailPhases = new Set(phases.map(p => p.number));
210
+ const missingDetails = [...checklistPhases].filter(p => !detailPhases.has(p));
211
+
212
+ const result = {
213
+ milestones,
214
+ phases,
215
+ phase_count: phases.length,
216
+ completed_phases: completedPhases,
217
+ total_plans: totalPlans,
218
+ total_summaries: totalSummaries,
219
+ progress_percent: totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0,
220
+ current_phase: currentPhase ? currentPhase.number : null,
221
+ next_phase: nextPhase ? nextPhase.number : null,
222
+ missing_phase_details: missingDetails.length > 0 ? missingDetails : null,
223
+ };
224
+
225
+ output(result, raw);
226
+ }
227
+
228
+ function cmdRoadmapUpdatePlanProgress(cwd, phaseNum, raw) {
229
+ if (!phaseNum) {
230
+ error('phase number required for roadmap update-plan-progress');
231
+ }
232
+
233
+ const roadmapPath = planningPaths(cwd).roadmap;
234
+
235
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
236
+ if (!phaseInfo) {
237
+ error(`Phase ${phaseNum} not found`);
238
+ }
239
+
240
+ const planCount = phaseInfo.plans.length;
241
+ const summaryCount = phaseInfo.summaries.length;
242
+
243
+ if (planCount === 0) {
244
+ output({ updated: false, reason: 'No plans found', plan_count: 0, summary_count: 0 }, raw, 'no plans');
245
+ return;
246
+ }
247
+
248
+ const isComplete = summaryCount >= planCount;
249
+ const status = isComplete ? 'Complete' : summaryCount > 0 ? 'In Progress' : 'Planned';
250
+ const today = new Date().toISOString().split('T')[0];
251
+
252
+ if (!fs.existsSync(roadmapPath)) {
253
+ output({ updated: false, reason: 'ROADMAP.md not found', plan_count: planCount, summary_count: summaryCount }, raw, 'no roadmap');
254
+ return;
255
+ }
256
+
257
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
258
+ const phaseEscaped = escapeRegex(phaseNum);
259
+
260
+ // Progress table row: update Plans/Status/Date columns (handles 4 or 5 column tables)
261
+ const tableRowPattern = new RegExp(
262
+ `^(\\|\\s*${phaseEscaped}\\.?\\s[^|]*(?:\\|[^\\n]*))$`,
263
+ 'im'
264
+ );
265
+ const dateField = isComplete ? ` ${today} ` : ' ';
266
+ roadmapContent = roadmapContent.replace(tableRowPattern, (fullRow) => {
267
+ const cells = fullRow.split('|').slice(1, -1); // drop leading/trailing empty from split
268
+ if (cells.length === 5) {
269
+ // 5-col: Phase | Milestone | Plans | Status | Completed
270
+ cells[2] = ` ${summaryCount}/${planCount} `;
271
+ cells[3] = ` ${status.padEnd(11)}`;
272
+ cells[4] = dateField;
273
+ } else if (cells.length === 4) {
274
+ // 4-col: Phase | Plans | Status | Completed
275
+ cells[1] = ` ${summaryCount}/${planCount} `;
276
+ cells[2] = ` ${status.padEnd(11)}`;
277
+ cells[3] = dateField;
278
+ }
279
+ return '|' + cells.join('|') + '|';
280
+ });
281
+
282
+ // Update plan count in phase detail section
283
+ const planCountPattern = new RegExp(
284
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
285
+ 'i'
286
+ );
287
+ const planCountText = isComplete
288
+ ? `${summaryCount}/${planCount} plans complete`
289
+ : `${summaryCount}/${planCount} plans executed`;
290
+ roadmapContent = replaceInCurrentMilestone(roadmapContent, planCountPattern, `$1${planCountText}`);
291
+
292
+ // If complete: check checkbox
293
+ if (isComplete) {
294
+ const checkboxPattern = new RegExp(
295
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${phaseEscaped}[:\\s][^\\n]*)`,
296
+ 'i'
297
+ );
298
+ roadmapContent = replaceInCurrentMilestone(roadmapContent, checkboxPattern, `$1x$2 (completed ${today})`);
299
+ }
300
+
301
+ // Mark completed plan checkboxes (e.g. "- [ ] 50-01-PLAN.md" or "- [ ] 50-01:")
302
+ for (const summaryFile of phaseInfo.summaries) {
303
+ const planId = summaryFile.replace('-SUMMARY.md', '').replace('SUMMARY.md', '');
304
+ if (!planId) continue;
305
+ const planEscaped = escapeRegex(planId);
306
+ const planCheckboxPattern = new RegExp(
307
+ `(-\\s*\\[) (\\]\\s*${planEscaped})`,
308
+ 'i'
309
+ );
310
+ roadmapContent = roadmapContent.replace(planCheckboxPattern, '$1x$2');
311
+ }
312
+
313
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
314
+
315
+ output({
316
+ updated: true,
317
+ phase: phaseNum,
318
+ plan_count: planCount,
319
+ summary_count: summaryCount,
320
+ status,
321
+ complete: isComplete,
322
+ }, raw, `${summaryCount}/${planCount} ${status}`);
323
+ }
324
+
325
+ module.exports = {
326
+ cmdRoadmapGetPhase,
327
+ cmdRoadmapAnalyze,
328
+ cmdRoadmapUpdatePlanProgress,
329
+ };
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Security — Input validation, path traversal prevention, and prompt injection guards
3
+ *
4
+ * This module centralizes security checks for MindForge tooling. Because MindForge generates
5
+ * markdown files that become LLM system prompts (agent instructions, workflow state,
6
+ * phase plans), any user-controlled text that flows into these files is a potential
7
+ * indirect prompt injection vector.
8
+ *
9
+ * Threat model:
10
+ * 1. Path traversal: user-supplied file paths escape the project directory
11
+ * 2. Prompt injection: malicious text in arguments/PRDs embeds LLM instructions
12
+ * 3. Shell metacharacter injection: user text interpreted by shell
13
+ * 4. JSON injection: malformed JSON crashes or corrupts state
14
+ * 5. Regex DoS: crafted input causes catastrophic backtracking
15
+ */
16
+ 'use strict';
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ // ─── Path Traversal Prevention ──────────────────────────────────────────────
22
+
23
+ /**
24
+ * Validate that a file path resolves within an allowed base directory.
25
+ * Prevents path traversal attacks via ../ sequences, symlinks, or absolute paths.
26
+ *
27
+ * @param {string} filePath - The user-supplied file path
28
+ * @param {string} baseDir - The allowed base directory (e.g., project root)
29
+ * @param {object} [opts] - Options
30
+ * @param {boolean} [opts.allowAbsolute=false] - Allow absolute paths (still must be within baseDir)
31
+ * @returns {{ safe: boolean, resolved: string, error?: string }}
32
+ */
33
+ function validatePath(filePath, baseDir, opts = {}) {
34
+ if (!filePath || typeof filePath !== 'string') {
35
+ return { safe: false, resolved: '', error: 'Empty or invalid file path' };
36
+ }
37
+
38
+ if (!baseDir || typeof baseDir !== 'string') {
39
+ return { safe: false, resolved: '', error: 'Empty or invalid base directory' };
40
+ }
41
+
42
+ // Reject null bytes (can bypass path checks in some environments)
43
+ if (filePath.includes('\0')) {
44
+ return { safe: false, resolved: '', error: 'Path contains null bytes' };
45
+ }
46
+
47
+ // Resolve symlinks in base directory to handle macOS /var -> /private/var
48
+ // and similar platform-specific symlink chains
49
+ let resolvedBase;
50
+ try {
51
+ resolvedBase = fs.realpathSync(path.resolve(baseDir));
52
+ } catch {
53
+ resolvedBase = path.resolve(baseDir);
54
+ }
55
+
56
+ let resolvedPath;
57
+
58
+ if (path.isAbsolute(filePath)) {
59
+ if (!opts.allowAbsolute) {
60
+ return { safe: false, resolved: '', error: 'Absolute paths not allowed' };
61
+ }
62
+ resolvedPath = path.resolve(filePath);
63
+ } else {
64
+ resolvedPath = path.resolve(baseDir, filePath);
65
+ }
66
+
67
+ // Resolve symlinks in the target path too
68
+ try {
69
+ resolvedPath = fs.realpathSync(resolvedPath);
70
+ } catch {
71
+ // File may not exist yet (e.g., about to be created) — use logical resolution
72
+ // but still resolve the parent directory if it exists
73
+ const parentDir = path.dirname(resolvedPath);
74
+ try {
75
+ const realParent = fs.realpathSync(parentDir);
76
+ resolvedPath = path.join(realParent, path.basename(resolvedPath));
77
+ } catch {
78
+ // Parent doesn't exist either — keep the resolved path as-is
79
+ }
80
+ }
81
+
82
+ // Normalize both paths and check containment
83
+ const normalizedBase = resolvedBase + path.sep;
84
+ const normalizedPath = resolvedPath + path.sep;
85
+
86
+ // The resolved path must start with the base directory
87
+ // (or be exactly the base directory)
88
+ if (resolvedPath !== resolvedBase && !normalizedPath.startsWith(normalizedBase)) {
89
+ return {
90
+ safe: false,
91
+ resolved: resolvedPath,
92
+ error: `Path escapes allowed directory: ${resolvedPath} is outside ${resolvedBase}`,
93
+ };
94
+ }
95
+
96
+ return { safe: true, resolved: resolvedPath };
97
+ }
98
+
99
+ /**
100
+ * Validate a file path and throw on traversal attempt.
101
+ * Convenience wrapper around validatePath for use in CLI commands.
102
+ */
103
+ function requireSafePath(filePath, baseDir, label, opts = {}) {
104
+ const result = validatePath(filePath, baseDir, opts);
105
+ if (!result.safe) {
106
+ throw new Error(`${label || 'Path'} validation failed: ${result.error}`);
107
+ }
108
+ return result.resolved;
109
+ }
110
+
111
+ // ─── Prompt Injection Detection ─────────────────────────────────────────────
112
+
113
+ /**
114
+ * Patterns that indicate prompt injection attempts in user-supplied text.
115
+ * These patterns catch common indirect prompt injection techniques where
116
+ * an attacker embeds LLM instructions in text that will be read by an agent.
117
+ *
118
+ * Note: This is defense-in-depth — not a complete solution. The primary defense
119
+ * is proper input/output boundaries in agent prompts.
120
+ */
121
+ const INJECTION_PATTERNS = [
122
+ // Direct instruction override attempts
123
+ /ignore\s+(all\s+)?previous\s+instructions/i,
124
+ /ignore\s+(all\s+)?above\s+instructions/i,
125
+ /disregard\s+(all\s+)?previous/i,
126
+ /forget\s+(all\s+)?(your\s+)?instructions/i,
127
+ /override\s+(system|previous)\s+(prompt|instructions)/i,
128
+
129
+ // Role/identity manipulation
130
+ /you\s+are\s+now\s+(?:a|an|the)\s+/i,
131
+ /act\s+as\s+(?:a|an|the)\s+(?!plan|phase|wave)/i, // allow "act as a plan"
132
+ /pretend\s+(?:you(?:'re| are)\s+|to\s+be\s+)/i,
133
+ /from\s+now\s+on,?\s+you\s+(?:are|will|should|must)/i,
134
+
135
+ // System prompt extraction
136
+ /(?:print|output|reveal|show|display|repeat)\s+(?:your\s+)?(?:system\s+)?(?:prompt|instructions)/i,
137
+ /what\s+(?:are|is)\s+your\s+(?:system\s+)?(?:prompt|instructions)/i,
138
+
139
+ // Hidden instruction markers (XML/HTML tags that mimic system messages)
140
+ // Note: <instructions> is excluded — MindForge uses it as legitimate prompt structure
141
+ // Requires > to close the tag (not just whitespace) to avoid matching generic types like Promise<User | null>
142
+ /<\/?(?:system|assistant|human)>/i,
143
+ /\[SYSTEM\]/i,
144
+ /\[INST\]/i,
145
+ /<<\s*SYS\s*>>/i,
146
+
147
+ // Exfiltration attempts
148
+ /(?:send|post|fetch|curl|wget)\s+(?:to|from)\s+https?:\/\//i,
149
+ /(?:base64|btoa|encode)\s+(?:and\s+)?(?:send|exfiltrate|output)/i,
150
+
151
+ // Tool manipulation
152
+ /(?:run|execute|call|invoke)\s+(?:the\s+)?(?:bash|shell|exec|spawn)\s+(?:tool|command)/i,
153
+ ];
154
+
155
+ /**
156
+ * Scan text for potential prompt injection patterns.
157
+ * Returns an array of findings (empty = clean).
158
+ *
159
+ * @param {string} text - The text to scan
160
+ * @param {object} [opts] - Options
161
+ * @param {boolean} [opts.strict=false] - Enable stricter matching (more false positives)
162
+ * @returns {{ clean: boolean, findings: string[] }}
163
+ */
164
+ function scanForInjection(text, opts = {}) {
165
+ if (!text || typeof text !== 'string') {
166
+ return { clean: true, findings: [] };
167
+ }
168
+
169
+ const findings = [];
170
+
171
+ for (const pattern of INJECTION_PATTERNS) {
172
+ if (pattern.test(text)) {
173
+ findings.push(`Matched injection pattern: ${pattern.source}`);
174
+ }
175
+ }
176
+
177
+ if (opts.strict) {
178
+ // Check for suspicious Unicode that could hide instructions
179
+ // (zero-width chars, RTL override, homoglyph attacks)
180
+ if (/[\u200B-\u200F\u2028-\u202F\uFEFF\u00AD]/.test(text)) {
181
+ findings.push('Contains suspicious zero-width or invisible Unicode characters');
182
+ }
183
+
184
+ // Check for extremely long strings that could be prompt stuffing
185
+ if (text.length > 50000) {
186
+ findings.push(`Suspicious text length: ${text.length} chars (potential prompt stuffing)`);
187
+ }
188
+ }
189
+
190
+ return { clean: findings.length === 0, findings };
191
+ }
192
+
193
+ /**
194
+ * Sanitize text that will be embedded in agent prompts or planning documents.
195
+ * Strips known injection markers while preserving legitimate content.
196
+ *
197
+ * This does NOT alter user intent — it neutralizes control characters and
198
+ * instruction-mimicking patterns that could hijack agent behavior.
199
+ *
200
+ * @param {string} text - Text to sanitize
201
+ * @returns {string} Sanitized text
202
+ */
203
+ function sanitizeForPrompt(text) {
204
+ if (!text || typeof text !== 'string') return text;
205
+
206
+ let sanitized = text;
207
+
208
+ // Strip zero-width characters that could hide instructions
209
+ sanitized = sanitized.replace(/[\u200B-\u200F\u2028-\u202F\uFEFF\u00AD]/g, '');
210
+
211
+ // Neutralize XML/HTML tags that mimic system boundaries
212
+ // Replace < > with full-width equivalents to prevent tag interpretation
213
+ // Note: <instructions> is excluded — MindForge uses it as legitimate prompt structure
214
+ sanitized = sanitized.replace(/<(\/?)(?:system|assistant|human)>/gi,
215
+ (_, slash) => `<${slash || ''}system-text>`);
216
+
217
+ // Neutralize [SYSTEM] / [INST] markers
218
+ sanitized = sanitized.replace(/\[(SYSTEM|INST)\]/gi, '[$1-TEXT]');
219
+
220
+ // Neutralize <<SYS>> markers
221
+ sanitized = sanitized.replace(/<<\s*SYS\s*>>/gi, '«SYS-TEXT»');
222
+
223
+ return sanitized;
224
+ }
225
+
226
+ // ─── Shell Safety ───────────────────────────────────────────────────────────
227
+
228
+ /**
229
+ * Validate that a string is safe to use as a shell argument when quoted.
230
+ * This is a defense-in-depth check — callers should always use array-based
231
+ * exec (spawnSync) where possible.
232
+ *
233
+ * @param {string} value - The value to check
234
+ * @param {string} label - Description for error messages
235
+ * @returns {string} The validated value
236
+ */
237
+ function validateShellArg(value, label) {
238
+ if (!value || typeof value !== 'string') {
239
+ throw new Error(`${label || 'Argument'}: empty or invalid value`);
240
+ }
241
+
242
+ // Reject null bytes
243
+ if (value.includes('\0')) {
244
+ throw new Error(`${label || 'Argument'}: contains null bytes`);
245
+ }
246
+
247
+ // Reject command substitution attempts
248
+ if (/[$`]/.test(value) && /\$\(|`/.test(value)) {
249
+ throw new Error(`${label || 'Argument'}: contains potential command substitution`);
250
+ }
251
+
252
+ return value;
253
+ }
254
+
255
+ // ─── JSON Safety ────────────────────────────────────────────────────────────
256
+
257
+ /**
258
+ * Safely parse JSON with error handling and optional size limits.
259
+ * Wraps JSON.parse to prevent uncaught exceptions from malformed input.
260
+ *
261
+ * @param {string} text - JSON string to parse
262
+ * @param {object} [opts] - Options
263
+ * @param {number} [opts.maxLength=1048576] - Maximum input length (1MB default)
264
+ * @param {string} [opts.label='JSON'] - Description for error messages
265
+ * @returns {{ ok: boolean, value?: any, error?: string }}
266
+ */
267
+ function safeJsonParse(text, opts = {}) {
268
+ const maxLength = opts.maxLength || 1048576;
269
+ const label = opts.label || 'JSON';
270
+
271
+ if (!text || typeof text !== 'string') {
272
+ return { ok: false, error: `${label}: empty or invalid input` };
273
+ }
274
+
275
+ if (text.length > maxLength) {
276
+ return { ok: false, error: `${label}: input exceeds ${maxLength} byte limit (got ${text.length})` };
277
+ }
278
+
279
+ try {
280
+ const value = JSON.parse(text);
281
+ return { ok: true, value };
282
+ } catch (err) {
283
+ return { ok: false, error: `${label}: parse error — ${err.message}` };
284
+ }
285
+ }
286
+
287
+ // ─── Phase/Argument Validation ──────────────────────────────────────────────
288
+
289
+ /**
290
+ * Validate a phase number argument.
291
+ * Phase numbers must match: integer, decimal (2.1), or letter suffix (12A).
292
+ * Rejects arbitrary strings that could be used for injection.
293
+ *
294
+ * @param {string} phase - The phase number to validate
295
+ * @returns {{ valid: boolean, normalized?: string, error?: string }}
296
+ */
297
+ function validatePhaseNumber(phase) {
298
+ if (!phase || typeof phase !== 'string') {
299
+ return { valid: false, error: 'Phase number is required' };
300
+ }
301
+
302
+ const trimmed = phase.trim();
303
+
304
+ // Standard numeric: 1, 01, 12A, 12.1, 12A.1.2
305
+ if (/^\d{1,4}[A-Z]?(?:\.\d{1,3})*$/i.test(trimmed)) {
306
+ return { valid: true, normalized: trimmed };
307
+ }
308
+
309
+ // Custom project IDs: PROJ-42, AUTH-101 (uppercase alphanumeric with hyphens)
310
+ if (/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){1,4}$/i.test(trimmed) && trimmed.length <= 30) {
311
+ return { valid: true, normalized: trimmed };
312
+ }
313
+
314
+ return { valid: false, error: `Invalid phase number format: "${trimmed}"` };
315
+ }
316
+
317
+ /**
318
+ * Validate a STATE.md field name to prevent injection into regex patterns.
319
+ * Field names must be alphanumeric with spaces, hyphens, underscores, or dots.
320
+ *
321
+ * @param {string} field - The field name to validate
322
+ * @returns {{ valid: boolean, error?: string }}
323
+ */
324
+ function validateFieldName(field) {
325
+ if (!field || typeof field !== 'string') {
326
+ return { valid: false, error: 'Field name is required' };
327
+ }
328
+
329
+ // Allow typical field names: "Current Phase", "active_plan", "Phase 1.2"
330
+ if (/^[A-Za-z][A-Za-z0-9 _.\-/]{0,60}$/.test(field)) {
331
+ return { valid: true };
332
+ }
333
+
334
+ return { valid: false, error: `Invalid field name: "${field}"` };
335
+ }
336
+
337
+ module.exports = {
338
+ // Path safety
339
+ validatePath,
340
+ requireSafePath,
341
+
342
+ // Prompt injection
343
+ INJECTION_PATTERNS,
344
+ scanForInjection,
345
+ sanitizeForPrompt,
346
+
347
+ // Shell safety
348
+ validateShellArg,
349
+
350
+ // JSON safety
351
+ safeJsonParse,
352
+
353
+ // Input validation
354
+ validatePhaseNumber,
355
+ validateFieldName,
356
+ };