@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,236 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * GSD File Lock — File locking utility for concurrent write protection
5
+ *
6
+ * Uses proper-lockfile to prevent concurrent writes to planning files
7
+ * Includes deadlock detection (30s timeout) and automatic lock cleanup
8
+ *
9
+ * Fallback: Uses simple lock file mechanism if proper-lockfile is not available
10
+ *
11
+ * Usage:
12
+ * const { withLock, isLocked, ifUnlocked } = require('./file-lock.cjs');
13
+ * await withLock('.planning/STATE.md', async () => {
14
+ * // Safe to write - no other process can modify this file
15
+ * });
16
+ */
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const Logger = require('./logger.cjs');
21
+ const logger = new Logger();
22
+
23
+ // Try to load proper-lockfile, fallback to simple implementation
24
+ let properLockfile = null;
25
+ try {
26
+ properLockfile = require('proper-lockfile');
27
+ } catch (err) {
28
+ logger.warn('proper-lockfile not available, using fallback implementation');
29
+ }
30
+
31
+ const DEFAULT_OPTIONS = {
32
+ staleTime: 30000, // Lock considered stale after 30s
33
+ update: 10000, // Update lock every 10s to prevent stale
34
+ retries: {
35
+ retries: 10,
36
+ factor: 1.1,
37
+ minTimeout: 100,
38
+ maxTimeout: 1000,
39
+ randomize: true
40
+ }
41
+ };
42
+
43
+ // Simple lock file implementation (fallback)
44
+ const LOCK_SUFFIX = '.lock';
45
+ const lockHolders = new Map(); // Track locks held by this process
46
+
47
+ /**
48
+ * Get lock file path
49
+ * @param {string} filePath - Original file path
50
+ * @returns {string} - Lock file path
51
+ */
52
+ function getLockPath(filePath) {
53
+ return filePath + LOCK_SUFFIX;
54
+ }
55
+
56
+ /**
57
+ * Simple lock acquisition (fallback when proper-lockfile unavailable)
58
+ */
59
+ async function simpleLock(filePath, options = {}) {
60
+ const lockPath = getLockPath(filePath);
61
+ const startTime = Date.now();
62
+ const timeout = options.timeout || 30000;
63
+ const staleTime = options.staleTime || 30000;
64
+
65
+ while (Date.now() - startTime < timeout) {
66
+ try {
67
+ // Check if lock file exists and is not stale
68
+ if (fs.existsSync(lockPath)) {
69
+ const stats = fs.statSync(lockPath);
70
+ const age = Date.now() - stats.mtimeMs;
71
+
72
+ if (age < staleTime) {
73
+ // Lock is held by another process, wait and retry
74
+ await new Promise(resolve => setTimeout(resolve, 100));
75
+ continue;
76
+ }
77
+ // Lock is stale, remove it
78
+ try {
79
+ fs.unlinkSync(lockPath);
80
+ } catch (err) {
81
+ // Ignore - another process might have removed it
82
+ }
83
+ }
84
+
85
+ // Try to create lock file
86
+ fs.writeFileSync(lockPath, JSON.stringify({
87
+ pid: process.pid,
88
+ timestamp: Date.now()
89
+ }), 'utf-8');
90
+
91
+ lockHolders.set(filePath, lockPath);
92
+
93
+ return {
94
+ release: async () => {
95
+ try {
96
+ if (fs.existsSync(lockPath)) {
97
+ fs.unlinkSync(lockPath);
98
+ }
99
+ lockHolders.delete(filePath);
100
+ } catch (err) {
101
+ logger.warn(`Failed to release lock: ${lockPath}`, { error: err.message });
102
+ }
103
+ }
104
+ };
105
+ } catch (err) {
106
+ // Lock acquisition failed, wait and retry
107
+ await new Promise(resolve => setTimeout(resolve, 100));
108
+ }
109
+ }
110
+
111
+ throw new Error(`Lock acquisition timed out after ${timeout}ms`);
112
+ }
113
+
114
+ /**
115
+ * Execute an operation with file lock
116
+ * @param {string} filePath - Path to file to lock
117
+ * @param {Function} operation - Async function to execute while locked
118
+ * @param {Object} options - Lock options
119
+ * @returns {Promise<any>} - Result of operation
120
+ */
121
+ async function withLock(filePath, operation, options = {}) {
122
+ const lockOptions = { ...DEFAULT_OPTIONS, ...options };
123
+ const absolutePath = path.resolve(filePath);
124
+
125
+ // Ensure file exists
126
+ if (!fs.existsSync(absolutePath)) {
127
+ const dir = path.dirname(absolutePath);
128
+ if (!fs.existsSync(dir)) {
129
+ fs.mkdirSync(dir, { recursive: true });
130
+ }
131
+ fs.writeFileSync(absolutePath, '', 'utf-8');
132
+ }
133
+
134
+ let release = null;
135
+ const startTime = Date.now();
136
+
137
+ try {
138
+ logger.debug(`Attempting to acquire lock: ${absolutePath}`);
139
+
140
+ if (properLockfile) {
141
+ // Use proper-lockfile
142
+ release = await properLockfile.lock(absolutePath, lockOptions);
143
+ } else {
144
+ // Use simple fallback
145
+ const lockResult = await simpleLock(absolutePath, lockOptions);
146
+ release = lockResult.release;
147
+ }
148
+
149
+ const acquireTime = Date.now() - startTime;
150
+ logger.debug(`Lock acquired: ${absolutePath} (${acquireTime}ms)`);
151
+
152
+ const result = await operation();
153
+ return result;
154
+ } catch (err) {
155
+ const waitTime = Date.now() - startTime;
156
+ if (err.message.includes('timed out') || err.code === 'ELOCKED') {
157
+ logger.error(`File locked by another process: ${absolutePath}`, {
158
+ waited: waitTime,
159
+ timeout: lockOptions.timeout || 30000
160
+ });
161
+ throw new Error(`File locked: ${filePath} (waited ${waitTime}ms)`);
162
+ }
163
+ logger.error(`Lock acquisition failed: ${absolutePath}`, {
164
+ error: err.message,
165
+ waited: waitTime
166
+ });
167
+ throw err;
168
+ } finally {
169
+ if (release) {
170
+ try {
171
+ await release();
172
+ logger.debug(`Lock released: ${absolutePath}`);
173
+ } catch (err) {
174
+ logger.warn(`Failed to release lock: ${absolutePath}`, {
175
+ error: err.message
176
+ });
177
+ }
178
+ }
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Check if a file is currently locked
184
+ * @param {string} filePath - Path to file
185
+ * @returns {Promise<boolean>} - True if locked
186
+ */
187
+ async function isLocked(filePath) {
188
+ const absolutePath = path.resolve(filePath);
189
+
190
+ if (properLockfile) {
191
+ if (!fs.existsSync(absolutePath)) {
192
+ return false;
193
+ }
194
+ return properLockfile.check(absolutePath);
195
+ }
196
+
197
+ // Simple fallback
198
+ const lockPath = getLockPath(filePath);
199
+ if (!fs.existsSync(lockPath)) {
200
+ return false;
201
+ }
202
+
203
+ // Check if lock is stale
204
+ try {
205
+ const stats = fs.statSync(lockPath);
206
+ const age = Date.now() - stats.mtimeMs;
207
+ const staleTime = 30000;
208
+
209
+ if (age >= staleTime) {
210
+ // Lock is stale, remove it
211
+ fs.unlinkSync(lockPath);
212
+ return false;
213
+ }
214
+ return true;
215
+ } catch (err) {
216
+ return false;
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Execute operation only if file is not locked
222
+ * @param {string} filePath - Path to file
223
+ * @param {Function} operation - Async function to execute
224
+ * @param {any} fallback - Value to return if file is locked
225
+ * @returns {Promise<any>} - Result of operation or fallback
226
+ */
227
+ async function ifUnlocked(filePath, operation, fallback = null) {
228
+ const locked = await isLocked(filePath);
229
+ if (locked) {
230
+ logger.debug(`File locked, using fallback: ${filePath}`);
231
+ return fallback;
232
+ }
233
+ return withLock(filePath, operation);
234
+ }
235
+
236
+ module.exports = { withLock, isLocked, ifUnlocked };
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Frontmatter — YAML frontmatter parsing, serialization, and CRUD commands
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { safeReadFile, output, error } = require('./core.cjs');
8
+
9
+ // ─── Parsing engine ───────────────────────────────────────────────────────────
10
+
11
+ function extractFrontmatter(content) {
12
+ const frontmatter = {};
13
+ const match = content.match(/^---\n([\s\S]+?)\n---/);
14
+ if (!match) return frontmatter;
15
+
16
+ const yaml = match[1];
17
+ const lines = yaml.split('\n');
18
+
19
+ // Stack to track nested objects: [{obj, key, indent}]
20
+ // obj = object to write to, key = current key collecting array items, indent = indentation level
21
+ let stack = [{ obj: frontmatter, key: null, indent: -1 }];
22
+
23
+ for (const line of lines) {
24
+ // Skip empty lines
25
+ if (line.trim() === '') continue;
26
+
27
+ // Calculate indentation (number of leading spaces)
28
+ const indentMatch = line.match(/^(\s*)/);
29
+ const indent = indentMatch ? indentMatch[1].length : 0;
30
+
31
+ // Pop stack back to appropriate level
32
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
33
+ stack.pop();
34
+ }
35
+
36
+ const current = stack[stack.length - 1];
37
+
38
+ // Check for key: value pattern
39
+ const keyMatch = line.match(/^(\s*)([a-zA-Z0-9_-]+):\s*(.*)/);
40
+ if (keyMatch) {
41
+ const key = keyMatch[2];
42
+ const value = keyMatch[3].trim();
43
+
44
+ if (value === '' || value === '[') {
45
+ // Key with no value or opening bracket — could be nested object or array
46
+ // We'll determine based on next lines, for now create placeholder
47
+ current.obj[key] = value === '[' ? [] : {};
48
+ current.key = null;
49
+ // Push new context for potential nested content
50
+ stack.push({ obj: current.obj[key], key: null, indent });
51
+ } else if (value.startsWith('[') && value.endsWith(']')) {
52
+ // Inline array: key: [a, b, c]
53
+ current.obj[key] = value.slice(1, -1).split(',').map(s => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
54
+ current.key = null;
55
+ } else {
56
+ // Simple key: value
57
+ current.obj[key] = value.replace(/^["']|["']$/g, '');
58
+ current.key = null;
59
+ }
60
+ } else if (line.trim().startsWith('- ')) {
61
+ // Array item
62
+ const itemValue = line.trim().slice(2).replace(/^["']|["']$/g, '');
63
+
64
+ // If current context is an empty object, convert to array
65
+ if (typeof current.obj === 'object' && !Array.isArray(current.obj) && Object.keys(current.obj).length === 0) {
66
+ // Find the key in parent that points to this object and convert it
67
+ const parent = stack.length > 1 ? stack[stack.length - 2] : null;
68
+ if (parent) {
69
+ for (const k of Object.keys(parent.obj)) {
70
+ if (parent.obj[k] === current.obj) {
71
+ parent.obj[k] = [itemValue];
72
+ current.obj = parent.obj[k];
73
+ break;
74
+ }
75
+ }
76
+ }
77
+ } else if (Array.isArray(current.obj)) {
78
+ current.obj.push(itemValue);
79
+ }
80
+ }
81
+ }
82
+
83
+ return frontmatter;
84
+ }
85
+
86
+ function reconstructFrontmatter(obj) {
87
+ const lines = [];
88
+ for (const [key, value] of Object.entries(obj)) {
89
+ if (value === null || value === undefined) continue;
90
+ if (Array.isArray(value)) {
91
+ if (value.length === 0) {
92
+ lines.push(`${key}: []`);
93
+ } else if (value.every(v => typeof v === 'string') && value.length <= 3 && value.join(', ').length < 60) {
94
+ lines.push(`${key}: [${value.join(', ')}]`);
95
+ } else {
96
+ lines.push(`${key}:`);
97
+ for (const item of value) {
98
+ lines.push(` - ${typeof item === 'string' && (item.includes(':') || item.includes('#')) ? `"${item}"` : item}`);
99
+ }
100
+ }
101
+ } else if (typeof value === 'object') {
102
+ lines.push(`${key}:`);
103
+ for (const [subkey, subval] of Object.entries(value)) {
104
+ if (subval === null || subval === undefined) continue;
105
+ if (Array.isArray(subval)) {
106
+ if (subval.length === 0) {
107
+ lines.push(` ${subkey}: []`);
108
+ } else if (subval.every(v => typeof v === 'string') && subval.length <= 3 && subval.join(', ').length < 60) {
109
+ lines.push(` ${subkey}: [${subval.join(', ')}]`);
110
+ } else {
111
+ lines.push(` ${subkey}:`);
112
+ for (const item of subval) {
113
+ lines.push(` - ${typeof item === 'string' && (item.includes(':') || item.includes('#')) ? `"${item}"` : item}`);
114
+ }
115
+ }
116
+ } else if (typeof subval === 'object') {
117
+ lines.push(` ${subkey}:`);
118
+ for (const [subsubkey, subsubval] of Object.entries(subval)) {
119
+ if (subsubval === null || subsubval === undefined) continue;
120
+ if (Array.isArray(subsubval)) {
121
+ if (subsubval.length === 0) {
122
+ lines.push(` ${subsubkey}: []`);
123
+ } else {
124
+ lines.push(` ${subsubkey}:`);
125
+ for (const item of subsubval) {
126
+ lines.push(` - ${item}`);
127
+ }
128
+ }
129
+ } else {
130
+ lines.push(` ${subsubkey}: ${subsubval}`);
131
+ }
132
+ }
133
+ } else {
134
+ const sv = String(subval);
135
+ lines.push(` ${subkey}: ${sv.includes(':') || sv.includes('#') ? `"${sv}"` : sv}`);
136
+ }
137
+ }
138
+ } else {
139
+ const sv = String(value);
140
+ if (sv.includes(':') || sv.includes('#') || sv.startsWith('[') || sv.startsWith('{')) {
141
+ lines.push(`${key}: "${sv}"`);
142
+ } else {
143
+ lines.push(`${key}: ${sv}`);
144
+ }
145
+ }
146
+ }
147
+ return lines.join('\n');
148
+ }
149
+
150
+ function spliceFrontmatter(content, newObj) {
151
+ const yamlStr = reconstructFrontmatter(newObj);
152
+ const match = content.match(/^---\n[\s\S]+?\n---/);
153
+ if (match) {
154
+ return `---\n${yamlStr}\n---` + content.slice(match[0].length);
155
+ }
156
+ return `---\n${yamlStr}\n---\n\n` + content;
157
+ }
158
+
159
+ function parseMustHavesBlock(content, blockName) {
160
+ // Extract a specific block from must_haves in raw frontmatter YAML
161
+ // Handles 3-level nesting: must_haves > artifacts/key_links > [{path, provides, ...}]
162
+ const fmMatch = content.match(/^---\n([\s\S]+?)\n---/);
163
+ if (!fmMatch) return [];
164
+
165
+ const yaml = fmMatch[1];
166
+ // Find the block (e.g., "truths:", "artifacts:", "key_links:")
167
+ const blockPattern = new RegExp(`^\\s{4}${blockName}:\\s*$`, 'm');
168
+ const blockStart = yaml.search(blockPattern);
169
+ if (blockStart === -1) return [];
170
+
171
+ const afterBlock = yaml.slice(blockStart);
172
+ const blockLines = afterBlock.split('\n').slice(1); // skip the header line
173
+
174
+ const items = [];
175
+ let current = null;
176
+
177
+ for (const line of blockLines) {
178
+ // Stop at same or lower indent level (non-continuation)
179
+ if (line.trim() === '') continue;
180
+ const indent = line.match(/^(\s*)/)[1].length;
181
+ if (indent <= 4 && line.trim() !== '') break; // back to must_haves level or higher
182
+
183
+ if (line.match(/^\s{6}-\s+/)) {
184
+ // New list item at 6-space indent
185
+ if (current) items.push(current);
186
+ current = {};
187
+ // Check if it's a simple string item
188
+ const simpleMatch = line.match(/^\s{6}-\s+"?([^"]+)"?\s*$/);
189
+ if (simpleMatch && !line.includes(':')) {
190
+ current = simpleMatch[1];
191
+ } else {
192
+ // Key-value on same line as dash: "- path: value"
193
+ const kvMatch = line.match(/^\s{6}-\s+(\w+):\s*"?([^"]*)"?\s*$/);
194
+ if (kvMatch) {
195
+ current = {};
196
+ current[kvMatch[1]] = kvMatch[2];
197
+ }
198
+ }
199
+ } else if (current && typeof current === 'object') {
200
+ // Continuation key-value at 8+ space indent
201
+ const kvMatch = line.match(/^\s{8,}(\w+):\s*"?([^"]*)"?\s*$/);
202
+ if (kvMatch) {
203
+ const val = kvMatch[2];
204
+ // Try to parse as number
205
+ current[kvMatch[1]] = /^\d+$/.test(val) ? parseInt(val, 10) : val;
206
+ }
207
+ // Array items under a key
208
+ const arrMatch = line.match(/^\s{10,}-\s+"?([^"]+)"?\s*$/);
209
+ if (arrMatch) {
210
+ // Find the last key added and convert to array
211
+ const keys = Object.keys(current);
212
+ const lastKey = keys[keys.length - 1];
213
+ if (lastKey && !Array.isArray(current[lastKey])) {
214
+ current[lastKey] = current[lastKey] ? [current[lastKey]] : [];
215
+ }
216
+ if (lastKey) current[lastKey].push(arrMatch[1]);
217
+ }
218
+ }
219
+ }
220
+ if (current) items.push(current);
221
+
222
+ return items;
223
+ }
224
+
225
+ // ─── Frontmatter CRUD commands ────────────────────────────────────────────────
226
+
227
+ const FRONTMATTER_SCHEMAS = {
228
+ plan: { required: ['phase', 'plan', 'type', 'wave', 'depends_on', 'files_modified', 'autonomous', 'must_haves'] },
229
+ summary: { required: ['phase', 'plan', 'subsystem', 'tags', 'duration', 'completed'] },
230
+ verification: { required: ['phase', 'verified', 'status', 'score'] },
231
+ };
232
+
233
+ function cmdFrontmatterGet(cwd, filePath, field, raw) {
234
+ if (!filePath) { error('file path required'); }
235
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
236
+ const content = safeReadFile(fullPath);
237
+ if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
238
+ const fm = extractFrontmatter(content);
239
+ if (field) {
240
+ const value = fm[field];
241
+ if (value === undefined) { output({ error: 'Field not found', field }, raw); return; }
242
+ output({ [field]: value }, raw, JSON.stringify(value));
243
+ } else {
244
+ output(fm, raw);
245
+ }
246
+ }
247
+
248
+ function cmdFrontmatterSet(cwd, filePath, field, value, raw) {
249
+ if (!filePath || !field || value === undefined) { error('file, field, and value required'); }
250
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
251
+ if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
252
+ const content = fs.readFileSync(fullPath, 'utf-8');
253
+ const fm = extractFrontmatter(content);
254
+ let parsedValue;
255
+ try { parsedValue = JSON.parse(value); } catch { parsedValue = value; }
256
+ fm[field] = parsedValue;
257
+ const newContent = spliceFrontmatter(content, fm);
258
+ fs.writeFileSync(fullPath, newContent, 'utf-8');
259
+ output({ updated: true, field, value: parsedValue }, raw, 'true');
260
+ }
261
+
262
+ function cmdFrontmatterMerge(cwd, filePath, data, raw) {
263
+ if (!filePath || !data) { error('file and data required'); }
264
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
265
+ if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
266
+ const content = fs.readFileSync(fullPath, 'utf-8');
267
+ const fm = extractFrontmatter(content);
268
+ let mergeData;
269
+ try { mergeData = JSON.parse(data); } catch { error('Invalid JSON for --data'); return; }
270
+ Object.assign(fm, mergeData);
271
+ const newContent = spliceFrontmatter(content, fm);
272
+ fs.writeFileSync(fullPath, newContent, 'utf-8');
273
+ output({ merged: true, fields: Object.keys(mergeData) }, raw, 'true');
274
+ }
275
+
276
+ function cmdFrontmatterValidate(cwd, filePath, schemaName, raw) {
277
+ if (!filePath || !schemaName) { error('file and schema required'); }
278
+ const schema = FRONTMATTER_SCHEMAS[schemaName];
279
+ if (!schema) { error(`Unknown schema: ${schemaName}. Available: ${Object.keys(FRONTMATTER_SCHEMAS).join(', ')}`); }
280
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
281
+ const content = safeReadFile(fullPath);
282
+ if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
283
+ const fm = extractFrontmatter(content);
284
+ const missing = schema.required.filter(f => fm[f] === undefined);
285
+ const present = schema.required.filter(f => fm[f] !== undefined);
286
+ output({ valid: missing.length === 0, missing, present, schema: schemaName }, raw, missing.length === 0 ? 'valid' : 'invalid');
287
+ }
288
+
289
+ module.exports = {
290
+ extractFrontmatter,
291
+ reconstructFrontmatter,
292
+ spliceFrontmatter,
293
+ parseMustHavesBlock,
294
+ FRONTMATTER_SCHEMAS,
295
+ cmdFrontmatterGet,
296
+ cmdFrontmatterSet,
297
+ cmdFrontmatterMerge,
298
+ cmdFrontmatterValidate,
299
+ };
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * GSD FS Utils — Cross-platform file system utilities
5
+ *
6
+ * Replaces Unix commands (find, grep, head, tail) with
7
+ * cross-platform JavaScript implementations.
8
+ *
9
+ * Usage:
10
+ * const { findFiles, grepContent, readLines } = require('./fs-utils.cjs');
11
+ * const files = await findFiles('./src', /\.js$/);
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+ const Logger = require('./logger.cjs');
17
+ const logger = new Logger();
18
+
19
+ /**
20
+ * Find files matching patterns (cross-platform find replacement)
21
+ * @param {string} dir - Directory to search
22
+ * @param {RegExp[]} patterns - File patterns to match
23
+ * @param {Object} options - Search options
24
+ * @returns {string[]} - Array of matching file paths
25
+ */
26
+ function findFiles(dir, patterns, options = {}) {
27
+ const { maxDepth = 5, exclude = ['node_modules', '.git', '.planning'] } = options;
28
+ const results = [];
29
+
30
+ function recurse(currentDir, depth) {
31
+ if (depth > maxDepth) return;
32
+
33
+ let entries;
34
+ try {
35
+ entries = fs.readdirSync(currentDir, { withFileTypes: true });
36
+ } catch (err) {
37
+ logger.warn('Cannot read directory', { dir: currentDir, error: err.message });
38
+ return;
39
+ }
40
+
41
+ for (const entry of entries) {
42
+ if (exclude.includes(entry.name)) continue;
43
+
44
+ const fullPath = path.join(currentDir, entry.name);
45
+
46
+ if (entry.isDirectory()) {
47
+ recurse(fullPath, depth + 1);
48
+ } else if (patterns.some(p => p.test(entry.name))) {
49
+ results.push(fullPath);
50
+ }
51
+ }
52
+ }
53
+
54
+ recurse(dir, 0);
55
+ return results;
56
+ }
57
+
58
+ /**
59
+ * Search file content (cross-platform grep replacement)
60
+ * @param {string} filePath - File to search
61
+ * @param {RegExp} pattern - Pattern to match
62
+ * @returns {Object[]} - Array of { line, lineNumber, match }
63
+ */
64
+ function grepContent(filePath, pattern) {
65
+ const results = [];
66
+
67
+ try {
68
+ const content = fs.readFileSync(filePath, 'utf-8');
69
+ const lines = content.split('\n');
70
+
71
+ lines.forEach((line, index) => {
72
+ if (pattern.test(line)) {
73
+ results.push({
74
+ line: line.trim(),
75
+ lineNumber: index + 1,
76
+ match: line.match(pattern)?.[0]
77
+ });
78
+ }
79
+ });
80
+ } catch (err) {
81
+ logger.warn('Cannot read file for grep', { filePath, error: err.message });
82
+ }
83
+
84
+ return results;
85
+ }
86
+
87
+ /**
88
+ * Read first N lines (cross-platform head replacement)
89
+ * @param {string} filePath - File to read
90
+ * @param {number} count - Number of lines
91
+ * @returns {string[]} - Array of lines
92
+ */
93
+ function readFirstLines(filePath, count = 10) {
94
+ try {
95
+ const content = fs.readFileSync(filePath, 'utf-8');
96
+ return content.split('\n').slice(0, count);
97
+ } catch (err) {
98
+ logger.warn('Cannot read file', { filePath, error: err.message });
99
+ return [];
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Read last N lines (cross-platform tail replacement)
105
+ * @param {string} filePath - File to read
106
+ * @param {number} count - Number of lines
107
+ * @returns {string[]} - Array of lines
108
+ */
109
+ function readLastLines(filePath, count = 10) {
110
+ try {
111
+ const content = fs.readFileSync(filePath, 'utf-8');
112
+ const lines = content.split('\n');
113
+ return lines.slice(-count);
114
+ } catch (err) {
115
+ logger.warn('Cannot read file', { filePath, error: err.message });
116
+ return [];
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Count lines in file (cross-platform wc -l replacement)
122
+ * @param {string} filePath - File to count
123
+ * @returns {number} - Line count
124
+ */
125
+ function countLines(filePath) {
126
+ try {
127
+ const content = fs.readFileSync(filePath, 'utf-8');
128
+ return content.split('\n').length;
129
+ } catch (err) {
130
+ logger.warn('Cannot count lines', { filePath, error: err.message });
131
+ return 0;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Ensure directory exists
137
+ * @param {string} dirPath - Directory path
138
+ */
139
+ function ensureDir(dirPath) {
140
+ if (!fs.existsSync(dirPath)) {
141
+ fs.mkdirSync(dirPath, { recursive: true });
142
+ logger.debug('Directory created', { dir: dirPath });
143
+ }
144
+ }
145
+
146
+ module.exports = {
147
+ findFiles,
148
+ grepContent,
149
+ readFirstLines,
150
+ readLastLines,
151
+ countLines,
152
+ ensureDir
153
+ };