@howlil/ez-agents 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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +845 -0
  3. package/README.zh-CN.md +702 -0
  4. package/agents/ez-codebase-mapper.md +770 -0
  5. package/agents/ez-debugger.md +1255 -0
  6. package/agents/ez-executor.md +487 -0
  7. package/agents/ez-integration-checker.md +443 -0
  8. package/agents/ez-nyquist-auditor.md +176 -0
  9. package/agents/ez-phase-researcher.md +553 -0
  10. package/agents/ez-plan-checker.md +706 -0
  11. package/agents/ez-planner.md +1307 -0
  12. package/agents/ez-project-researcher.md +629 -0
  13. package/agents/ez-research-synthesizer.md +247 -0
  14. package/agents/ez-roadmapper.md +650 -0
  15. package/agents/ez-ui-auditor.md +441 -0
  16. package/agents/ez-ui-checker.md +302 -0
  17. package/agents/ez-ui-researcher.md +355 -0
  18. package/agents/ez-verifier.md +579 -0
  19. package/bin/install.js +2862 -0
  20. package/bin/update.js +214 -0
  21. package/commands/ez/add-phase.md +43 -0
  22. package/commands/ez/add-tests.md +41 -0
  23. package/commands/ez/add-todo.md +47 -0
  24. package/commands/ez/audit-milestone.md +36 -0
  25. package/commands/ez/autonomous.md +41 -0
  26. package/commands/ez/check-todos.md +45 -0
  27. package/commands/ez/cleanup.md +18 -0
  28. package/commands/ez/complete-milestone.md +136 -0
  29. package/commands/ez/debug.md +168 -0
  30. package/commands/ez/discuss-phase.md +90 -0
  31. package/commands/ez/execute-phase.md +41 -0
  32. package/commands/ez/health.md +22 -0
  33. package/commands/ez/help.md +22 -0
  34. package/commands/ez/insert-phase.md +32 -0
  35. package/commands/ez/join-discord.md +18 -0
  36. package/commands/ez/list-phase-assumptions.md +46 -0
  37. package/commands/ez/map-codebase.md +71 -0
  38. package/commands/ez/new-milestone.md +44 -0
  39. package/commands/ez/new-project.md +42 -0
  40. package/commands/ez/pause-work.md +38 -0
  41. package/commands/ez/plan-milestone-gaps.md +34 -0
  42. package/commands/ez/plan-phase.md +45 -0
  43. package/commands/ez/progress.md +24 -0
  44. package/commands/ez/quick.md +45 -0
  45. package/commands/ez/reapply-patches.md +124 -0
  46. package/commands/ez/remove-phase.md +31 -0
  47. package/commands/ez/research-phase.md +190 -0
  48. package/commands/ez/resume-work.md +40 -0
  49. package/commands/ez/set-profile.md +34 -0
  50. package/commands/ez/settings.md +36 -0
  51. package/commands/ez/stats.md +18 -0
  52. package/commands/ez/ui-phase.md +34 -0
  53. package/commands/ez/ui-review.md +32 -0
  54. package/commands/ez/update.md +37 -0
  55. package/commands/ez/validate-phase.md +35 -0
  56. package/commands/ez/verify-work.md +38 -0
  57. package/get-shit-done/bin/ez-tools.cjs +598 -0
  58. package/get-shit-done/bin/lib/assistant-adapter.cjs +205 -0
  59. package/get-shit-done/bin/lib/audit-exec.cjs +150 -0
  60. package/get-shit-done/bin/lib/auth.cjs +175 -0
  61. package/get-shit-done/bin/lib/circuit-breaker.cjs +118 -0
  62. package/get-shit-done/bin/lib/commands.cjs +666 -0
  63. package/get-shit-done/bin/lib/config.cjs +183 -0
  64. package/get-shit-done/bin/lib/core.cjs +495 -0
  65. package/get-shit-done/bin/lib/file-lock.cjs +236 -0
  66. package/get-shit-done/bin/lib/frontmatter.cjs +299 -0
  67. package/get-shit-done/bin/lib/fs-utils.cjs +153 -0
  68. package/get-shit-done/bin/lib/git-utils.cjs +203 -0
  69. package/get-shit-done/bin/lib/health-check.cjs +163 -0
  70. package/get-shit-done/bin/lib/index.cjs +113 -0
  71. package/get-shit-done/bin/lib/init.cjs +710 -0
  72. package/get-shit-done/bin/lib/logger.cjs +117 -0
  73. package/get-shit-done/bin/lib/milestone.cjs +241 -0
  74. package/get-shit-done/bin/lib/model-provider.cjs +146 -0
  75. package/get-shit-done/bin/lib/phase.cjs +908 -0
  76. package/get-shit-done/bin/lib/retry.cjs +119 -0
  77. package/get-shit-done/bin/lib/roadmap.cjs +305 -0
  78. package/get-shit-done/bin/lib/safe-exec.cjs +128 -0
  79. package/get-shit-done/bin/lib/safe-path.cjs +130 -0
  80. package/get-shit-done/bin/lib/state.cjs +721 -0
  81. package/get-shit-done/bin/lib/temp-file.cjs +239 -0
  82. package/get-shit-done/bin/lib/template.cjs +222 -0
  83. package/get-shit-done/bin/lib/test-file-lock.cjs +112 -0
  84. package/get-shit-done/bin/lib/test-graceful.cjs +93 -0
  85. package/get-shit-done/bin/lib/test-logger.cjs +60 -0
  86. package/get-shit-done/bin/lib/test-safe-exec.cjs +38 -0
  87. package/get-shit-done/bin/lib/test-safe-path.cjs +33 -0
  88. package/get-shit-done/bin/lib/test-temp-file.cjs +125 -0
  89. package/get-shit-done/bin/lib/timeout-exec.cjs +62 -0
  90. package/get-shit-done/bin/lib/verify.cjs +820 -0
  91. package/get-shit-done/references/checkpoints.md +776 -0
  92. package/get-shit-done/references/continuation-format.md +249 -0
  93. package/get-shit-done/references/decimal-phase-calculation.md +65 -0
  94. package/get-shit-done/references/git-integration.md +248 -0
  95. package/get-shit-done/references/git-planning-commit.md +38 -0
  96. package/get-shit-done/references/model-profile-resolution.md +34 -0
  97. package/get-shit-done/references/model-profiles.md +93 -0
  98. package/get-shit-done/references/phase-argument-parsing.md +61 -0
  99. package/get-shit-done/references/planning-config.md +200 -0
  100. package/get-shit-done/references/questioning.md +162 -0
  101. package/get-shit-done/references/tdd.md +263 -0
  102. package/get-shit-done/references/ui-brand.md +160 -0
  103. package/get-shit-done/references/verification-patterns.md +612 -0
  104. package/get-shit-done/templates/DEBUG.md +164 -0
  105. package/get-shit-done/templates/UAT.md +247 -0
  106. package/get-shit-done/templates/UI-SPEC.md +100 -0
  107. package/get-shit-done/templates/VALIDATION.md +76 -0
  108. package/get-shit-done/templates/codebase/architecture.md +255 -0
  109. package/get-shit-done/templates/codebase/concerns.md +310 -0
  110. package/get-shit-done/templates/codebase/conventions.md +307 -0
  111. package/get-shit-done/templates/codebase/integrations.md +280 -0
  112. package/get-shit-done/templates/codebase/stack.md +186 -0
  113. package/get-shit-done/templates/codebase/structure.md +285 -0
  114. package/get-shit-done/templates/codebase/testing.md +480 -0
  115. package/get-shit-done/templates/config.json +37 -0
  116. package/get-shit-done/templates/context.md +352 -0
  117. package/get-shit-done/templates/continue-here.md +78 -0
  118. package/get-shit-done/templates/copilot-instructions.md +7 -0
  119. package/get-shit-done/templates/debug-subagent-prompt.md +91 -0
  120. package/get-shit-done/templates/discovery.md +146 -0
  121. package/get-shit-done/templates/milestone-archive.md +123 -0
  122. package/get-shit-done/templates/milestone.md +115 -0
  123. package/get-shit-done/templates/phase-prompt.md +610 -0
  124. package/get-shit-done/templates/planner-subagent-prompt.md +117 -0
  125. package/get-shit-done/templates/project.md +184 -0
  126. package/get-shit-done/templates/requirements.md +231 -0
  127. package/get-shit-done/templates/research-project/ARCHITECTURE.md +204 -0
  128. package/get-shit-done/templates/research-project/FEATURES.md +147 -0
  129. package/get-shit-done/templates/research-project/PITFALLS.md +200 -0
  130. package/get-shit-done/templates/research-project/STACK.md +120 -0
  131. package/get-shit-done/templates/research-project/SUMMARY.md +170 -0
  132. package/get-shit-done/templates/research.md +552 -0
  133. package/get-shit-done/templates/retrospective.md +54 -0
  134. package/get-shit-done/templates/roadmap.md +202 -0
  135. package/get-shit-done/templates/state.md +176 -0
  136. package/get-shit-done/templates/summary-complex.md +59 -0
  137. package/get-shit-done/templates/summary-minimal.md +41 -0
  138. package/get-shit-done/templates/summary-standard.md +48 -0
  139. package/get-shit-done/templates/summary.md +248 -0
  140. package/get-shit-done/templates/user-setup.md +311 -0
  141. package/get-shit-done/templates/verification-report.md +322 -0
  142. package/get-shit-done/workflows/add-phase.md +112 -0
  143. package/get-shit-done/workflows/add-tests.md +351 -0
  144. package/get-shit-done/workflows/add-todo.md +158 -0
  145. package/get-shit-done/workflows/audit-milestone.md +332 -0
  146. package/get-shit-done/workflows/autonomous.md +743 -0
  147. package/get-shit-done/workflows/check-todos.md +177 -0
  148. package/get-shit-done/workflows/cleanup.md +152 -0
  149. package/get-shit-done/workflows/complete-milestone.md +766 -0
  150. package/get-shit-done/workflows/diagnose-issues.md +219 -0
  151. package/get-shit-done/workflows/discovery-phase.md +289 -0
  152. package/get-shit-done/workflows/discuss-phase.md +762 -0
  153. package/get-shit-done/workflows/execute-phase.md +468 -0
  154. package/get-shit-done/workflows/execute-plan.md +483 -0
  155. package/get-shit-done/workflows/health.md +159 -0
  156. package/get-shit-done/workflows/help.md +492 -0
  157. package/get-shit-done/workflows/insert-phase.md +130 -0
  158. package/get-shit-done/workflows/list-phase-assumptions.md +178 -0
  159. package/get-shit-done/workflows/map-codebase.md +316 -0
  160. package/get-shit-done/workflows/new-milestone.md +384 -0
  161. package/get-shit-done/workflows/new-project.md +1111 -0
  162. package/get-shit-done/workflows/node-repair.md +92 -0
  163. package/get-shit-done/workflows/pause-work.md +122 -0
  164. package/get-shit-done/workflows/plan-milestone-gaps.md +274 -0
  165. package/get-shit-done/workflows/plan-phase.md +651 -0
  166. package/get-shit-done/workflows/progress.md +382 -0
  167. package/get-shit-done/workflows/quick.md +610 -0
  168. package/get-shit-done/workflows/remove-phase.md +155 -0
  169. package/get-shit-done/workflows/research-phase.md +74 -0
  170. package/get-shit-done/workflows/resume-project.md +307 -0
  171. package/get-shit-done/workflows/set-profile.md +81 -0
  172. package/get-shit-done/workflows/settings.md +242 -0
  173. package/get-shit-done/workflows/stats.md +57 -0
  174. package/get-shit-done/workflows/transition.md +544 -0
  175. package/get-shit-done/workflows/ui-phase.md +290 -0
  176. package/get-shit-done/workflows/ui-review.md +157 -0
  177. package/get-shit-done/workflows/update.md +320 -0
  178. package/get-shit-done/workflows/validate-phase.md +167 -0
  179. package/get-shit-done/workflows/verify-phase.md +243 -0
  180. package/get-shit-done/workflows/verify-work.md +584 -0
  181. package/package.json +55 -0
  182. package/scripts/build-hooks.js +43 -0
  183. package/scripts/run-tests.cjs +29 -0
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * GSD Retry — Retry utility with exponential backoff
5
+ *
6
+ * Features:
7
+ * - Configurable max retries, base delay, max delay
8
+ * - Jitter to prevent thundering herd
9
+ * - Error classification (retryable vs non-retryable)
10
+ *
11
+ * Usage:
12
+ * const { retry, isRetryableError } = require('./retry.cjs');
13
+ * const result = await retry(() => fetch(url), { maxRetries: 3 });
14
+ */
15
+
16
+ const Logger = require('./logger.cjs');
17
+ const logger = new Logger();
18
+
19
+ /**
20
+ * Retry an operation with exponential backoff
21
+ * @param {Function} operation - Async function to retry
22
+ * @param {Object} options - Retry options
23
+ * @returns {Promise<any>} - Result of operation
24
+ */
25
+ async function retry(operation, options = {}) {
26
+ const {
27
+ maxRetries = 3,
28
+ baseDelay = 1000,
29
+ maxDelay = 30000,
30
+ jitter = true,
31
+ shouldRetry = isRetryableError
32
+ } = options;
33
+
34
+ let lastError;
35
+ let lastAttempt = null;
36
+
37
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
38
+ try {
39
+ lastAttempt = attempt;
40
+ return await operation();
41
+ } catch (err) {
42
+ lastError = err;
43
+
44
+ // Don't retry if error is not retryable or max retries reached
45
+ if (attempt === maxRetries || !shouldRetry(err)) {
46
+ logger.error('Operation failed after retries', {
47
+ attempts: attempt + 1,
48
+ error: err.message
49
+ });
50
+ break;
51
+ }
52
+
53
+ // Calculate delay with exponential backoff and jitter
54
+ const delay = Math.min(
55
+ baseDelay * Math.pow(2, attempt),
56
+ maxDelay
57
+ );
58
+ const jitteredDelay = jitter ? delay * (0.5 + Math.random()) : delay;
59
+
60
+ logger.warn('Retrying operation', {
61
+ attempt: attempt + 1,
62
+ maxRetries,
63
+ delay: Math.round(jitteredDelay),
64
+ error: err.message
65
+ });
66
+
67
+ await new Promise(resolve => setTimeout(resolve, jitteredDelay));
68
+ }
69
+ }
70
+
71
+ const error = new Error(`Operation failed after ${lastAttempt + 1} attempts: ${lastError.message}`);
72
+ error.cause = lastError;
73
+ throw error;
74
+ }
75
+
76
+ /**
77
+ * Check if error is retryable
78
+ * @param {Error} err - Error to check
79
+ * @returns {boolean} - True if retryable
80
+ */
81
+ function isRetryableError(err) {
82
+ const retryableCodes = ['ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'ENOTFOUND'];
83
+ const retryableStatus = [429, 500, 502, 503, 504];
84
+
85
+ if (err.code && retryableCodes.includes(err.code)) return true;
86
+ if (err.status && retryableStatus.includes(err.status)) return true;
87
+ if (err.message?.includes('rate limit')) return true;
88
+ if (err.message?.includes('timeout')) return true;
89
+ if (err.message?.includes('network')) return true;
90
+
91
+ return false;
92
+ }
93
+
94
+ /**
95
+ * Classify error type
96
+ * @param {Error} err - Error to classify
97
+ * @returns {string} - Error classification
98
+ */
99
+ function classifyError(err) {
100
+ if (isRetryableError(err)) {
101
+ return 'retryable';
102
+ }
103
+
104
+ if (err.code === 'ENOENT' || err.code === 'EPERM') {
105
+ return 'filesystem';
106
+ }
107
+
108
+ if (err.message?.includes('parse') || err.message?.includes('invalid')) {
109
+ return 'validation';
110
+ }
111
+
112
+ return 'unknown';
113
+ }
114
+
115
+ module.exports = {
116
+ retry,
117
+ isRetryableError,
118
+ classifyError
119
+ };
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Roadmap — Roadmap parsing and update operations
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { escapeRegex, normalizePhaseName, output, error, findPhaseInternal } = require('./core.cjs');
8
+
9
+ function cmdRoadmapGetPhase(cwd, phaseNum, raw) {
10
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
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 = fs.readFileSync(roadmapPath, 'utf-8');
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 = path.join(cwd, '.planning', 'ROADMAP.md');
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 content = fs.readFileSync(roadmapPath, 'utf-8');
102
+ const phasesDir = path.join(cwd, '.planning', 'phases');
103
+
104
+ // Extract all phase headings: ## Phase N: Name or ### Phase N: Name
105
+ const phasePattern = /#{2,4}\s*Phase\s+(\d+[A-Z]?(?:\.\d+)*)\s*:\s*([^\n]+)/gi;
106
+ const phases = [];
107
+ let match;
108
+
109
+ while ((match = phasePattern.exec(content)) !== null) {
110
+ const phaseNum = match[1];
111
+ const phaseName = match[2].replace(/\(INSERTED\)/i, '').trim();
112
+
113
+ // Extract goal from the section
114
+ const sectionStart = match.index;
115
+ const restOfContent = content.slice(sectionStart);
116
+ const nextHeader = restOfContent.match(/\n#{2,4}\s+Phase\s+\d/i);
117
+ const sectionEnd = nextHeader ? sectionStart + nextHeader.index : content.length;
118
+ const section = content.slice(sectionStart, sectionEnd);
119
+
120
+ const goalMatch = section.match(/\*\*Goal(?::\*\*|\*\*:)\s*([^\n]+)/i);
121
+ const goal = goalMatch ? goalMatch[1].trim() : null;
122
+
123
+ const dependsMatch = section.match(/\*\*Depends on(?::\*\*|\*\*:)\s*([^\n]+)/i);
124
+ const depends_on = dependsMatch ? dependsMatch[1].trim() : null;
125
+
126
+ // Check completion on disk
127
+ const normalized = normalizePhaseName(phaseNum);
128
+ let diskStatus = 'no_directory';
129
+ let planCount = 0;
130
+ let summaryCount = 0;
131
+ let hasContext = false;
132
+ let hasResearch = false;
133
+
134
+ try {
135
+ const entries = fs.readdirSync(phasesDir, { withFileTypes: true });
136
+ const dirs = entries.filter(e => e.isDirectory()).map(e => e.name);
137
+ const dirMatch = dirs.find(d => d.startsWith(normalized + '-') || d === normalized);
138
+
139
+ if (dirMatch) {
140
+ const phaseFiles = fs.readdirSync(path.join(phasesDir, dirMatch));
141
+ planCount = phaseFiles.filter(f => f.endsWith('-PLAN.md') || f === 'PLAN.md').length;
142
+ summaryCount = phaseFiles.filter(f => f.endsWith('-SUMMARY.md') || f === 'SUMMARY.md').length;
143
+ hasContext = phaseFiles.some(f => f.endsWith('-CONTEXT.md') || f === 'CONTEXT.md');
144
+ hasResearch = phaseFiles.some(f => f.endsWith('-RESEARCH.md') || f === 'RESEARCH.md');
145
+
146
+ if (summaryCount >= planCount && planCount > 0) diskStatus = 'complete';
147
+ else if (summaryCount > 0) diskStatus = 'partial';
148
+ else if (planCount > 0) diskStatus = 'planned';
149
+ else if (hasResearch) diskStatus = 'researched';
150
+ else if (hasContext) diskStatus = 'discussed';
151
+ else diskStatus = 'empty';
152
+ }
153
+ } catch {}
154
+
155
+ // Check ROADMAP checkbox status
156
+ const checkboxPattern = new RegExp(`-\\s*\\[(x| )\\]\\s*.*Phase\\s+${escapeRegex(phaseNum)}`, 'i');
157
+ const checkboxMatch = content.match(checkboxPattern);
158
+ const roadmapComplete = checkboxMatch ? checkboxMatch[1] === 'x' : false;
159
+
160
+ // If roadmap marks phase complete, trust that over disk file structure.
161
+ // Phases completed before GSD tracking (or via external tools) may lack
162
+ // the standard PLAN/SUMMARY pairs but are still done.
163
+ if (roadmapComplete && diskStatus !== 'complete') {
164
+ diskStatus = 'complete';
165
+ }
166
+
167
+ phases.push({
168
+ number: phaseNum,
169
+ name: phaseName,
170
+ goal,
171
+ depends_on,
172
+ plan_count: planCount,
173
+ summary_count: summaryCount,
174
+ has_context: hasContext,
175
+ has_research: hasResearch,
176
+ disk_status: diskStatus,
177
+ roadmap_complete: roadmapComplete,
178
+ });
179
+ }
180
+
181
+ // Extract milestone info
182
+ const milestones = [];
183
+ const milestonePattern = /##\s*(.*v(\d+\.\d+)[^(\n]*)/gi;
184
+ let mMatch;
185
+ while ((mMatch = milestonePattern.exec(content)) !== null) {
186
+ milestones.push({
187
+ heading: mMatch[1].trim(),
188
+ version: 'v' + mMatch[2],
189
+ });
190
+ }
191
+
192
+ // Find current and next phase
193
+ const currentPhase = phases.find(p => p.disk_status === 'planned' || p.disk_status === 'partial') || null;
194
+ const nextPhase = phases.find(p => p.disk_status === 'empty' || p.disk_status === 'no_directory' || p.disk_status === 'discussed' || p.disk_status === 'researched') || null;
195
+
196
+ // Aggregated stats
197
+ const totalPlans = phases.reduce((sum, p) => sum + p.plan_count, 0);
198
+ const totalSummaries = phases.reduce((sum, p) => sum + p.summary_count, 0);
199
+ const completedPhases = phases.filter(p => p.disk_status === 'complete').length;
200
+
201
+ // Detect phases in summary list without detail sections (malformed ROADMAP)
202
+ const checklistPattern = /-\s*\[[ x]\]\s*\*\*Phase\s+(\d+[A-Z]?(?:\.\d+)*)/gi;
203
+ const checklistPhases = new Set();
204
+ let checklistMatch;
205
+ while ((checklistMatch = checklistPattern.exec(content)) !== null) {
206
+ checklistPhases.add(checklistMatch[1]);
207
+ }
208
+ const detailPhases = new Set(phases.map(p => p.number));
209
+ const missingDetails = [...checklistPhases].filter(p => !detailPhases.has(p));
210
+
211
+ const result = {
212
+ milestones,
213
+ phases,
214
+ phase_count: phases.length,
215
+ completed_phases: completedPhases,
216
+ total_plans: totalPlans,
217
+ total_summaries: totalSummaries,
218
+ progress_percent: totalPlans > 0 ? Math.min(100, Math.round((totalSummaries / totalPlans) * 100)) : 0,
219
+ current_phase: currentPhase ? currentPhase.number : null,
220
+ next_phase: nextPhase ? nextPhase.number : null,
221
+ missing_phase_details: missingDetails.length > 0 ? missingDetails : null,
222
+ };
223
+
224
+ output(result, raw);
225
+ }
226
+
227
+ function cmdRoadmapUpdatePlanProgress(cwd, phaseNum, raw) {
228
+ if (!phaseNum) {
229
+ error('phase number required for roadmap update-plan-progress');
230
+ }
231
+
232
+ const roadmapPath = path.join(cwd, '.planning', 'ROADMAP.md');
233
+
234
+ const phaseInfo = findPhaseInternal(cwd, phaseNum);
235
+ if (!phaseInfo) {
236
+ error(`Phase ${phaseNum} not found`);
237
+ }
238
+
239
+ const planCount = phaseInfo.plans.length;
240
+ const summaryCount = phaseInfo.summaries.length;
241
+
242
+ if (planCount === 0) {
243
+ output({ updated: false, reason: 'No plans found', plan_count: 0, summary_count: 0 }, raw, 'no plans');
244
+ return;
245
+ }
246
+
247
+ const isComplete = summaryCount >= planCount;
248
+ const status = isComplete ? 'Complete' : summaryCount > 0 ? 'In Progress' : 'Planned';
249
+ const today = new Date().toISOString().split('T')[0];
250
+
251
+ if (!fs.existsSync(roadmapPath)) {
252
+ output({ updated: false, reason: 'ROADMAP.md not found', plan_count: planCount, summary_count: summaryCount }, raw, 'no roadmap');
253
+ return;
254
+ }
255
+
256
+ let roadmapContent = fs.readFileSync(roadmapPath, 'utf-8');
257
+ const phaseEscaped = escapeRegex(phaseNum);
258
+
259
+ // Progress table row: update Plans column (summaries/plans) and Status column
260
+ const tablePattern = new RegExp(
261
+ `(\\|\\s*${phaseEscaped}\\.?\\s[^|]*\\|)[^|]*(\\|)\\s*[^|]*(\\|)\\s*[^|]*(\\|)`,
262
+ 'i'
263
+ );
264
+ const dateField = isComplete ? ` ${today} ` : ' ';
265
+ roadmapContent = roadmapContent.replace(
266
+ tablePattern,
267
+ `$1 ${summaryCount}/${planCount} $2 ${status.padEnd(11)}$3${dateField}$4`
268
+ );
269
+
270
+ // Update plan count in phase detail section
271
+ const planCountPattern = new RegExp(
272
+ `(#{2,4}\\s*Phase\\s+${phaseEscaped}[\\s\\S]*?\\*\\*Plans:\\*\\*\\s*)[^\\n]+`,
273
+ 'i'
274
+ );
275
+ const planCountText = isComplete
276
+ ? `${summaryCount}/${planCount} plans complete`
277
+ : `${summaryCount}/${planCount} plans executed`;
278
+ roadmapContent = roadmapContent.replace(planCountPattern, `$1${planCountText}`);
279
+
280
+ // If complete: check checkbox
281
+ if (isComplete) {
282
+ const checkboxPattern = new RegExp(
283
+ `(-\\s*\\[)[ ](\\]\\s*.*Phase\\s+${phaseEscaped}[:\\s][^\\n]*)`,
284
+ 'i'
285
+ );
286
+ roadmapContent = roadmapContent.replace(checkboxPattern, `$1x$2 (completed ${today})`);
287
+ }
288
+
289
+ fs.writeFileSync(roadmapPath, roadmapContent, 'utf-8');
290
+
291
+ output({
292
+ updated: true,
293
+ phase: phaseNum,
294
+ plan_count: planCount,
295
+ summary_count: summaryCount,
296
+ status,
297
+ complete: isComplete,
298
+ }, raw, `${summaryCount}/${planCount} ${status}`);
299
+ }
300
+
301
+ module.exports = {
302
+ cmdRoadmapGetPhase,
303
+ cmdRoadmapAnalyze,
304
+ cmdRoadmapUpdatePlanProgress,
305
+ };
@@ -0,0 +1,128 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * GSD Safe Exec — Secure command execution with allowlist and validation
5
+ *
6
+ * Prevents command injection by:
7
+ * - Using execFile instead of execSync with string concatenation
8
+ * - Validating commands against allowlist
9
+ * - Blocking dangerous shell metacharacters in arguments
10
+ * - Logging all commands for audit
11
+ *
12
+ * Usage:
13
+ * const { safeExec, safeExecJSON } = require('./safe-exec.cjs');
14
+ * const result = await safeExec('git', ['status']);
15
+ */
16
+
17
+ const { execFile } = require('child_process');
18
+ const { promisify } = require('util');
19
+ const execFileAsync = promisify(execFile);
20
+ const Logger = require('./logger.cjs');
21
+ const logger = new Logger();
22
+
23
+ // Allowlist of safe commands
24
+ const ALLOWED_COMMANDS = new Set([
25
+ 'git', 'node', 'npm', 'npx', 'find', 'grep', 'head', 'tail', 'wc',
26
+ 'mkdir', 'cp', 'mv', 'rm', 'cat', 'echo', 'test', 'ls', 'dir',
27
+ 'pwd', 'cd', 'type', 'where', 'which', 'chmod', 'touch'
28
+ ]);
29
+
30
+ // Dangerous shell metacharacters that could enable injection
31
+ const DANGEROUS_PATTERN = /[;&|`$(){}\\<>]/;
32
+
33
+ /**
34
+ * Validate command is in allowlist
35
+ * @param {string} cmd - Command to validate
36
+ * @throws {Error} If command not allowed
37
+ */
38
+ function validateCommand(cmd) {
39
+ const baseCmd = cmd.split(' ')[0].toLowerCase();
40
+ if (!ALLOWED_COMMANDS.has(baseCmd)) {
41
+ throw new Error(`Command not allowed: ${cmd}. Allowed: ${Array.from(ALLOWED_COMMANDS).join(', ')}`);
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Validate arguments don't contain injection patterns
47
+ * @param {string[]} args - Arguments to validate
48
+ * @throws {Error} If dangerous pattern found
49
+ */
50
+ function validateArgs(args) {
51
+ for (const arg of args) {
52
+ if (DANGEROUS_PATTERN.test(arg)) {
53
+ throw new Error(`Dangerous argument rejected: ${arg}`);
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Execute command safely with validation and logging
60
+ * @param {string} cmd - Command to execute
61
+ * @param {string[]} args - Command arguments
62
+ * @param {Object} options - Execution options
63
+ * @returns {Promise<string>} - Command stdout
64
+ */
65
+ async function safeExec(cmd, args = [], options = {}) {
66
+ const { timeout = 30000, log = true } = options;
67
+
68
+ // Validate command and arguments
69
+ validateCommand(cmd);
70
+ validateArgs(args);
71
+
72
+ const startTime = Date.now();
73
+
74
+ try {
75
+ if (log) {
76
+ logger.info('Executing command', {
77
+ cmd,
78
+ args,
79
+ timestamp: new Date().toISOString()
80
+ });
81
+ }
82
+
83
+ const result = await execFileAsync(cmd, args, {
84
+ timeout,
85
+ maxBuffer: 10 * 1024 * 1024 // 10MB buffer
86
+ });
87
+
88
+ const duration = Date.now() - startTime;
89
+ if (log) {
90
+ logger.debug('Command completed', {
91
+ cmd,
92
+ duration,
93
+ stdout_length: result.stdout?.length || 0
94
+ });
95
+ }
96
+
97
+ return result.stdout.trim();
98
+ } catch (err) {
99
+ const duration = Date.now() - startTime;
100
+ logger.error('Command failed', {
101
+ cmd,
102
+ args,
103
+ error: err.message,
104
+ duration,
105
+ code: err.code,
106
+ signal: err.signal
107
+ });
108
+ throw err;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Execute command and return JSON parsed output
114
+ * @param {string} cmd - Command to execute
115
+ * @param {string[]} args - Command arguments
116
+ * @returns {Promise<Object>} - Parsed JSON output
117
+ */
118
+ async function safeExecJSON(cmd, args = []) {
119
+ const output = await safeExec(cmd, args);
120
+ try {
121
+ return JSON.parse(output);
122
+ } catch (err) {
123
+ logger.error('Failed to parse JSON output', { cmd, output });
124
+ throw new Error(`Invalid JSON from ${cmd}: ${err.message}`);
125
+ }
126
+ }
127
+
128
+ module.exports = { safeExec, safeExecJSON, ALLOWED_COMMANDS };
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * GSD Safe Path — Path traversal prevention utility
5
+ *
6
+ * Prevents path traversal attacks by:
7
+ * - Resolving and validating paths against base directory
8
+ * - Blocking paths that escape base directory
9
+ * - Handling Windows and Unix path formats
10
+ * - Logging blocked attempts for security audit
11
+ *
12
+ * Usage:
13
+ * const { normalizePath, isPathSafe, safeReadFile } = require('./safe-path.cjs');
14
+ * const safePath = normalizePath(process.cwd(), userPath);
15
+ */
16
+
17
+ const path = require('path');
18
+ const fs = require('fs');
19
+ const Logger = require('./logger.cjs');
20
+ const logger = new Logger();
21
+
22
+ /**
23
+ * Normalize and validate a user-provided path against a base directory
24
+ * @param {string} baseDir - Base directory (trusted)
25
+ * @param {string} userPath - User-provided path (untrusted)
26
+ * @returns {string} - Resolved absolute path if safe
27
+ * @throws {Error} If path traversal detected
28
+ */
29
+ function normalizePath(baseDir, userPath) {
30
+ // Resolve both paths to absolute
31
+ const resolvedBase = path.resolve(baseDir);
32
+ const resolvedUser = path.resolve(baseDir, userPath);
33
+
34
+ // Normalize for comparison (handle Windows backslashes)
35
+ const normalizedBase = resolvedBase + path.sep;
36
+
37
+ // Check if user path is within base directory
38
+ const isWithin =
39
+ resolvedUser === resolvedBase ||
40
+ resolvedUser.startsWith(normalizedBase);
41
+
42
+ if (!isWithin) {
43
+ logger.error('Path traversal detected', {
44
+ baseDir: resolvedBase,
45
+ userPath,
46
+ resolvedUser,
47
+ timestamp: new Date().toISOString()
48
+ });
49
+ throw new Error(`Path traversal detected: ${userPath}`);
50
+ }
51
+
52
+ return resolvedUser;
53
+ }
54
+
55
+ /**
56
+ * Check if a path is safe (within base directory) without throwing
57
+ * @param {string} baseDir - Base directory (trusted)
58
+ * @param {string} userPath - User-provided path (untrusted)
59
+ * @returns {boolean} - True if path is safe
60
+ */
61
+ function isPathSafe(baseDir, userPath) {
62
+ try {
63
+ normalizePath(baseDir, userPath);
64
+ return true;
65
+ } catch (err) {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Validate path exists and is safe
72
+ * @param {string} baseDir - Base directory
73
+ * @param {string} userPath - User-provided path
74
+ * @returns {string} - Resolved path if exists and safe
75
+ * @throws {Error} If not found or traversal detected
76
+ */
77
+ function validatePathExists(baseDir, userPath) {
78
+ const resolvedPath = normalizePath(baseDir, userPath);
79
+
80
+ if (!fs.existsSync(resolvedPath)) {
81
+ logger.warn('Path does not exist', {
82
+ resolvedPath,
83
+ userPath
84
+ });
85
+ throw new Error(`Path not found: ${userPath}`);
86
+ }
87
+
88
+ return resolvedPath;
89
+ }
90
+
91
+ /**
92
+ * Safely read a file (validates path before reading)
93
+ * @param {string} baseDir - Base directory
94
+ * @param {string} userPath - User-provided path
95
+ * @param {string} encoding - File encoding (default: utf-8)
96
+ * @returns {string} - File content
97
+ * @throws {Error} If path unsafe or file not found
98
+ */
99
+ function safeReadFile(baseDir, userPath, encoding = 'utf-8') {
100
+ const resolvedPath = validatePathExists(baseDir, userPath);
101
+
102
+ logger.debug('Reading file', { resolvedPath, userPath });
103
+
104
+ return fs.readFileSync(resolvedPath, encoding);
105
+ }
106
+
107
+ /**
108
+ * Get relative path from base, with validation
109
+ * @param {string} baseDir - Base directory
110
+ * @param {string} fullPath - Full path to convert
111
+ * @returns {string} - Relative path or throws if outside base
112
+ */
113
+ function toRelativePath(baseDir, fullPath) {
114
+ const resolvedFull = path.resolve(fullPath);
115
+ const resolvedBase = path.resolve(baseDir);
116
+
117
+ if (!isPathSafe(baseDir, resolvedFull)) {
118
+ throw new Error(`Path outside base: ${fullPath}`);
119
+ }
120
+
121
+ return path.relative(resolvedBase, resolvedFull);
122
+ }
123
+
124
+ module.exports = {
125
+ normalizePath,
126
+ isPathSafe,
127
+ validatePathExists,
128
+ safeReadFile,
129
+ toRelativePath
130
+ };