@bhargavvc/sdd-cc 1.30.1 → 1.35.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 (242) hide show
  1. package/README.ja-JP.md +144 -110
  2. package/README.ko-KR.md +143 -107
  3. package/README.md +183 -112
  4. package/README.pt-BR.md +90 -52
  5. package/README.zh-CN.md +141 -101
  6. package/agents/sdd-advisor-researcher.md +23 -0
  7. package/agents/sdd-ai-researcher.md +133 -0
  8. package/agents/sdd-code-fixer.md +516 -0
  9. package/agents/sdd-code-reviewer.md +355 -0
  10. package/agents/sdd-codebase-mapper.md +3 -3
  11. package/agents/sdd-debugger.md +17 -5
  12. package/agents/sdd-doc-verifier.md +201 -0
  13. package/agents/sdd-doc-writer.md +602 -0
  14. package/agents/sdd-domain-researcher.md +153 -0
  15. package/agents/sdd-eval-auditor.md +164 -0
  16. package/agents/sdd-eval-planner.md +154 -0
  17. package/agents/sdd-executor.md +87 -4
  18. package/agents/sdd-framework-selector.md +160 -0
  19. package/agents/sdd-intel-updater.md +314 -0
  20. package/agents/sdd-nyquist-auditor.md +1 -1
  21. package/agents/sdd-phase-researcher.md +71 -4
  22. package/agents/sdd-plan-checker.md +100 -6
  23. package/agents/sdd-planner.md +145 -206
  24. package/agents/sdd-project-researcher.md +25 -2
  25. package/agents/sdd-research-synthesizer.md +3 -3
  26. package/agents/sdd-roadmapper.md +6 -6
  27. package/agents/sdd-security-auditor.md +128 -0
  28. package/agents/sdd-ui-auditor.md +43 -3
  29. package/agents/sdd-ui-checker.md +5 -5
  30. package/agents/sdd-ui-researcher.md +27 -4
  31. package/agents/sdd-user-profiler.md +2 -2
  32. package/agents/sdd-verifier.md +142 -22
  33. package/bin/install.js +2145 -545
  34. package/commands/sdd/add-backlog.md +5 -5
  35. package/commands/sdd/add-tests.md +2 -2
  36. package/commands/sdd/ai-integration-phase.md +36 -0
  37. package/commands/sdd/analyze-dependencies.md +34 -0
  38. package/commands/sdd/audit-fix.md +33 -0
  39. package/commands/sdd/autonomous.md +7 -2
  40. package/commands/sdd/cleanup.md +5 -0
  41. package/commands/sdd/code-review-fix.md +52 -0
  42. package/commands/sdd/code-review.md +55 -0
  43. package/commands/sdd/complete-milestone.md +6 -6
  44. package/commands/sdd/debug.md +22 -9
  45. package/commands/sdd/discuss-phase.md +7 -2
  46. package/commands/sdd/do.md +1 -1
  47. package/commands/sdd/docs-update.md +48 -0
  48. package/commands/sdd/eval-review.md +32 -0
  49. package/commands/sdd/execute-phase.md +4 -0
  50. package/commands/sdd/explore.md +27 -0
  51. package/commands/sdd/fast.md +2 -2
  52. package/commands/sdd/from-sdd2.md +45 -0
  53. package/commands/sdd/help.md +2 -0
  54. package/commands/sdd/import.md +36 -0
  55. package/commands/sdd/intel.md +179 -0
  56. package/commands/sdd/join-discord.md +2 -1
  57. package/commands/sdd/manager.md +1 -0
  58. package/commands/sdd/map-codebase.md +3 -3
  59. package/commands/sdd/new-milestone.md +1 -1
  60. package/commands/sdd/new-project.md +5 -1
  61. package/commands/sdd/new-workspace.md +1 -1
  62. package/commands/sdd/next.md +2 -0
  63. package/commands/sdd/plan-milestone-gaps.md +2 -2
  64. package/commands/sdd/plan-phase.md +6 -1
  65. package/commands/sdd/plant-seed.md +1 -1
  66. package/commands/sdd/profile-user.md +1 -1
  67. package/commands/sdd/quick.md +5 -3
  68. package/commands/sdd/reapply-patches.md +230 -42
  69. package/commands/sdd/research-phase.md +3 -3
  70. package/commands/sdd/review-backlog.md +1 -0
  71. package/commands/sdd/review.md +6 -3
  72. package/commands/sdd/scan.md +26 -0
  73. package/commands/sdd/secure-phase.md +35 -0
  74. package/commands/sdd/ship.md +1 -1
  75. package/commands/sdd/thread.md +5 -5
  76. package/commands/sdd/undo.md +34 -0
  77. package/commands/sdd/verify-work.md +1 -1
  78. package/commands/sdd/workstreams.md +17 -11
  79. package/hooks/dist/sdd-check-update.js +33 -8
  80. package/hooks/dist/sdd-context-monitor.js +17 -8
  81. package/hooks/dist/sdd-phase-boundary.sh +27 -0
  82. package/hooks/dist/sdd-prompt-guard.js +1 -0
  83. package/hooks/dist/sdd-read-guard.js +82 -0
  84. package/hooks/dist/sdd-session-state.sh +33 -0
  85. package/hooks/dist/sdd-statusline.js +137 -15
  86. package/hooks/dist/sdd-validate-commit.sh +47 -0
  87. package/hooks/dist/sdd-workflow-guard.js +4 -4
  88. package/hooks/sdd-check-update.js +139 -0
  89. package/hooks/sdd-context-monitor.js +165 -0
  90. package/hooks/sdd-phase-boundary.sh +27 -0
  91. package/hooks/sdd-prompt-guard.js +97 -0
  92. package/hooks/sdd-read-guard.js +82 -0
  93. package/hooks/sdd-session-state.sh +33 -0
  94. package/hooks/sdd-statusline.js +241 -0
  95. package/hooks/sdd-validate-commit.sh +47 -0
  96. package/hooks/sdd-workflow-guard.js +94 -0
  97. package/package.json +3 -3
  98. package/scripts/build-hooks.js +18 -7
  99. package/scripts/prompt-injection-scan.sh +1 -0
  100. package/scripts/rebrand-gsd-to-sdd.sh +221 -220
  101. package/scripts/run-tests.cjs +5 -1
  102. package/scripts/sync-upstream.sh +1 -1
  103. package/sdd/bin/lib/commands.cjs +79 -17
  104. package/sdd/bin/lib/config.cjs +90 -48
  105. package/sdd/bin/lib/core.cjs +452 -87
  106. package/sdd/bin/lib/docs.cjs +267 -0
  107. package/sdd/bin/lib/frontmatter.cjs +381 -336
  108. package/sdd/bin/lib/init.cjs +110 -16
  109. package/sdd/bin/lib/intel.cjs +660 -0
  110. package/sdd/bin/lib/learnings.cjs +378 -0
  111. package/sdd/bin/lib/milestone.cjs +42 -11
  112. package/sdd/bin/lib/model-profiles.cjs +17 -15
  113. package/sdd/bin/lib/phase.cjs +367 -288
  114. package/sdd/bin/lib/profile-output.cjs +106 -10
  115. package/sdd/bin/lib/roadmap.cjs +146 -115
  116. package/sdd/bin/lib/schema-detect.cjs +238 -0
  117. package/sdd/bin/lib/sdd2-import.cjs +511 -0
  118. package/sdd/bin/lib/security.cjs +124 -3
  119. package/sdd/bin/lib/state.cjs +648 -264
  120. package/sdd/bin/lib/template.cjs +8 -4
  121. package/sdd/bin/lib/verify.cjs +209 -28
  122. package/sdd/bin/lib/workstream.cjs +7 -3
  123. package/sdd/bin/sdd-tools.cjs +184 -12
  124. package/sdd/contexts/dev.md +21 -0
  125. package/sdd/contexts/research.md +22 -0
  126. package/sdd/contexts/review.md +22 -0
  127. package/sdd/references/agent-contracts.md +79 -0
  128. package/sdd/references/ai-evals.md +156 -0
  129. package/sdd/references/ai-frameworks.md +186 -0
  130. package/sdd/references/artifact-types.md +113 -0
  131. package/sdd/references/common-bug-patterns.md +114 -0
  132. package/sdd/references/context-budget.md +49 -0
  133. package/sdd/references/continuation-format.md +25 -25
  134. package/sdd/references/domain-probes.md +125 -0
  135. package/sdd/references/few-shot-examples/plan-checker.md +73 -0
  136. package/sdd/references/few-shot-examples/verifier.md +109 -0
  137. package/sdd/references/gate-prompts.md +100 -0
  138. package/sdd/references/gates.md +70 -0
  139. package/sdd/references/git-integration.md +1 -1
  140. package/sdd/references/ios-scaffold.md +123 -0
  141. package/sdd/references/model-profile-resolution.md +2 -0
  142. package/sdd/references/model-profiles.md +24 -18
  143. package/sdd/references/planner-gap-closure.md +62 -0
  144. package/sdd/references/planner-reviews.md +39 -0
  145. package/sdd/references/planner-revision.md +87 -0
  146. package/sdd/references/planning-config.md +252 -0
  147. package/sdd/references/revision-loop.md +97 -0
  148. package/sdd/references/thinking-models-debug.md +44 -0
  149. package/sdd/references/thinking-models-execution.md +50 -0
  150. package/sdd/references/thinking-models-planning.md +62 -0
  151. package/sdd/references/thinking-models-research.md +50 -0
  152. package/sdd/references/thinking-models-verification.md +55 -0
  153. package/sdd/references/thinking-partner.md +96 -0
  154. package/sdd/references/ui-brand.md +4 -4
  155. package/sdd/references/universal-anti-patterns.md +63 -0
  156. package/sdd/references/verification-overrides.md +227 -0
  157. package/sdd/references/workstream-flag.md +56 -3
  158. package/sdd/templates/AI-SPEC.md +246 -0
  159. package/sdd/templates/DEBUG.md +1 -1
  160. package/sdd/templates/SECURITY.md +61 -0
  161. package/sdd/templates/UAT.md +4 -4
  162. package/sdd/templates/VALIDATION.md +4 -4
  163. package/sdd/templates/claude-md.md +32 -9
  164. package/sdd/templates/config.json +4 -0
  165. package/sdd/templates/debug-subagent-prompt.md +1 -1
  166. package/sdd/templates/dev-preferences.md +1 -1
  167. package/sdd/templates/discovery.md +2 -2
  168. package/sdd/templates/phase-prompt.md +1 -1
  169. package/sdd/templates/planner-subagent-prompt.md +3 -3
  170. package/sdd/templates/project.md +1 -1
  171. package/sdd/templates/research.md +1 -1
  172. package/sdd/templates/state.md +2 -2
  173. package/sdd/workflows/add-phase.md +8 -8
  174. package/sdd/workflows/add-tests.md +12 -9
  175. package/sdd/workflows/add-todo.md +5 -3
  176. package/sdd/workflows/ai-integration-phase.md +284 -0
  177. package/sdd/workflows/analyze-dependencies.md +96 -0
  178. package/sdd/workflows/audit-fix.md +157 -0
  179. package/sdd/workflows/audit-milestone.md +11 -11
  180. package/sdd/workflows/audit-uat.md +2 -2
  181. package/sdd/workflows/autonomous.md +195 -27
  182. package/sdd/workflows/check-todos.md +12 -10
  183. package/sdd/workflows/cleanup.md +2 -0
  184. package/sdd/workflows/code-review-fix.md +497 -0
  185. package/sdd/workflows/code-review.md +515 -0
  186. package/sdd/workflows/complete-milestone.md +56 -22
  187. package/sdd/workflows/diagnose-issues.md +10 -3
  188. package/sdd/workflows/discovery-phase.md +5 -3
  189. package/sdd/workflows/discuss-phase-assumptions.md +24 -6
  190. package/sdd/workflows/discuss-phase-power.md +291 -0
  191. package/sdd/workflows/discuss-phase.md +173 -21
  192. package/sdd/workflows/do.md +23 -21
  193. package/sdd/workflows/docs-update.md +1155 -0
  194. package/sdd/workflows/eval-review.md +155 -0
  195. package/sdd/workflows/execute-phase.md +594 -38
  196. package/sdd/workflows/execute-plan.md +67 -96
  197. package/sdd/workflows/explore.md +139 -0
  198. package/sdd/workflows/fast.md +5 -5
  199. package/sdd/workflows/forensics.md +2 -2
  200. package/sdd/workflows/health.md +4 -4
  201. package/sdd/workflows/help.md +122 -119
  202. package/sdd/workflows/import.md +276 -0
  203. package/sdd/workflows/inbox.md +387 -0
  204. package/sdd/workflows/insert-phase.md +7 -7
  205. package/sdd/workflows/list-phase-assumptions.md +4 -4
  206. package/sdd/workflows/list-workspaces.md +2 -2
  207. package/sdd/workflows/manager.md +35 -32
  208. package/sdd/workflows/map-codebase.md +7 -5
  209. package/sdd/workflows/milestone-summary.md +2 -2
  210. package/sdd/workflows/new-milestone.md +17 -9
  211. package/sdd/workflows/new-project.md +50 -25
  212. package/sdd/workflows/new-workspace.md +7 -5
  213. package/sdd/workflows/next.md +67 -11
  214. package/sdd/workflows/note.md +9 -7
  215. package/sdd/workflows/pause-work.md +75 -12
  216. package/sdd/workflows/plan-milestone-gaps.md +8 -8
  217. package/sdd/workflows/plan-phase.md +294 -42
  218. package/sdd/workflows/plant-seed.md +6 -3
  219. package/sdd/workflows/pr-branch.md +42 -14
  220. package/sdd/workflows/profile-user.md +9 -7
  221. package/sdd/workflows/progress.md +45 -45
  222. package/sdd/workflows/quick.md +195 -47
  223. package/sdd/workflows/remove-phase.md +6 -6
  224. package/sdd/workflows/remove-workspace.md +3 -1
  225. package/sdd/workflows/research-phase.md +2 -2
  226. package/sdd/workflows/resume-project.md +12 -12
  227. package/sdd/workflows/review.md +109 -9
  228. package/sdd/workflows/scan.md +102 -0
  229. package/sdd/workflows/secure-phase.md +166 -0
  230. package/sdd/workflows/session-report.md +2 -2
  231. package/sdd/workflows/settings.md +38 -12
  232. package/sdd/workflows/ship.md +21 -9
  233. package/sdd/workflows/stats.md +1 -1
  234. package/sdd/workflows/transition.md +23 -23
  235. package/sdd/workflows/ui-phase.md +15 -7
  236. package/sdd/workflows/ui-review.md +29 -4
  237. package/sdd/workflows/undo.md +314 -0
  238. package/sdd/workflows/update.md +171 -20
  239. package/sdd/workflows/validate-phase.md +6 -4
  240. package/sdd/workflows/verify-phase.md +210 -6
  241. package/sdd/workflows/verify-work.md +83 -9
  242. package/sdd/commands/sdd/workstreams.md +0 -63
@@ -1,336 +1,381 @@
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, normalizeMd, output, error } = require('./core.cjs');
8
-
9
- // ─── Parsing engine ───────────────────────────────────────────────────────────
10
-
11
- function extractFrontmatter(content) {
12
- const frontmatter = {};
13
- // Find ALL frontmatter blocks at the start of the file.
14
- // If multiple blocks exist (corruption from CRLF mismatch), use the LAST one
15
- // since it represents the most recent state sync.
16
- const allBlocks = [...content.matchAll(/(?:^|\n)\s*---\r?\n([\s\S]+?)\r?\n---/g)];
17
- const match = allBlocks.length > 0 ? allBlocks[allBlocks.length - 1] : null;
18
- if (!match) return frontmatter;
19
-
20
- const yaml = match[1];
21
- const lines = yaml.split(/\r?\n/);
22
-
23
- // Stack to track nested objects: [{obj, key, indent}]
24
- // obj = object to write to, key = current key collecting array items, indent = indentation level
25
- let stack = [{ obj: frontmatter, key: null, indent: -1 }];
26
-
27
- for (const line of lines) {
28
- // Skip empty lines
29
- if (line.trim() === '') continue;
30
-
31
- // Calculate indentation (number of leading spaces)
32
- const indentMatch = line.match(/^(\s*)/);
33
- const indent = indentMatch ? indentMatch[1].length : 0;
34
-
35
- // Pop stack back to appropriate level
36
- while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
37
- stack.pop();
38
- }
39
-
40
- const current = stack[stack.length - 1];
41
-
42
- // Check for key: value pattern
43
- const keyMatch = line.match(/^(\s*)([a-zA-Z0-9_-]+):\s*(.*)/);
44
- if (keyMatch) {
45
- const key = keyMatch[2];
46
- const value = keyMatch[3].trim();
47
-
48
- if (value === '' || value === '[') {
49
- // Key with no value or opening bracket could be nested object or array
50
- // We'll determine based on next lines, for now create placeholder
51
- current.obj[key] = value === '[' ? [] : {};
52
- current.key = null;
53
- // Push new context for potential nested content
54
- stack.push({ obj: current.obj[key], key: null, indent });
55
- } else if (value.startsWith('[') && value.endsWith(']')) {
56
- // Inline array: key: [a, b, c]
57
- current.obj[key] = value.slice(1, -1).split(',').map(s => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean);
58
- current.key = null;
59
- } else {
60
- // Simple key: value
61
- current.obj[key] = value.replace(/^["']|["']$/g, '');
62
- current.key = null;
63
- }
64
- } else if (line.trim().startsWith('- ')) {
65
- // Array item
66
- const itemValue = line.trim().slice(2).replace(/^["']|["']$/g, '');
67
-
68
- // If current context is an empty object, convert to array
69
- if (typeof current.obj === 'object' && !Array.isArray(current.obj) && Object.keys(current.obj).length === 0) {
70
- // Find the key in parent that points to this object and convert it
71
- const parent = stack.length > 1 ? stack[stack.length - 2] : null;
72
- if (parent) {
73
- for (const k of Object.keys(parent.obj)) {
74
- if (parent.obj[k] === current.obj) {
75
- parent.obj[k] = [itemValue];
76
- current.obj = parent.obj[k];
77
- break;
78
- }
79
- }
80
- }
81
- } else if (Array.isArray(current.obj)) {
82
- current.obj.push(itemValue);
83
- }
84
- }
85
- }
86
-
87
- return frontmatter;
88
- }
89
-
90
- function reconstructFrontmatter(obj) {
91
- const lines = [];
92
- for (const [key, value] of Object.entries(obj)) {
93
- if (value === null || value === undefined) continue;
94
- if (Array.isArray(value)) {
95
- if (value.length === 0) {
96
- lines.push(`${key}: []`);
97
- } else if (value.every(v => typeof v === 'string') && value.length <= 3 && value.join(', ').length < 60) {
98
- lines.push(`${key}: [${value.join(', ')}]`);
99
- } else {
100
- lines.push(`${key}:`);
101
- for (const item of value) {
102
- lines.push(` - ${typeof item === 'string' && (item.includes(':') || item.includes('#')) ? `"${item}"` : item}`);
103
- }
104
- }
105
- } else if (typeof value === 'object') {
106
- lines.push(`${key}:`);
107
- for (const [subkey, subval] of Object.entries(value)) {
108
- if (subval === null || subval === undefined) continue;
109
- if (Array.isArray(subval)) {
110
- if (subval.length === 0) {
111
- lines.push(` ${subkey}: []`);
112
- } else if (subval.every(v => typeof v === 'string') && subval.length <= 3 && subval.join(', ').length < 60) {
113
- lines.push(` ${subkey}: [${subval.join(', ')}]`);
114
- } else {
115
- lines.push(` ${subkey}:`);
116
- for (const item of subval) {
117
- lines.push(` - ${typeof item === 'string' && (item.includes(':') || item.includes('#')) ? `"${item}"` : item}`);
118
- }
119
- }
120
- } else if (typeof subval === 'object') {
121
- lines.push(` ${subkey}:`);
122
- for (const [subsubkey, subsubval] of Object.entries(subval)) {
123
- if (subsubval === null || subsubval === undefined) continue;
124
- if (Array.isArray(subsubval)) {
125
- if (subsubval.length === 0) {
126
- lines.push(` ${subsubkey}: []`);
127
- } else {
128
- lines.push(` ${subsubkey}:`);
129
- for (const item of subsubval) {
130
- lines.push(` - ${item}`);
131
- }
132
- }
133
- } else {
134
- lines.push(` ${subsubkey}: ${subsubval}`);
135
- }
136
- }
137
- } else {
138
- const sv = String(subval);
139
- lines.push(` ${subkey}: ${sv.includes(':') || sv.includes('#') ? `"${sv}"` : sv}`);
140
- }
141
- }
142
- } else {
143
- const sv = String(value);
144
- if (sv.includes(':') || sv.includes('#') || sv.startsWith('[') || sv.startsWith('{')) {
145
- lines.push(`${key}: "${sv}"`);
146
- } else {
147
- lines.push(`${key}: ${sv}`);
148
- }
149
- }
150
- }
151
- return lines.join('\n');
152
- }
153
-
154
- function spliceFrontmatter(content, newObj) {
155
- const yamlStr = reconstructFrontmatter(newObj);
156
- const match = content.match(/^---\r?\n[\s\S]+?\r?\n---/);
157
- if (match) {
158
- return `---\n${yamlStr}\n---` + content.slice(match[0].length);
159
- }
160
- return `---\n${yamlStr}\n---\n\n` + content;
161
- }
162
-
163
- function parseMustHavesBlock(content, blockName) {
164
- // Extract a specific block from must_haves in raw frontmatter YAML
165
- // Handles 3-level nesting: must_haves > artifacts/key_links > [{path, provides, ...}]
166
- const fmMatch = content.match(/^---\r?\n([\s\S]+?)\r?\n---/);
167
- if (!fmMatch) return [];
168
-
169
- const yaml = fmMatch[1];
170
-
171
- // Find must_haves: first to detect its indentation level
172
- const mustHavesMatch = yaml.match(/^(\s*)must_haves:\s*$/m);
173
- if (!mustHavesMatch) return [];
174
- const mustHavesIndent = mustHavesMatch[1].length;
175
-
176
- // Find the block (e.g., "truths:", "artifacts:", "key_links:") under must_haves
177
- // It must be indented more than must_haves but we detect the actual indent dynamically
178
- const blockPattern = new RegExp(`^(\\s+)${blockName}:\\s*$`, 'm');
179
- const blockMatch = yaml.match(blockPattern);
180
- if (!blockMatch) return [];
181
-
182
- const blockIndent = blockMatch[1].length;
183
- // The block must be nested under must_haves (more indented)
184
- if (blockIndent <= mustHavesIndent) return [];
185
-
186
- // Find where the block starts in the yaml string
187
- const blockStart = yaml.indexOf(blockMatch[0]);
188
- if (blockStart === -1) return [];
189
-
190
- const afterBlock = yaml.slice(blockStart);
191
- const blockLines = afterBlock.split(/\r?\n/).slice(1); // skip the header line
192
-
193
- // List items are indented one level deeper than blockIndent
194
- // Continuation KVs are indented one level deeper than list items
195
- const items = [];
196
- let current = null;
197
- let listItemIndent = -1; // detected from first "- " line
198
-
199
- for (const line of blockLines) {
200
- // Skip empty lines
201
- if (line.trim() === '') continue;
202
- const indent = line.match(/^(\s*)/)[1].length;
203
- // Stop at same or lower indent level than the block header
204
- if (indent <= blockIndent && line.trim() !== '') break;
205
-
206
- const trimmed = line.trim();
207
-
208
- if (trimmed.startsWith('- ')) {
209
- // Detect list item indent from the first occurrence
210
- if (listItemIndent === -1) listItemIndent = indent;
211
-
212
- // Only treat as a top-level list item if at the expected indent
213
- if (indent === listItemIndent) {
214
- if (current) items.push(current);
215
- current = {};
216
- const afterDash = trimmed.slice(2);
217
- // Check if it's a simple string item (no colon means not a key-value)
218
- if (!afterDash.includes(':')) {
219
- current = afterDash.replace(/^["']|["']$/g, '');
220
- } else {
221
- // Key-value on same line as dash: "- path: value"
222
- const kvMatch = afterDash.match(/^(\w+):\s*"?([^"]*)"?\s*$/);
223
- if (kvMatch) {
224
- current = {};
225
- current[kvMatch[1]] = kvMatch[2];
226
- }
227
- }
228
- continue;
229
- }
230
- }
231
-
232
- if (current && typeof current === 'object' && indent > listItemIndent) {
233
- // Continuation key-value or nested array item
234
- if (trimmed.startsWith('- ')) {
235
- // Array item under a key
236
- const arrVal = trimmed.slice(2).replace(/^["']|["']$/g, '');
237
- const keys = Object.keys(current);
238
- const lastKey = keys[keys.length - 1];
239
- if (lastKey && !Array.isArray(current[lastKey])) {
240
- current[lastKey] = current[lastKey] ? [current[lastKey]] : [];
241
- }
242
- if (lastKey) current[lastKey].push(arrVal);
243
- } else {
244
- const kvMatch = trimmed.match(/^(\w+):\s*"?([^"]*)"?\s*$/);
245
- if (kvMatch) {
246
- const val = kvMatch[2];
247
- // Try to parse as number
248
- current[kvMatch[1]] = /^\d+$/.test(val) ? parseInt(val, 10) : val;
249
- }
250
- }
251
- }
252
- }
253
- if (current) items.push(current);
254
-
255
- return items;
256
- }
257
-
258
- // ─── Frontmatter CRUD commands ────────────────────────────────────────────────
259
-
260
- const FRONTMATTER_SCHEMAS = {
261
- plan: { required: ['phase', 'plan', 'type', 'wave', 'depends_on', 'files_modified', 'autonomous', 'must_haves'] },
262
- summary: { required: ['phase', 'plan', 'subsystem', 'tags', 'duration', 'completed'] },
263
- verification: { required: ['phase', 'verified', 'status', 'score'] },
264
- };
265
-
266
- function cmdFrontmatterGet(cwd, filePath, field, raw) {
267
- if (!filePath) { error('file path required'); }
268
- // Path traversal guard: reject null bytes
269
- if (filePath.includes('\0')) { error('file path contains null bytes'); }
270
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
271
- const content = safeReadFile(fullPath);
272
- if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
273
- const fm = extractFrontmatter(content);
274
- if (field) {
275
- const value = fm[field];
276
- if (value === undefined) { output({ error: 'Field not found', field }, raw); return; }
277
- output({ [field]: value }, raw, JSON.stringify(value));
278
- } else {
279
- output(fm, raw);
280
- }
281
- }
282
-
283
- function cmdFrontmatterSet(cwd, filePath, field, value, raw) {
284
- if (!filePath || !field || value === undefined) { error('file, field, and value required'); }
285
- // Path traversal guard: reject null bytes
286
- if (filePath.includes('\0')) { error('file path contains null bytes'); }
287
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
288
- if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
289
- const content = fs.readFileSync(fullPath, 'utf-8');
290
- const fm = extractFrontmatter(content);
291
- let parsedValue;
292
- try { parsedValue = JSON.parse(value); } catch { parsedValue = value; }
293
- fm[field] = parsedValue;
294
- const newContent = spliceFrontmatter(content, fm);
295
- fs.writeFileSync(fullPath, normalizeMd(newContent), 'utf-8');
296
- output({ updated: true, field, value: parsedValue }, raw, 'true');
297
- }
298
-
299
- function cmdFrontmatterMerge(cwd, filePath, data, raw) {
300
- if (!filePath || !data) { error('file and data required'); }
301
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
302
- if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
303
- const content = fs.readFileSync(fullPath, 'utf-8');
304
- const fm = extractFrontmatter(content);
305
- let mergeData;
306
- try { mergeData = JSON.parse(data); } catch { error('Invalid JSON for --data'); return; }
307
- Object.assign(fm, mergeData);
308
- const newContent = spliceFrontmatter(content, fm);
309
- fs.writeFileSync(fullPath, normalizeMd(newContent), 'utf-8');
310
- output({ merged: true, fields: Object.keys(mergeData) }, raw, 'true');
311
- }
312
-
313
- function cmdFrontmatterValidate(cwd, filePath, schemaName, raw) {
314
- if (!filePath || !schemaName) { error('file and schema required'); }
315
- const schema = FRONTMATTER_SCHEMAS[schemaName];
316
- if (!schema) { error(`Unknown schema: ${schemaName}. Available: ${Object.keys(FRONTMATTER_SCHEMAS).join(', ')}`); }
317
- const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
318
- const content = safeReadFile(fullPath);
319
- if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
320
- const fm = extractFrontmatter(content);
321
- const missing = schema.required.filter(f => fm[f] === undefined);
322
- const present = schema.required.filter(f => fm[f] !== undefined);
323
- output({ valid: missing.length === 0, missing, present, schema: schemaName }, raw, missing.length === 0 ? 'valid' : 'invalid');
324
- }
325
-
326
- module.exports = {
327
- extractFrontmatter,
328
- reconstructFrontmatter,
329
- spliceFrontmatter,
330
- parseMustHavesBlock,
331
- FRONTMATTER_SCHEMAS,
332
- cmdFrontmatterGet,
333
- cmdFrontmatterSet,
334
- cmdFrontmatterMerge,
335
- cmdFrontmatterValidate,
336
- };
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, normalizeMd, output, error } = require('./core.cjs');
8
+
9
+ // ─── Parsing engine ───────────────────────────────────────────────────────────
10
+
11
+ /**
12
+ * Split a YAML inline array body on commas, respecting quoted strings.
13
+ * e.g. '"a, b", c' ['a, b', 'c']
14
+ */
15
+ function splitInlineArray(body) {
16
+ const items = [];
17
+ let current = '';
18
+ let inQuote = null; // null | '"' | "'"
19
+
20
+ for (let i = 0; i < body.length; i++) {
21
+ const ch = body[i];
22
+ if (inQuote) {
23
+ if (ch === inQuote) {
24
+ inQuote = null;
25
+ } else {
26
+ current += ch;
27
+ }
28
+ } else if (ch === '"' || ch === "'") {
29
+ inQuote = ch;
30
+ } else if (ch === ',') {
31
+ const trimmed = current.trim();
32
+ if (trimmed) items.push(trimmed);
33
+ current = '';
34
+ } else {
35
+ current += ch;
36
+ }
37
+ }
38
+ const trimmed = current.trim();
39
+ if (trimmed) items.push(trimmed);
40
+ return items;
41
+ }
42
+
43
+ function extractFrontmatter(content) {
44
+ const frontmatter = {};
45
+ // Find ALL frontmatter blocks at the start of the file.
46
+ // If multiple blocks exist (corruption from CRLF mismatch), use the LAST one
47
+ // since it represents the most recent state sync.
48
+ const allBlocks = [...content.matchAll(/(?:^|\n)\s*---\r?\n([\s\S]+?)\r?\n---/g)];
49
+ const match = allBlocks.length > 0 ? allBlocks[allBlocks.length - 1] : null;
50
+ if (!match) return frontmatter;
51
+
52
+ const yaml = match[1];
53
+ const lines = yaml.split(/\r?\n/);
54
+
55
+ // Stack to track nested objects: [{obj, key, indent}]
56
+ // obj = object to write to, key = current key collecting array items, indent = indentation level
57
+ let stack = [{ obj: frontmatter, key: null, indent: -1 }];
58
+
59
+ for (const line of lines) {
60
+ // Skip empty lines
61
+ if (line.trim() === '') continue;
62
+
63
+ // Calculate indentation (number of leading spaces)
64
+ const indentMatch = line.match(/^(\s*)/);
65
+ const indent = indentMatch ? indentMatch[1].length : 0;
66
+
67
+ // Pop stack back to appropriate level
68
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
69
+ stack.pop();
70
+ }
71
+
72
+ const current = stack[stack.length - 1];
73
+
74
+ // Check for key: value pattern
75
+ const keyMatch = line.match(/^(\s*)([a-zA-Z0-9_-]+):\s*(.*)/);
76
+ if (keyMatch) {
77
+ const key = keyMatch[2];
78
+ const value = keyMatch[3].trim();
79
+
80
+ if (value === '' || value === '[') {
81
+ // Key with no value or opening bracket — could be nested object or array
82
+ // We'll determine based on next lines, for now create placeholder
83
+ current.obj[key] = value === '[' ? [] : {};
84
+ current.key = null;
85
+ // Push new context for potential nested content
86
+ stack.push({ obj: current.obj[key], key: null, indent });
87
+ } else if (value.startsWith('[') && value.endsWith(']')) {
88
+ // Inline array: key: [a, b, c] — quote-aware split (REG-04 fix)
89
+ current.obj[key] = splitInlineArray(value.slice(1, -1));
90
+ current.key = null;
91
+ } else {
92
+ // Simple key: value
93
+ current.obj[key] = value.replace(/^["']|["']$/g, '');
94
+ current.key = null;
95
+ }
96
+ } else if (line.trim().startsWith('- ')) {
97
+ // Array item
98
+ const itemValue = line.trim().slice(2).replace(/^["']|["']$/g, '');
99
+
100
+ // If current context is an empty object, convert to array
101
+ if (typeof current.obj === 'object' && !Array.isArray(current.obj) && Object.keys(current.obj).length === 0) {
102
+ // Find the key in parent that points to this object and convert it
103
+ const parent = stack.length > 1 ? stack[stack.length - 2] : null;
104
+ if (parent) {
105
+ for (const k of Object.keys(parent.obj)) {
106
+ if (parent.obj[k] === current.obj) {
107
+ parent.obj[k] = [itemValue];
108
+ current.obj = parent.obj[k];
109
+ break;
110
+ }
111
+ }
112
+ }
113
+ } else if (Array.isArray(current.obj)) {
114
+ current.obj.push(itemValue);
115
+ }
116
+ }
117
+ }
118
+
119
+ return frontmatter;
120
+ }
121
+
122
+ function reconstructFrontmatter(obj) {
123
+ const lines = [];
124
+ for (const [key, value] of Object.entries(obj)) {
125
+ if (value === null || value === undefined) continue;
126
+ if (Array.isArray(value)) {
127
+ if (value.length === 0) {
128
+ lines.push(`${key}: []`);
129
+ } else if (value.every(v => typeof v === 'string') && value.length <= 3 && value.join(', ').length < 60) {
130
+ lines.push(`${key}: [${value.join(', ')}]`);
131
+ } else {
132
+ lines.push(`${key}:`);
133
+ for (const item of value) {
134
+ lines.push(` - ${typeof item === 'string' && (item.includes(':') || item.includes('#')) ? `"${item}"` : item}`);
135
+ }
136
+ }
137
+ } else if (typeof value === 'object') {
138
+ lines.push(`${key}:`);
139
+ for (const [subkey, subval] of Object.entries(value)) {
140
+ if (subval === null || subval === undefined) continue;
141
+ if (Array.isArray(subval)) {
142
+ if (subval.length === 0) {
143
+ lines.push(` ${subkey}: []`);
144
+ } else if (subval.every(v => typeof v === 'string') && subval.length <= 3 && subval.join(', ').length < 60) {
145
+ lines.push(` ${subkey}: [${subval.join(', ')}]`);
146
+ } else {
147
+ lines.push(` ${subkey}:`);
148
+ for (const item of subval) {
149
+ lines.push(` - ${typeof item === 'string' && (item.includes(':') || item.includes('#')) ? `"${item}"` : item}`);
150
+ }
151
+ }
152
+ } else if (typeof subval === 'object') {
153
+ lines.push(` ${subkey}:`);
154
+ for (const [subsubkey, subsubval] of Object.entries(subval)) {
155
+ if (subsubval === null || subsubval === undefined) continue;
156
+ if (Array.isArray(subsubval)) {
157
+ if (subsubval.length === 0) {
158
+ lines.push(` ${subsubkey}: []`);
159
+ } else {
160
+ lines.push(` ${subsubkey}:`);
161
+ for (const item of subsubval) {
162
+ lines.push(` - ${item}`);
163
+ }
164
+ }
165
+ } else {
166
+ lines.push(` ${subsubkey}: ${subsubval}`);
167
+ }
168
+ }
169
+ } else {
170
+ const sv = String(subval);
171
+ lines.push(` ${subkey}: ${sv.includes(':') || sv.includes('#') ? `"${sv}"` : sv}`);
172
+ }
173
+ }
174
+ } else {
175
+ const sv = String(value);
176
+ if (sv.includes(':') || sv.includes('#') || sv.startsWith('[') || sv.startsWith('{')) {
177
+ lines.push(`${key}: "${sv}"`);
178
+ } else {
179
+ lines.push(`${key}: ${sv}`);
180
+ }
181
+ }
182
+ }
183
+ return lines.join('\n');
184
+ }
185
+
186
+ function spliceFrontmatter(content, newObj) {
187
+ const yamlStr = reconstructFrontmatter(newObj);
188
+ const match = content.match(/^---\r?\n[\s\S]+?\r?\n---/);
189
+ if (match) {
190
+ return `---\n${yamlStr}\n---` + content.slice(match[0].length);
191
+ }
192
+ return `---\n${yamlStr}\n---\n\n` + content;
193
+ }
194
+
195
+ function parseMustHavesBlock(content, blockName) {
196
+ // Extract a specific block from must_haves in raw frontmatter YAML
197
+ // Handles 3-level nesting: must_haves > artifacts/key_links > [{path, provides, ...}]
198
+ const fmMatch = content.match(/^---\r?\n([\s\S]+?)\r?\n---/);
199
+ if (!fmMatch) return [];
200
+
201
+ const yaml = fmMatch[1];
202
+
203
+ // Find must_haves: first to detect its indentation level
204
+ const mustHavesMatch = yaml.match(/^(\s*)must_haves:\s*$/m);
205
+ if (!mustHavesMatch) return [];
206
+ const mustHavesIndent = mustHavesMatch[1].length;
207
+
208
+ // Find the block (e.g., "truths:", "artifacts:", "key_links:") under must_haves
209
+ // It must be indented more than must_haves but we detect the actual indent dynamically
210
+ const blockPattern = new RegExp(`^(\\s+)${blockName}:\\s*$`, 'm');
211
+ const blockMatch = yaml.match(blockPattern);
212
+ if (!blockMatch) return [];
213
+
214
+ const blockIndent = blockMatch[1].length;
215
+ // The block must be nested under must_haves (more indented)
216
+ if (blockIndent <= mustHavesIndent) return [];
217
+
218
+ // Find where the block starts in the yaml string
219
+ const blockStart = yaml.indexOf(blockMatch[0]);
220
+ if (blockStart === -1) return [];
221
+
222
+ const afterBlock = yaml.slice(blockStart);
223
+ const blockLines = afterBlock.split(/\r?\n/).slice(1); // skip the header line
224
+
225
+ // List items are indented one level deeper than blockIndent
226
+ // Continuation KVs are indented one level deeper than list items
227
+ const items = [];
228
+ let current = null;
229
+ let listItemIndent = -1; // detected from first "- " line
230
+
231
+ for (const line of blockLines) {
232
+ // Skip empty lines
233
+ if (line.trim() === '') continue;
234
+ const indent = line.match(/^(\s*)/)[1].length;
235
+ // Stop at same or lower indent level than the block header
236
+ if (indent <= blockIndent && line.trim() !== '') break;
237
+
238
+ const trimmed = line.trim();
239
+
240
+ if (trimmed.startsWith('- ')) {
241
+ // Detect list item indent from the first occurrence
242
+ if (listItemIndent === -1) listItemIndent = indent;
243
+
244
+ // Only treat as a top-level list item if at the expected indent
245
+ if (indent === listItemIndent) {
246
+ if (current) items.push(current);
247
+ current = {};
248
+ const afterDash = trimmed.slice(2);
249
+ // Check if it's a simple string item (no colon means not a key-value)
250
+ if (!afterDash.includes(':')) {
251
+ current = afterDash.replace(/^["']|["']$/g, '');
252
+ } else {
253
+ // Key-value on same line as dash: "- path: value"
254
+ const kvMatch = afterDash.match(/^(\w+):\s*"?([^"]*)"?\s*$/);
255
+ if (kvMatch) {
256
+ current = {};
257
+ current[kvMatch[1]] = kvMatch[2];
258
+ }
259
+ }
260
+ continue;
261
+ }
262
+ }
263
+
264
+ if (current && typeof current === 'object' && indent > listItemIndent) {
265
+ // Continuation key-value or nested array item
266
+ if (trimmed.startsWith('- ')) {
267
+ // Array item under a key
268
+ const arrVal = trimmed.slice(2).replace(/^["']|["']$/g, '');
269
+ const keys = Object.keys(current);
270
+ const lastKey = keys[keys.length - 1];
271
+ if (lastKey && !Array.isArray(current[lastKey])) {
272
+ current[lastKey] = current[lastKey] ? [current[lastKey]] : [];
273
+ }
274
+ if (lastKey) current[lastKey].push(arrVal);
275
+ } else {
276
+ const kvMatch = trimmed.match(/^(\w+):\s*"?([^"]*)"?\s*$/);
277
+ if (kvMatch) {
278
+ const val = kvMatch[2];
279
+ // Try to parse as number
280
+ current[kvMatch[1]] = /^\d+$/.test(val) ? parseInt(val, 10) : val;
281
+ }
282
+ }
283
+ }
284
+ }
285
+ if (current) items.push(current);
286
+
287
+ // Warn when must_haves block exists but parsed as empty -- likely YAML formatting issue.
288
+ // This is a critical diagnostic: empty must_haves causes verification to silently degrade
289
+ // to Option C (LLM-derived truths) instead of checking documented contracts.
290
+ if (items.length === 0 && blockLines.length > 0) {
291
+ const nonEmptyLines = blockLines.filter(l => l.trim() !== '').length;
292
+ if (nonEmptyLines > 0) {
293
+ process.stderr.write(
294
+ `[sdd-tools] WARNING: must_haves.${blockName} block has ${nonEmptyLines} content lines but parsed 0 items. ` +
295
+ `Possible YAML formatting issue — verification will fall back to LLM-derived truths.\n`
296
+ );
297
+ }
298
+ }
299
+
300
+ return items;
301
+ }
302
+
303
+ // ─── Frontmatter CRUD commands ────────────────────────────────────────────────
304
+
305
+ const FRONTMATTER_SCHEMAS = {
306
+ plan: { required: ['phase', 'plan', 'type', 'wave', 'depends_on', 'files_modified', 'autonomous', 'must_haves'] },
307
+ summary: { required: ['phase', 'plan', 'subsystem', 'tags', 'duration', 'completed'] },
308
+ verification: { required: ['phase', 'verified', 'status', 'score'] },
309
+ };
310
+
311
+ function cmdFrontmatterGet(cwd, filePath, field, raw) {
312
+ if (!filePath) { error('file path required'); }
313
+ // Path traversal guard: reject null bytes
314
+ if (filePath.includes('\0')) { error('file path contains null bytes'); }
315
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
316
+ const content = safeReadFile(fullPath);
317
+ if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
318
+ const fm = extractFrontmatter(content);
319
+ if (field) {
320
+ const value = fm[field];
321
+ if (value === undefined) { output({ error: 'Field not found', field }, raw); return; }
322
+ output({ [field]: value }, raw, JSON.stringify(value));
323
+ } else {
324
+ output(fm, raw);
325
+ }
326
+ }
327
+
328
+ function cmdFrontmatterSet(cwd, filePath, field, value, raw) {
329
+ if (!filePath || !field || value === undefined) { error('file, field, and value required'); }
330
+ // Path traversal guard: reject null bytes
331
+ if (filePath.includes('\0')) { error('file path contains null bytes'); }
332
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
333
+ if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
334
+ const content = fs.readFileSync(fullPath, 'utf-8');
335
+ const fm = extractFrontmatter(content);
336
+ let parsedValue;
337
+ try { parsedValue = JSON.parse(value); } catch { parsedValue = value; }
338
+ fm[field] = parsedValue;
339
+ const newContent = spliceFrontmatter(content, fm);
340
+ fs.writeFileSync(fullPath, normalizeMd(newContent), 'utf-8');
341
+ output({ updated: true, field, value: parsedValue }, raw, 'true');
342
+ }
343
+
344
+ function cmdFrontmatterMerge(cwd, filePath, data, raw) {
345
+ if (!filePath || !data) { error('file and data required'); }
346
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
347
+ if (!fs.existsSync(fullPath)) { output({ error: 'File not found', path: filePath }, raw); return; }
348
+ const content = fs.readFileSync(fullPath, 'utf-8');
349
+ const fm = extractFrontmatter(content);
350
+ let mergeData;
351
+ try { mergeData = JSON.parse(data); } catch { error('Invalid JSON for --data'); return; }
352
+ Object.assign(fm, mergeData);
353
+ const newContent = spliceFrontmatter(content, fm);
354
+ fs.writeFileSync(fullPath, normalizeMd(newContent), 'utf-8');
355
+ output({ merged: true, fields: Object.keys(mergeData) }, raw, 'true');
356
+ }
357
+
358
+ function cmdFrontmatterValidate(cwd, filePath, schemaName, raw) {
359
+ if (!filePath || !schemaName) { error('file and schema required'); }
360
+ const schema = FRONTMATTER_SCHEMAS[schemaName];
361
+ if (!schema) { error(`Unknown schema: ${schemaName}. Available: ${Object.keys(FRONTMATTER_SCHEMAS).join(', ')}`); }
362
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath);
363
+ const content = safeReadFile(fullPath);
364
+ if (!content) { output({ error: 'File not found', path: filePath }, raw); return; }
365
+ const fm = extractFrontmatter(content);
366
+ const missing = schema.required.filter(f => fm[f] === undefined);
367
+ const present = schema.required.filter(f => fm[f] !== undefined);
368
+ output({ valid: missing.length === 0, missing, present, schema: schemaName }, raw, missing.length === 0 ? 'valid' : 'invalid');
369
+ }
370
+
371
+ module.exports = {
372
+ extractFrontmatter,
373
+ reconstructFrontmatter,
374
+ spliceFrontmatter,
375
+ parseMustHavesBlock,
376
+ FRONTMATTER_SCHEMAS,
377
+ cmdFrontmatterGet,
378
+ cmdFrontmatterSet,
379
+ cmdFrontmatterMerge,
380
+ cmdFrontmatterValidate,
381
+ };