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