declare-cc 1.0.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +153 -187
  2. package/dist/client/assets/index-BVuhr02G.css +1 -0
  3. package/dist/client/assets/index-DujGXAYw.js +9 -0
  4. package/dist/client/index.html +23 -0
  5. package/dist/index.js +17459 -0
  6. package/package.json +38 -45
  7. package/src/agents/prompts/00-research.md +90 -0
  8. package/src/agents/prompts/01-vision.md +38 -0
  9. package/src/agents/prompts/02-declarations.md +47 -0
  10. package/src/agents/prompts/03-milestones.md +43 -0
  11. package/src/agents/prompts/04-actions.md +90 -0
  12. package/src/agents/prompts/05-execution.md +63 -0
  13. package/src/agents/prompts/06-verification.md +104 -0
  14. package/LICENSE +0 -21
  15. package/agents/declare-codebase-mapper.md +0 -761
  16. package/agents/declare-debugger.md +0 -1198
  17. package/agents/declare-executor.md +0 -353
  18. package/agents/declare-integration-checker.md +0 -440
  19. package/agents/declare-plan-checker.md +0 -608
  20. package/agents/declare-planner.md +0 -1015
  21. package/agents/declare-research-synthesizer.md +0 -309
  22. package/agents/declare-researcher.md +0 -484
  23. package/agents/declare-roadmapper.md +0 -639
  24. package/agents/declare-verifier.md +0 -555
  25. package/bin/declare.js +0 -16
  26. package/bin/install.js +0 -1907
  27. package/commands/declare/actions.md +0 -113
  28. package/commands/declare/add-todo.md +0 -41
  29. package/commands/declare/audit.md +0 -76
  30. package/commands/declare/check-todos.md +0 -125
  31. package/commands/declare/complete-milestone.md +0 -215
  32. package/commands/declare/dashboard.md +0 -65
  33. package/commands/declare/debug.md +0 -162
  34. package/commands/declare/discuss.md +0 -65
  35. package/commands/declare/execute.md +0 -521
  36. package/commands/declare/future.md +0 -72
  37. package/commands/declare/health.md +0 -92
  38. package/commands/declare/help.md +0 -31
  39. package/commands/declare/init.md +0 -39
  40. package/commands/declare/map-codebase.md +0 -149
  41. package/commands/declare/milestones.md +0 -98
  42. package/commands/declare/new-cycle.md +0 -172
  43. package/commands/declare/new-project.md +0 -565
  44. package/commands/declare/pause.md +0 -138
  45. package/commands/declare/plan.md +0 -320
  46. package/commands/declare/prioritize.md +0 -65
  47. package/commands/declare/progress.md +0 -116
  48. package/commands/declare/quick.md +0 -119
  49. package/commands/declare/reapply-patches.md +0 -178
  50. package/commands/declare/research.md +0 -267
  51. package/commands/declare/resume.md +0 -146
  52. package/commands/declare/set-profile.md +0 -66
  53. package/commands/declare/settings.md +0 -119
  54. package/commands/declare/status.md +0 -65
  55. package/commands/declare/trace.md +0 -81
  56. package/commands/declare/update.md +0 -251
  57. package/commands/declare/verify.md +0 -65
  58. package/commands/declare/visualize.md +0 -74
  59. package/dist/declare-tools.cjs +0 -9428
  60. package/dist/public/app.js +0 -9086
  61. package/dist/public/index.html +0 -4292
  62. package/hooks/declare-activity.js +0 -106
  63. package/hooks/declare-check-update.js +0 -62
  64. package/hooks/declare-server.js +0 -116
  65. package/hooks/declare-statusline.js +0 -91
  66. package/scripts/build-hooks.js +0 -42
  67. package/scripts/release.js +0 -50
  68. package/templates/future.md +0 -4
  69. package/templates/milestones.md +0 -11
  70. package/workflows/actions.md +0 -89
  71. package/workflows/discuss.md +0 -476
  72. package/workflows/future.md +0 -185
  73. package/workflows/milestones.md +0 -87
  74. package/workflows/scope.md +0 -94
  75. package/workflows/verify.md +0 -504
package/bin/install.js DELETED
@@ -1,1907 +0,0 @@
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
- ' Declare ' + dim + 'v' + pkg.version + reset + '\n' +
139
- ' A future-driven meta-prompting engine for agentic development.\n' +
140
- ' Forked from GSD · https://github.com/decocms/declare-cc\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 declare-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 Declare (remove all Declare 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 declare-cc\n\n ${dim}# Install for Claude Code globally${reset}\n npx declare-cc --claude --global\n\n ${dim}# Install for Gemini globally${reset}\n npx declare-cc --gemini --global\n\n ${dim}# Install for all runtimes globally${reset}\n npx declare-cc --all --global\n\n ${dim}# Install to custom config directory${reset}\n npx declare-cc --claude --global --config-dir ~/.claude-bc\n\n ${dim}# Install to current project only${reset}\n npx declare-cc --claude --local\n\n ${dim}# Uninstall Declare from Claude Code globally${reset}\n npx declare-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(/\/declare:/g, '/declare-');
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
- const distToolsRegex = /dist\/declare-tools\.cjs/g;
665
- const workflowsRegex = /@workflows\//g;
666
- content = content.replace(globalClaudeRegex, pathPrefix);
667
- content = content.replace(localClaudeRegex, `./${getDirName(runtime)}/`);
668
- content = content.replace(opencodeDirRegex, pathPrefix);
669
- content = content.replace(distToolsRegex, `${pathPrefix}declare-tools.cjs`);
670
- content = content.replace(workflowsRegex, `@${pathPrefix}workflows/`);
671
- content = processAttribution(content, getCommitAttribution(runtime));
672
- content = convertClaudeToOpencodeFrontmatter(content);
673
-
674
- fs.writeFileSync(destPath, content);
675
- }
676
- }
677
- }
678
-
679
- /**
680
- * Recursively copy directory, replacing paths in .md files
681
- * Deletes existing destDir first to remove orphaned files from previous versions
682
- * @param {string} srcDir - Source directory
683
- * @param {string} destDir - Destination directory
684
- * @param {string} pathPrefix - Path prefix for file references
685
- * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini')
686
- */
687
- function copyWithPathReplacement(srcDir, destDir, pathPrefix, runtime) {
688
- const isOpencode = runtime === 'opencode';
689
- const dirName = getDirName(runtime);
690
-
691
- // Clean install: remove existing destination to prevent orphaned files
692
- if (fs.existsSync(destDir)) {
693
- fs.rmSync(destDir, { recursive: true });
694
- }
695
- fs.mkdirSync(destDir, { recursive: true });
696
-
697
- const entries = fs.readdirSync(srcDir, { withFileTypes: true });
698
-
699
- for (const entry of entries) {
700
- const srcPath = path.join(srcDir, entry.name);
701
- const destPath = path.join(destDir, entry.name);
702
-
703
- if (entry.isDirectory()) {
704
- copyWithPathReplacement(srcPath, destPath, pathPrefix, runtime);
705
- } else if (entry.name.endsWith('.md')) {
706
- // Replace ~/.claude/, ./.claude/, and dist/declare-tools.cjs with runtime-appropriate paths
707
- let content = fs.readFileSync(srcPath, 'utf8');
708
- const globalClaudeRegex = /~\/\.claude\//g;
709
- const localClaudeRegex = /\.\/\.claude\//g;
710
- const distToolsRegex = /dist\/declare-tools\.cjs/g;
711
- const workflowsRegex = /@workflows\//g;
712
- content = content.replace(globalClaudeRegex, pathPrefix);
713
- content = content.replace(localClaudeRegex, `./${dirName}/`);
714
- content = content.replace(distToolsRegex, `${pathPrefix}declare-tools.cjs`);
715
- content = content.replace(workflowsRegex, `@${pathPrefix}workflows/`);
716
- content = processAttribution(content, getCommitAttribution(runtime));
717
-
718
- // Convert frontmatter for opencode compatibility
719
- if (isOpencode) {
720
- content = convertClaudeToOpencodeFrontmatter(content);
721
- fs.writeFileSync(destPath, content);
722
- } else if (runtime === 'gemini') {
723
- // Convert to TOML for Gemini (strip <sub> tags — terminals can't render subscript)
724
- content = stripSubTags(content);
725
- const tomlContent = convertClaudeToGeminiToml(content);
726
- // Replace extension with .toml
727
- const tomlPath = destPath.replace(/\.md$/, '.toml');
728
- fs.writeFileSync(tomlPath, tomlContent);
729
- } else {
730
- fs.writeFileSync(destPath, content);
731
- }
732
- } else {
733
- fs.copyFileSync(srcPath, destPath);
734
- }
735
- }
736
- }
737
-
738
- /**
739
- * Clean up orphaned files from previous GSD versions
740
- */
741
- function cleanupOrphanedFiles(configDir) {
742
- const orphanedFiles = [
743
- 'hooks/gsd-notify.sh', // Removed in v1.6.x
744
- 'hooks/statusline.js', // Renamed to declare-statusline.js in v1.9.0
745
- ];
746
-
747
- for (const relPath of orphanedFiles) {
748
- const fullPath = path.join(configDir, relPath);
749
- if (fs.existsSync(fullPath)) {
750
- fs.unlinkSync(fullPath);
751
- console.log(` ${green}✓${reset} Removed orphaned ${relPath}`);
752
- }
753
- }
754
- }
755
-
756
- /**
757
- * Clean up orphaned hook registrations from settings.json
758
- */
759
- function cleanupOrphanedHooks(settings) {
760
- const orphanedHookPatterns = [
761
- 'gsd-notify.sh', // Removed in v1.6.x
762
- 'hooks/statusline.js', // Renamed to declare-statusline.js in v1.9.0
763
- 'gsd-intel-index.js', // Removed in v1.9.2
764
- 'gsd-intel-session.js', // Removed in v1.9.2
765
- 'gsd-intel-prune.js', // Removed in v1.9.2
766
- ];
767
-
768
- let cleanedHooks = false;
769
-
770
- // Check all hook event types (Stop, SessionStart, etc.)
771
- if (settings.hooks) {
772
- for (const eventType of Object.keys(settings.hooks)) {
773
- const hookEntries = settings.hooks[eventType];
774
- if (Array.isArray(hookEntries)) {
775
- // Filter out entries that contain orphaned hooks
776
- const filtered = hookEntries.filter(entry => {
777
- if (entry.hooks && Array.isArray(entry.hooks)) {
778
- // Check if any hook in this entry matches orphaned patterns
779
- const hasOrphaned = entry.hooks.some(h =>
780
- h.command && orphanedHookPatterns.some(pattern => h.command.includes(pattern))
781
- );
782
- if (hasOrphaned) {
783
- cleanedHooks = true;
784
- return false; // Remove this entry
785
- }
786
- }
787
- return true; // Keep this entry
788
- });
789
- settings.hooks[eventType] = filtered;
790
- }
791
- }
792
- }
793
-
794
- if (cleanedHooks) {
795
- console.log(` ${green}✓${reset} Removed orphaned hook registrations`);
796
- }
797
-
798
- // Fix #330: Update statusLine if it points to old statusline.js path
799
- if (settings.statusLine && settings.statusLine.command &&
800
- settings.statusLine.command.includes('statusline.js') &&
801
- !settings.statusLine.command.includes('declare-statusline.js')) {
802
- // Replace old path with new path
803
- settings.statusLine.command = settings.statusLine.command.replace(
804
- /statusline\.js/,
805
- 'declare-statusline.js'
806
- );
807
- console.log(` ${green}✓${reset} Updated statusline path (statusline.js → declare-statusline.js)`);
808
- }
809
-
810
- return settings;
811
- }
812
-
813
- /**
814
- * Uninstall GSD from the specified directory for a specific runtime
815
- * Removes only GSD-specific files/directories, preserves user content
816
- * @param {boolean} isGlobal - Whether to uninstall from global or local
817
- * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini')
818
- */
819
- function uninstall(isGlobal, runtime = 'claude') {
820
- const isOpencode = runtime === 'opencode';
821
- const dirName = getDirName(runtime);
822
-
823
- // Get the target directory based on runtime and install type
824
- const targetDir = isGlobal
825
- ? getGlobalDir(runtime, explicitConfigDir)
826
- : path.join(process.cwd(), dirName);
827
-
828
- const locationLabel = isGlobal
829
- ? targetDir.replace(os.homedir(), '~')
830
- : targetDir.replace(process.cwd(), '.');
831
-
832
- let runtimeLabel = 'Claude Code';
833
- if (runtime === 'opencode') runtimeLabel = 'OpenCode';
834
- if (runtime === 'gemini') runtimeLabel = 'Gemini';
835
-
836
- console.log(` Uninstalling Declare from ${cyan}${runtimeLabel}${reset} at ${cyan}${locationLabel}${reset}\n`);
837
-
838
- // Check if target directory exists
839
- if (!fs.existsSync(targetDir)) {
840
- console.log(` ${yellow}⚠${reset} Directory does not exist: ${locationLabel}`);
841
- console.log(` Nothing to uninstall.\n`);
842
- return;
843
- }
844
-
845
- let removedCount = 0;
846
-
847
- // 1. Remove Declare commands directory
848
- if (isOpencode) {
849
- // OpenCode: remove command/declare-*.md files (and old gsd-*.md)
850
- const commandDir = path.join(targetDir, 'command');
851
- if (fs.existsSync(commandDir)) {
852
- const files = fs.readdirSync(commandDir);
853
- for (const file of files) {
854
- if ((file.startsWith('declare-') || file.startsWith('gsd-')) && file.endsWith('.md')) {
855
- fs.unlinkSync(path.join(commandDir, file));
856
- removedCount++;
857
- }
858
- }
859
- console.log(` ${green}✓${reset} Removed Declare commands from command/`);
860
- }
861
- } else {
862
- // Claude Code & Gemini: remove commands/declare/ (and legacy commands/gsd/)
863
- for (const dir of ['declare', 'gsd']) {
864
- const cmdDir = path.join(targetDir, 'commands', dir);
865
- if (fs.existsSync(cmdDir)) {
866
- fs.rmSync(cmdDir, { recursive: true });
867
- removedCount++;
868
- console.log(` ${green}✓${reset} Removed commands/${dir}/`);
869
- }
870
- }
871
- }
872
-
873
- // 2. Remove declare/ metadata directory (and legacy get-shit-done/)
874
- for (const dir of ['declare', 'get-shit-done']) {
875
- const metaDir = path.join(targetDir, dir);
876
- if (fs.existsSync(metaDir)) {
877
- fs.rmSync(metaDir, { recursive: true });
878
- removedCount++;
879
- console.log(` ${green}✓${reset} Removed ${dir}/`);
880
- }
881
- }
882
-
883
- // 3. Remove Declare agents (declare-*.md and legacy gsd-*.md files)
884
- const agentsDir = path.join(targetDir, 'agents');
885
- if (fs.existsSync(agentsDir)) {
886
- const files = fs.readdirSync(agentsDir);
887
- let agentCount = 0;
888
- for (const file of files) {
889
- if ((file.startsWith('declare-') || file.startsWith('gsd-')) && file.endsWith('.md')) {
890
- fs.unlinkSync(path.join(agentsDir, file));
891
- agentCount++;
892
- }
893
- }
894
- if (agentCount > 0) {
895
- removedCount++;
896
- console.log(` ${green}✓${reset} Removed ${agentCount} Declare agents`);
897
- }
898
- }
899
-
900
- // 4. Remove Declare hooks
901
- const hooksDir = path.join(targetDir, 'hooks');
902
- if (fs.existsSync(hooksDir)) {
903
- const gsdHooks = ['declare-statusline.js', 'declare-check-update.js', 'gsd-check-update.sh', 'gsd-statusline.js', 'gsd-check-update.js'];
904
- let hookCount = 0;
905
- for (const hook of gsdHooks) {
906
- const hookPath = path.join(hooksDir, hook);
907
- if (fs.existsSync(hookPath)) {
908
- fs.unlinkSync(hookPath);
909
- hookCount++;
910
- }
911
- }
912
- if (hookCount > 0) {
913
- removedCount++;
914
- console.log(` ${green}✓${reset} Removed ${hookCount} GSD hooks`);
915
- }
916
- }
917
-
918
- // 5. Remove GSD package.json (CommonJS mode marker)
919
- const pkgJsonPath = path.join(targetDir, 'package.json');
920
- if (fs.existsSync(pkgJsonPath)) {
921
- try {
922
- const content = fs.readFileSync(pkgJsonPath, 'utf8').trim();
923
- // Only remove if it's our minimal CommonJS marker
924
- if (content === '{"type":"commonjs"}') {
925
- fs.unlinkSync(pkgJsonPath);
926
- removedCount++;
927
- console.log(` ${green}✓${reset} Removed GSD package.json`);
928
- }
929
- } catch (e) {
930
- // Ignore read errors
931
- }
932
- }
933
-
934
- // 6. Clean up settings.json (remove GSD hooks and statusline)
935
- const settingsPath = path.join(targetDir, 'settings.json');
936
- if (fs.existsSync(settingsPath)) {
937
- let settings = readSettings(settingsPath);
938
- let settingsModified = false;
939
-
940
- // Remove Declare/GSD statusline if it references our hooks
941
- if (settings.statusLine && settings.statusLine.command &&
942
- (settings.statusLine.command.includes('declare-statusline') ||
943
- settings.statusLine.command.includes('gsd-statusline'))) {
944
- delete settings.statusLine;
945
- settingsModified = true;
946
- console.log(` ${green}✓${reset} Removed Declare statusline from settings`);
947
- }
948
-
949
- // Remove Declare/GSD hooks from SessionStart
950
- if (settings.hooks && settings.hooks.SessionStart) {
951
- const before = settings.hooks.SessionStart.length;
952
- settings.hooks.SessionStart = settings.hooks.SessionStart.filter(entry => {
953
- if (entry.hooks && Array.isArray(entry.hooks)) {
954
- const hasDeclareHook = entry.hooks.some(h =>
955
- h.command && (
956
- h.command.includes('declare-check-update') ||
957
- h.command.includes('declare-statusline') ||
958
- h.command.includes('gsd-check-update') ||
959
- h.command.includes('gsd-statusline')
960
- )
961
- );
962
- return !hasDeclareHook;
963
- }
964
- return true;
965
- });
966
- if (settings.hooks.SessionStart.length < before) {
967
- settingsModified = true;
968
- console.log(` ${green}✓${reset} Removed Declare hooks from settings`);
969
- }
970
- // Clean up empty array
971
- if (settings.hooks.SessionStart.length === 0) {
972
- delete settings.hooks.SessionStart;
973
- }
974
- // Clean up empty hooks object
975
- if (Object.keys(settings.hooks).length === 0) {
976
- delete settings.hooks;
977
- }
978
- }
979
-
980
- if (settingsModified) {
981
- writeSettings(settingsPath, settings);
982
- removedCount++;
983
- }
984
- }
985
-
986
- // 6. For OpenCode, clean up permissions from opencode.json
987
- if (isOpencode) {
988
- // For local uninstalls, clean up ./.opencode/opencode.json
989
- // For global uninstalls, clean up ~/.config/opencode/opencode.json
990
- const opencodeConfigDir = isGlobal
991
- ? getOpencodeGlobalDir()
992
- : path.join(process.cwd(), '.opencode');
993
- const configPath = path.join(opencodeConfigDir, 'opencode.json');
994
- if (fs.existsSync(configPath)) {
995
- try {
996
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
997
- let modified = false;
998
-
999
- // Remove GSD permission entries
1000
- if (config.permission) {
1001
- for (const permType of ['read', 'external_directory']) {
1002
- if (config.permission[permType]) {
1003
- const keys = Object.keys(config.permission[permType]);
1004
- for (const key of keys) {
1005
- if (key.includes('get-shit-done') || key.includes('/declare/')) {
1006
- delete config.permission[permType][key];
1007
- modified = true;
1008
- }
1009
- }
1010
- // Clean up empty objects
1011
- if (Object.keys(config.permission[permType]).length === 0) {
1012
- delete config.permission[permType];
1013
- }
1014
- }
1015
- }
1016
- if (Object.keys(config.permission).length === 0) {
1017
- delete config.permission;
1018
- }
1019
- }
1020
-
1021
- if (modified) {
1022
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
1023
- removedCount++;
1024
- console.log(` ${green}✓${reset} Removed GSD permissions from opencode.json`);
1025
- }
1026
- } catch (e) {
1027
- // Ignore JSON parse errors
1028
- }
1029
- }
1030
- }
1031
-
1032
- if (removedCount === 0) {
1033
- console.log(` ${yellow}⚠${reset} No Declare files found to remove.`);
1034
- }
1035
-
1036
- console.log(`
1037
- ${green}Done!${reset} Declare has been uninstalled from ${runtimeLabel}.
1038
- Your other files and settings have been preserved.
1039
- `);
1040
- }
1041
-
1042
- /**
1043
- * Parse JSONC (JSON with Comments) by stripping comments and trailing commas.
1044
- * OpenCode supports JSONC format via jsonc-parser, so users may have comments.
1045
- * This is a lightweight inline parser to avoid adding dependencies.
1046
- */
1047
- function parseJsonc(content) {
1048
- // Strip BOM if present
1049
- if (content.charCodeAt(0) === 0xFEFF) {
1050
- content = content.slice(1);
1051
- }
1052
-
1053
- // Remove single-line and block comments while preserving strings
1054
- let result = '';
1055
- let inString = false;
1056
- let i = 0;
1057
- while (i < content.length) {
1058
- const char = content[i];
1059
- const next = content[i + 1];
1060
-
1061
- if (inString) {
1062
- result += char;
1063
- // Handle escape sequences
1064
- if (char === '\\' && i + 1 < content.length) {
1065
- result += next;
1066
- i += 2;
1067
- continue;
1068
- }
1069
- if (char === '"') {
1070
- inString = false;
1071
- }
1072
- i++;
1073
- } else {
1074
- if (char === '"') {
1075
- inString = true;
1076
- result += char;
1077
- i++;
1078
- } else if (char === '/' && next === '/') {
1079
- // Skip single-line comment until end of line
1080
- while (i < content.length && content[i] !== '\n') {
1081
- i++;
1082
- }
1083
- } else if (char === '/' && next === '*') {
1084
- // Skip block comment
1085
- i += 2;
1086
- while (i < content.length - 1 && !(content[i] === '*' && content[i + 1] === '/')) {
1087
- i++;
1088
- }
1089
- i += 2; // Skip closing */
1090
- } else {
1091
- result += char;
1092
- i++;
1093
- }
1094
- }
1095
- }
1096
-
1097
- // Remove trailing commas before } or ]
1098
- result = result.replace(/,(\s*[}\]])/g, '$1');
1099
-
1100
- return JSON.parse(result);
1101
- }
1102
-
1103
- /**
1104
- * Configure OpenCode permissions to allow reading GSD reference docs
1105
- * This prevents permission prompts when GSD accesses the get-shit-done directory
1106
- * @param {boolean} isGlobal - Whether this is a global or local install
1107
- */
1108
- function configureOpencodePermissions(isGlobal = true) {
1109
- // For local installs, use ./.opencode/opencode.json
1110
- // For global installs, use ~/.config/opencode/opencode.json
1111
- const opencodeConfigDir = isGlobal
1112
- ? getOpencodeGlobalDir()
1113
- : path.join(process.cwd(), '.opencode');
1114
- const configPath = path.join(opencodeConfigDir, 'opencode.json');
1115
-
1116
- // Ensure config directory exists
1117
- fs.mkdirSync(opencodeConfigDir, { recursive: true });
1118
-
1119
- // Read existing config or create empty object
1120
- let config = {};
1121
- if (fs.existsSync(configPath)) {
1122
- try {
1123
- const content = fs.readFileSync(configPath, 'utf8');
1124
- config = parseJsonc(content);
1125
- } catch (e) {
1126
- // Cannot parse - DO NOT overwrite user's config
1127
- console.log(` ${yellow}⚠${reset} Could not parse opencode.json - skipping permission config`);
1128
- console.log(` ${dim}Reason: ${e.message}${reset}`);
1129
- console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`);
1130
- return;
1131
- }
1132
- }
1133
-
1134
- // Ensure permission structure exists
1135
- if (!config.permission) {
1136
- config.permission = {};
1137
- }
1138
-
1139
- // Build the Declare path using the actual config directory
1140
- // Use ~ shorthand if it's in the default location, otherwise use full path
1141
- const defaultConfigDir = path.join(os.homedir(), '.config', 'opencode');
1142
- const gsdPath = opencodeConfigDir === defaultConfigDir
1143
- ? '~/.config/opencode/declare/*'
1144
- : `${opencodeConfigDir.replace(/\\/g, '/')}/declare/*`;
1145
-
1146
- let modified = false;
1147
-
1148
- // Configure read permission
1149
- if (!config.permission.read || typeof config.permission.read !== 'object') {
1150
- config.permission.read = {};
1151
- }
1152
- if (config.permission.read[gsdPath] !== 'allow') {
1153
- config.permission.read[gsdPath] = 'allow';
1154
- modified = true;
1155
- }
1156
-
1157
- // Configure external_directory permission (the safety guard for paths outside project)
1158
- if (!config.permission.external_directory || typeof config.permission.external_directory !== 'object') {
1159
- config.permission.external_directory = {};
1160
- }
1161
- if (config.permission.external_directory[gsdPath] !== 'allow') {
1162
- config.permission.external_directory[gsdPath] = 'allow';
1163
- modified = true;
1164
- }
1165
-
1166
- if (!modified) {
1167
- return; // Already configured
1168
- }
1169
-
1170
- // Write config back
1171
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
1172
- console.log(` ${green}✓${reset} Configured read permission for Declare docs`);
1173
- }
1174
-
1175
- /**
1176
- * Verify a directory exists and contains files
1177
- */
1178
- function verifyInstalled(dirPath, description) {
1179
- if (!fs.existsSync(dirPath)) {
1180
- console.error(` ${yellow}✗${reset} Failed to install ${description}: directory not created`);
1181
- return false;
1182
- }
1183
- try {
1184
- const entries = fs.readdirSync(dirPath);
1185
- if (entries.length === 0) {
1186
- console.error(` ${yellow}✗${reset} Failed to install ${description}: directory is empty`);
1187
- return false;
1188
- }
1189
- } catch (e) {
1190
- console.error(` ${yellow}✗${reset} Failed to install ${description}: ${e.message}`);
1191
- return false;
1192
- }
1193
- return true;
1194
- }
1195
-
1196
- /**
1197
- * Verify a file exists
1198
- */
1199
- function verifyFileInstalled(filePath, description) {
1200
- if (!fs.existsSync(filePath)) {
1201
- console.error(` ${yellow}✗${reset} Failed to install ${description}: file not created`);
1202
- return false;
1203
- }
1204
- return true;
1205
- }
1206
-
1207
- /**
1208
- * Install to the specified directory for a specific runtime
1209
- * @param {boolean} isGlobal - Whether to install globally or locally
1210
- * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini')
1211
- */
1212
-
1213
- // ──────────────────────────────────────────────────────
1214
- // Local Patch Persistence
1215
- // ──────────────────────────────────────────────────────
1216
-
1217
- const PATCHES_DIR_NAME = 'declare-local-patches';
1218
- const MANIFEST_NAME = 'declare-file-manifest.json';
1219
-
1220
- /**
1221
- * Compute SHA256 hash of file contents
1222
- */
1223
- function fileHash(filePath) {
1224
- const content = fs.readFileSync(filePath);
1225
- return crypto.createHash('sha256').update(content).digest('hex');
1226
- }
1227
-
1228
- /**
1229
- * Recursively collect all files in dir with their hashes
1230
- */
1231
- function generateManifest(dir, baseDir) {
1232
- if (!baseDir) baseDir = dir;
1233
- const manifest = {};
1234
- if (!fs.existsSync(dir)) return manifest;
1235
- const entries = fs.readdirSync(dir, { withFileTypes: true });
1236
- for (const entry of entries) {
1237
- const fullPath = path.join(dir, entry.name);
1238
- const relPath = path.relative(baseDir, fullPath).replace(/\\/g, '/');
1239
- if (entry.isDirectory()) {
1240
- Object.assign(manifest, generateManifest(fullPath, baseDir));
1241
- } else {
1242
- manifest[relPath] = fileHash(fullPath);
1243
- }
1244
- }
1245
- return manifest;
1246
- }
1247
-
1248
- /**
1249
- * Write file manifest after installation for future modification detection
1250
- */
1251
- function writeManifest(configDir) {
1252
- const declareDir = path.join(configDir, 'declare');
1253
- const commandsDir = path.join(configDir, 'commands', 'declare');
1254
- const agentsDir = path.join(configDir, 'agents');
1255
- const manifest = { version: pkg.version, timestamp: new Date().toISOString(), files: {} };
1256
-
1257
- const declareHashes = generateManifest(declareDir);
1258
- for (const [rel, hash] of Object.entries(declareHashes)) {
1259
- manifest.files['declare/' + rel] = hash;
1260
- }
1261
- if (fs.existsSync(commandsDir)) {
1262
- const cmdHashes = generateManifest(commandsDir);
1263
- for (const [rel, hash] of Object.entries(cmdHashes)) {
1264
- manifest.files['commands/declare/' + rel] = hash;
1265
- }
1266
- }
1267
- if (fs.existsSync(agentsDir)) {
1268
- for (const file of fs.readdirSync(agentsDir)) {
1269
- if (file.startsWith('gsd-') && file.endsWith('.md')) {
1270
- manifest.files['agents/' + file] = fileHash(path.join(agentsDir, file));
1271
- }
1272
- }
1273
- }
1274
-
1275
- fs.writeFileSync(path.join(configDir, MANIFEST_NAME), JSON.stringify(manifest, null, 2));
1276
- return manifest;
1277
- }
1278
-
1279
- /**
1280
- * Detect user-modified GSD files by comparing against install manifest.
1281
- * Backs up modified files to gsd-local-patches/ for reapply after update.
1282
- */
1283
- function saveLocalPatches(configDir) {
1284
- const manifestPath = path.join(configDir, MANIFEST_NAME);
1285
- if (!fs.existsSync(manifestPath)) return [];
1286
-
1287
- let manifest;
1288
- try { manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')); } catch { return []; }
1289
-
1290
- const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
1291
- const modified = [];
1292
-
1293
- for (const [relPath, originalHash] of Object.entries(manifest.files || {})) {
1294
- const fullPath = path.join(configDir, relPath);
1295
- if (!fs.existsSync(fullPath)) continue;
1296
- const currentHash = fileHash(fullPath);
1297
- if (currentHash !== originalHash) {
1298
- const backupPath = path.join(patchesDir, relPath);
1299
- fs.mkdirSync(path.dirname(backupPath), { recursive: true });
1300
- fs.copyFileSync(fullPath, backupPath);
1301
- modified.push(relPath);
1302
- }
1303
- }
1304
-
1305
- if (modified.length > 0) {
1306
- const meta = {
1307
- backed_up_at: new Date().toISOString(),
1308
- from_version: manifest.version,
1309
- files: modified
1310
- };
1311
- fs.writeFileSync(path.join(patchesDir, 'backup-meta.json'), JSON.stringify(meta, null, 2));
1312
- console.log(' ' + yellow + 'i' + reset + ' Found ' + modified.length + ' locally modified GSD file(s) — backed up to ' + PATCHES_DIR_NAME + '/');
1313
- for (const f of modified) {
1314
- console.log(' ' + dim + f + reset);
1315
- }
1316
- }
1317
- return modified;
1318
- }
1319
-
1320
- /**
1321
- * After install, report backed-up patches for user to reapply.
1322
- */
1323
- function reportLocalPatches(configDir) {
1324
- const patchesDir = path.join(configDir, PATCHES_DIR_NAME);
1325
- const metaPath = path.join(patchesDir, 'backup-meta.json');
1326
- if (!fs.existsSync(metaPath)) return [];
1327
-
1328
- let meta;
1329
- try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8')); } catch { return []; }
1330
-
1331
- if (meta.files && meta.files.length > 0) {
1332
- console.log('');
1333
- console.log(' ' + yellow + 'Local patches detected' + reset + ' (from v' + meta.from_version + '):');
1334
- for (const f of meta.files) {
1335
- console.log(' ' + cyan + f + reset);
1336
- }
1337
- console.log('');
1338
- console.log(' Your modifications are saved in ' + cyan + PATCHES_DIR_NAME + '/' + reset);
1339
- console.log(' Run ' + cyan + '/declare:reapply-patches' + reset + ' to merge them into the new version.');
1340
- console.log(' Or manually compare and merge the files.');
1341
- console.log('');
1342
- }
1343
- return meta.files || [];
1344
- }
1345
-
1346
- function install(isGlobal, runtime = 'claude') {
1347
- const isOpencode = runtime === 'opencode';
1348
- const isGemini = runtime === 'gemini';
1349
- const dirName = getDirName(runtime);
1350
- const src = path.join(__dirname, '..');
1351
-
1352
- // Get the target directory based on runtime and install type
1353
- const targetDir = isGlobal
1354
- ? getGlobalDir(runtime, explicitConfigDir)
1355
- : path.join(process.cwd(), dirName);
1356
-
1357
- const locationLabel = isGlobal
1358
- ? targetDir.replace(os.homedir(), '~')
1359
- : targetDir.replace(process.cwd(), '.');
1360
-
1361
- // Path prefix for file references in markdown content
1362
- // For global installs: use full path
1363
- // For local installs: use relative
1364
- const pathPrefix = isGlobal
1365
- ? `${targetDir.replace(/\\/g, '/')}/`
1366
- : `./${dirName}/`;
1367
-
1368
- let runtimeLabel = 'Claude Code';
1369
- if (isOpencode) runtimeLabel = 'OpenCode';
1370
- if (isGemini) runtimeLabel = 'Gemini';
1371
-
1372
- console.log(` Installing for ${cyan}${runtimeLabel}${reset} to ${cyan}${locationLabel}${reset}\n`);
1373
-
1374
- // Track installation failures
1375
- const failures = [];
1376
-
1377
- // Save any locally modified GSD files before they get wiped
1378
- saveLocalPatches(targetDir);
1379
-
1380
- // Clean up orphaned files from previous versions
1381
- cleanupOrphanedFiles(targetDir);
1382
-
1383
- // OpenCode uses 'command/' (singular) with flat structure
1384
- // Claude Code & Gemini use 'commands/' (plural) with nested structure
1385
- if (isOpencode) {
1386
- // OpenCode: flat structure in command/ directory
1387
- const commandDir = path.join(targetDir, 'command');
1388
- fs.mkdirSync(commandDir, { recursive: true });
1389
-
1390
- // Copy commands/declare/*.md as command/declare-*.md (flatten structure)
1391
- const declareSrc = path.join(src, 'commands', 'declare');
1392
- copyFlattenedCommands(declareSrc, commandDir, 'declare', pathPrefix, runtime);
1393
- const count = fs.readdirSync(commandDir).filter(f => f.startsWith('declare-')).length;
1394
- if (count > 0) {
1395
- console.log(` ${green}✓${reset} Installed ${count} commands to command/`);
1396
- } else {
1397
- failures.push('command/declare-*');
1398
- }
1399
- } else {
1400
- // Claude Code & Gemini: nested structure in commands/ directory
1401
- const commandsDir = path.join(targetDir, 'commands');
1402
- fs.mkdirSync(commandsDir, { recursive: true });
1403
-
1404
- const declareSrc = path.join(src, 'commands', 'declare');
1405
- const declareDest = path.join(commandsDir, 'declare');
1406
- copyWithPathReplacement(declareSrc, declareDest, pathPrefix, runtime);
1407
- if (verifyInstalled(declareDest, 'commands/declare')) {
1408
- const count = fs.readdirSync(declareDest).filter(f => f.endsWith('.md')).length;
1409
- console.log(` ${green}✓${reset} Installed ${count} commands to commands/declare`);
1410
- } else {
1411
- failures.push('commands/declare');
1412
- }
1413
- }
1414
-
1415
- // Copy agents to agents directory
1416
- const agentsSrc = path.join(src, 'agents');
1417
- if (fs.existsSync(agentsSrc)) {
1418
- const agentsDest = path.join(targetDir, 'agents');
1419
- fs.mkdirSync(agentsDest, { recursive: true });
1420
-
1421
- // Remove old GSD agents (gsd-*.md) before copying new ones
1422
- if (fs.existsSync(agentsDest)) {
1423
- for (const file of fs.readdirSync(agentsDest)) {
1424
- if (file.startsWith('gsd-') && file.endsWith('.md')) {
1425
- fs.unlinkSync(path.join(agentsDest, file));
1426
- }
1427
- }
1428
- }
1429
-
1430
- // Copy new agents
1431
- const agentEntries = fs.readdirSync(agentsSrc, { withFileTypes: true });
1432
- for (const entry of agentEntries) {
1433
- if (entry.isFile() && entry.name.endsWith('.md')) {
1434
- let content = fs.readFileSync(path.join(agentsSrc, entry.name), 'utf8');
1435
- // Always replace ~/.claude/ as it is the source of truth in the repo
1436
- const dirRegex = /~\/\.claude\//g;
1437
- content = content.replace(dirRegex, pathPrefix);
1438
- content = processAttribution(content, getCommitAttribution(runtime));
1439
- // Convert frontmatter for runtime compatibility
1440
- if (isOpencode) {
1441
- content = convertClaudeToOpencodeFrontmatter(content);
1442
- } else if (isGemini) {
1443
- content = convertClaudeToGeminiAgent(content);
1444
- }
1445
- fs.writeFileSync(path.join(agentsDest, entry.name), content);
1446
- }
1447
- }
1448
- if (verifyInstalled(agentsDest, 'agents')) {
1449
- console.log(` ${green}✓${reset} Installed agents`);
1450
- } else {
1451
- failures.push('agents');
1452
- }
1453
- }
1454
-
1455
- // Copy workflows/ so @workflows/ references in commands resolve correctly
1456
- const workflowsSrc = path.join(src, 'workflows');
1457
- if (fs.existsSync(workflowsSrc)) {
1458
- const workflowsDest = path.join(targetDir, 'workflows');
1459
- fs.mkdirSync(workflowsDest, { recursive: true });
1460
- for (const entry of fs.readdirSync(workflowsSrc, { withFileTypes: true })) {
1461
- if (entry.isFile()) {
1462
- fs.copyFileSync(path.join(workflowsSrc, entry.name), path.join(workflowsDest, entry.name));
1463
- }
1464
- }
1465
- console.log(` ${green}✓${reset} Installed workflows/`);
1466
- }
1467
-
1468
- // Copy dashboard static files (dist/public/) → .claude/server/public/
1469
- // dist/public/ ships in the npm package (built by esbuild.config.js)
1470
- const publicSrc = path.join(src, 'dist', 'public');
1471
- if (fs.existsSync(publicSrc)) {
1472
- const publicDest = path.join(targetDir, 'server', 'public');
1473
- fs.mkdirSync(publicDest, { recursive: true });
1474
- for (const entry of fs.readdirSync(publicSrc, { withFileTypes: true })) {
1475
- if (entry.isFile()) {
1476
- fs.copyFileSync(path.join(publicSrc, entry.name), path.join(publicDest, entry.name));
1477
- }
1478
- }
1479
- console.log(` ${green}✓${reset} Installed dashboard (server/public/)`);
1480
- }
1481
-
1482
- // Copy declare-tools.cjs bundle so commands can run `node {pathPrefix}declare-tools.cjs`
1483
- const bundleSrc = path.join(src, 'dist', 'declare-tools.cjs');
1484
- const bundleDest = path.join(targetDir, 'declare-tools.cjs');
1485
- if (fs.existsSync(bundleSrc)) {
1486
- fs.copyFileSync(bundleSrc, bundleDest);
1487
- console.log(` ${green}✓${reset} Installed declare-tools.cjs`);
1488
- } else {
1489
- failures.push('declare-tools.cjs');
1490
- }
1491
-
1492
- // Ensure declare/ metadata dir exists for VERSION and CHANGELOG
1493
- const declareMetaDir = path.join(targetDir, 'declare');
1494
- fs.mkdirSync(declareMetaDir, { recursive: true });
1495
-
1496
- // Copy CHANGELOG.md
1497
- const changelogSrc = path.join(src, 'CHANGELOG.md');
1498
- const changelogDest = path.join(declareMetaDir, 'CHANGELOG.md');
1499
- if (fs.existsSync(changelogSrc)) {
1500
- fs.copyFileSync(changelogSrc, changelogDest);
1501
- if (verifyFileInstalled(changelogDest, 'CHANGELOG.md')) {
1502
- console.log(` ${green}✓${reset} Installed CHANGELOG.md`);
1503
- } else {
1504
- failures.push('CHANGELOG.md');
1505
- }
1506
- }
1507
-
1508
- // Write VERSION file
1509
- const versionDest = path.join(declareMetaDir, 'VERSION');
1510
- fs.writeFileSync(versionDest, pkg.version);
1511
- if (verifyFileInstalled(versionDest, 'VERSION')) {
1512
- console.log(` ${green}✓${reset} Wrote VERSION (${pkg.version})`);
1513
- } else {
1514
- failures.push('VERSION');
1515
- }
1516
-
1517
- // Refresh update-check cache so the "update available" UI clears immediately
1518
- try {
1519
- const cacheDir = path.join(os.homedir(), '.claude', 'cache');
1520
- fs.mkdirSync(cacheDir, { recursive: true });
1521
- fs.writeFileSync(path.join(cacheDir, 'declare-update-check.json'), JSON.stringify({
1522
- update_available: false,
1523
- installed: pkg.version,
1524
- latest: pkg.version,
1525
- checked: Math.floor(Date.now() / 1000),
1526
- }));
1527
- } catch (e) { /* non-fatal */ }
1528
-
1529
- // Write package.json to force CommonJS mode for GSD scripts
1530
- // Prevents "require is not defined" errors when project has "type": "module"
1531
- // Node.js walks up looking for package.json - this stops inheritance from project
1532
- const pkgJsonDest = path.join(targetDir, 'package.json');
1533
- fs.writeFileSync(pkgJsonDest, '{"type":"commonjs"}\n');
1534
- console.log(` ${green}✓${reset} Wrote package.json (CommonJS mode)`);
1535
-
1536
- // Copy hooks (replaces '.claude' with runtime-specific config dir in .js files)
1537
- const hooksSrc = path.join(src, 'hooks');
1538
- if (fs.existsSync(hooksSrc)) {
1539
- const hooksDest = path.join(targetDir, 'hooks');
1540
- fs.mkdirSync(hooksDest, { recursive: true });
1541
- const hookEntries = fs.readdirSync(hooksSrc);
1542
- const configDirReplacement = getConfigDirFromHome(runtime, isGlobal);
1543
- for (const entry of hookEntries) {
1544
- const srcFile = path.join(hooksSrc, entry);
1545
- if (fs.statSync(srcFile).isFile()) {
1546
- const destFile = path.join(hooksDest, entry);
1547
- // Template .js files to replace '.claude' with runtime-specific config dir
1548
- if (entry.endsWith('.js')) {
1549
- let content = fs.readFileSync(srcFile, 'utf8');
1550
- content = content.replace(/'\.claude'/g, configDirReplacement);
1551
- fs.writeFileSync(destFile, content);
1552
- } else {
1553
- fs.copyFileSync(srcFile, destFile);
1554
- }
1555
- }
1556
- }
1557
- if (verifyInstalled(hooksDest, 'hooks')) {
1558
- console.log(` ${green}✓${reset} Installed hooks (bundled)`);
1559
- } else {
1560
- failures.push('hooks');
1561
- }
1562
- }
1563
-
1564
- if (failures.length > 0) {
1565
- console.error(`\n ${yellow}Installation incomplete!${reset} Failed: ${failures.join(', ')}`);
1566
- process.exit(1);
1567
- }
1568
-
1569
- // Configure statusline and hooks in settings.json
1570
- // Gemini shares same hook system as Claude Code for now
1571
- const settingsPath = path.join(targetDir, 'settings.json');
1572
- const settings = cleanupOrphanedHooks(readSettings(settingsPath));
1573
- const statuslineCommand = isGlobal
1574
- ? buildHookCommand(targetDir, 'declare-statusline.js')
1575
- : 'node ' + dirName + '/hooks/declare-statusline.js';
1576
- const updateCheckCommand = isGlobal
1577
- ? buildHookCommand(targetDir, 'declare-check-update.js')
1578
- : 'node ' + dirName + '/hooks/declare-check-update.js';
1579
- const activityCommand = isGlobal
1580
- ? buildHookCommand(targetDir, 'declare-activity.js')
1581
- : 'node ' + dirName + '/hooks/declare-activity.js';
1582
- const serverCommand = isGlobal
1583
- ? buildHookCommand(targetDir, 'declare-server.js')
1584
- : 'node ' + dirName + '/hooks/declare-server.js';
1585
-
1586
- // Enable experimental agents for Gemini CLI (required for custom sub-agents)
1587
- if (isGemini) {
1588
- if (!settings.experimental) {
1589
- settings.experimental = {};
1590
- }
1591
- if (!settings.experimental.enableAgents) {
1592
- settings.experimental.enableAgents = true;
1593
- console.log(` ${green}✓${reset} Enabled experimental agents`);
1594
- }
1595
- }
1596
-
1597
- // Configure SessionStart hook for update checking (skip for opencode)
1598
- if (!isOpencode) {
1599
- if (!settings.hooks) {
1600
- settings.hooks = {};
1601
- }
1602
- if (!settings.hooks.SessionStart) {
1603
- settings.hooks.SessionStart = [];
1604
- }
1605
-
1606
- const hasGsdUpdateHook = settings.hooks.SessionStart.some(entry =>
1607
- entry.hooks && entry.hooks.some(h => h.command && h.command.includes('gsd-check-update'))
1608
- );
1609
-
1610
- if (!hasGsdUpdateHook) {
1611
- settings.hooks.SessionStart.push({
1612
- hooks: [{ type: 'command', command: updateCheckCommand }]
1613
- });
1614
- console.log(` ${green}✓${reset} Configured update check hook`);
1615
- }
1616
-
1617
- // Dashboard server hook — starts/restarts server for this project on SessionStart
1618
- const hasServerHook = settings.hooks.SessionStart.some(entry =>
1619
- entry.hooks && entry.hooks.some(h => h.command && h.command.includes('declare-server'))
1620
- );
1621
- if (!hasServerHook) {
1622
- settings.hooks.SessionStart.push({
1623
- hooks: [{ type: 'command', command: serverCommand }]
1624
- });
1625
- console.log(` ${green}✓${reset} Configured dashboard server hook`);
1626
- }
1627
-
1628
- // Configure PreToolUse + PostToolUse hooks for activity feed (Claude Code only)
1629
- if (!isOpencode && !isGemini) {
1630
- if (!settings.hooks.PreToolUse) settings.hooks.PreToolUse = [];
1631
- if (!settings.hooks.PostToolUse) settings.hooks.PostToolUse = [];
1632
-
1633
- const hasActivityPre = settings.hooks.PreToolUse.some(e =>
1634
- e.hooks && e.hooks.some(h => h.command && h.command.includes('declare-activity'))
1635
- );
1636
- if (!hasActivityPre) {
1637
- settings.hooks.PreToolUse.push({ hooks: [{ type: 'command', command: activityCommand }] });
1638
- settings.hooks.PostToolUse.push({ hooks: [{ type: 'command', command: activityCommand }] });
1639
- console.log(` ${green}✓${reset} Configured activity feed hooks`);
1640
- }
1641
- }
1642
- }
1643
-
1644
- // Write file manifest for future modification detection
1645
- writeManifest(targetDir);
1646
- console.log(` ${green}✓${reset} Wrote file manifest (${MANIFEST_NAME})`);
1647
-
1648
- // Report any backed-up local patches
1649
- reportLocalPatches(targetDir);
1650
-
1651
- return { settingsPath, settings, statuslineCommand, runtime };
1652
- }
1653
-
1654
- /**
1655
- * Apply statusline config, then print completion message
1656
- */
1657
- function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallStatusline, runtime = 'claude', isGlobal = true) {
1658
- const isOpencode = runtime === 'opencode';
1659
-
1660
- // Statusline is a global UI element — only configure it for global installs.
1661
- // Local installs must not write statusLine: it would point to a project-specific
1662
- // path that breaks when the project moves or is deleted.
1663
- // Users who only do local installs should run `npx declare-cc --claude --global`
1664
- // once to get the statusline, or configure it manually.
1665
- if (shouldInstallStatusline && !isOpencode && isGlobal) {
1666
- settings.statusLine = { type: 'command', command: statuslineCommand };
1667
- console.log(` ${green}✓${reset} Configured statusline`);
1668
- }
1669
-
1670
- // Always write settings
1671
- writeSettings(settingsPath, settings);
1672
-
1673
- // Configure OpenCode permissions
1674
- if (isOpencode) {
1675
- configureOpencodePermissions(isGlobal);
1676
- }
1677
-
1678
- let program = 'Claude Code';
1679
- if (runtime === 'opencode') program = 'OpenCode';
1680
- if (runtime === 'gemini') program = 'Gemini';
1681
-
1682
- const command = isOpencode ? '/declare-help' : '/declare:help';
1683
- const statuslineNote = (!isGlobal && !isOpencode)
1684
- ? `\n ${yellow}Tip:${reset} For the context-window statusline, run once globally:\n ${dim}npx declare-cc --claude --global${reset}\n`
1685
- : '';
1686
- console.log(`
1687
- ${green}Done!${reset} Launch ${program} and run ${cyan}${command}${reset}.
1688
- ${statuslineNote}
1689
- ${cyan}Docs & source:${reset} https://github.com/decocms/declare-cc
1690
- `);
1691
- }
1692
-
1693
- /**
1694
- * Handle statusline configuration with optional prompt
1695
- */
1696
- function handleStatusline(settings, isInteractive, callback) {
1697
- const hasExisting = settings.statusLine != null;
1698
-
1699
- if (!hasExisting) {
1700
- callback(true);
1701
- return;
1702
- }
1703
-
1704
- if (forceStatusline) {
1705
- callback(true);
1706
- return;
1707
- }
1708
-
1709
- if (!isInteractive) {
1710
- console.log(` ${yellow}⚠${reset} Skipping statusline (already configured)`);
1711
- console.log(` Use ${cyan}--force-statusline${reset} to replace\n`);
1712
- callback(false);
1713
- return;
1714
- }
1715
-
1716
- const existingCmd = settings.statusLine.command || settings.statusLine.url || '(custom)';
1717
-
1718
- const rl = readline.createInterface({
1719
- input: process.stdin,
1720
- output: process.stdout
1721
- });
1722
-
1723
- console.log(`
1724
- ${yellow}⚠${reset} Existing statusline detected\n
1725
- Your current statusline:
1726
- ${dim}command: ${existingCmd}${reset}
1727
-
1728
- Declare includes a statusline showing:
1729
- • Model name
1730
- • Current task (from todo list)
1731
- • Context window usage (color-coded)
1732
-
1733
- ${cyan}1${reset}) Keep existing
1734
- ${cyan}2${reset}) Replace with Declare statusline
1735
- `);
1736
-
1737
- rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
1738
- rl.close();
1739
- const choice = answer.trim() || '1';
1740
- callback(choice === '2');
1741
- });
1742
- }
1743
-
1744
- /**
1745
- * Prompt for runtime selection
1746
- */
1747
- function promptRuntime(callback) {
1748
- const rl = readline.createInterface({
1749
- input: process.stdin,
1750
- output: process.stdout
1751
- });
1752
-
1753
- let answered = false;
1754
-
1755
- rl.on('close', () => {
1756
- if (!answered) {
1757
- answered = true;
1758
- console.log(`\n ${yellow}Installation cancelled${reset}\n`);
1759
- process.exit(0);
1760
- }
1761
- });
1762
-
1763
- console.log(` ${yellow}Which runtime(s) would you like to install for?${reset}\n\n ${cyan}1${reset}) Claude Code ${dim}(~/.claude)${reset}
1764
- ${cyan}2${reset}) OpenCode ${dim}(~/.config/opencode)${reset} - open source, free models
1765
- ${cyan}3${reset}) Gemini ${dim}(~/.gemini)${reset}
1766
- ${cyan}4${reset}) All
1767
- `);
1768
-
1769
- rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
1770
- answered = true;
1771
- rl.close();
1772
- const choice = answer.trim() || '1';
1773
- if (choice === '4') {
1774
- callback(['claude', 'opencode', 'gemini']);
1775
- } else if (choice === '3') {
1776
- callback(['gemini']);
1777
- } else if (choice === '2') {
1778
- callback(['opencode']);
1779
- } else {
1780
- callback(['claude']);
1781
- }
1782
- });
1783
- }
1784
-
1785
- /**
1786
- * Prompt for install location
1787
- */
1788
- function promptLocation(runtimes) {
1789
- if (!process.stdin.isTTY) {
1790
- console.log(` ${yellow}Non-interactive terminal detected, defaulting to global install${reset}\n`);
1791
- installAllRuntimes(runtimes, true, false);
1792
- return;
1793
- }
1794
-
1795
- const rl = readline.createInterface({
1796
- input: process.stdin,
1797
- output: process.stdout
1798
- });
1799
-
1800
- let answered = false;
1801
-
1802
- rl.on('close', () => {
1803
- if (!answered) {
1804
- answered = true;
1805
- console.log(`\n ${yellow}Installation cancelled${reset}\n`);
1806
- process.exit(0);
1807
- }
1808
- });
1809
-
1810
- const pathExamples = runtimes.map(r => {
1811
- const globalPath = getGlobalDir(r, explicitConfigDir);
1812
- return globalPath.replace(os.homedir(), '~');
1813
- }).join(', ');
1814
-
1815
- const localExamples = runtimes.map(r => `./${getDirName(r)}`).join(', ');
1816
-
1817
- console.log(` ${yellow}Where would you like to install?${reset}\n\n ${cyan}1${reset}) Global ${dim}(${pathExamples})${reset} - available in all projects
1818
- ${cyan}2${reset}) Local ${dim}(${localExamples})${reset} - this project only
1819
- `);
1820
-
1821
- rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
1822
- answered = true;
1823
- rl.close();
1824
- const choice = answer.trim() || '1';
1825
- const isGlobal = choice !== '2';
1826
- installAllRuntimes(runtimes, isGlobal, true);
1827
- });
1828
- }
1829
-
1830
- /**
1831
- * Install GSD for all selected runtimes
1832
- */
1833
- function installAllRuntimes(runtimes, isGlobal, isInteractive) {
1834
- const results = [];
1835
-
1836
- for (const runtime of runtimes) {
1837
- const result = install(isGlobal, runtime);
1838
- results.push(result);
1839
- }
1840
-
1841
- // Handle statusline for Claude & Gemini (OpenCode uses themes)
1842
- const claudeResult = results.find(r => r.runtime === 'claude');
1843
- const geminiResult = results.find(r => r.runtime === 'gemini');
1844
-
1845
- // Logic: if both are present, ask once if interactive? Or ask for each?
1846
- // Simpler: Ask once and apply to both if applicable.
1847
-
1848
- if (claudeResult || geminiResult) {
1849
- // Use whichever settings exist to check for existing statusline
1850
- const primaryResult = claudeResult || geminiResult;
1851
-
1852
- handleStatusline(primaryResult.settings, isInteractive, (shouldInstallStatusline) => {
1853
- if (claudeResult) {
1854
- finishInstall(claudeResult.settingsPath, claudeResult.settings, claudeResult.statuslineCommand, shouldInstallStatusline, 'claude', isGlobal);
1855
- }
1856
- if (geminiResult) {
1857
- finishInstall(geminiResult.settingsPath, geminiResult.settings, geminiResult.statuslineCommand, shouldInstallStatusline, 'gemini', isGlobal);
1858
- }
1859
-
1860
- const opencodeResult = results.find(r => r.runtime === 'opencode');
1861
- if (opencodeResult) {
1862
- finishInstall(opencodeResult.settingsPath, opencodeResult.settings, opencodeResult.statuslineCommand, false, 'opencode', isGlobal);
1863
- }
1864
- });
1865
- } else {
1866
- // Only OpenCode
1867
- const opencodeResult = results[0];
1868
- finishInstall(opencodeResult.settingsPath, opencodeResult.settings, opencodeResult.statuslineCommand, false, 'opencode', isGlobal);
1869
- }
1870
- }
1871
-
1872
- // Main logic
1873
- if (hasGlobal && hasLocal) {
1874
- console.error(` ${yellow}Cannot specify both --global and --local${reset}`);
1875
- process.exit(1);
1876
- } else if (explicitConfigDir && hasLocal) {
1877
- console.error(` ${yellow}Cannot use --config-dir with --local${reset}`);
1878
- process.exit(1);
1879
- } else if (hasUninstall) {
1880
- if (!hasGlobal && !hasLocal) {
1881
- console.error(` ${yellow}--uninstall requires --global or --local${reset}`);
1882
- process.exit(1);
1883
- }
1884
- const runtimes = selectedRuntimes.length > 0 ? selectedRuntimes : ['claude'];
1885
- for (const runtime of runtimes) {
1886
- uninstall(hasGlobal, runtime);
1887
- }
1888
- } else if (selectedRuntimes.length > 0) {
1889
- if (!hasGlobal && !hasLocal) {
1890
- promptLocation(selectedRuntimes);
1891
- } else {
1892
- installAllRuntimes(selectedRuntimes, hasGlobal, false);
1893
- }
1894
- } else if (hasGlobal || hasLocal) {
1895
- // Default to Claude if no runtime specified but location is
1896
- installAllRuntimes(['claude'], hasGlobal, false);
1897
- } else {
1898
- // Interactive
1899
- if (!process.stdin.isTTY) {
1900
- console.log(` ${yellow}Non-interactive terminal detected, defaulting to Claude Code global install${reset}\n`);
1901
- installAllRuntimes(['claude'], true, false);
1902
- } else {
1903
- promptRuntime((runtimes) => {
1904
- promptLocation(runtimes);
1905
- });
1906
- }
1907
- }