code-as-plan 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 (188) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja-JP.md +834 -0
  3. package/README.ko-KR.md +823 -0
  4. package/README.md +1006 -0
  5. package/README.pt-BR.md +452 -0
  6. package/README.zh-CN.md +800 -0
  7. package/agents/cap-brainstormer.md +154 -0
  8. package/agents/cap-debugger.md +221 -0
  9. package/agents/cap-prototyper.md +170 -0
  10. package/agents/cap-reviewer.md +230 -0
  11. package/agents/cap-tester.md +193 -0
  12. package/bin/install.js +5002 -0
  13. package/cap/bin/gsd-tools.cjs +1141 -0
  14. package/cap/bin/lib/arc-scanner.cjs +341 -0
  15. package/cap/bin/lib/cap-feature-map.cjs +506 -0
  16. package/cap/bin/lib/cap-session.cjs +191 -0
  17. package/cap/bin/lib/cap-stack-docs.cjs +598 -0
  18. package/cap/bin/lib/cap-tag-scanner.cjs +458 -0
  19. package/cap/bin/lib/commands.cjs +959 -0
  20. package/cap/bin/lib/config.cjs +466 -0
  21. package/cap/bin/lib/convention-reader.cjs +180 -0
  22. package/cap/bin/lib/core.cjs +1230 -0
  23. package/cap/bin/lib/feature-aggregator.cjs +422 -0
  24. package/cap/bin/lib/frontmatter.cjs +336 -0
  25. package/cap/bin/lib/init.cjs +1442 -0
  26. package/cap/bin/lib/manifest-generator.cjs +381 -0
  27. package/cap/bin/lib/milestone.cjs +252 -0
  28. package/cap/bin/lib/model-profiles.cjs +68 -0
  29. package/cap/bin/lib/monorepo-context.cjs +224 -0
  30. package/cap/bin/lib/monorepo-migrator.cjs +507 -0
  31. package/cap/bin/lib/phase.cjs +888 -0
  32. package/cap/bin/lib/profile-output.cjs +952 -0
  33. package/cap/bin/lib/profile-pipeline.cjs +539 -0
  34. package/cap/bin/lib/roadmap.cjs +329 -0
  35. package/cap/bin/lib/security.cjs +382 -0
  36. package/cap/bin/lib/session-manager.cjs +290 -0
  37. package/cap/bin/lib/skeleton-generator.cjs +177 -0
  38. package/cap/bin/lib/state.cjs +1031 -0
  39. package/cap/bin/lib/template.cjs +222 -0
  40. package/cap/bin/lib/test-detector.cjs +61 -0
  41. package/cap/bin/lib/uat.cjs +282 -0
  42. package/cap/bin/lib/verify.cjs +888 -0
  43. package/cap/bin/lib/workspace-detector.cjs +369 -0
  44. package/cap/bin/lib/workstream.cjs +491 -0
  45. package/cap/commands/gsd/workstreams.md +63 -0
  46. package/cap/references/arc-standard.md +315 -0
  47. package/cap/references/cap-agent-architecture.md +102 -0
  48. package/cap/references/cap-gitignore-template +9 -0
  49. package/cap/references/cap-zero-deps.md +158 -0
  50. package/cap/references/checkpoints.md +778 -0
  51. package/cap/references/continuation-format.md +249 -0
  52. package/cap/references/decimal-phase-calculation.md +64 -0
  53. package/cap/references/feature-map-template.md +25 -0
  54. package/cap/references/git-integration.md +295 -0
  55. package/cap/references/git-planning-commit.md +38 -0
  56. package/cap/references/model-profile-resolution.md +36 -0
  57. package/cap/references/model-profiles.md +139 -0
  58. package/cap/references/phase-argument-parsing.md +61 -0
  59. package/cap/references/planning-config.md +202 -0
  60. package/cap/references/questioning.md +162 -0
  61. package/cap/references/session-template.json +8 -0
  62. package/cap/references/tdd.md +263 -0
  63. package/cap/references/ui-brand.md +160 -0
  64. package/cap/references/user-profiling.md +681 -0
  65. package/cap/references/verification-patterns.md +612 -0
  66. package/cap/references/workstream-flag.md +58 -0
  67. package/cap/templates/DEBUG.md +164 -0
  68. package/cap/templates/UAT.md +265 -0
  69. package/cap/templates/UI-SPEC.md +100 -0
  70. package/cap/templates/VALIDATION.md +76 -0
  71. package/cap/templates/claude-md.md +122 -0
  72. package/cap/templates/codebase/architecture.md +255 -0
  73. package/cap/templates/codebase/concerns.md +310 -0
  74. package/cap/templates/codebase/conventions.md +307 -0
  75. package/cap/templates/codebase/integrations.md +280 -0
  76. package/cap/templates/codebase/stack.md +186 -0
  77. package/cap/templates/codebase/structure.md +285 -0
  78. package/cap/templates/codebase/testing.md +480 -0
  79. package/cap/templates/config.json +44 -0
  80. package/cap/templates/context.md +352 -0
  81. package/cap/templates/continue-here.md +78 -0
  82. package/cap/templates/copilot-instructions.md +7 -0
  83. package/cap/templates/debug-subagent-prompt.md +91 -0
  84. package/cap/templates/dev-preferences.md +21 -0
  85. package/cap/templates/discovery.md +146 -0
  86. package/cap/templates/discussion-log.md +63 -0
  87. package/cap/templates/milestone-archive.md +123 -0
  88. package/cap/templates/milestone.md +115 -0
  89. package/cap/templates/phase-prompt.md +610 -0
  90. package/cap/templates/planner-subagent-prompt.md +117 -0
  91. package/cap/templates/project.md +186 -0
  92. package/cap/templates/requirements.md +231 -0
  93. package/cap/templates/research-project/ARCHITECTURE.md +204 -0
  94. package/cap/templates/research-project/FEATURES.md +147 -0
  95. package/cap/templates/research-project/PITFALLS.md +200 -0
  96. package/cap/templates/research-project/STACK.md +120 -0
  97. package/cap/templates/research-project/SUMMARY.md +170 -0
  98. package/cap/templates/research.md +552 -0
  99. package/cap/templates/retrospective.md +54 -0
  100. package/cap/templates/roadmap.md +202 -0
  101. package/cap/templates/state.md +176 -0
  102. package/cap/templates/summary-complex.md +59 -0
  103. package/cap/templates/summary-minimal.md +41 -0
  104. package/cap/templates/summary-standard.md +48 -0
  105. package/cap/templates/summary.md +248 -0
  106. package/cap/templates/user-profile.md +146 -0
  107. package/cap/templates/user-setup.md +311 -0
  108. package/cap/templates/verification-report.md +322 -0
  109. package/cap/workflows/add-phase.md +112 -0
  110. package/cap/workflows/add-tests.md +351 -0
  111. package/cap/workflows/add-todo.md +158 -0
  112. package/cap/workflows/audit-milestone.md +340 -0
  113. package/cap/workflows/audit-uat.md +109 -0
  114. package/cap/workflows/autonomous.md +891 -0
  115. package/cap/workflows/check-todos.md +177 -0
  116. package/cap/workflows/cleanup.md +152 -0
  117. package/cap/workflows/complete-milestone.md +767 -0
  118. package/cap/workflows/diagnose-issues.md +231 -0
  119. package/cap/workflows/discovery-phase.md +289 -0
  120. package/cap/workflows/discuss-phase-assumptions.md +653 -0
  121. package/cap/workflows/discuss-phase.md +1049 -0
  122. package/cap/workflows/do.md +104 -0
  123. package/cap/workflows/execute-phase.md +846 -0
  124. package/cap/workflows/execute-plan.md +514 -0
  125. package/cap/workflows/fast.md +105 -0
  126. package/cap/workflows/forensics.md +265 -0
  127. package/cap/workflows/health.md +181 -0
  128. package/cap/workflows/help.md +660 -0
  129. package/cap/workflows/insert-phase.md +130 -0
  130. package/cap/workflows/list-phase-assumptions.md +178 -0
  131. package/cap/workflows/list-workspaces.md +56 -0
  132. package/cap/workflows/manager.md +362 -0
  133. package/cap/workflows/map-codebase.md +377 -0
  134. package/cap/workflows/milestone-summary.md +223 -0
  135. package/cap/workflows/new-milestone.md +486 -0
  136. package/cap/workflows/new-project.md +1250 -0
  137. package/cap/workflows/new-workspace.md +237 -0
  138. package/cap/workflows/next.md +97 -0
  139. package/cap/workflows/node-repair.md +92 -0
  140. package/cap/workflows/note.md +156 -0
  141. package/cap/workflows/pause-work.md +176 -0
  142. package/cap/workflows/plan-milestone-gaps.md +273 -0
  143. package/cap/workflows/plan-phase.md +859 -0
  144. package/cap/workflows/plant-seed.md +169 -0
  145. package/cap/workflows/pr-branch.md +129 -0
  146. package/cap/workflows/profile-user.md +450 -0
  147. package/cap/workflows/progress.md +507 -0
  148. package/cap/workflows/quick.md +757 -0
  149. package/cap/workflows/remove-phase.md +155 -0
  150. package/cap/workflows/remove-workspace.md +90 -0
  151. package/cap/workflows/research-phase.md +82 -0
  152. package/cap/workflows/resume-project.md +326 -0
  153. package/cap/workflows/review.md +228 -0
  154. package/cap/workflows/session-report.md +146 -0
  155. package/cap/workflows/settings.md +283 -0
  156. package/cap/workflows/ship.md +228 -0
  157. package/cap/workflows/stats.md +60 -0
  158. package/cap/workflows/transition.md +671 -0
  159. package/cap/workflows/ui-phase.md +302 -0
  160. package/cap/workflows/ui-review.md +165 -0
  161. package/cap/workflows/update.md +323 -0
  162. package/cap/workflows/validate-phase.md +174 -0
  163. package/cap/workflows/verify-phase.md +254 -0
  164. package/cap/workflows/verify-work.md +637 -0
  165. package/commands/cap/annotate.md +165 -0
  166. package/commands/cap/brainstorm.md +238 -0
  167. package/commands/cap/debug.md +297 -0
  168. package/commands/cap/init.md +262 -0
  169. package/commands/cap/iterate.md +234 -0
  170. package/commands/cap/prototype.md +281 -0
  171. package/commands/cap/refresh-docs.md +37 -0
  172. package/commands/cap/review.md +272 -0
  173. package/commands/cap/scan.md +249 -0
  174. package/commands/cap/start.md +234 -0
  175. package/commands/cap/status.md +189 -0
  176. package/commands/cap/test.md +250 -0
  177. package/hooks/dist/gsd-check-update.js +114 -0
  178. package/hooks/dist/gsd-context-monitor.js +156 -0
  179. package/hooks/dist/gsd-prompt-guard.js +96 -0
  180. package/hooks/dist/gsd-statusline.js +119 -0
  181. package/hooks/dist/gsd-workflow-guard.js +94 -0
  182. package/package.json +51 -0
  183. package/scripts/base64-scan.sh +262 -0
  184. package/scripts/build-hooks.js +82 -0
  185. package/scripts/cap-removal-checklist.md +202 -0
  186. package/scripts/prompt-injection-scan.sh +198 -0
  187. package/scripts/run-tests.cjs +29 -0
  188. package/scripts/secret-scan.sh +227 -0
@@ -0,0 +1,466 @@
1
+ /**
2
+ * Config — Planning config CRUD operations
3
+ */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { output, error, planningRoot } = require('./core.cjs');
8
+ const {
9
+ VALID_PROFILES,
10
+ getAgentToModelMapForProfile,
11
+ formatAgentToModelMapAsTable,
12
+ } = require('./model-profiles.cjs');
13
+
14
+ const VALID_CONFIG_KEYS = new Set([
15
+ 'mode', 'granularity', 'parallelization', 'commit_docs', 'model_profile',
16
+ 'search_gitignored', 'brave_search', 'firecrawl', 'exa_search',
17
+ 'workflow.research', 'workflow.plan_check', 'workflow.verifier',
18
+ 'workflow.nyquist_validation', 'workflow.ui_phase', 'workflow.ui_safety_gate',
19
+ 'workflow.auto_advance', 'workflow.node_repair', 'workflow.node_repair_budget',
20
+ 'workflow.text_mode',
21
+ 'workflow.research_before_questions',
22
+ 'workflow.discuss_mode',
23
+ 'workflow.skip_discuss',
24
+ 'workflow._auto_chain_active',
25
+ 'git.branching_strategy', 'git.phase_branch_template', 'git.milestone_branch_template', 'git.quick_branch_template',
26
+ 'planning.commit_docs', 'planning.search_gitignored',
27
+ 'hooks.context_warnings',
28
+ 'arc.enabled', 'arc.tag_prefix', 'arc.comment_anchors',
29
+ 'phase_modes.default', 'default_phase_mode',
30
+ ]);
31
+
32
+ /**
33
+ * Check whether a config key path is valid.
34
+ * Supports exact matches from VALID_CONFIG_KEYS plus dynamic patterns
35
+ * like `agent_skills.<agent-type>` where the sub-key is freeform.
36
+ */
37
+ function isValidConfigKey(keyPath) {
38
+ if (VALID_CONFIG_KEYS.has(keyPath)) return true;
39
+ // Allow agent_skills.<agent-type> with any agent type string
40
+ if (/^agent_skills\.[a-zA-Z0-9_-]+$/.test(keyPath)) return true;
41
+ // Allow phase_modes.<number> for per-phase mode overrides
42
+ if (/^phase_modes\.\d+$/.test(keyPath)) return true;
43
+ return false;
44
+ }
45
+
46
+ const CONFIG_KEY_SUGGESTIONS = {
47
+ 'workflow.nyquist_validation_enabled': 'workflow.nyquist_validation',
48
+ 'agents.nyquist_validation_enabled': 'workflow.nyquist_validation',
49
+ 'nyquist.validation_enabled': 'workflow.nyquist_validation',
50
+ 'hooks.research_questions': 'workflow.research_before_questions',
51
+ 'workflow.research_questions': 'workflow.research_before_questions',
52
+ };
53
+
54
+ function validateKnownConfigKeyPath(keyPath) {
55
+ const suggested = CONFIG_KEY_SUGGESTIONS[keyPath];
56
+ if (suggested) {
57
+ error(`Unknown config key: ${keyPath}. Did you mean ${suggested}?`);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Build a fully-materialized config object for a new project.
63
+ *
64
+ * Merges (increasing priority):
65
+ * 1. Hardcoded defaults — every key that loadConfig() resolves, plus mode/granularity
66
+ * 2. User-level defaults from ~/.gsd/defaults.json (if present)
67
+ * 3. userChoices — the settings the user explicitly selected during /gsd:new-project
68
+ *
69
+ * Uses the canonical `git` namespace for branching keys (consistent with VALID_CONFIG_KEYS
70
+ * and the settings workflow). loadConfig() handles both flat and nested formats, so this
71
+ * is backward-compatible with existing projects that have flat keys.
72
+ *
73
+ * Returns a plain object — does NOT write any files.
74
+ */
75
+ function buildNewProjectConfig(userChoices) {
76
+ const choices = userChoices || {};
77
+ const homedir = require('os').homedir();
78
+
79
+ // Detect API key availability
80
+ const braveKeyFile = path.join(homedir, '.gsd', 'brave_api_key');
81
+ const hasBraveSearch = !!(process.env.BRAVE_API_KEY || fs.existsSync(braveKeyFile));
82
+ const firecrawlKeyFile = path.join(homedir, '.gsd', 'firecrawl_api_key');
83
+ const hasFirecrawl = !!(process.env.FIRECRAWL_API_KEY || fs.existsSync(firecrawlKeyFile));
84
+ const exaKeyFile = path.join(homedir, '.gsd', 'exa_api_key');
85
+ const hasExaSearch = !!(process.env.EXA_API_KEY || fs.existsSync(exaKeyFile));
86
+
87
+ // Load user-level defaults from ~/.gsd/defaults.json if available
88
+ const globalDefaultsPath = path.join(homedir, '.gsd', 'defaults.json');
89
+ let userDefaults = {};
90
+ try {
91
+ if (fs.existsSync(globalDefaultsPath)) {
92
+ userDefaults = JSON.parse(fs.readFileSync(globalDefaultsPath, 'utf-8'));
93
+ // Migrate deprecated "depth" key to "granularity"
94
+ if ('depth' in userDefaults && !('granularity' in userDefaults)) {
95
+ const depthToGranularity = { quick: 'coarse', standard: 'standard', comprehensive: 'fine' };
96
+ userDefaults.granularity = depthToGranularity[userDefaults.depth] || userDefaults.depth;
97
+ delete userDefaults.depth;
98
+ try {
99
+ fs.writeFileSync(globalDefaultsPath, JSON.stringify(userDefaults, null, 2), 'utf-8');
100
+ } catch { /* intentionally empty */ }
101
+ }
102
+ }
103
+ } catch {
104
+ // Ignore malformed global defaults
105
+ }
106
+
107
+ const hardcoded = {
108
+ model_profile: 'balanced',
109
+ commit_docs: true,
110
+ parallelization: true,
111
+ search_gitignored: false,
112
+ brave_search: hasBraveSearch,
113
+ firecrawl: hasFirecrawl,
114
+ exa_search: hasExaSearch,
115
+ git: {
116
+ branching_strategy: 'none',
117
+ phase_branch_template: 'gsd/phase-{phase}-{slug}',
118
+ milestone_branch_template: 'gsd/{milestone}-{slug}',
119
+ quick_branch_template: null,
120
+ },
121
+ workflow: {
122
+ research: true,
123
+ plan_check: true,
124
+ verifier: true,
125
+ nyquist_validation: true,
126
+ auto_advance: false,
127
+ node_repair: true,
128
+ node_repair_budget: 2,
129
+ ui_phase: true,
130
+ ui_safety_gate: true,
131
+ text_mode: false,
132
+ research_before_questions: false,
133
+ discuss_mode: 'discuss',
134
+ skip_discuss: false,
135
+ },
136
+ hooks: {
137
+ context_warnings: true,
138
+ },
139
+ agent_skills: {},
140
+ arc: {
141
+ enabled: true,
142
+ tag_prefix: '@gsd-',
143
+ comment_anchors: ['//', '#', '/*', '--'],
144
+ },
145
+ phase_modes: {},
146
+ default_phase_mode: 'plan-first',
147
+ };
148
+
149
+ // Three-level deep merge: hardcoded <- userDefaults <- choices
150
+ return {
151
+ ...hardcoded,
152
+ ...userDefaults,
153
+ ...choices,
154
+ git: {
155
+ ...hardcoded.git,
156
+ ...(userDefaults.git || {}),
157
+ ...(choices.git || {}),
158
+ },
159
+ workflow: {
160
+ ...hardcoded.workflow,
161
+ ...(userDefaults.workflow || {}),
162
+ ...(choices.workflow || {}),
163
+ },
164
+ hooks: {
165
+ ...hardcoded.hooks,
166
+ ...(userDefaults.hooks || {}),
167
+ ...(choices.hooks || {}),
168
+ },
169
+ agent_skills: {
170
+ ...hardcoded.agent_skills,
171
+ ...(userDefaults.agent_skills || {}),
172
+ ...(choices.agent_skills || {}),
173
+ },
174
+ arc: {
175
+ ...hardcoded.arc,
176
+ ...(userDefaults.arc || {}),
177
+ ...(choices.arc || {}),
178
+ },
179
+ phase_modes: {
180
+ ...hardcoded.phase_modes,
181
+ ...(userDefaults.phase_modes || {}),
182
+ ...(choices.phase_modes || {}),
183
+ },
184
+ default_phase_mode: choices.default_phase_mode || userDefaults.default_phase_mode || hardcoded.default_phase_mode,
185
+ };
186
+ }
187
+
188
+ /**
189
+ * Command: create a fully-materialized .planning/config.json for a new project.
190
+ *
191
+ * Accepts user-chosen settings as a JSON string (the keys the user explicitly
192
+ * configured during /gsd:new-project). All remaining keys are filled from
193
+ * hardcoded defaults and optional ~/.gsd/defaults.json.
194
+ *
195
+ * Idempotent: if config.json already exists, returns { created: false }.
196
+ */
197
+ function cmdConfigNewProject(cwd, choicesJson, raw) {
198
+ const planningBase = planningRoot(cwd);
199
+ const configPath = path.join(planningBase, 'config.json');
200
+
201
+ // Idempotent: don't overwrite existing config
202
+ if (fs.existsSync(configPath)) {
203
+ output({ created: false, reason: 'already_exists' }, raw, 'exists');
204
+ return;
205
+ }
206
+
207
+ // Parse user choices
208
+ let userChoices = {};
209
+ if (choicesJson && choicesJson.trim() !== '') {
210
+ try {
211
+ userChoices = JSON.parse(choicesJson);
212
+ } catch (err) {
213
+ error('Invalid JSON for config-new-project: ' + err.message);
214
+ }
215
+ }
216
+
217
+ // Ensure .planning directory exists
218
+ try {
219
+ if (!fs.existsSync(planningBase)) {
220
+ fs.mkdirSync(planningBase, { recursive: true });
221
+ }
222
+ } catch (err) {
223
+ error('Failed to create .planning directory: ' + err.message);
224
+ }
225
+
226
+ const config = buildNewProjectConfig(userChoices);
227
+
228
+ try {
229
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
230
+ output({ created: true, path: '.planning/config.json' }, raw, 'created');
231
+ } catch (err) {
232
+ error('Failed to write config.json: ' + err.message);
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Ensures the config file exists (creates it if needed).
238
+ *
239
+ * Does not call `output()`, so can be used as one step in a command without triggering `exit(0)` in
240
+ * the happy path. But note that `error()` will still `exit(1)` out of the process.
241
+ */
242
+ function ensureConfigFile(cwd) {
243
+ const planningBase = planningRoot(cwd);
244
+ const configPath = path.join(planningBase, 'config.json');
245
+
246
+ // Ensure .planning directory exists
247
+ try {
248
+ if (!fs.existsSync(planningBase)) {
249
+ fs.mkdirSync(planningBase, { recursive: true });
250
+ }
251
+ } catch (err) {
252
+ error('Failed to create .planning directory: ' + err.message);
253
+ }
254
+
255
+ // Check if config already exists
256
+ if (fs.existsSync(configPath)) {
257
+ return { created: false, reason: 'already_exists' };
258
+ }
259
+
260
+ const config = buildNewProjectConfig({});
261
+
262
+ try {
263
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
264
+ return { created: true, path: '.planning/config.json' };
265
+ } catch (err) {
266
+ error('Failed to create config.json: ' + err.message);
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Command to ensure the config file exists (creates it if needed).
272
+ *
273
+ * Note that this exits the process (via `output()`) even in the happy path; use
274
+ * `ensureConfigFile()` directly if you need to avoid this.
275
+ */
276
+ function cmdConfigEnsureSection(cwd, raw) {
277
+ const ensureConfigFileResult = ensureConfigFile(cwd);
278
+ if (ensureConfigFileResult.created) {
279
+ output(ensureConfigFileResult, raw, 'created');
280
+ } else {
281
+ output(ensureConfigFileResult, raw, 'exists');
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Sets a value in the config file, allowing nested values via dot notation (e.g.,
287
+ * "workflow.research").
288
+ *
289
+ * Does not call `output()`, so can be used as one step in a command without triggering `exit(0)` in
290
+ * the happy path. But note that `error()` will still `exit(1)` out of the process.
291
+ */
292
+ function setConfigValue(cwd, keyPath, parsedValue) {
293
+ const configPath = path.join(planningRoot(cwd), 'config.json');
294
+
295
+ // Load existing config or start with empty object
296
+ let config = {};
297
+ try {
298
+ if (fs.existsSync(configPath)) {
299
+ config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
300
+ }
301
+ } catch (err) {
302
+ error('Failed to read config.json: ' + err.message);
303
+ }
304
+
305
+ // Set nested value using dot notation (e.g., "workflow.research")
306
+ const keys = keyPath.split('.');
307
+ let current = config;
308
+ for (let i = 0; i < keys.length - 1; i++) {
309
+ const key = keys[i];
310
+ if (current[key] === undefined || typeof current[key] !== 'object') {
311
+ current[key] = {};
312
+ }
313
+ current = current[key];
314
+ }
315
+ const previousValue = current[keys[keys.length - 1]]; // Capture previous value before overwriting
316
+ current[keys[keys.length - 1]] = parsedValue;
317
+
318
+ // Write back
319
+ try {
320
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf-8');
321
+ return { updated: true, key: keyPath, value: parsedValue, previousValue };
322
+ } catch (err) {
323
+ error('Failed to write config.json: ' + err.message);
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Command to set a value in the config file, allowing nested values via dot notation (e.g.,
329
+ * "workflow.research").
330
+ *
331
+ * Note that this exits the process (via `output()`) even in the happy path; use `setConfigValue()`
332
+ * directly if you need to avoid this.
333
+ */
334
+ function cmdConfigSet(cwd, keyPath, value, raw) {
335
+ if (!keyPath) {
336
+ error('Usage: config-set <key.path> <value>');
337
+ }
338
+
339
+ validateKnownConfigKeyPath(keyPath);
340
+
341
+ if (!isValidConfigKey(keyPath)) {
342
+ error(`Unknown config key: "${keyPath}". Valid keys: ${[...VALID_CONFIG_KEYS].sort().join(', ')}, agent_skills.<agent-type>`);
343
+ }
344
+
345
+ // Parse value (handle booleans, numbers, and JSON arrays/objects)
346
+ let parsedValue = value;
347
+ if (value === 'true') parsedValue = true;
348
+ else if (value === 'false') parsedValue = false;
349
+ else if (!isNaN(value) && value !== '') parsedValue = Number(value);
350
+ else if (typeof value === 'string' && (value.startsWith('[') || value.startsWith('{'))) {
351
+ try { parsedValue = JSON.parse(value); } catch { /* keep as string */ }
352
+ }
353
+
354
+ const setConfigValueResult = setConfigValue(cwd, keyPath, parsedValue);
355
+ output(setConfigValueResult, raw, `${keyPath}=${parsedValue}`);
356
+ }
357
+
358
+ function cmdConfigGet(cwd, keyPath, raw) {
359
+ const configPath = path.join(planningRoot(cwd), 'config.json');
360
+
361
+ if (!keyPath) {
362
+ error('Usage: config-get <key.path>');
363
+ }
364
+
365
+ let config = {};
366
+ try {
367
+ if (fs.existsSync(configPath)) {
368
+ config = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
369
+ } else {
370
+ error('No config.json found at ' + configPath);
371
+ }
372
+ } catch (err) {
373
+ if (err.message.startsWith('No config.json')) throw err;
374
+ error('Failed to read config.json: ' + err.message);
375
+ }
376
+
377
+ // Traverse dot-notation path (e.g., "workflow.auto_advance")
378
+ const keys = keyPath.split('.');
379
+ let current = config;
380
+ for (const key of keys) {
381
+ if (current === undefined || current === null || typeof current !== 'object') {
382
+ error(`Key not found: ${keyPath}`);
383
+ }
384
+ current = current[key];
385
+ }
386
+
387
+ if (current === undefined) {
388
+ error(`Key not found: ${keyPath}`);
389
+ }
390
+
391
+ output(current, raw, String(current));
392
+ }
393
+
394
+ /**
395
+ * Command to set the model profile in the config file.
396
+ *
397
+ * Note that this exits the process (via `output()`) even in the happy path.
398
+ */
399
+ function cmdConfigSetModelProfile(cwd, profile, raw) {
400
+ if (!profile) {
401
+ error(`Usage: config-set-model-profile <${VALID_PROFILES.join('|')}>`);
402
+ }
403
+
404
+ const normalizedProfile = profile.toLowerCase().trim();
405
+ if (!VALID_PROFILES.includes(normalizedProfile)) {
406
+ error(`Invalid profile '${profile}'. Valid profiles: ${VALID_PROFILES.join(', ')}`);
407
+ }
408
+
409
+ // Ensure config exists (create if needed)
410
+ ensureConfigFile(cwd);
411
+
412
+ // Set the model profile in the config
413
+ const { previousValue } = setConfigValue(cwd, 'model_profile', normalizedProfile, raw);
414
+ const previousProfile = previousValue || 'balanced';
415
+
416
+ // Build result value / message and return
417
+ const agentToModelMap = getAgentToModelMapForProfile(normalizedProfile);
418
+ const result = {
419
+ updated: true,
420
+ profile: normalizedProfile,
421
+ previousProfile,
422
+ agentToModelMap,
423
+ };
424
+ const rawValue = getCmdConfigSetModelProfileResultMessage(
425
+ normalizedProfile,
426
+ previousProfile,
427
+ agentToModelMap
428
+ );
429
+ output(result, raw, rawValue);
430
+ }
431
+
432
+ /**
433
+ * Returns the message to display for the result of the `config-set-model-profile` command when
434
+ * displaying raw output.
435
+ */
436
+ function getCmdConfigSetModelProfileResultMessage(
437
+ normalizedProfile,
438
+ previousProfile,
439
+ agentToModelMap
440
+ ) {
441
+ const agentToModelTable = formatAgentToModelMapAsTable(agentToModelMap);
442
+ const didChange = previousProfile !== normalizedProfile;
443
+ const paragraphs = didChange
444
+ ? [
445
+ `✓ Model profile set to: ${normalizedProfile} (was: ${previousProfile})`,
446
+ 'Agents will now use:',
447
+ agentToModelTable,
448
+ 'Next spawned agents will use the new profile.',
449
+ ]
450
+ : [
451
+ `✓ Model profile is already set to: ${normalizedProfile}`,
452
+ 'Agents are using:',
453
+ agentToModelTable,
454
+ ];
455
+ return paragraphs.join('\n\n');
456
+ }
457
+
458
+ module.exports = {
459
+ buildNewProjectConfig,
460
+ cmdConfigEnsureSection,
461
+ cmdConfigSet,
462
+ cmdConfigGet,
463
+ cmdConfigSetModelProfile,
464
+ cmdConfigNewProject,
465
+ setConfigValue,
466
+ };
@@ -0,0 +1,180 @@
1
+ // @gsd-context(phase:11) Convention reader utility -- discovers existing project conventions for architecture mode
2
+ // @gsd-decision Implemented as a standalone CJS module (not inline in the agent) so it can be tested independently
3
+ // @gsd-ref(ref:ARCH-03) gsd-prototyper reads existing project conventions before generating skeleton
4
+ // @gsd-constraint Zero external dependencies -- uses only Node.js built-ins (fs, path)
5
+
6
+ 'use strict';
7
+
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+
11
+ // @gsd-api readProjectConventions(projectRoot) -- returns ConventionReport object describing discovered patterns
12
+ // @gsd-pattern Convention reader returns a structured report that the agent prompt can serialize into context
13
+
14
+ /**
15
+ * @typedef {Object} ConventionReport
16
+ * @property {string} moduleType - 'esm' | 'cjs' | 'unknown'
17
+ * @property {string} namingConvention - 'kebab-case' | 'camelCase' | 'PascalCase' | 'snake_case' | 'unknown'
18
+ * @property {string} testPattern - 'colocated' | 'separate-dir' | 'unknown'
19
+ * @property {string|null} testRunner - detected test runner name or null
20
+ * @property {Object} pathAliases - e.g., { '@/*': ['src/*'] }
21
+ * @property {string|null} buildTool - detected build tool or null
22
+ * @property {string|null} linter - detected linter or null
23
+ * @property {string[]} existingDirs - list of existing directories (max depth 3)
24
+ * @property {Object} packageJson - parsed package.json or null
25
+ */
26
+
27
+ /**
28
+ * Reads existing project conventions from config files and directory structure.
29
+ * Used by gsd-prototyper in architecture mode to match generated skeleton
30
+ * to the project's established patterns.
31
+ *
32
+ * @param {string} projectRoot - absolute path to project root
33
+ * @returns {ConventionReport}
34
+ */
35
+ function readProjectConventions(projectRoot) {
36
+ // @gsd-todo(ref:AC-3) Implement full convention discovery: package.json parsing, tsconfig reading, directory pattern detection, linter config extraction
37
+ const report = {
38
+ moduleType: 'unknown',
39
+ namingConvention: 'unknown',
40
+ testPattern: 'unknown',
41
+ testRunner: null,
42
+ pathAliases: {},
43
+ buildTool: null,
44
+ linter: null,
45
+ existingDirs: [],
46
+ packageJson: null,
47
+ };
48
+
49
+ // --- package.json detection ---
50
+ // @gsd-context Reads package.json for module type, naming conventions, and dependency-based framework detection
51
+ const pkgPath = path.join(projectRoot, 'package.json');
52
+ if (fs.existsSync(pkgPath)) {
53
+ try {
54
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
55
+ report.packageJson = pkg;
56
+ report.moduleType = pkg.type === 'module' ? 'esm' : 'cjs';
57
+
58
+ // @gsd-decision Detect test runner from devDependencies keys rather than config files -- faster and covers most cases
59
+ if (pkg.devDependencies) {
60
+ if (pkg.devDependencies.vitest) report.testRunner = 'vitest';
61
+ else if (pkg.devDependencies.jest) report.testRunner = 'jest';
62
+ else if (pkg.devDependencies.mocha) report.testRunner = 'mocha';
63
+ else if (pkg.devDependencies.ava) report.testRunner = 'ava';
64
+ }
65
+
66
+ // @gsd-decision Detect build tool from devDependencies -- covers esbuild, webpack, vite, rollup
67
+ if (pkg.devDependencies) {
68
+ if (pkg.devDependencies.esbuild) report.buildTool = 'esbuild';
69
+ else if (pkg.devDependencies.vite) report.buildTool = 'vite';
70
+ else if (pkg.devDependencies.webpack) report.buildTool = 'webpack';
71
+ else if (pkg.devDependencies.rollup) report.buildTool = 'rollup';
72
+ }
73
+ } catch (_e) {
74
+ // @gsd-risk Malformed package.json silently ignored -- could produce incorrect convention report
75
+ }
76
+ }
77
+
78
+ // --- tsconfig.json / jsconfig.json detection ---
79
+ // @gsd-context Reads TypeScript/JavaScript config for path aliases and module resolution
80
+ const tsconfigPath = path.join(projectRoot, 'tsconfig.json');
81
+ const jsconfigPath = path.join(projectRoot, 'jsconfig.json');
82
+ const configPath = fs.existsSync(tsconfigPath) ? tsconfigPath : (fs.existsSync(jsconfigPath) ? jsconfigPath : null);
83
+
84
+ if (configPath) {
85
+ try {
86
+ // Strip JS-style comments (// and /* */) before parsing — handles JSONC tsconfig files
87
+ let raw = fs.readFileSync(configPath, 'utf8');
88
+ raw = raw.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
89
+ const config = JSON.parse(raw);
90
+ if (config.compilerOptions && config.compilerOptions.paths) {
91
+ report.pathAliases = config.compilerOptions.paths;
92
+ }
93
+ } catch (_e) {
94
+ // Malformed config silently ignored
95
+ }
96
+ }
97
+
98
+ // --- Directory structure detection ---
99
+ // @gsd-context Reads directory names to detect naming convention (kebab-case vs camelCase etc.)
100
+ report.existingDirs = discoverDirectories(projectRoot, 3);
101
+ report.namingConvention = detectNamingConvention(report.existingDirs);
102
+
103
+ // --- Test pattern detection ---
104
+ // @gsd-decision Check for tests/ or __tests__/ directory first, then fall back to checking for colocated .test. files
105
+ const hasTestsDir = report.existingDirs.some(d => d === 'tests' || d === '__tests__' || d.endsWith('/tests') || d.endsWith('/__tests__'));
106
+ if (hasTestsDir) {
107
+ report.testPattern = 'separate-dir';
108
+ }
109
+ // @gsd-todo Detect colocated test pattern by scanning for *.test.* files alongside source files
110
+
111
+ // --- Linter detection ---
112
+ // @gsd-context Checks for linter config files to match code style in generated skeleton
113
+ const linterFiles = ['.eslintrc', '.eslintrc.js', '.eslintrc.json', '.eslintrc.cjs', 'biome.json', 'biome.jsonc'];
114
+ for (const f of linterFiles) {
115
+ if (fs.existsSync(path.join(projectRoot, f))) {
116
+ report.linter = f.includes('biome') ? 'biome' : 'eslint';
117
+ break;
118
+ }
119
+ }
120
+
121
+ return report;
122
+ }
123
+
124
+ /**
125
+ * Recursively discovers directories up to maxDepth.
126
+ * @param {string} dir
127
+ * @param {number} maxDepth
128
+ * @param {number} [currentDepth=0]
129
+ * @returns {string[]}
130
+ */
131
+ function discoverDirectories(dir, maxDepth, currentDepth = 0) {
132
+ // @gsd-constraint Uses readdirSync (not glob) per project zero-dep constraint
133
+ if (currentDepth >= maxDepth) return [];
134
+
135
+ const results = [];
136
+ try {
137
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
138
+ for (const entry of entries) {
139
+ if (!entry.isDirectory()) continue;
140
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.planning') continue;
141
+
142
+ const fullPath = path.join(dir, entry.name);
143
+ const relativePath = path.relative(dir, fullPath);
144
+ results.push(relativePath);
145
+ const children = discoverDirectories(fullPath, maxDepth, currentDepth + 1);
146
+ results.push(...children.map(c => path.join(entry.name, c)));
147
+ }
148
+ } catch (_e) {
149
+ // Permission errors etc.
150
+ }
151
+
152
+ return results;
153
+ }
154
+
155
+ /**
156
+ * Detects naming convention from directory names.
157
+ * @param {string[]} dirs
158
+ * @returns {string}
159
+ */
160
+ function detectNamingConvention(dirs) {
161
+ // @gsd-decision Simple heuristic: check if majority of directory names match a pattern
162
+ // @gsd-risk Heuristic may misclassify projects with mixed naming -- returns 'unknown' when ambiguous
163
+ const leafNames = dirs.map(d => path.basename(d)).filter(n => n.length > 1);
164
+ if (leafNames.length === 0) return 'unknown';
165
+
166
+ const kebab = leafNames.filter(n => /^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(n)).length;
167
+ const camel = leafNames.filter(n => /^[a-z][a-zA-Z0-9]+$/.test(n) && /[A-Z]/.test(n)).length;
168
+ const pascal = leafNames.filter(n => /^[A-Z][a-zA-Z0-9]+$/.test(n)).length;
169
+ const snake = leafNames.filter(n => /^[a-z][a-z0-9]*(_[a-z0-9]+)+$/.test(n)).length;
170
+
171
+ const max = Math.max(kebab, camel, pascal, snake);
172
+ if (max === 0) return 'unknown';
173
+ if (kebab === max) return 'kebab-case';
174
+ if (camel === max) return 'camelCase';
175
+ if (pascal === max) return 'PascalCase';
176
+ if (snake === max) return 'snake_case';
177
+ return 'unknown';
178
+ }
179
+
180
+ module.exports = { readProjectConventions, discoverDirectories, detectNamingConvention };