declare-cc 0.1.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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +326 -0
  3. package/agents/gsd-codebase-mapper.md +761 -0
  4. package/agents/gsd-debugger.md +1198 -0
  5. package/agents/gsd-executor.md +451 -0
  6. package/agents/gsd-integration-checker.md +440 -0
  7. package/agents/gsd-phase-researcher.md +484 -0
  8. package/agents/gsd-plan-checker.md +625 -0
  9. package/agents/gsd-planner.md +1164 -0
  10. package/agents/gsd-project-researcher.md +618 -0
  11. package/agents/gsd-research-synthesizer.md +236 -0
  12. package/agents/gsd-roadmapper.md +639 -0
  13. package/agents/gsd-verifier.md +555 -0
  14. package/bin/install.js +1815 -0
  15. package/commands/declare/actions.md +78 -0
  16. package/commands/declare/future.md +52 -0
  17. package/commands/declare/milestones.md +81 -0
  18. package/commands/declare/status.md +62 -0
  19. package/commands/gsd/add-phase.md +39 -0
  20. package/commands/gsd/add-todo.md +42 -0
  21. package/commands/gsd/audit-milestone.md +42 -0
  22. package/commands/gsd/check-todos.md +41 -0
  23. package/commands/gsd/cleanup.md +18 -0
  24. package/commands/gsd/complete-milestone.md +136 -0
  25. package/commands/gsd/debug.md +162 -0
  26. package/commands/gsd/discuss-phase.md +87 -0
  27. package/commands/gsd/execute-phase.md +42 -0
  28. package/commands/gsd/health.md +22 -0
  29. package/commands/gsd/help.md +22 -0
  30. package/commands/gsd/insert-phase.md +33 -0
  31. package/commands/gsd/join-discord.md +18 -0
  32. package/commands/gsd/list-phase-assumptions.md +50 -0
  33. package/commands/gsd/map-codebase.md +71 -0
  34. package/commands/gsd/new-milestone.md +51 -0
  35. package/commands/gsd/new-project.md +42 -0
  36. package/commands/gsd/new-project.md.bak +1041 -0
  37. package/commands/gsd/pause-work.md +35 -0
  38. package/commands/gsd/plan-milestone-gaps.md +40 -0
  39. package/commands/gsd/plan-phase.md +44 -0
  40. package/commands/gsd/progress.md +24 -0
  41. package/commands/gsd/quick.md +40 -0
  42. package/commands/gsd/reapply-patches.md +110 -0
  43. package/commands/gsd/remove-phase.md +32 -0
  44. package/commands/gsd/research-phase.md +187 -0
  45. package/commands/gsd/resume-work.md +40 -0
  46. package/commands/gsd/set-profile.md +34 -0
  47. package/commands/gsd/settings.md +36 -0
  48. package/commands/gsd/update.md +37 -0
  49. package/commands/gsd/verify-work.md +39 -0
  50. package/dist/declare-tools.cjs +2962 -0
  51. package/package.json +45 -0
  52. package/scripts/build-hooks.js +42 -0
package/bin/install.js ADDED
@@ -0,0 +1,1815 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const os = require('os');
6
+ const readline = require('readline');
7
+ const crypto = require('crypto');
8
+
9
+ // Colors
10
+ const cyan = '\x1b[36m';
11
+ const green = '\x1b[32m';
12
+ const yellow = '\x1b[33m';
13
+ const dim = '\x1b[2m';
14
+ const reset = '\x1b[0m';
15
+
16
+ // Get version from package.json
17
+ const pkg = require('../package.json');
18
+
19
+ // Parse args
20
+ const args = process.argv.slice(2);
21
+ const hasGlobal = args.includes('--global') || args.includes('-g');
22
+ const hasLocal = args.includes('--local') || args.includes('-l');
23
+ const hasOpencode = args.includes('--opencode');
24
+ const hasClaude = args.includes('--claude');
25
+ const hasGemini = args.includes('--gemini');
26
+ const hasBoth = args.includes('--both'); // Legacy flag, keeps working
27
+ const hasAll = args.includes('--all');
28
+ const hasUninstall = args.includes('--uninstall') || args.includes('-u');
29
+
30
+ // Runtime selection - can be set by flags or interactive prompt
31
+ let selectedRuntimes = [];
32
+ if (hasAll) {
33
+ selectedRuntimes = ['claude', 'opencode', 'gemini'];
34
+ } else if (hasBoth) {
35
+ selectedRuntimes = ['claude', 'opencode'];
36
+ } else {
37
+ if (hasOpencode) selectedRuntimes.push('opencode');
38
+ if (hasClaude) selectedRuntimes.push('claude');
39
+ if (hasGemini) selectedRuntimes.push('gemini');
40
+ }
41
+
42
+ // Helper to get directory name for a runtime (used for local/project installs)
43
+ function getDirName(runtime) {
44
+ if (runtime === 'opencode') return '.opencode';
45
+ if (runtime === 'gemini') return '.gemini';
46
+ return '.claude';
47
+ }
48
+
49
+ /**
50
+ * Get the config directory path relative to home directory for a runtime
51
+ * Used for templating hooks that use path.join(homeDir, '<configDir>', ...)
52
+ * @param {string} runtime - 'claude', 'opencode', or 'gemini'
53
+ * @param {boolean} isGlobal - Whether this is a global install
54
+ */
55
+ function getConfigDirFromHome(runtime, isGlobal) {
56
+ if (!isGlobal) {
57
+ // Local installs use the same dir name pattern
58
+ return `'${getDirName(runtime)}'`;
59
+ }
60
+ // Global installs - OpenCode uses XDG path structure
61
+ if (runtime === 'opencode') {
62
+ // OpenCode: ~/.config/opencode -> '.config', 'opencode'
63
+ // Return as comma-separated for path.join() replacement
64
+ return "'.config', 'opencode'";
65
+ }
66
+ if (runtime === 'gemini') return "'.gemini'";
67
+ return "'.claude'";
68
+ }
69
+
70
+ /**
71
+ * Get the global config directory for OpenCode
72
+ * OpenCode follows XDG Base Directory spec and uses ~/.config/opencode/
73
+ * Priority: OPENCODE_CONFIG_DIR > dirname(OPENCODE_CONFIG) > XDG_CONFIG_HOME/opencode > ~/.config/opencode
74
+ */
75
+ function getOpencodeGlobalDir() {
76
+ // 1. Explicit OPENCODE_CONFIG_DIR env var
77
+ if (process.env.OPENCODE_CONFIG_DIR) {
78
+ return expandTilde(process.env.OPENCODE_CONFIG_DIR);
79
+ }
80
+
81
+ // 2. OPENCODE_CONFIG env var (use its directory)
82
+ if (process.env.OPENCODE_CONFIG) {
83
+ return path.dirname(expandTilde(process.env.OPENCODE_CONFIG));
84
+ }
85
+
86
+ // 3. XDG_CONFIG_HOME/opencode
87
+ if (process.env.XDG_CONFIG_HOME) {
88
+ return path.join(expandTilde(process.env.XDG_CONFIG_HOME), 'opencode');
89
+ }
90
+
91
+ // 4. Default: ~/.config/opencode (XDG default)
92
+ return path.join(os.homedir(), '.config', 'opencode');
93
+ }
94
+
95
+ /**
96
+ * Get the global config directory for a runtime
97
+ * @param {string} runtime - 'claude', 'opencode', or 'gemini'
98
+ * @param {string|null} explicitDir - Explicit directory from --config-dir flag
99
+ */
100
+ function getGlobalDir(runtime, explicitDir = null) {
101
+ if (runtime === 'opencode') {
102
+ // For OpenCode, --config-dir overrides env vars
103
+ if (explicitDir) {
104
+ return expandTilde(explicitDir);
105
+ }
106
+ return getOpencodeGlobalDir();
107
+ }
108
+
109
+ if (runtime === 'gemini') {
110
+ // Gemini: --config-dir > GEMINI_CONFIG_DIR > ~/.gemini
111
+ if (explicitDir) {
112
+ return expandTilde(explicitDir);
113
+ }
114
+ if (process.env.GEMINI_CONFIG_DIR) {
115
+ return expandTilde(process.env.GEMINI_CONFIG_DIR);
116
+ }
117
+ return path.join(os.homedir(), '.gemini');
118
+ }
119
+
120
+ // Claude Code: --config-dir > CLAUDE_CONFIG_DIR > ~/.claude
121
+ if (explicitDir) {
122
+ return expandTilde(explicitDir);
123
+ }
124
+ if (process.env.CLAUDE_CONFIG_DIR) {
125
+ return expandTilde(process.env.CLAUDE_CONFIG_DIR);
126
+ }
127
+ return path.join(os.homedir(), '.claude');
128
+ }
129
+
130
+ const banner = '\n' +
131
+ cyan + ' ██████╗ ███████╗██████╗\n' +
132
+ ' ██╔════╝ ██╔════╝██╔══██╗\n' +
133
+ ' ██║ ███╗███████╗██║ ██║\n' +
134
+ ' ██║ ██║╚════██║██║ ██║\n' +
135
+ ' ╚██████╔╝███████║██████╔╝\n' +
136
+ ' ╚═════╝ ╚══════╝╚═════╝' + reset + '\n' +
137
+ '\n' +
138
+ ' Get Shit Done ' + dim + 'v' + pkg.version + reset + '\n' +
139
+ ' A meta-prompting, context engineering and spec-driven\n' +
140
+ ' development system for Claude Code, OpenCode, and Gemini by TÂCHES.\n';
141
+
142
+ // Parse --config-dir argument
143
+ function parseConfigDirArg() {
144
+ const configDirIndex = args.findIndex(arg => arg === '--config-dir' || arg === '-c');
145
+ if (configDirIndex !== -1) {
146
+ const nextArg = args[configDirIndex + 1];
147
+ // Error if --config-dir is provided without a value or next arg is another flag
148
+ if (!nextArg || nextArg.startsWith('-')) {
149
+ console.error(` ${yellow}--config-dir requires a path argument${reset}`);
150
+ process.exit(1);
151
+ }
152
+ return nextArg;
153
+ }
154
+ // Also handle --config-dir=value format
155
+ const configDirArg = args.find(arg => arg.startsWith('--config-dir=') || arg.startsWith('-c='));
156
+ if (configDirArg) {
157
+ const value = configDirArg.split('=')[1];
158
+ if (!value) {
159
+ console.error(` ${yellow}--config-dir requires a non-empty path${reset}`);
160
+ process.exit(1);
161
+ }
162
+ return value;
163
+ }
164
+ return null;
165
+ }
166
+ const explicitConfigDir = parseConfigDirArg();
167
+ const hasHelp = args.includes('--help') || args.includes('-h');
168
+ const forceStatusline = args.includes('--force-statusline');
169
+
170
+ console.log(banner);
171
+
172
+ // Show help if requested
173
+ if (hasHelp) {
174
+ console.log(` ${yellow}Usage:${reset} npx get-shit-done-cc [options]\n\n ${yellow}Options:${reset}\n ${cyan}-g, --global${reset} Install globally (to config directory)\n ${cyan}-l, --local${reset} Install locally (to current directory)\n ${cyan}--claude${reset} Install for Claude Code only\n ${cyan}--opencode${reset} Install for OpenCode only\n ${cyan}--gemini${reset} Install for Gemini only\n ${cyan}--all${reset} Install for all runtimes\n ${cyan}-u, --uninstall${reset} Uninstall GSD (remove all GSD files)\n ${cyan}-c, --config-dir <path>${reset} Specify custom config directory\n ${cyan}-h, --help${reset} Show this help message\n ${cyan}--force-statusline${reset} Replace existing statusline config\n\n ${yellow}Examples:${reset}\n ${dim}# Interactive install (prompts for runtime and location)${reset}\n npx get-shit-done-cc\n\n ${dim}# Install for Claude Code globally${reset}\n npx get-shit-done-cc --claude --global\n\n ${dim}# Install for Gemini globally${reset}\n npx get-shit-done-cc --gemini --global\n\n ${dim}# Install for all runtimes globally${reset}\n npx get-shit-done-cc --all --global\n\n ${dim}# Install to custom config directory${reset}\n npx get-shit-done-cc --claude --global --config-dir ~/.claude-bc\n\n ${dim}# Install to current project only${reset}\n npx get-shit-done-cc --claude --local\n\n ${dim}# Uninstall GSD from Claude Code globally${reset}\n npx get-shit-done-cc --claude --global --uninstall\n\n ${yellow}Notes:${reset}\n The --config-dir option is useful when you have multiple configurations.\n It takes priority over CLAUDE_CONFIG_DIR / GEMINI_CONFIG_DIR environment variables.\n`);
175
+ process.exit(0);
176
+ }
177
+
178
+ /**
179
+ * Expand ~ to home directory (shell doesn't expand in env vars passed to node)
180
+ */
181
+ function expandTilde(filePath) {
182
+ if (filePath && filePath.startsWith('~/')) {
183
+ return path.join(os.homedir(), filePath.slice(2));
184
+ }
185
+ return filePath;
186
+ }
187
+
188
+ /**
189
+ * Build a hook command path using forward slashes for cross-platform compatibility.
190
+ * On Windows, $HOME is not expanded by cmd.exe/PowerShell, so we use the actual path.
191
+ */
192
+ function buildHookCommand(configDir, hookName) {
193
+ // Use forward slashes for Node.js compatibility on all platforms
194
+ const hooksPath = configDir.replace(/\\/g, '/') + '/hooks/' + hookName;
195
+ return `node "${hooksPath}"`;
196
+ }
197
+
198
+ /**
199
+ * Read and parse settings.json, returning empty object if it doesn't exist
200
+ */
201
+ function readSettings(settingsPath) {
202
+ if (fs.existsSync(settingsPath)) {
203
+ try {
204
+ return JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
205
+ } catch (e) {
206
+ return {};
207
+ }
208
+ }
209
+ return {};
210
+ }
211
+
212
+ /**
213
+ * Write settings.json with proper formatting
214
+ */
215
+ function writeSettings(settingsPath, settings) {
216
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
217
+ }
218
+
219
+ // Cache for attribution settings (populated once per runtime during install)
220
+ const attributionCache = new Map();
221
+
222
+ /**
223
+ * Get commit attribution setting for a runtime
224
+ * @param {string} runtime - 'claude', 'opencode', or 'gemini'
225
+ * @returns {null|undefined|string} null = remove, undefined = keep default, string = custom
226
+ */
227
+ function getCommitAttribution(runtime) {
228
+ // Return cached value if available
229
+ if (attributionCache.has(runtime)) {
230
+ return attributionCache.get(runtime);
231
+ }
232
+
233
+ let result;
234
+
235
+ if (runtime === 'opencode') {
236
+ const config = readSettings(path.join(getGlobalDir('opencode', null), 'opencode.json'));
237
+ result = config.disable_ai_attribution === true ? null : undefined;
238
+ } else if (runtime === 'gemini') {
239
+ // Gemini: check gemini settings.json for attribution config
240
+ const settings = readSettings(path.join(getGlobalDir('gemini', explicitConfigDir), 'settings.json'));
241
+ if (!settings.attribution || settings.attribution.commit === undefined) {
242
+ result = undefined;
243
+ } else if (settings.attribution.commit === '') {
244
+ result = null;
245
+ } else {
246
+ result = settings.attribution.commit;
247
+ }
248
+ } else {
249
+ // Claude Code
250
+ const settings = readSettings(path.join(getGlobalDir('claude', explicitConfigDir), 'settings.json'));
251
+ if (!settings.attribution || settings.attribution.commit === undefined) {
252
+ result = undefined;
253
+ } else if (settings.attribution.commit === '') {
254
+ result = null;
255
+ } else {
256
+ result = settings.attribution.commit;
257
+ }
258
+ }
259
+
260
+ // Cache and return
261
+ attributionCache.set(runtime, result);
262
+ return result;
263
+ }
264
+
265
+ /**
266
+ * Process Co-Authored-By lines based on attribution setting
267
+ * @param {string} content - File content to process
268
+ * @param {null|undefined|string} attribution - null=remove, undefined=keep, string=replace
269
+ * @returns {string} Processed content
270
+ */
271
+ function processAttribution(content, attribution) {
272
+ if (attribution === null) {
273
+ // Remove Co-Authored-By lines and the preceding blank line
274
+ return content.replace(/(\r?\n){2}Co-Authored-By:.*$/gim, '');
275
+ }
276
+ if (attribution === undefined) {
277
+ return content;
278
+ }
279
+ // Replace with custom attribution (escape $ to prevent backreference injection)
280
+ const safeAttribution = attribution.replace(/\$/g, '$$$$');
281
+ return content.replace(/Co-Authored-By:.*$/gim, `Co-Authored-By: ${safeAttribution}`);
282
+ }
283
+
284
+ /**
285
+ * Convert Claude Code frontmatter to opencode format
286
+ * - Converts 'allowed-tools:' array to 'permission:' object
287
+ * @param {string} content - Markdown file content with YAML frontmatter
288
+ * @returns {string} - Content with converted frontmatter
289
+ */
290
+ // Color name to hex mapping for opencode compatibility
291
+ const colorNameToHex = {
292
+ cyan: '#00FFFF',
293
+ red: '#FF0000',
294
+ green: '#00FF00',
295
+ blue: '#0000FF',
296
+ yellow: '#FFFF00',
297
+ magenta: '#FF00FF',
298
+ orange: '#FFA500',
299
+ purple: '#800080',
300
+ pink: '#FFC0CB',
301
+ white: '#FFFFFF',
302
+ black: '#000000',
303
+ gray: '#808080',
304
+ grey: '#808080',
305
+ };
306
+
307
+ // Tool name mapping from Claude Code to OpenCode
308
+ // OpenCode uses lowercase tool names; special mappings for renamed tools
309
+ const claudeToOpencodeTools = {
310
+ AskUserQuestion: 'question',
311
+ SlashCommand: 'skill',
312
+ TodoWrite: 'todowrite',
313
+ WebFetch: 'webfetch',
314
+ WebSearch: 'websearch', // Plugin/MCP - keep for compatibility
315
+ };
316
+
317
+ // Tool name mapping from Claude Code to Gemini CLI
318
+ // Gemini CLI uses snake_case built-in tool names
319
+ const claudeToGeminiTools = {
320
+ Read: 'read_file',
321
+ Write: 'write_file',
322
+ Edit: 'replace',
323
+ Bash: 'run_shell_command',
324
+ Glob: 'glob',
325
+ Grep: 'search_file_content',
326
+ WebSearch: 'google_web_search',
327
+ WebFetch: 'web_fetch',
328
+ TodoWrite: 'write_todos',
329
+ AskUserQuestion: 'ask_user',
330
+ };
331
+
332
+ /**
333
+ * Convert a Claude Code tool name to OpenCode format
334
+ * - Applies special mappings (AskUserQuestion -> question, etc.)
335
+ * - Converts to lowercase (except MCP tools which keep their format)
336
+ */
337
+ function convertToolName(claudeTool) {
338
+ // Check for special mapping first
339
+ if (claudeToOpencodeTools[claudeTool]) {
340
+ return claudeToOpencodeTools[claudeTool];
341
+ }
342
+ // MCP tools (mcp__*) keep their format
343
+ if (claudeTool.startsWith('mcp__')) {
344
+ return claudeTool;
345
+ }
346
+ // Default: convert to lowercase
347
+ return claudeTool.toLowerCase();
348
+ }
349
+
350
+ /**
351
+ * Convert a Claude Code tool name to Gemini CLI format
352
+ * - Applies Claude→Gemini mapping (Read→read_file, Bash→run_shell_command, etc.)
353
+ * - Filters out MCP tools (mcp__*) — they are auto-discovered at runtime in Gemini
354
+ * - Filters out Task — agents are auto-registered as tools in Gemini
355
+ * @returns {string|null} Gemini tool name, or null if tool should be excluded
356
+ */
357
+ function convertGeminiToolName(claudeTool) {
358
+ // MCP tools: exclude — auto-discovered from mcpServers config at runtime
359
+ if (claudeTool.startsWith('mcp__')) {
360
+ return null;
361
+ }
362
+ // Task: exclude — agents are auto-registered as callable tools
363
+ if (claudeTool === 'Task') {
364
+ return null;
365
+ }
366
+ // Check for explicit mapping
367
+ if (claudeToGeminiTools[claudeTool]) {
368
+ return claudeToGeminiTools[claudeTool];
369
+ }
370
+ // Default: lowercase
371
+ return claudeTool.toLowerCase();
372
+ }
373
+
374
+ /**
375
+ * Strip HTML <sub> tags for Gemini CLI output
376
+ * Terminals don't support subscript — Gemini renders these as raw HTML.
377
+ * Converts <sub>text</sub> to italic *(text)* for readable terminal output.
378
+ */
379
+ function stripSubTags(content) {
380
+ return content.replace(/<sub>(.*?)<\/sub>/g, '*($1)*');
381
+ }
382
+
383
+ /**
384
+ * Convert Claude Code agent frontmatter to Gemini CLI format
385
+ * Gemini agents use .md files with YAML frontmatter, same as Claude,
386
+ * but with different field names and formats:
387
+ * - tools: must be a YAML array (not comma-separated string)
388
+ * - tool names: must use Gemini built-in names (read_file, not Read)
389
+ * - color: must be removed (causes validation error)
390
+ * - mcp__* tools: must be excluded (auto-discovered at runtime)
391
+ */
392
+ function convertClaudeToGeminiAgent(content) {
393
+ if (!content.startsWith('---')) return content;
394
+
395
+ const endIndex = content.indexOf('---', 3);
396
+ if (endIndex === -1) return content;
397
+
398
+ const frontmatter = content.substring(3, endIndex).trim();
399
+ const body = content.substring(endIndex + 3);
400
+
401
+ const lines = frontmatter.split('\n');
402
+ const newLines = [];
403
+ let inAllowedTools = false;
404
+ const tools = [];
405
+
406
+ for (const line of lines) {
407
+ const trimmed = line.trim();
408
+
409
+ // Convert allowed-tools YAML array to tools list
410
+ if (trimmed.startsWith('allowed-tools:')) {
411
+ inAllowedTools = true;
412
+ continue;
413
+ }
414
+
415
+ // Handle inline tools: field (comma-separated string)
416
+ if (trimmed.startsWith('tools:')) {
417
+ const toolsValue = trimmed.substring(6).trim();
418
+ if (toolsValue) {
419
+ const parsed = toolsValue.split(',').map(t => t.trim()).filter(t => t);
420
+ for (const t of parsed) {
421
+ const mapped = convertGeminiToolName(t);
422
+ if (mapped) tools.push(mapped);
423
+ }
424
+ } else {
425
+ // tools: with no value means YAML array follows
426
+ inAllowedTools = true;
427
+ }
428
+ continue;
429
+ }
430
+
431
+ // Strip color field (not supported by Gemini CLI, causes validation error)
432
+ if (trimmed.startsWith('color:')) continue;
433
+
434
+ // Collect allowed-tools/tools array items
435
+ if (inAllowedTools) {
436
+ if (trimmed.startsWith('- ')) {
437
+ const mapped = convertGeminiToolName(trimmed.substring(2).trim());
438
+ if (mapped) tools.push(mapped);
439
+ continue;
440
+ } else if (trimmed && !trimmed.startsWith('-')) {
441
+ inAllowedTools = false;
442
+ }
443
+ }
444
+
445
+ if (!inAllowedTools) {
446
+ newLines.push(line);
447
+ }
448
+ }
449
+
450
+ // Add tools as YAML array (Gemini requires array format)
451
+ if (tools.length > 0) {
452
+ newLines.push('tools:');
453
+ for (const tool of tools) {
454
+ newLines.push(` - ${tool}`);
455
+ }
456
+ }
457
+
458
+ const newFrontmatter = newLines.join('\n').trim();
459
+
460
+ // Escape ${VAR} patterns in agent body for Gemini CLI compatibility.
461
+ // Gemini's templateString() treats all ${word} patterns as template variables
462
+ // and throws "Template validation failed: Missing required input parameters"
463
+ // when they can't be resolved. GSD agents use ${PHASE}, ${PLAN}, etc. as
464
+ // shell variables in bash code blocks — convert to $VAR (no braces) which
465
+ // is equivalent bash and invisible to Gemini's /\$\{(\w+)\}/g regex.
466
+ const escapedBody = body.replace(/\$\{(\w+)\}/g, '$$$1');
467
+
468
+ return `---\n${newFrontmatter}\n---${stripSubTags(escapedBody)}`;
469
+ }
470
+
471
+ function convertClaudeToOpencodeFrontmatter(content) {
472
+ // Replace tool name references in content (applies to all files)
473
+ let convertedContent = content;
474
+ convertedContent = convertedContent.replace(/\bAskUserQuestion\b/g, 'question');
475
+ convertedContent = convertedContent.replace(/\bSlashCommand\b/g, 'skill');
476
+ convertedContent = convertedContent.replace(/\bTodoWrite\b/g, 'todowrite');
477
+ // Replace /gsd:command with /gsd-command for opencode (flat command structure)
478
+ convertedContent = convertedContent.replace(/\/gsd:/g, '/gsd-');
479
+ // Replace ~/.claude with ~/.config/opencode (OpenCode's correct config location)
480
+ convertedContent = convertedContent.replace(/~\/\.claude\b/g, '~/.config/opencode');
481
+ // Replace general-purpose subagent type with OpenCode's equivalent "general"
482
+ convertedContent = convertedContent.replace(/subagent_type="general-purpose"/g, 'subagent_type="general"');
483
+
484
+ // Check if content has frontmatter
485
+ if (!convertedContent.startsWith('---')) {
486
+ return convertedContent;
487
+ }
488
+
489
+ // Find the end of frontmatter
490
+ const endIndex = convertedContent.indexOf('---', 3);
491
+ if (endIndex === -1) {
492
+ return convertedContent;
493
+ }
494
+
495
+ const frontmatter = convertedContent.substring(3, endIndex).trim();
496
+ const body = convertedContent.substring(endIndex + 3);
497
+
498
+ // Parse frontmatter line by line (simple YAML parsing)
499
+ const lines = frontmatter.split('\n');
500
+ const newLines = [];
501
+ let inAllowedTools = false;
502
+ const allowedTools = [];
503
+
504
+ for (const line of lines) {
505
+ const trimmed = line.trim();
506
+
507
+ // Detect start of allowed-tools array
508
+ if (trimmed.startsWith('allowed-tools:')) {
509
+ inAllowedTools = true;
510
+ continue;
511
+ }
512
+
513
+ // Detect inline tools: field (comma-separated string)
514
+ if (trimmed.startsWith('tools:')) {
515
+ const toolsValue = trimmed.substring(6).trim();
516
+ if (toolsValue) {
517
+ // Parse comma-separated tools
518
+ const tools = toolsValue.split(',').map(t => t.trim()).filter(t => t);
519
+ allowedTools.push(...tools);
520
+ }
521
+ continue;
522
+ }
523
+
524
+ // Remove name: field - opencode uses filename for command name
525
+ if (trimmed.startsWith('name:')) {
526
+ continue;
527
+ }
528
+
529
+ // Convert color names to hex for opencode
530
+ if (trimmed.startsWith('color:')) {
531
+ const colorValue = trimmed.substring(6).trim().toLowerCase();
532
+ const hexColor = colorNameToHex[colorValue];
533
+ if (hexColor) {
534
+ newLines.push(`color: "${hexColor}"`);
535
+ } else if (colorValue.startsWith('#')) {
536
+ // Validate hex color format (#RGB or #RRGGBB)
537
+ if (/^#[0-9a-f]{3}$|^#[0-9a-f]{6}$/i.test(colorValue)) {
538
+ // Already hex and valid, keep as is
539
+ newLines.push(line);
540
+ }
541
+ // Skip invalid hex colors
542
+ }
543
+ // Skip unknown color names
544
+ continue;
545
+ }
546
+
547
+ // Collect allowed-tools items
548
+ if (inAllowedTools) {
549
+ if (trimmed.startsWith('- ')) {
550
+ allowedTools.push(trimmed.substring(2).trim());
551
+ continue;
552
+ } else if (trimmed && !trimmed.startsWith('-')) {
553
+ // End of array, new field started
554
+ inAllowedTools = false;
555
+ }
556
+ }
557
+
558
+ // Keep other fields (including name: which opencode ignores)
559
+ if (!inAllowedTools) {
560
+ newLines.push(line);
561
+ }
562
+ }
563
+
564
+ // Add tools object if we had allowed-tools or tools
565
+ if (allowedTools.length > 0) {
566
+ newLines.push('tools:');
567
+ for (const tool of allowedTools) {
568
+ newLines.push(` ${convertToolName(tool)}: true`);
569
+ }
570
+ }
571
+
572
+ // Rebuild frontmatter (body already has tool names converted)
573
+ const newFrontmatter = newLines.join('\n').trim();
574
+ return `---\n${newFrontmatter}\n---${body}`;
575
+ }
576
+
577
+ /**
578
+ * Convert Claude Code markdown command to Gemini TOML format
579
+ * @param {string} content - Markdown file content with YAML frontmatter
580
+ * @returns {string} - TOML content
581
+ */
582
+ function convertClaudeToGeminiToml(content) {
583
+ // Check if content has frontmatter
584
+ if (!content.startsWith('---')) {
585
+ return `prompt = ${JSON.stringify(content)}\n`;
586
+ }
587
+
588
+ const endIndex = content.indexOf('---', 3);
589
+ if (endIndex === -1) {
590
+ return `prompt = ${JSON.stringify(content)}\n`;
591
+ }
592
+
593
+ const frontmatter = content.substring(3, endIndex).trim();
594
+ const body = content.substring(endIndex + 3).trim();
595
+
596
+ // Extract description from frontmatter
597
+ let description = '';
598
+ const lines = frontmatter.split('\n');
599
+ for (const line of lines) {
600
+ const trimmed = line.trim();
601
+ if (trimmed.startsWith('description:')) {
602
+ description = trimmed.substring(12).trim();
603
+ break;
604
+ }
605
+ }
606
+
607
+ // Construct TOML
608
+ let toml = '';
609
+ if (description) {
610
+ toml += `description = ${JSON.stringify(description)}\n`;
611
+ }
612
+
613
+ toml += `prompt = ${JSON.stringify(body)}\n`;
614
+
615
+ return toml;
616
+ }
617
+
618
+ /**
619
+ * Copy commands to a flat structure for OpenCode
620
+ * OpenCode expects: command/gsd-help.md (invoked as /gsd-help)
621
+ * Source structure: commands/gsd/help.md
622
+ *
623
+ * @param {string} srcDir - Source directory (e.g., commands/gsd/)
624
+ * @param {string} destDir - Destination directory (e.g., command/)
625
+ * @param {string} prefix - Prefix for filenames (e.g., 'gsd')
626
+ * @param {string} pathPrefix - Path prefix for file references
627
+ * @param {string} runtime - Target runtime ('claude' or 'opencode')
628
+ */
629
+ function copyFlattenedCommands(srcDir, destDir, prefix, pathPrefix, runtime) {
630
+ if (!fs.existsSync(srcDir)) {
631
+ return;
632
+ }
633
+
634
+ // Remove old gsd-*.md files before copying new ones
635
+ if (fs.existsSync(destDir)) {
636
+ for (const file of fs.readdirSync(destDir)) {
637
+ if (file.startsWith(`${prefix}-`) && file.endsWith('.md')) {
638
+ fs.unlinkSync(path.join(destDir, file));
639
+ }
640
+ }
641
+ } else {
642
+ fs.mkdirSync(destDir, { recursive: true });
643
+ }
644
+
645
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
646
+
647
+ for (const entry of entries) {
648
+ const srcPath = path.join(srcDir, entry.name);
649
+
650
+ if (entry.isDirectory()) {
651
+ // Recurse into subdirectories, adding to prefix
652
+ // e.g., commands/gsd/debug/start.md -> command/gsd-debug-start.md
653
+ copyFlattenedCommands(srcPath, destDir, `${prefix}-${entry.name}`, pathPrefix, runtime);
654
+ } else if (entry.name.endsWith('.md')) {
655
+ // Flatten: help.md -> gsd-help.md
656
+ const baseName = entry.name.replace('.md', '');
657
+ const destName = `${prefix}-${baseName}.md`;
658
+ const destPath = path.join(destDir, destName);
659
+
660
+ let content = fs.readFileSync(srcPath, 'utf8');
661
+ const globalClaudeRegex = /~\/\.claude\//g;
662
+ const localClaudeRegex = /\.\/\.claude\//g;
663
+ const opencodeDirRegex = /~\/\.opencode\//g;
664
+ content = content.replace(globalClaudeRegex, pathPrefix);
665
+ content = content.replace(localClaudeRegex, `./${getDirName(runtime)}/`);
666
+ content = content.replace(opencodeDirRegex, pathPrefix);
667
+ content = processAttribution(content, getCommitAttribution(runtime));
668
+ content = convertClaudeToOpencodeFrontmatter(content);
669
+
670
+ fs.writeFileSync(destPath, content);
671
+ }
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Recursively copy directory, replacing paths in .md files
677
+ * Deletes existing destDir first to remove orphaned files from previous versions
678
+ * @param {string} srcDir - Source directory
679
+ * @param {string} destDir - Destination directory
680
+ * @param {string} pathPrefix - Path prefix for file references
681
+ * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini')
682
+ */
683
+ function copyWithPathReplacement(srcDir, destDir, pathPrefix, runtime) {
684
+ const isOpencode = runtime === 'opencode';
685
+ const dirName = getDirName(runtime);
686
+
687
+ // Clean install: remove existing destination to prevent orphaned files
688
+ if (fs.existsSync(destDir)) {
689
+ fs.rmSync(destDir, { recursive: true });
690
+ }
691
+ fs.mkdirSync(destDir, { recursive: true });
692
+
693
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
694
+
695
+ for (const entry of entries) {
696
+ const srcPath = path.join(srcDir, entry.name);
697
+ const destPath = path.join(destDir, entry.name);
698
+
699
+ if (entry.isDirectory()) {
700
+ copyWithPathReplacement(srcPath, destPath, pathPrefix, runtime);
701
+ } else if (entry.name.endsWith('.md')) {
702
+ // Replace ~/.claude/ and ./.claude/ with runtime-appropriate paths
703
+ let content = fs.readFileSync(srcPath, 'utf8');
704
+ const globalClaudeRegex = /~\/\.claude\//g;
705
+ const localClaudeRegex = /\.\/\.claude\//g;
706
+ content = content.replace(globalClaudeRegex, pathPrefix);
707
+ content = content.replace(localClaudeRegex, `./${dirName}/`);
708
+ content = processAttribution(content, getCommitAttribution(runtime));
709
+
710
+ // Convert frontmatter for opencode compatibility
711
+ if (isOpencode) {
712
+ content = convertClaudeToOpencodeFrontmatter(content);
713
+ fs.writeFileSync(destPath, content);
714
+ } else if (runtime === 'gemini') {
715
+ // Convert to TOML for Gemini (strip <sub> tags — terminals can't render subscript)
716
+ content = stripSubTags(content);
717
+ const tomlContent = convertClaudeToGeminiToml(content);
718
+ // Replace extension with .toml
719
+ const tomlPath = destPath.replace(/\.md$/, '.toml');
720
+ fs.writeFileSync(tomlPath, tomlContent);
721
+ } else {
722
+ fs.writeFileSync(destPath, content);
723
+ }
724
+ } else {
725
+ fs.copyFileSync(srcPath, destPath);
726
+ }
727
+ }
728
+ }
729
+
730
+ /**
731
+ * Clean up orphaned files from previous GSD versions
732
+ */
733
+ function cleanupOrphanedFiles(configDir) {
734
+ const orphanedFiles = [
735
+ 'hooks/gsd-notify.sh', // Removed in v1.6.x
736
+ 'hooks/statusline.js', // Renamed to gsd-statusline.js in v1.9.0
737
+ ];
738
+
739
+ for (const relPath of orphanedFiles) {
740
+ const fullPath = path.join(configDir, relPath);
741
+ if (fs.existsSync(fullPath)) {
742
+ fs.unlinkSync(fullPath);
743
+ console.log(` ${green}✓${reset} Removed orphaned ${relPath}`);
744
+ }
745
+ }
746
+ }
747
+
748
+ /**
749
+ * Clean up orphaned hook registrations from settings.json
750
+ */
751
+ function cleanupOrphanedHooks(settings) {
752
+ const orphanedHookPatterns = [
753
+ 'gsd-notify.sh', // Removed in v1.6.x
754
+ 'hooks/statusline.js', // Renamed to gsd-statusline.js in v1.9.0
755
+ 'gsd-intel-index.js', // Removed in v1.9.2
756
+ 'gsd-intel-session.js', // Removed in v1.9.2
757
+ 'gsd-intel-prune.js', // Removed in v1.9.2
758
+ ];
759
+
760
+ let cleanedHooks = false;
761
+
762
+ // Check all hook event types (Stop, SessionStart, etc.)
763
+ if (settings.hooks) {
764
+ for (const eventType of Object.keys(settings.hooks)) {
765
+ const hookEntries = settings.hooks[eventType];
766
+ if (Array.isArray(hookEntries)) {
767
+ // Filter out entries that contain orphaned hooks
768
+ const filtered = hookEntries.filter(entry => {
769
+ if (entry.hooks && Array.isArray(entry.hooks)) {
770
+ // Check if any hook in this entry matches orphaned patterns
771
+ const hasOrphaned = entry.hooks.some(h =>
772
+ h.command && orphanedHookPatterns.some(pattern => h.command.includes(pattern))
773
+ );
774
+ if (hasOrphaned) {
775
+ cleanedHooks = true;
776
+ return false; // Remove this entry
777
+ }
778
+ }
779
+ return true; // Keep this entry
780
+ });
781
+ settings.hooks[eventType] = filtered;
782
+ }
783
+ }
784
+ }
785
+
786
+ if (cleanedHooks) {
787
+ console.log(` ${green}✓${reset} Removed orphaned hook registrations`);
788
+ }
789
+
790
+ // Fix #330: Update statusLine if it points to old statusline.js path
791
+ if (settings.statusLine && settings.statusLine.command &&
792
+ settings.statusLine.command.includes('statusline.js') &&
793
+ !settings.statusLine.command.includes('gsd-statusline.js')) {
794
+ // Replace old path with new path
795
+ settings.statusLine.command = settings.statusLine.command.replace(
796
+ /statusline\.js/,
797
+ 'gsd-statusline.js'
798
+ );
799
+ console.log(` ${green}✓${reset} Updated statusline path (statusline.js → gsd-statusline.js)`);
800
+ }
801
+
802
+ return settings;
803
+ }
804
+
805
+ /**
806
+ * Uninstall GSD from the specified directory for a specific runtime
807
+ * Removes only GSD-specific files/directories, preserves user content
808
+ * @param {boolean} isGlobal - Whether to uninstall from global or local
809
+ * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini')
810
+ */
811
+ function uninstall(isGlobal, runtime = 'claude') {
812
+ const isOpencode = runtime === 'opencode';
813
+ const dirName = getDirName(runtime);
814
+
815
+ // Get the target directory based on runtime and install type
816
+ const targetDir = isGlobal
817
+ ? getGlobalDir(runtime, explicitConfigDir)
818
+ : path.join(process.cwd(), dirName);
819
+
820
+ const locationLabel = isGlobal
821
+ ? targetDir.replace(os.homedir(), '~')
822
+ : targetDir.replace(process.cwd(), '.');
823
+
824
+ let runtimeLabel = 'Claude Code';
825
+ if (runtime === 'opencode') runtimeLabel = 'OpenCode';
826
+ if (runtime === 'gemini') runtimeLabel = 'Gemini';
827
+
828
+ console.log(` Uninstalling GSD from ${cyan}${runtimeLabel}${reset} at ${cyan}${locationLabel}${reset}\n`);
829
+
830
+ // Check if target directory exists
831
+ if (!fs.existsSync(targetDir)) {
832
+ console.log(` ${yellow}⚠${reset} Directory does not exist: ${locationLabel}`);
833
+ console.log(` Nothing to uninstall.\n`);
834
+ return;
835
+ }
836
+
837
+ let removedCount = 0;
838
+
839
+ // 1. Remove GSD commands directory
840
+ if (isOpencode) {
841
+ // OpenCode: remove command/gsd-*.md files
842
+ const commandDir = path.join(targetDir, 'command');
843
+ if (fs.existsSync(commandDir)) {
844
+ const files = fs.readdirSync(commandDir);
845
+ for (const file of files) {
846
+ if (file.startsWith('gsd-') && file.endsWith('.md')) {
847
+ fs.unlinkSync(path.join(commandDir, file));
848
+ removedCount++;
849
+ }
850
+ }
851
+ console.log(` ${green}✓${reset} Removed GSD commands from command/`);
852
+ }
853
+ } else {
854
+ // Claude Code & Gemini: remove commands/gsd/ directory
855
+ const gsdCommandsDir = path.join(targetDir, 'commands', 'gsd');
856
+ if (fs.existsSync(gsdCommandsDir)) {
857
+ fs.rmSync(gsdCommandsDir, { recursive: true });
858
+ removedCount++;
859
+ console.log(` ${green}✓${reset} Removed commands/gsd/`);
860
+ }
861
+ }
862
+
863
+ // 2. Remove get-shit-done directory
864
+ const gsdDir = path.join(targetDir, 'get-shit-done');
865
+ if (fs.existsSync(gsdDir)) {
866
+ fs.rmSync(gsdDir, { recursive: true });
867
+ removedCount++;
868
+ console.log(` ${green}✓${reset} Removed get-shit-done/`);
869
+ }
870
+
871
+ // 3. Remove GSD agents (gsd-*.md files only)
872
+ const agentsDir = path.join(targetDir, 'agents');
873
+ if (fs.existsSync(agentsDir)) {
874
+ const files = fs.readdirSync(agentsDir);
875
+ let agentCount = 0;
876
+ for (const file of files) {
877
+ if (file.startsWith('gsd-') && file.endsWith('.md')) {
878
+ fs.unlinkSync(path.join(agentsDir, file));
879
+ agentCount++;
880
+ }
881
+ }
882
+ if (agentCount > 0) {
883
+ removedCount++;
884
+ console.log(` ${green}✓${reset} Removed ${agentCount} GSD agents`);
885
+ }
886
+ }
887
+
888
+ // 4. Remove GSD hooks
889
+ const hooksDir = path.join(targetDir, 'hooks');
890
+ if (fs.existsSync(hooksDir)) {
891
+ const gsdHooks = ['gsd-statusline.js', 'gsd-check-update.js', 'gsd-check-update.sh'];
892
+ let hookCount = 0;
893
+ for (const hook of gsdHooks) {
894
+ const hookPath = path.join(hooksDir, hook);
895
+ if (fs.existsSync(hookPath)) {
896
+ fs.unlinkSync(hookPath);
897
+ hookCount++;
898
+ }
899
+ }
900
+ if (hookCount > 0) {
901
+ removedCount++;
902
+ console.log(` ${green}✓${reset} Removed ${hookCount} GSD hooks`);
903
+ }
904
+ }
905
+
906
+ // 5. Remove GSD package.json (CommonJS mode marker)
907
+ const pkgJsonPath = path.join(targetDir, 'package.json');
908
+ if (fs.existsSync(pkgJsonPath)) {
909
+ try {
910
+ const content = fs.readFileSync(pkgJsonPath, 'utf8').trim();
911
+ // Only remove if it's our minimal CommonJS marker
912
+ if (content === '{"type":"commonjs"}') {
913
+ fs.unlinkSync(pkgJsonPath);
914
+ removedCount++;
915
+ console.log(` ${green}✓${reset} Removed GSD package.json`);
916
+ }
917
+ } catch (e) {
918
+ // Ignore read errors
919
+ }
920
+ }
921
+
922
+ // 6. Clean up settings.json (remove GSD hooks and statusline)
923
+ const settingsPath = path.join(targetDir, 'settings.json');
924
+ if (fs.existsSync(settingsPath)) {
925
+ let settings = readSettings(settingsPath);
926
+ let settingsModified = false;
927
+
928
+ // Remove GSD statusline if it references our hook
929
+ if (settings.statusLine && settings.statusLine.command &&
930
+ settings.statusLine.command.includes('gsd-statusline')) {
931
+ delete settings.statusLine;
932
+ settingsModified = true;
933
+ console.log(` ${green}✓${reset} Removed GSD statusline from settings`);
934
+ }
935
+
936
+ // Remove GSD hooks from SessionStart
937
+ if (settings.hooks && settings.hooks.SessionStart) {
938
+ const before = settings.hooks.SessionStart.length;
939
+ settings.hooks.SessionStart = settings.hooks.SessionStart.filter(entry => {
940
+ if (entry.hooks && Array.isArray(entry.hooks)) {
941
+ // Filter out GSD hooks
942
+ const hasGsdHook = entry.hooks.some(h =>
943
+ h.command && (h.command.includes('gsd-check-update') || h.command.includes('gsd-statusline'))
944
+ );
945
+ return !hasGsdHook;
946
+ }
947
+ return true;
948
+ });
949
+ if (settings.hooks.SessionStart.length < before) {
950
+ settingsModified = true;
951
+ console.log(` ${green}✓${reset} Removed GSD hooks from settings`);
952
+ }
953
+ // Clean up empty array
954
+ if (settings.hooks.SessionStart.length === 0) {
955
+ delete settings.hooks.SessionStart;
956
+ }
957
+ // Clean up empty hooks object
958
+ if (Object.keys(settings.hooks).length === 0) {
959
+ delete settings.hooks;
960
+ }
961
+ }
962
+
963
+ if (settingsModified) {
964
+ writeSettings(settingsPath, settings);
965
+ removedCount++;
966
+ }
967
+ }
968
+
969
+ // 6. For OpenCode, clean up permissions from opencode.json
970
+ if (isOpencode) {
971
+ // For local uninstalls, clean up ./.opencode/opencode.json
972
+ // For global uninstalls, clean up ~/.config/opencode/opencode.json
973
+ const opencodeConfigDir = isGlobal
974
+ ? getOpencodeGlobalDir()
975
+ : path.join(process.cwd(), '.opencode');
976
+ const configPath = path.join(opencodeConfigDir, 'opencode.json');
977
+ if (fs.existsSync(configPath)) {
978
+ try {
979
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
980
+ let modified = false;
981
+
982
+ // Remove GSD permission entries
983
+ if (config.permission) {
984
+ for (const permType of ['read', 'external_directory']) {
985
+ if (config.permission[permType]) {
986
+ const keys = Object.keys(config.permission[permType]);
987
+ for (const key of keys) {
988
+ if (key.includes('get-shit-done')) {
989
+ delete config.permission[permType][key];
990
+ modified = true;
991
+ }
992
+ }
993
+ // Clean up empty objects
994
+ if (Object.keys(config.permission[permType]).length === 0) {
995
+ delete config.permission[permType];
996
+ }
997
+ }
998
+ }
999
+ if (Object.keys(config.permission).length === 0) {
1000
+ delete config.permission;
1001
+ }
1002
+ }
1003
+
1004
+ if (modified) {
1005
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
1006
+ removedCount++;
1007
+ console.log(` ${green}✓${reset} Removed GSD permissions from opencode.json`);
1008
+ }
1009
+ } catch (e) {
1010
+ // Ignore JSON parse errors
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ if (removedCount === 0) {
1016
+ console.log(` ${yellow}⚠${reset} No GSD files found to remove.`);
1017
+ }
1018
+
1019
+ console.log(`
1020
+ ${green}Done!${reset} GSD has been uninstalled from ${runtimeLabel}.
1021
+ Your other files and settings have been preserved.
1022
+ `);
1023
+ }
1024
+
1025
+ /**
1026
+ * Parse JSONC (JSON with Comments) by stripping comments and trailing commas.
1027
+ * OpenCode supports JSONC format via jsonc-parser, so users may have comments.
1028
+ * This is a lightweight inline parser to avoid adding dependencies.
1029
+ */
1030
+ function parseJsonc(content) {
1031
+ // Strip BOM if present
1032
+ if (content.charCodeAt(0) === 0xFEFF) {
1033
+ content = content.slice(1);
1034
+ }
1035
+
1036
+ // Remove single-line and block comments while preserving strings
1037
+ let result = '';
1038
+ let inString = false;
1039
+ let i = 0;
1040
+ while (i < content.length) {
1041
+ const char = content[i];
1042
+ const next = content[i + 1];
1043
+
1044
+ if (inString) {
1045
+ result += char;
1046
+ // Handle escape sequences
1047
+ if (char === '\\' && i + 1 < content.length) {
1048
+ result += next;
1049
+ i += 2;
1050
+ continue;
1051
+ }
1052
+ if (char === '"') {
1053
+ inString = false;
1054
+ }
1055
+ i++;
1056
+ } else {
1057
+ if (char === '"') {
1058
+ inString = true;
1059
+ result += char;
1060
+ i++;
1061
+ } else if (char === '/' && next === '/') {
1062
+ // Skip single-line comment until end of line
1063
+ while (i < content.length && content[i] !== '\n') {
1064
+ i++;
1065
+ }
1066
+ } else if (char === '/' && next === '*') {
1067
+ // Skip block comment
1068
+ i += 2;
1069
+ while (i < content.length - 1 && !(content[i] === '*' && content[i + 1] === '/')) {
1070
+ i++;
1071
+ }
1072
+ i += 2; // Skip closing */
1073
+ } else {
1074
+ result += char;
1075
+ i++;
1076
+ }
1077
+ }
1078
+ }
1079
+
1080
+ // Remove trailing commas before } or ]
1081
+ result = result.replace(/,(\s*[}\]])/g, '$1');
1082
+
1083
+ return JSON.parse(result);
1084
+ }
1085
+
1086
+ /**
1087
+ * Configure OpenCode permissions to allow reading GSD reference docs
1088
+ * This prevents permission prompts when GSD accesses the get-shit-done directory
1089
+ * @param {boolean} isGlobal - Whether this is a global or local install
1090
+ */
1091
+ function configureOpencodePermissions(isGlobal = true) {
1092
+ // For local installs, use ./.opencode/opencode.json
1093
+ // For global installs, use ~/.config/opencode/opencode.json
1094
+ const opencodeConfigDir = isGlobal
1095
+ ? getOpencodeGlobalDir()
1096
+ : path.join(process.cwd(), '.opencode');
1097
+ const configPath = path.join(opencodeConfigDir, 'opencode.json');
1098
+
1099
+ // Ensure config directory exists
1100
+ fs.mkdirSync(opencodeConfigDir, { recursive: true });
1101
+
1102
+ // Read existing config or create empty object
1103
+ let config = {};
1104
+ if (fs.existsSync(configPath)) {
1105
+ try {
1106
+ const content = fs.readFileSync(configPath, 'utf8');
1107
+ config = parseJsonc(content);
1108
+ } catch (e) {
1109
+ // Cannot parse - DO NOT overwrite user's config
1110
+ console.log(` ${yellow}⚠${reset} Could not parse opencode.json - skipping permission config`);
1111
+ console.log(` ${dim}Reason: ${e.message}${reset}`);
1112
+ console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`);
1113
+ return;
1114
+ }
1115
+ }
1116
+
1117
+ // Ensure permission structure exists
1118
+ if (!config.permission) {
1119
+ config.permission = {};
1120
+ }
1121
+
1122
+ // Build the GSD path using the actual config directory
1123
+ // Use ~ shorthand if it's in the default location, otherwise use full path
1124
+ const defaultConfigDir = path.join(os.homedir(), '.config', 'opencode');
1125
+ const gsdPath = opencodeConfigDir === defaultConfigDir
1126
+ ? '~/.config/opencode/get-shit-done/*'
1127
+ : `${opencodeConfigDir.replace(/\\/g, '/')}/get-shit-done/*`;
1128
+
1129
+ let modified = false;
1130
+
1131
+ // Configure read permission
1132
+ if (!config.permission.read || typeof config.permission.read !== 'object') {
1133
+ config.permission.read = {};
1134
+ }
1135
+ if (config.permission.read[gsdPath] !== 'allow') {
1136
+ config.permission.read[gsdPath] = 'allow';
1137
+ modified = true;
1138
+ }
1139
+
1140
+ // Configure external_directory permission (the safety guard for paths outside project)
1141
+ if (!config.permission.external_directory || typeof config.permission.external_directory !== 'object') {
1142
+ config.permission.external_directory = {};
1143
+ }
1144
+ if (config.permission.external_directory[gsdPath] !== 'allow') {
1145
+ config.permission.external_directory[gsdPath] = 'allow';
1146
+ modified = true;
1147
+ }
1148
+
1149
+ if (!modified) {
1150
+ return; // Already configured
1151
+ }
1152
+
1153
+ // Write config back
1154
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
1155
+ console.log(` ${green}✓${reset} Configured read permission for GSD docs`);
1156
+ }
1157
+
1158
+ /**
1159
+ * Verify a directory exists and contains files
1160
+ */
1161
+ function verifyInstalled(dirPath, description) {
1162
+ if (!fs.existsSync(dirPath)) {
1163
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: directory not created`);
1164
+ return false;
1165
+ }
1166
+ try {
1167
+ const entries = fs.readdirSync(dirPath);
1168
+ if (entries.length === 0) {
1169
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: directory is empty`);
1170
+ return false;
1171
+ }
1172
+ } catch (e) {
1173
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: ${e.message}`);
1174
+ return false;
1175
+ }
1176
+ return true;
1177
+ }
1178
+
1179
+ /**
1180
+ * Verify a file exists
1181
+ */
1182
+ function verifyFileInstalled(filePath, description) {
1183
+ if (!fs.existsSync(filePath)) {
1184
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: file not created`);
1185
+ return false;
1186
+ }
1187
+ return true;
1188
+ }
1189
+
1190
+ /**
1191
+ * Install to the specified directory for a specific runtime
1192
+ * @param {boolean} isGlobal - Whether to install globally or locally
1193
+ * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini')
1194
+ */
1195
+
1196
+ // ──────────────────────────────────────────────────────
1197
+ // Local Patch Persistence
1198
+ // ──────────────────────────────────────────────────────
1199
+
1200
+ const PATCHES_DIR_NAME = 'gsd-local-patches';
1201
+ const MANIFEST_NAME = 'gsd-file-manifest.json';
1202
+
1203
+ /**
1204
+ * Compute SHA256 hash of file contents
1205
+ */
1206
+ function fileHash(filePath) {
1207
+ const content = fs.readFileSync(filePath);
1208
+ return crypto.createHash('sha256').update(content).digest('hex');
1209
+ }
1210
+
1211
+ /**
1212
+ * Recursively collect all files in dir with their hashes
1213
+ */
1214
+ function generateManifest(dir, baseDir) {
1215
+ if (!baseDir) baseDir = dir;
1216
+ const manifest = {};
1217
+ if (!fs.existsSync(dir)) return manifest;
1218
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
1219
+ for (const entry of entries) {
1220
+ const fullPath = path.join(dir, entry.name);
1221
+ const relPath = path.relative(baseDir, fullPath).replace(/\\/g, '/');
1222
+ if (entry.isDirectory()) {
1223
+ Object.assign(manifest, generateManifest(fullPath, baseDir));
1224
+ } else {
1225
+ manifest[relPath] = fileHash(fullPath);
1226
+ }
1227
+ }
1228
+ return manifest;
1229
+ }
1230
+
1231
+ /**
1232
+ * Write file manifest after installation for future modification detection
1233
+ */
1234
+ function writeManifest(configDir) {
1235
+ const gsdDir = path.join(configDir, 'get-shit-done');
1236
+ const commandsDir = path.join(configDir, 'commands', 'gsd');
1237
+ const agentsDir = path.join(configDir, 'agents');
1238
+ const manifest = { version: pkg.version, timestamp: new Date().toISOString(), files: {} };
1239
+
1240
+ const gsdHashes = generateManifest(gsdDir);
1241
+ for (const [rel, hash] of Object.entries(gsdHashes)) {
1242
+ manifest.files['get-shit-done/' + rel] = hash;
1243
+ }
1244
+ if (fs.existsSync(commandsDir)) {
1245
+ const cmdHashes = generateManifest(commandsDir);
1246
+ for (const [rel, hash] of Object.entries(cmdHashes)) {
1247
+ manifest.files['commands/gsd/' + rel] = hash;
1248
+ }
1249
+ }
1250
+ if (fs.existsSync(agentsDir)) {
1251
+ for (const file of fs.readdirSync(agentsDir)) {
1252
+ if (file.startsWith('gsd-') && file.endsWith('.md')) {
1253
+ manifest.files['agents/' + file] = fileHash(path.join(agentsDir, file));
1254
+ }
1255
+ }
1256
+ }
1257
+
1258
+ fs.writeFileSync(path.join(configDir, MANIFEST_NAME), JSON.stringify(manifest, null, 2));
1259
+ return manifest;
1260
+ }
1261
+
1262
+ /**
1263
+ * Detect user-modified GSD files by comparing against install manifest.
1264
+ * Backs up modified files to gsd-local-patches/ for reapply after update.
1265
+ */
1266
+ function saveLocalPatches(configDir) {
1267
+ const manifestPath = path.join(configDir, MANIFEST_NAME);
1268
+ if (!fs.existsSync(manifestPath)) return [];
1269
+
1270
+ let manifest;
1271
+ try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { return []; }
1272
+
1273
+ const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
1274
+ const modified = [];
1275
+
1276
+ for (const [relPath, originalHash] of Object.entries(manifest.files || {})) {
1277
+ const fullPath = path.join(configDir, relPath);
1278
+ if (!fs.existsSync(fullPath)) continue;
1279
+ const currentHash = fileHash(fullPath);
1280
+ if (currentHash !== originalHash) {
1281
+ const backupPath = path.join(patchesDir, relPath);
1282
+ fs.mkdirSync(path.dirname(backupPath), { recursive: true });
1283
+ fs.copyFileSync(fullPath, backupPath);
1284
+ modified.push(relPath);
1285
+ }
1286
+ }
1287
+
1288
+ if (modified.length > 0) {
1289
+ const meta = {
1290
+ backed_up_at: new Date().toISOString(),
1291
+ from_version: manifest.version,
1292
+ files: modified
1293
+ };
1294
+ fs.writeFileSync(path.join(patchesDir, 'backup-meta.json'), JSON.stringify(meta, null, 2));
1295
+ console.log(' ' + yellow + 'i' + reset + ' Found ' + modified.length + ' locally modified GSD file(s) — backed up to ' + PATCHES_DIR_NAME + '/');
1296
+ for (const f of modified) {
1297
+ console.log(' ' + dim + f + reset);
1298
+ }
1299
+ }
1300
+ return modified;
1301
+ }
1302
+
1303
+ /**
1304
+ * After install, report backed-up patches for user to reapply.
1305
+ */
1306
+ function reportLocalPatches(configDir) {
1307
+ const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
1308
+ const metaPath = path.join(patchesDir, 'backup-meta.json');
1309
+ if (!fs.existsSync(metaPath)) return [];
1310
+
1311
+ let meta;
1312
+ try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8')); } catch { return []; }
1313
+
1314
+ if (meta.files && meta.files.length > 0) {
1315
+ console.log('');
1316
+ console.log(' ' + yellow + 'Local patches detected' + reset + ' (from v' + meta.from_version + '):');
1317
+ for (const f of meta.files) {
1318
+ console.log(' ' + cyan + f + reset);
1319
+ }
1320
+ console.log('');
1321
+ console.log(' Your modifications are saved in ' + cyan + PATCHES_DIR_NAME + '/' + reset);
1322
+ console.log(' Run ' + cyan + '/gsd:reapply-patches' + reset + ' to merge them into the new version.');
1323
+ console.log(' Or manually compare and merge the files.');
1324
+ console.log('');
1325
+ }
1326
+ return meta.files || [];
1327
+ }
1328
+
1329
+ function install(isGlobal, runtime = 'claude') {
1330
+ const isOpencode = runtime === 'opencode';
1331
+ const isGemini = runtime === 'gemini';
1332
+ const dirName = getDirName(runtime);
1333
+ const src = path.join(__dirname, '..');
1334
+
1335
+ // Get the target directory based on runtime and install type
1336
+ const targetDir = isGlobal
1337
+ ? getGlobalDir(runtime, explicitConfigDir)
1338
+ : path.join(process.cwd(), dirName);
1339
+
1340
+ const locationLabel = isGlobal
1341
+ ? targetDir.replace(os.homedir(), '~')
1342
+ : targetDir.replace(process.cwd(), '.');
1343
+
1344
+ // Path prefix for file references in markdown content
1345
+ // For global installs: use full path
1346
+ // For local installs: use relative
1347
+ const pathPrefix = isGlobal
1348
+ ? `${targetDir.replace(/\\/g, '/')}/`
1349
+ : `./${dirName}/`;
1350
+
1351
+ let runtimeLabel = 'Claude Code';
1352
+ if (isOpencode) runtimeLabel = 'OpenCode';
1353
+ if (isGemini) runtimeLabel = 'Gemini';
1354
+
1355
+ console.log(` Installing for ${cyan}${runtimeLabel}${reset} to ${cyan}${locationLabel}${reset}\n`);
1356
+
1357
+ // Track installation failures
1358
+ const failures = [];
1359
+
1360
+ // Save any locally modified GSD files before they get wiped
1361
+ saveLocalPatches(targetDir);
1362
+
1363
+ // Clean up orphaned files from previous versions
1364
+ cleanupOrphanedFiles(targetDir);
1365
+
1366
+ // OpenCode uses 'command/' (singular) with flat structure
1367
+ // Claude Code & Gemini use 'commands/' (plural) with nested structure
1368
+ if (isOpencode) {
1369
+ // OpenCode: flat structure in command/ directory
1370
+ const commandDir = path.join(targetDir, 'command');
1371
+ fs.mkdirSync(commandDir, { recursive: true });
1372
+
1373
+ // Copy commands/gsd/*.md as command/gsd-*.md (flatten structure)
1374
+ const gsdSrc = path.join(src, 'commands', 'gsd');
1375
+ copyFlattenedCommands(gsdSrc, commandDir, 'gsd', pathPrefix, runtime);
1376
+ if (verifyInstalled(commandDir, 'command/gsd-*')) {
1377
+ const count = fs.readdirSync(commandDir).filter(f => f.startsWith('gsd-')).length;
1378
+ console.log(` ${green}✓${reset} Installed ${count} commands to command/`);
1379
+ } else {
1380
+ failures.push('command/gsd-*');
1381
+ }
1382
+ } else {
1383
+ // Claude Code & Gemini: nested structure in commands/ directory
1384
+ const commandsDir = path.join(targetDir, 'commands');
1385
+ fs.mkdirSync(commandsDir, { recursive: true });
1386
+
1387
+ const gsdSrc = path.join(src, 'commands', 'gsd');
1388
+ const gsdDest = path.join(commandsDir, 'gsd');
1389
+ copyWithPathReplacement(gsdSrc, gsdDest, pathPrefix, runtime);
1390
+ if (verifyInstalled(gsdDest, 'commands/gsd')) {
1391
+ console.log(` ${green}✓${reset} Installed commands/gsd`);
1392
+ } else {
1393
+ failures.push('commands/gsd');
1394
+ }
1395
+ }
1396
+
1397
+ // Copy get-shit-done skill with path replacement
1398
+ const skillSrc = path.join(src, 'get-shit-done');
1399
+ const skillDest = path.join(targetDir, 'get-shit-done');
1400
+ copyWithPathReplacement(skillSrc, skillDest, pathPrefix, runtime);
1401
+ if (verifyInstalled(skillDest, 'get-shit-done')) {
1402
+ console.log(` ${green}✓${reset} Installed get-shit-done`);
1403
+ } else {
1404
+ failures.push('get-shit-done');
1405
+ }
1406
+
1407
+ // Copy agents to agents directory
1408
+ const agentsSrc = path.join(src, 'agents');
1409
+ if (fs.existsSync(agentsSrc)) {
1410
+ const agentsDest = path.join(targetDir, 'agents');
1411
+ fs.mkdirSync(agentsDest, { recursive: true });
1412
+
1413
+ // Remove old GSD agents (gsd-*.md) before copying new ones
1414
+ if (fs.existsSync(agentsDest)) {
1415
+ for (const file of fs.readdirSync(agentsDest)) {
1416
+ if (file.startsWith('gsd-') && file.endsWith('.md')) {
1417
+ fs.unlinkSync(path.join(agentsDest, file));
1418
+ }
1419
+ }
1420
+ }
1421
+
1422
+ // Copy new agents
1423
+ const agentEntries = fs.readdirSync(agentsSrc, { withFileTypes: true });
1424
+ for (const entry of agentEntries) {
1425
+ if (entry.isFile() && entry.name.endsWith('.md')) {
1426
+ let content = fs.readFileSync(path.join(agentsSrc, entry.name), 'utf8');
1427
+ // Always replace ~/.claude/ as it is the source of truth in the repo
1428
+ const dirRegex = /~\/\.claude\//g;
1429
+ content = content.replace(dirRegex, pathPrefix);
1430
+ content = processAttribution(content, getCommitAttribution(runtime));
1431
+ // Convert frontmatter for runtime compatibility
1432
+ if (isOpencode) {
1433
+ content = convertClaudeToOpencodeFrontmatter(content);
1434
+ } else if (isGemini) {
1435
+ content = convertClaudeToGeminiAgent(content);
1436
+ }
1437
+ fs.writeFileSync(path.join(agentsDest, entry.name), content);
1438
+ }
1439
+ }
1440
+ if (verifyInstalled(agentsDest, 'agents')) {
1441
+ console.log(` ${green}✓${reset} Installed agents`);
1442
+ } else {
1443
+ failures.push('agents');
1444
+ }
1445
+ }
1446
+
1447
+ // Copy CHANGELOG.md
1448
+ const changelogSrc = path.join(src, 'CHANGELOG.md');
1449
+ const changelogDest = path.join(targetDir, 'get-shit-done', 'CHANGELOG.md');
1450
+ if (fs.existsSync(changelogSrc)) {
1451
+ fs.copyFileSync(changelogSrc, changelogDest);
1452
+ if (verifyFileInstalled(changelogDest, 'CHANGELOG.md')) {
1453
+ console.log(` ${green}✓${reset} Installed CHANGELOG.md`);
1454
+ } else {
1455
+ failures.push('CHANGELOG.md');
1456
+ }
1457
+ }
1458
+
1459
+ // Write VERSION file
1460
+ const versionDest = path.join(targetDir, 'get-shit-done', 'VERSION');
1461
+ fs.writeFileSync(versionDest, pkg.version);
1462
+ if (verifyFileInstalled(versionDest, 'VERSION')) {
1463
+ console.log(` ${green}✓${reset} Wrote VERSION (${pkg.version})`);
1464
+ } else {
1465
+ failures.push('VERSION');
1466
+ }
1467
+
1468
+ // Write package.json to force CommonJS mode for GSD scripts
1469
+ // Prevents "require is not defined" errors when project has "type": "module"
1470
+ // Node.js walks up looking for package.json - this stops inheritance from project
1471
+ const pkgJsonDest = path.join(targetDir, 'package.json');
1472
+ fs.writeFileSync(pkgJsonDest, '{"type":"commonjs"}\n');
1473
+ console.log(` ${green}✓${reset} Wrote package.json (CommonJS mode)`);
1474
+
1475
+ // Copy hooks from dist/ (bundled with dependencies)
1476
+ // Template paths for the target runtime (replaces '.claude' with correct config dir)
1477
+ const hooksSrc = path.join(src, 'hooks', 'dist');
1478
+ if (fs.existsSync(hooksSrc)) {
1479
+ const hooksDest = path.join(targetDir, 'hooks');
1480
+ fs.mkdirSync(hooksDest, { recursive: true });
1481
+ const hookEntries = fs.readdirSync(hooksSrc);
1482
+ const configDirReplacement = getConfigDirFromHome(runtime, isGlobal);
1483
+ for (const entry of hookEntries) {
1484
+ const srcFile = path.join(hooksSrc, entry);
1485
+ if (fs.statSync(srcFile).isFile()) {
1486
+ const destFile = path.join(hooksDest, entry);
1487
+ // Template .js files to replace '.claude' with runtime-specific config dir
1488
+ if (entry.endsWith('.js')) {
1489
+ let content = fs.readFileSync(srcFile, 'utf8');
1490
+ content = content.replace(/'\.claude'/g, configDirReplacement);
1491
+ fs.writeFileSync(destFile, content);
1492
+ } else {
1493
+ fs.copyFileSync(srcFile, destFile);
1494
+ }
1495
+ }
1496
+ }
1497
+ if (verifyInstalled(hooksDest, 'hooks')) {
1498
+ console.log(` ${green}✓${reset} Installed hooks (bundled)`);
1499
+ } else {
1500
+ failures.push('hooks');
1501
+ }
1502
+ }
1503
+
1504
+ if (failures.length > 0) {
1505
+ console.error(`\n ${yellow}Installation incomplete!${reset} Failed: ${failures.join(', ')}`);
1506
+ process.exit(1);
1507
+ }
1508
+
1509
+ // Configure statusline and hooks in settings.json
1510
+ // Gemini shares same hook system as Claude Code for now
1511
+ const settingsPath = path.join(targetDir, 'settings.json');
1512
+ const settings = cleanupOrphanedHooks(readSettings(settingsPath));
1513
+ const statuslineCommand = isGlobal
1514
+ ? buildHookCommand(targetDir, 'gsd-statusline.js')
1515
+ : 'node ' + dirName + '/hooks/gsd-statusline.js';
1516
+ const updateCheckCommand = isGlobal
1517
+ ? buildHookCommand(targetDir, 'gsd-check-update.js')
1518
+ : 'node ' + dirName + '/hooks/gsd-check-update.js';
1519
+
1520
+ // Enable experimental agents for Gemini CLI (required for custom sub-agents)
1521
+ if (isGemini) {
1522
+ if (!settings.experimental) {
1523
+ settings.experimental = {};
1524
+ }
1525
+ if (!settings.experimental.enableAgents) {
1526
+ settings.experimental.enableAgents = true;
1527
+ console.log(` ${green}✓${reset} Enabled experimental agents`);
1528
+ }
1529
+ }
1530
+
1531
+ // Configure SessionStart hook for update checking (skip for opencode)
1532
+ if (!isOpencode) {
1533
+ if (!settings.hooks) {
1534
+ settings.hooks = {};
1535
+ }
1536
+ if (!settings.hooks.SessionStart) {
1537
+ settings.hooks.SessionStart = [];
1538
+ }
1539
+
1540
+ const hasGsdUpdateHook = settings.hooks.SessionStart.some(entry =>
1541
+ entry.hooks && entry.hooks.some(h => h.command && h.command.includes('gsd-check-update'))
1542
+ );
1543
+
1544
+ if (!hasGsdUpdateHook) {
1545
+ settings.hooks.SessionStart.push({
1546
+ hooks: [
1547
+ {
1548
+ type: 'command',
1549
+ command: updateCheckCommand
1550
+ }
1551
+ ]
1552
+ });
1553
+ console.log(` ${green}✓${reset} Configured update check hook`);
1554
+ }
1555
+ }
1556
+
1557
+ // Write file manifest for future modification detection
1558
+ writeManifest(targetDir);
1559
+ console.log(` ${green}✓${reset} Wrote file manifest (${MANIFEST_NAME})`);
1560
+
1561
+ // Report any backed-up local patches
1562
+ reportLocalPatches(targetDir);
1563
+
1564
+ return { settingsPath, settings, statuslineCommand, runtime };
1565
+ }
1566
+
1567
+ /**
1568
+ * Apply statusline config, then print completion message
1569
+ */
1570
+ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallStatusline, runtime = 'claude', isGlobal = true) {
1571
+ const isOpencode = runtime === 'opencode';
1572
+
1573
+ if (shouldInstallStatusline && !isOpencode) {
1574
+ settings.statusLine = {
1575
+ type: 'command',
1576
+ command: statuslineCommand
1577
+ };
1578
+ console.log(` ${green}✓${reset} Configured statusline`);
1579
+ }
1580
+
1581
+ // Always write settings
1582
+ writeSettings(settingsPath, settings);
1583
+
1584
+ // Configure OpenCode permissions
1585
+ if (isOpencode) {
1586
+ configureOpencodePermissions(isGlobal);
1587
+ }
1588
+
1589
+ let program = 'Claude Code';
1590
+ if (runtime === 'opencode') program = 'OpenCode';
1591
+ if (runtime === 'gemini') program = 'Gemini';
1592
+
1593
+ const command = isOpencode ? '/gsd-help' : '/gsd:help';
1594
+ console.log(`
1595
+ ${green}Done!${reset} Launch ${program} and run ${cyan}${command}${reset}.
1596
+
1597
+ ${cyan}Join the community:${reset} https://discord.gg/5JJgD5svVS
1598
+ `);
1599
+ }
1600
+
1601
+ /**
1602
+ * Handle statusline configuration with optional prompt
1603
+ */
1604
+ function handleStatusline(settings, isInteractive, callback) {
1605
+ const hasExisting = settings.statusLine != null;
1606
+
1607
+ if (!hasExisting) {
1608
+ callback(true);
1609
+ return;
1610
+ }
1611
+
1612
+ if (forceStatusline) {
1613
+ callback(true);
1614
+ return;
1615
+ }
1616
+
1617
+ if (!isInteractive) {
1618
+ console.log(` ${yellow}⚠${reset} Skipping statusline (already configured)`);
1619
+ console.log(` Use ${cyan}--force-statusline${reset} to replace\n`);
1620
+ callback(false);
1621
+ return;
1622
+ }
1623
+
1624
+ const existingCmd = settings.statusLine.command || settings.statusLine.url || '(custom)';
1625
+
1626
+ const rl = readline.createInterface({
1627
+ input: process.stdin,
1628
+ output: process.stdout
1629
+ });
1630
+
1631
+ console.log(`
1632
+ ${yellow}⚠${reset} Existing statusline detected\n
1633
+ Your current statusline:
1634
+ ${dim}command: ${existingCmd}${reset}
1635
+
1636
+ GSD includes a statusline showing:
1637
+ • Model name
1638
+ • Current task (from todo list)
1639
+ • Context window usage (color-coded)
1640
+
1641
+ ${cyan}1${reset}) Keep existing
1642
+ ${cyan}2${reset}) Replace with GSD statusline
1643
+ `);
1644
+
1645
+ rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
1646
+ rl.close();
1647
+ const choice = answer.trim() || '1';
1648
+ callback(choice === '2');
1649
+ });
1650
+ }
1651
+
1652
+ /**
1653
+ * Prompt for runtime selection
1654
+ */
1655
+ function promptRuntime(callback) {
1656
+ const rl = readline.createInterface({
1657
+ input: process.stdin,
1658
+ output: process.stdout
1659
+ });
1660
+
1661
+ let answered = false;
1662
+
1663
+ rl.on('close', () => {
1664
+ if (!answered) {
1665
+ answered = true;
1666
+ console.log(`\n ${yellow}Installation cancelled${reset}\n`);
1667
+ process.exit(0);
1668
+ }
1669
+ });
1670
+
1671
+ console.log(` ${yellow}Which runtime(s) would you like to install for?${reset}\n\n ${cyan}1${reset}) Claude Code ${dim}(~/.claude)${reset}
1672
+ ${cyan}2${reset}) OpenCode ${dim}(~/.config/opencode)${reset} - open source, free models
1673
+ ${cyan}3${reset}) Gemini ${dim}(~/.gemini)${reset}
1674
+ ${cyan}4${reset}) All
1675
+ `);
1676
+
1677
+ rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
1678
+ answered = true;
1679
+ rl.close();
1680
+ const choice = answer.trim() || '1';
1681
+ if (choice === '4') {
1682
+ callback(['claude', 'opencode', 'gemini']);
1683
+ } else if (choice === '3') {
1684
+ callback(['gemini']);
1685
+ } else if (choice === '2') {
1686
+ callback(['opencode']);
1687
+ } else {
1688
+ callback(['claude']);
1689
+ }
1690
+ });
1691
+ }
1692
+
1693
+ /**
1694
+ * Prompt for install location
1695
+ */
1696
+ function promptLocation(runtimes) {
1697
+ if (!process.stdin.isTTY) {
1698
+ console.log(` ${yellow}Non-interactive terminal detected, defaulting to global install${reset}\n`);
1699
+ installAllRuntimes(runtimes, true, false);
1700
+ return;
1701
+ }
1702
+
1703
+ const rl = readline.createInterface({
1704
+ input: process.stdin,
1705
+ output: process.stdout
1706
+ });
1707
+
1708
+ let answered = false;
1709
+
1710
+ rl.on('close', () => {
1711
+ if (!answered) {
1712
+ answered = true;
1713
+ console.log(`\n ${yellow}Installation cancelled${reset}\n`);
1714
+ process.exit(0);
1715
+ }
1716
+ });
1717
+
1718
+ const pathExamples = runtimes.map(r => {
1719
+ const globalPath = getGlobalDir(r, explicitConfigDir);
1720
+ return globalPath.replace(os.homedir(), '~');
1721
+ }).join(', ');
1722
+
1723
+ const localExamples = runtimes.map(r => `./${getDirName(r)}`).join(', ');
1724
+
1725
+ console.log(` ${yellow}Where would you like to install?${reset}\n\n ${cyan}1${reset}) Global ${dim}(${pathExamples})${reset} - available in all projects
1726
+ ${cyan}2${reset}) Local ${dim}(${localExamples})${reset} - this project only
1727
+ `);
1728
+
1729
+ rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
1730
+ answered = true;
1731
+ rl.close();
1732
+ const choice = answer.trim() || '1';
1733
+ const isGlobal = choice !== '2';
1734
+ installAllRuntimes(runtimes, isGlobal, true);
1735
+ });
1736
+ }
1737
+
1738
+ /**
1739
+ * Install GSD for all selected runtimes
1740
+ */
1741
+ function installAllRuntimes(runtimes, isGlobal, isInteractive) {
1742
+ const results = [];
1743
+
1744
+ for (const runtime of runtimes) {
1745
+ const result = install(isGlobal, runtime);
1746
+ results.push(result);
1747
+ }
1748
+
1749
+ // Handle statusline for Claude & Gemini (OpenCode uses themes)
1750
+ const claudeResult = results.find(r => r.runtime === 'claude');
1751
+ const geminiResult = results.find(r => r.runtime === 'gemini');
1752
+
1753
+ // Logic: if both are present, ask once if interactive? Or ask for each?
1754
+ // Simpler: Ask once and apply to both if applicable.
1755
+
1756
+ if (claudeResult || geminiResult) {
1757
+ // Use whichever settings exist to check for existing statusline
1758
+ const primaryResult = claudeResult || geminiResult;
1759
+
1760
+ handleStatusline(primaryResult.settings, isInteractive, (shouldInstallStatusline) => {
1761
+ if (claudeResult) {
1762
+ finishInstall(claudeResult.settingsPath, claudeResult.settings, claudeResult.statuslineCommand, shouldInstallStatusline, 'claude', isGlobal);
1763
+ }
1764
+ if (geminiResult) {
1765
+ finishInstall(geminiResult.settingsPath, geminiResult.settings, geminiResult.statuslineCommand, shouldInstallStatusline, 'gemini', isGlobal);
1766
+ }
1767
+
1768
+ const opencodeResult = results.find(r => r.runtime === 'opencode');
1769
+ if (opencodeResult) {
1770
+ finishInstall(opencodeResult.settingsPath, opencodeResult.settings, opencodeResult.statuslineCommand, false, 'opencode', isGlobal);
1771
+ }
1772
+ });
1773
+ } else {
1774
+ // Only OpenCode
1775
+ const opencodeResult = results[0];
1776
+ finishInstall(opencodeResult.settingsPath, opencodeResult.settings, opencodeResult.statuslineCommand, false, 'opencode', isGlobal);
1777
+ }
1778
+ }
1779
+
1780
+ // Main logic
1781
+ if (hasGlobal && hasLocal) {
1782
+ console.error(` ${yellow}Cannot specify both --global and --local${reset}`);
1783
+ process.exit(1);
1784
+ } else if (explicitConfigDir && hasLocal) {
1785
+ console.error(` ${yellow}Cannot use --config-dir with --local${reset}`);
1786
+ process.exit(1);
1787
+ } else if (hasUninstall) {
1788
+ if (!hasGlobal && !hasLocal) {
1789
+ console.error(` ${yellow}--uninstall requires --global or --local${reset}`);
1790
+ process.exit(1);
1791
+ }
1792
+ const runtimes = selectedRuntimes.length > 0 ? selectedRuntimes : ['claude'];
1793
+ for (const runtime of runtimes) {
1794
+ uninstall(hasGlobal, runtime);
1795
+ }
1796
+ } else if (selectedRuntimes.length > 0) {
1797
+ if (!hasGlobal && !hasLocal) {
1798
+ promptLocation(selectedRuntimes);
1799
+ } else {
1800
+ installAllRuntimes(selectedRuntimes, hasGlobal, false);
1801
+ }
1802
+ } else if (hasGlobal || hasLocal) {
1803
+ // Default to Claude if no runtime specified but location is
1804
+ installAllRuntimes(['claude'], hasGlobal, false);
1805
+ } else {
1806
+ // Interactive
1807
+ if (!process.stdin.isTTY) {
1808
+ console.log(` ${yellow}Non-interactive terminal detected, defaulting to Claude Code global install${reset}\n`);
1809
+ installAllRuntimes(['claude'], true, false);
1810
+ } else {
1811
+ promptRuntime((runtimes) => {
1812
+ promptLocation(runtimes);
1813
+ });
1814
+ }
1815
+ }