@mobiman/vector 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (225) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +117 -0
  3. package/agents/vector-codebase-mapper.md +770 -0
  4. package/agents/vector-debugger.md +1338 -0
  5. package/agents/vector-executor.md +487 -0
  6. package/agents/vector-integration-checker.md +443 -0
  7. package/agents/vector-nyquist-auditor.md +176 -0
  8. package/agents/vector-phase-researcher.md +553 -0
  9. package/agents/vector-plan-checker.md +706 -0
  10. package/agents/vector-planner.md +1307 -0
  11. package/agents/vector-project-researcher.md +629 -0
  12. package/agents/vector-research-synthesizer.md +247 -0
  13. package/agents/vector-roadmapper.md +650 -0
  14. package/agents/vector-ui-auditor.md +439 -0
  15. package/agents/vector-ui-checker.md +300 -0
  16. package/agents/vector-ui-researcher.md +353 -0
  17. package/agents/vector-verifier.md +579 -0
  18. package/bin/install.cjs +2907 -0
  19. package/bin/install.cjs.map +1 -0
  20. package/bin/install.cts +3103 -0
  21. package/bin/install.d.cts +3 -0
  22. package/bin/install.d.cts.map +1 -0
  23. package/commands/vector/add-phase.md +43 -0
  24. package/commands/vector/add-tests.md +41 -0
  25. package/commands/vector/add-todo.md +47 -0
  26. package/commands/vector/audit-milestone.md +36 -0
  27. package/commands/vector/autonomous.md +41 -0
  28. package/commands/vector/check-todos.md +45 -0
  29. package/commands/vector/cleanup.md +18 -0
  30. package/commands/vector/complete-milestone.md +136 -0
  31. package/commands/vector/debug.md +168 -0
  32. package/commands/vector/discuss-phase.md +90 -0
  33. package/commands/vector/do.md +30 -0
  34. package/commands/vector/execute-phase.md +41 -0
  35. package/commands/vector/health.md +22 -0
  36. package/commands/vector/help.md +22 -0
  37. package/commands/vector/insert-phase.md +32 -0
  38. package/commands/vector/join-discord.md +18 -0
  39. package/commands/vector/list-phase-assumptions.md +46 -0
  40. package/commands/vector/map-codebase.md +71 -0
  41. package/commands/vector/new-milestone.md +44 -0
  42. package/commands/vector/new-project.md +42 -0
  43. package/commands/vector/pause-work.md +38 -0
  44. package/commands/vector/plan-milestone-gaps.md +34 -0
  45. package/commands/vector/plan-phase.md +45 -0
  46. package/commands/vector/progress.md +24 -0
  47. package/commands/vector/quick.md +47 -0
  48. package/commands/vector/reapply-patches.md +123 -0
  49. package/commands/vector/remove-phase.md +31 -0
  50. package/commands/vector/research-phase.md +190 -0
  51. package/commands/vector/resume-work.md +40 -0
  52. package/commands/vector/set-profile.md +12 -0
  53. package/commands/vector/settings.md +36 -0
  54. package/commands/vector/stats.md +18 -0
  55. package/commands/vector/ui-phase.md +34 -0
  56. package/commands/vector/ui-review.md +32 -0
  57. package/commands/vector/update.md +37 -0
  58. package/commands/vector/validate-phase.md +35 -0
  59. package/commands/vector/verify-work.md +38 -0
  60. package/core/bin/lib/commands.cjs +641 -0
  61. package/core/bin/lib/commands.cjs.map +1 -0
  62. package/core/bin/lib/commands.cts +712 -0
  63. package/core/bin/lib/commands.d.cts +23 -0
  64. package/core/bin/lib/commands.d.cts.map +1 -0
  65. package/core/bin/lib/config.cjs +281 -0
  66. package/core/bin/lib/config.cjs.map +1 -0
  67. package/core/bin/lib/config.cts +301 -0
  68. package/core/bin/lib/config.d.cts +50 -0
  69. package/core/bin/lib/config.d.cts.map +1 -0
  70. package/core/bin/lib/core.cjs +483 -0
  71. package/core/bin/lib/core.cjs.map +1 -0
  72. package/core/bin/lib/core.cts +544 -0
  73. package/core/bin/lib/core.d.cts +96 -0
  74. package/core/bin/lib/core.d.cts.map +1 -0
  75. package/core/bin/lib/frontmatter.cjs +341 -0
  76. package/core/bin/lib/frontmatter.cjs.map +1 -0
  77. package/core/bin/lib/frontmatter.cts +295 -0
  78. package/core/bin/lib/frontmatter.d.cts +18 -0
  79. package/core/bin/lib/frontmatter.d.cts.map +1 -0
  80. package/core/bin/lib/init.cjs +674 -0
  81. package/core/bin/lib/init.cjs.map +1 -0
  82. package/core/bin/lib/init.cts +775 -0
  83. package/core/bin/lib/init.d.cts +16 -0
  84. package/core/bin/lib/init.d.cts.map +1 -0
  85. package/core/bin/lib/milestone.cjs +210 -0
  86. package/core/bin/lib/milestone.cjs.map +1 -0
  87. package/core/bin/lib/milestone.cts +241 -0
  88. package/core/bin/lib/milestone.d.cts +11 -0
  89. package/core/bin/lib/milestone.d.cts.map +1 -0
  90. package/core/bin/lib/model-profiles.cjs +62 -0
  91. package/core/bin/lib/model-profiles.cjs.map +1 -0
  92. package/core/bin/lib/model-profiles.cts +66 -0
  93. package/core/bin/lib/model-profiles.d.cts +33 -0
  94. package/core/bin/lib/model-profiles.d.cts.map +1 -0
  95. package/core/bin/lib/phase.cjs +713 -0
  96. package/core/bin/lib/phase.cjs.map +1 -0
  97. package/core/bin/lib/phase.cts +914 -0
  98. package/core/bin/lib/phase.d.cts +21 -0
  99. package/core/bin/lib/phase.d.cts.map +1 -0
  100. package/core/bin/lib/roadmap.cjs +246 -0
  101. package/core/bin/lib/roadmap.cjs.map +1 -0
  102. package/core/bin/lib/roadmap.cts +311 -0
  103. package/core/bin/lib/roadmap.d.cts +7 -0
  104. package/core/bin/lib/roadmap.d.cts.map +1 -0
  105. package/core/bin/lib/state.cjs +709 -0
  106. package/core/bin/lib/state.cjs.map +1 -0
  107. package/core/bin/lib/state.cts +718 -0
  108. package/core/bin/lib/state.d.cts +47 -0
  109. package/core/bin/lib/state.d.cts.map +1 -0
  110. package/core/bin/lib/template.cjs +220 -0
  111. package/core/bin/lib/template.cjs.map +1 -0
  112. package/core/bin/lib/template.cts +229 -0
  113. package/core/bin/lib/template.d.cts +15 -0
  114. package/core/bin/lib/template.d.cts.map +1 -0
  115. package/core/bin/lib/verify.cjs +824 -0
  116. package/core/bin/lib/verify.cjs.map +1 -0
  117. package/core/bin/lib/verify.cts +829 -0
  118. package/core/bin/lib/verify.d.cts +17 -0
  119. package/core/bin/lib/verify.d.cts.map +1 -0
  120. package/core/bin/vector-tools.cjs +641 -0
  121. package/core/bin/vector-tools.cjs.map +1 -0
  122. package/core/bin/vector-tools.cts +603 -0
  123. package/core/bin/vector-tools.d.cts +128 -0
  124. package/core/bin/vector-tools.d.cts.map +1 -0
  125. package/core/references/checkpoints.md +776 -0
  126. package/core/references/continuation-format.md +249 -0
  127. package/core/references/decimal-phase-calculation.md +65 -0
  128. package/core/references/git-integration.md +248 -0
  129. package/core/references/git-planning-commit.md +38 -0
  130. package/core/references/model-profile-resolution.md +36 -0
  131. package/core/references/model-profiles.md +101 -0
  132. package/core/references/phase-argument-parsing.md +61 -0
  133. package/core/references/planning-config.md +200 -0
  134. package/core/references/questioning.md +162 -0
  135. package/core/references/tdd.md +263 -0
  136. package/core/references/ui-brand.md +160 -0
  137. package/core/references/verification-patterns.md +612 -0
  138. package/core/templates/DEBUG.md +164 -0
  139. package/core/templates/UAT.md +247 -0
  140. package/core/templates/UI-SPEC.md +100 -0
  141. package/core/templates/VALIDATION.md +76 -0
  142. package/core/templates/codebase/architecture.md +255 -0
  143. package/core/templates/codebase/concerns.md +310 -0
  144. package/core/templates/codebase/conventions.md +307 -0
  145. package/core/templates/codebase/integrations.md +280 -0
  146. package/core/templates/codebase/stack.md +186 -0
  147. package/core/templates/codebase/structure.md +285 -0
  148. package/core/templates/codebase/testing.md +480 -0
  149. package/core/templates/config.json +37 -0
  150. package/core/templates/context.md +352 -0
  151. package/core/templates/continue-here.md +78 -0
  152. package/core/templates/copilot-instructions.md +7 -0
  153. package/core/templates/debug-subagent-prompt.md +91 -0
  154. package/core/templates/discovery.md +146 -0
  155. package/core/templates/milestone-archive.md +123 -0
  156. package/core/templates/milestone.md +115 -0
  157. package/core/templates/phase-prompt.md +610 -0
  158. package/core/templates/planner-subagent-prompt.md +117 -0
  159. package/core/templates/project.md +184 -0
  160. package/core/templates/requirements.md +231 -0
  161. package/core/templates/research-project/ARCHITECTURE.md +204 -0
  162. package/core/templates/research-project/FEATURES.md +147 -0
  163. package/core/templates/research-project/PITFALLS.md +200 -0
  164. package/core/templates/research-project/STACK.md +120 -0
  165. package/core/templates/research-project/SUMMARY.md +170 -0
  166. package/core/templates/research.md +552 -0
  167. package/core/templates/retrospective.md +54 -0
  168. package/core/templates/roadmap.md +202 -0
  169. package/core/templates/state.md +176 -0
  170. package/core/templates/summary-complex.md +59 -0
  171. package/core/templates/summary-minimal.md +41 -0
  172. package/core/templates/summary-standard.md +48 -0
  173. package/core/templates/summary.md +248 -0
  174. package/core/templates/user-setup.md +311 -0
  175. package/core/templates/verification-report.md +322 -0
  176. package/core/workflows/add-phase.md +112 -0
  177. package/core/workflows/add-tests.md +351 -0
  178. package/core/workflows/add-todo.md +158 -0
  179. package/core/workflows/audit-milestone.md +332 -0
  180. package/core/workflows/autonomous.md +743 -0
  181. package/core/workflows/check-todos.md +177 -0
  182. package/core/workflows/cleanup.md +152 -0
  183. package/core/workflows/complete-milestone.md +766 -0
  184. package/core/workflows/diagnose-issues.md +219 -0
  185. package/core/workflows/discovery-phase.md +289 -0
  186. package/core/workflows/discuss-phase.md +762 -0
  187. package/core/workflows/do.md +104 -0
  188. package/core/workflows/execute-phase.md +468 -0
  189. package/core/workflows/execute-plan.md +483 -0
  190. package/core/workflows/health.md +159 -0
  191. package/core/workflows/help.md +513 -0
  192. package/core/workflows/insert-phase.md +130 -0
  193. package/core/workflows/list-phase-assumptions.md +178 -0
  194. package/core/workflows/map-codebase.md +316 -0
  195. package/core/workflows/new-milestone.md +386 -0
  196. package/core/workflows/new-project.md +1113 -0
  197. package/core/workflows/node-repair.md +92 -0
  198. package/core/workflows/pause-work.md +122 -0
  199. package/core/workflows/plan-milestone-gaps.md +274 -0
  200. package/core/workflows/plan-phase.md +666 -0
  201. package/core/workflows/progress.md +382 -0
  202. package/core/workflows/quick.md +717 -0
  203. package/core/workflows/remove-phase.md +155 -0
  204. package/core/workflows/research-phase.md +74 -0
  205. package/core/workflows/resume-project.md +307 -0
  206. package/core/workflows/settings.md +243 -0
  207. package/core/workflows/stats.md +60 -0
  208. package/core/workflows/transition.md +544 -0
  209. package/core/workflows/ui-phase.md +290 -0
  210. package/core/workflows/ui-review.md +157 -0
  211. package/core/workflows/update.md +320 -0
  212. package/core/workflows/validate-phase.md +167 -0
  213. package/core/workflows/verify-phase.md +243 -0
  214. package/core/workflows/verify-work.md +584 -0
  215. package/package.json +55 -0
  216. package/scripts/build-hooks.cjs +38 -0
  217. package/scripts/build-hooks.cjs.map +1 -0
  218. package/scripts/build-hooks.cts +41 -0
  219. package/scripts/build-hooks.d.cts +6 -0
  220. package/scripts/build-hooks.d.cts.map +1 -0
  221. package/scripts/run-tests.cjs +28 -0
  222. package/scripts/run-tests.cjs.map +1 -0
  223. package/scripts/run-tests.cts +28 -0
  224. package/scripts/run-tests.d.cts +3 -0
  225. package/scripts/run-tests.d.cts.map +1 -0
@@ -0,0 +1,2907 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const os_1 = __importDefault(require("os"));
10
+ const readline_1 = __importDefault(require("readline"));
11
+ const crypto_1 = __importDefault(require("crypto"));
12
+ const package_json_1 = __importDefault(require("../package.json"));
13
+ // Colors
14
+ const cyan = '\x1b[36m';
15
+ const green = '\x1b[32m';
16
+ const yellow = '\x1b[33m';
17
+ const dim = '\x1b[2m';
18
+ const reset = '\x1b[0m';
19
+ // Codex config.toml constants
20
+ const GSD_CODEX_MARKER = '# Vector Agent Configuration \u2014 managed by core installer';
21
+ // Copilot instructions marker constants
22
+ const GSD_COPILOT_INSTRUCTIONS_MARKER = '<!-- Vector Configuration \u2014 managed by core installer -->';
23
+ const GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER = '<!-- /Vector Configuration -->';
24
+ const CODEX_AGENT_SANDBOX = {
25
+ 'vector-executor': 'workspace-write',
26
+ 'vector-planner': 'workspace-write',
27
+ 'vector-phase-researcher': 'workspace-write',
28
+ 'vector-project-researcher': 'workspace-write',
29
+ 'vector-research-synthesizer': 'workspace-write',
30
+ 'vector-verifier': 'workspace-write',
31
+ 'vector-codebase-mapper': 'workspace-write',
32
+ 'vector-roadmapper': 'workspace-write',
33
+ 'vector-debugger': 'workspace-write',
34
+ 'vector-plan-checker': 'read-only',
35
+ 'vector-integration-checker': 'read-only',
36
+ };
37
+ // Copilot tool name mapping — Claude Code tools to GitHub Copilot tools
38
+ // Tool mapping applies ONLY to agents, NOT to skills (per CONTEXT.md decision)
39
+ const claudeToCopilotTools = {
40
+ Read: 'read',
41
+ Write: 'edit',
42
+ Edit: 'edit',
43
+ Bash: 'execute',
44
+ Grep: 'search',
45
+ Glob: 'search',
46
+ Task: 'agent',
47
+ WebSearch: 'web',
48
+ WebFetch: 'web',
49
+ TodoWrite: 'todo',
50
+ AskUserQuestion: 'ask_user',
51
+ SlashCommand: 'skill',
52
+ };
53
+ // pkg imported at top of file
54
+ // Parse args
55
+ const args = process.argv.slice(2);
56
+ const hasGlobal = args.includes('--global') || args.includes('-g');
57
+ const hasLocal = args.includes('--local') || args.includes('-l');
58
+ const hasOpencode = args.includes('--opencode');
59
+ const hasClaude = args.includes('--claude');
60
+ const hasGemini = args.includes('--gemini');
61
+ const hasCodex = args.includes('--codex');
62
+ const hasCopilot = args.includes('--copilot');
63
+ const hasAntigravity = args.includes('--antigravity');
64
+ const hasBoth = args.includes('--both'); // Legacy flag, keeps working
65
+ const hasAll = args.includes('--all');
66
+ const hasUninstall = args.includes('--uninstall') || args.includes('-u');
67
+ // Runtime selection - can be set by flags or interactive prompt
68
+ let selectedRuntimes = [];
69
+ if (hasAll) {
70
+ selectedRuntimes = ['claude', 'opencode', 'gemini', 'codex', 'copilot', 'antigravity'];
71
+ }
72
+ else if (hasBoth) {
73
+ selectedRuntimes = ['claude', 'opencode'];
74
+ }
75
+ else {
76
+ if (hasOpencode)
77
+ selectedRuntimes.push('opencode');
78
+ if (hasClaude)
79
+ selectedRuntimes.push('claude');
80
+ if (hasGemini)
81
+ selectedRuntimes.push('gemini');
82
+ if (hasCodex)
83
+ selectedRuntimes.push('codex');
84
+ if (hasCopilot)
85
+ selectedRuntimes.push('copilot');
86
+ if (hasAntigravity)
87
+ selectedRuntimes.push('antigravity');
88
+ }
89
+ // WSL + Windows Node.js detection
90
+ // When Windows-native Node runs on WSL, os.homedir() and path.join() produce
91
+ // backslash paths that don't resolve correctly on the Linux filesystem.
92
+ if (process.platform === 'win32') {
93
+ let isWSL = false;
94
+ try {
95
+ if (process.env.WSL_DISTRO_NAME) {
96
+ isWSL = true;
97
+ }
98
+ else if (fs_1.default.existsSync('/proc/version')) {
99
+ const procVersion = fs_1.default.readFileSync('/proc/version', 'utf8').toLowerCase();
100
+ if (procVersion.includes('microsoft') || procVersion.includes('wsl')) {
101
+ isWSL = true;
102
+ }
103
+ }
104
+ }
105
+ catch {
106
+ // Ignore read errors — not WSL
107
+ }
108
+ if (isWSL) {
109
+ console.error(`
110
+ ${yellow}⚠ Detected WSL with Windows-native Node.js.${reset}
111
+
112
+ This causes path resolution issues that prevent correct installation.
113
+ Please install a Linux-native Node.js inside WSL:
114
+
115
+ curl -fsSL https://fnm.vercel.app/install | bash
116
+ fnm install --lts
117
+
118
+ Then re-run: npx vector@latest
119
+ `);
120
+ process.exit(1);
121
+ }
122
+ }
123
+ // Helper to get directory name for a runtime (used for local/project installs)
124
+ function getDirName(runtime) {
125
+ if (runtime === 'copilot')
126
+ return '.github';
127
+ if (runtime === 'opencode')
128
+ return '.opencode';
129
+ if (runtime === 'gemini')
130
+ return '.gemini';
131
+ if (runtime === 'codex')
132
+ return '.codex';
133
+ if (runtime === 'antigravity')
134
+ return '.agent';
135
+ return '.claude';
136
+ }
137
+ /**
138
+ * Get the config directory path relative to home directory for a runtime
139
+ * Used for templating hooks that use path.join(homeDir, '<configDir>', ...)
140
+ * @param {string} runtime - 'claude', 'opencode', 'gemini', 'codex', or 'copilot'
141
+ * @param {boolean} isGlobal - Whether this is a global install
142
+ */
143
+ function getConfigDirFromHome(runtime, isGlobal) {
144
+ if (!isGlobal) {
145
+ // Local installs use the same dir name pattern
146
+ return `'${getDirName(runtime)}'`;
147
+ }
148
+ // Global installs - OpenCode uses XDG path structure
149
+ if (runtime === 'copilot')
150
+ return "'.copilot'";
151
+ if (runtime === 'opencode') {
152
+ // OpenCode: ~/.config/opencode -> '.config', 'opencode'
153
+ // Return as comma-separated for path.join() replacement
154
+ return "'.config', 'opencode'";
155
+ }
156
+ if (runtime === 'gemini')
157
+ return "'.gemini'";
158
+ if (runtime === 'codex')
159
+ return "'.codex'";
160
+ if (runtime === 'antigravity') {
161
+ if (!isGlobal)
162
+ return "'.agent'";
163
+ return "'.gemini', 'antigravity'";
164
+ }
165
+ return "'.claude'";
166
+ }
167
+ /**
168
+ * Get the global config directory for OpenCode
169
+ * OpenCode follows XDG Base Directory spec and uses ~/.config/opencode/
170
+ * Priority: OPENCODE_CONFIG_DIR > dirname(OPENCODE_CONFIG) > XDG_CONFIG_HOME/opencode > ~/.config/opencode
171
+ */
172
+ function getOpencodeGlobalDir() {
173
+ // 1. Explicit OPENCODE_CONFIG_DIR env var
174
+ if (process.env.OPENCODE_CONFIG_DIR) {
175
+ return expandTilde(process.env.OPENCODE_CONFIG_DIR);
176
+ }
177
+ // 2. OPENCODE_CONFIG env var (use its directory)
178
+ if (process.env.OPENCODE_CONFIG) {
179
+ return path_1.default.dirname(expandTilde(process.env.OPENCODE_CONFIG));
180
+ }
181
+ // 3. XDG_CONFIG_HOME/opencode
182
+ if (process.env.XDG_CONFIG_HOME) {
183
+ return path_1.default.join(expandTilde(process.env.XDG_CONFIG_HOME), 'opencode');
184
+ }
185
+ // 4. Default: ~/.config/opencode (XDG default)
186
+ return path_1.default.join(os_1.default.homedir(), '.config', 'opencode');
187
+ }
188
+ /**
189
+ * Get the global config directory for a runtime
190
+ * @param {string} runtime - 'claude', 'opencode', 'gemini', 'codex', or 'copilot'
191
+ * @param {string|null} explicitDir - Explicit directory from --config-dir flag
192
+ */
193
+ function getGlobalDir(runtime, explicitDir = null) {
194
+ if (runtime === 'opencode') {
195
+ // For OpenCode, --config-dir overrides env vars
196
+ if (explicitDir) {
197
+ return expandTilde(explicitDir);
198
+ }
199
+ return getOpencodeGlobalDir();
200
+ }
201
+ if (runtime === 'gemini') {
202
+ // Gemini: --config-dir > GEMINI_CONFIG_DIR > ~/.gemini
203
+ if (explicitDir) {
204
+ return expandTilde(explicitDir);
205
+ }
206
+ if (process.env.GEMINI_CONFIG_DIR) {
207
+ return expandTilde(process.env.GEMINI_CONFIG_DIR);
208
+ }
209
+ return path_1.default.join(os_1.default.homedir(), '.gemini');
210
+ }
211
+ if (runtime === 'codex') {
212
+ // Codex: --config-dir > CODEX_HOME > ~/.codex
213
+ if (explicitDir) {
214
+ return expandTilde(explicitDir);
215
+ }
216
+ if (process.env.CODEX_HOME) {
217
+ return expandTilde(process.env.CODEX_HOME);
218
+ }
219
+ return path_1.default.join(os_1.default.homedir(), '.codex');
220
+ }
221
+ if (runtime === 'copilot') {
222
+ // Copilot: --config-dir > COPILOT_CONFIG_DIR > ~/.copilot
223
+ if (explicitDir) {
224
+ return expandTilde(explicitDir);
225
+ }
226
+ if (process.env.COPILOT_CONFIG_DIR) {
227
+ return expandTilde(process.env.COPILOT_CONFIG_DIR);
228
+ }
229
+ return path_1.default.join(os_1.default.homedir(), '.copilot');
230
+ }
231
+ if (runtime === 'antigravity') {
232
+ // Antigravity: --config-dir > ANTIGRAVITY_CONFIG_DIR > ~/.gemini/antigravity
233
+ if (explicitDir) {
234
+ return expandTilde(explicitDir);
235
+ }
236
+ if (process.env.ANTIGRAVITY_CONFIG_DIR) {
237
+ return expandTilde(process.env.ANTIGRAVITY_CONFIG_DIR);
238
+ }
239
+ return path_1.default.join(os_1.default.homedir(), '.gemini', 'antigravity');
240
+ }
241
+ // Claude Code: --config-dir > CLAUDE_CONFIG_DIR > ~/.claude
242
+ if (explicitDir) {
243
+ return expandTilde(explicitDir);
244
+ }
245
+ if (process.env.CLAUDE_CONFIG_DIR) {
246
+ return expandTilde(process.env.CLAUDE_CONFIG_DIR);
247
+ }
248
+ return path_1.default.join(os_1.default.homedir(), '.claude');
249
+ }
250
+ const banner = '\n' +
251
+ cyan + ' ██████╗ ███████╗██████╗\n' +
252
+ ' ██╔════╝ ██╔════╝██╔══██╗\n' +
253
+ ' ██║ ███╗███████╗██║ ██║\n' +
254
+ ' ██║ ██║╚════██║██║ ██║\n' +
255
+ ' ╚██████╔╝███████║██████╔╝\n' +
256
+ ' ╚═════╝ ╚══════╝╚═════╝' + reset + '\n' +
257
+ '\n' +
258
+ ' Vector ' + dim + 'v' + package_json_1.default.version + reset + '\n' +
259
+ ' A meta-prompting, context engineering and spec-driven\n' +
260
+ ' development system for Claude Code, OpenCode, Gemini, Codex, Copilot, and Antigravity by TÂCHES.\n';
261
+ // Parse --config-dir argument
262
+ function parseConfigDirArg() {
263
+ const configDirIndex = args.findIndex(arg => arg === '--config-dir' || arg === '-c');
264
+ if (configDirIndex !== -1) {
265
+ const nextArg = args[configDirIndex + 1];
266
+ // Error if --config-dir is provided without a value or next arg is another flag
267
+ if (!nextArg || nextArg.startsWith('-')) {
268
+ console.error(` ${yellow}--config-dir requires a path argument${reset}`);
269
+ process.exit(1);
270
+ }
271
+ return nextArg;
272
+ }
273
+ // Also handle --config-dir=value format
274
+ const configDirArg = args.find(arg => arg.startsWith('--config-dir=') || arg.startsWith('-c='));
275
+ if (configDirArg) {
276
+ const value = configDirArg.split('=')[1];
277
+ if (!value) {
278
+ console.error(` ${yellow}--config-dir requires a non-empty path${reset}`);
279
+ process.exit(1);
280
+ }
281
+ return value;
282
+ }
283
+ return null;
284
+ }
285
+ const explicitConfigDir = parseConfigDirArg();
286
+ const hasHelp = args.includes('--help') || args.includes('-h');
287
+ const forceStatusline = args.includes('--force-statusline');
288
+ console.log(banner);
289
+ if (hasUninstall) {
290
+ console.log(' Mode: Uninstall\n');
291
+ }
292
+ // Show help if requested
293
+ if (hasHelp) {
294
+ console.log(` ${yellow}Usage:${reset} npx vector [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}--codex${reset} Install for Codex only\n ${cyan}--copilot${reset} Install for Copilot only\n ${cyan}--antigravity${reset} Install for Antigravity only\n ${cyan}--all${reset} Install for all runtimes\n ${cyan}-u, --uninstall${reset} Uninstall Vector (remove all Vector 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 vector\n\n ${dim}# Install for Claude Code globally${reset}\n npx vector --claude --global\n\n ${dim}# Install for Gemini globally${reset}\n npx vector --gemini --global\n\n ${dim}# Install for Codex globally${reset}\n npx vector --codex --global\n\n ${dim}# Install for Copilot globally${reset}\n npx vector --copilot --global\n\n ${dim}# Install for Copilot locally${reset}\n npx vector --copilot --local\n\n ${dim}# Install for Antigravity globally${reset}\n npx vector --antigravity --global\n\n ${dim}# Install for Antigravity locally${reset}\n npx vector --antigravity --local\n\n ${dim}# Install for all runtimes globally${reset}\n npx vector --all --global\n\n ${dim}# Install to custom config directory${reset}\n npx vector --codex --global --config-dir ~/.codex-work\n\n ${dim}# Install to current project only${reset}\n npx vector --claude --local\n\n ${dim}# Uninstall Vector from Codex globally${reset}\n npx vector --codex --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 / CODEX_HOME / COPILOT_CONFIG_DIR / ANTIGRAVITY_CONFIG_DIR environment variables.\n`);
295
+ process.exit(0);
296
+ }
297
+ /**
298
+ * Expand ~ to home directory (shell doesn't expand in env vars passed to node)
299
+ */
300
+ function expandTilde(filePath) {
301
+ if (filePath && filePath.startsWith('~/')) {
302
+ return path_1.default.join(os_1.default.homedir(), filePath.slice(2));
303
+ }
304
+ return filePath;
305
+ }
306
+ /**
307
+ * Build a hook command path using forward slashes for cross-platform compatibility.
308
+ * On Windows, $HOME is not expanded by cmd.exe/PowerShell, so we use the actual path.
309
+ */
310
+ function buildHookCommand(configDir, hookName) {
311
+ // Use forward slashes for Node.js compatibility on all platforms
312
+ const hooksPath = configDir.replace(/\\/g, '/') + '/hooks/' + hookName;
313
+ return `node "${hooksPath}"`;
314
+ }
315
+ /**
316
+ * Resolve the opencode config file path, preferring .jsonc if it exists.
317
+ */
318
+ function resolveOpencodeConfigPath(configDir) {
319
+ const jsoncPath = path_1.default.join(configDir, 'opencode.jsonc');
320
+ if (fs_1.default.existsSync(jsoncPath)) {
321
+ return jsoncPath;
322
+ }
323
+ return path_1.default.join(configDir, 'opencode.json');
324
+ }
325
+ /**
326
+ * Read and parse settings.json, returning empty object if it doesn't exist
327
+ */
328
+ function readSettings(settingsPath) {
329
+ if (fs_1.default.existsSync(settingsPath)) {
330
+ try {
331
+ return JSON.parse(fs_1.default.readFileSync(settingsPath, 'utf8'));
332
+ }
333
+ catch (e) {
334
+ return {};
335
+ }
336
+ }
337
+ return {};
338
+ }
339
+ /**
340
+ * Write settings.json with proper formatting
341
+ */
342
+ function writeSettings(settingsPath, settings) {
343
+ fs_1.default.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
344
+ }
345
+ // Cache for attribution settings (populated once per runtime during install)
346
+ const attributionCache = new Map();
347
+ /**
348
+ * Get commit attribution setting for a runtime
349
+ * @param {string} runtime - 'claude', 'opencode', 'gemini', 'codex', or 'copilot'
350
+ * @returns {null|undefined|string} null = remove, undefined = keep default, string = custom
351
+ */
352
+ function getCommitAttribution(runtime) {
353
+ // Return cached value if available
354
+ if (attributionCache.has(runtime)) {
355
+ return attributionCache.get(runtime);
356
+ }
357
+ let result;
358
+ if (runtime === 'opencode') {
359
+ const config = readSettings(resolveOpencodeConfigPath(getGlobalDir('opencode', null)));
360
+ result = config.disable_ai_attribution === true ? null : undefined;
361
+ }
362
+ else if (runtime === 'gemini') {
363
+ // Gemini: check gemini settings.json for attribution config
364
+ const settings = readSettings(path_1.default.join(getGlobalDir('gemini', explicitConfigDir), 'settings.json'));
365
+ const attribution = settings.attribution;
366
+ if (!attribution || attribution.commit === undefined) {
367
+ result = undefined;
368
+ }
369
+ else if (attribution.commit === '') {
370
+ result = null;
371
+ }
372
+ else {
373
+ result = attribution.commit;
374
+ }
375
+ }
376
+ else if (runtime === 'claude') {
377
+ // Claude Code
378
+ const settings = readSettings(path_1.default.join(getGlobalDir('claude', explicitConfigDir), 'settings.json'));
379
+ const attribution = settings.attribution;
380
+ if (!attribution || attribution.commit === undefined) {
381
+ result = undefined;
382
+ }
383
+ else if (attribution.commit === '') {
384
+ result = null;
385
+ }
386
+ else {
387
+ result = attribution.commit;
388
+ }
389
+ }
390
+ else {
391
+ // Codex and Copilot currently have no attribution setting equivalent
392
+ result = undefined;
393
+ }
394
+ // Cache and return
395
+ attributionCache.set(runtime, result);
396
+ return result;
397
+ }
398
+ /**
399
+ * Process Co-Authored-By lines based on attribution setting
400
+ * @param {string} content - File content to process
401
+ * @param {null|undefined|string} attribution - null=remove, undefined=keep, string=replace
402
+ * @returns {string} Processed content
403
+ */
404
+ function processAttribution(content, attribution) {
405
+ if (attribution === null) {
406
+ // Remove Co-Authored-By lines and the preceding blank line
407
+ return content.replace(/(\r?\n){2}Co-Authored-By:.*$/gim, '');
408
+ }
409
+ if (attribution === undefined) {
410
+ return content;
411
+ }
412
+ // Replace with custom attribution (escape $ to prevent backreference injection)
413
+ const safeAttribution = attribution.replace(/\$/g, '$$$$');
414
+ return content.replace(/Co-Authored-By:.*$/gim, `Co-Authored-By: ${safeAttribution}`);
415
+ }
416
+ /**
417
+ * Convert Claude Code frontmatter to opencode format
418
+ * - Converts 'allowed-tools:' array to 'permission:' object
419
+ * @param {string} content - Markdown file content with YAML frontmatter
420
+ * @returns {string} - Content with converted frontmatter
421
+ */
422
+ // Color name to hex mapping for opencode compatibility
423
+ const colorNameToHex = {
424
+ cyan: '#00FFFF',
425
+ red: '#FF0000',
426
+ green: '#00FF00',
427
+ blue: '#0000FF',
428
+ yellow: '#FFFF00',
429
+ magenta: '#FF00FF',
430
+ orange: '#FFA500',
431
+ purple: '#800080',
432
+ pink: '#FFC0CB',
433
+ white: '#FFFFFF',
434
+ black: '#000000',
435
+ gray: '#808080',
436
+ grey: '#808080',
437
+ };
438
+ // Tool name mapping from Claude Code to OpenCode
439
+ // OpenCode uses lowercase tool names; special mappings for renamed tools
440
+ const claudeToOpencodeTools = {
441
+ AskUserQuestion: 'question',
442
+ SlashCommand: 'skill',
443
+ TodoWrite: 'todowrite',
444
+ WebFetch: 'webfetch',
445
+ WebSearch: 'websearch', // Plugin/MCP - keep for compatibility
446
+ };
447
+ // Tool name mapping from Claude Code to Gemini CLI
448
+ // Gemini CLI uses snake_case built-in tool names
449
+ const claudeToGeminiTools = {
450
+ Read: 'read_file',
451
+ Write: 'write_file',
452
+ Edit: 'replace',
453
+ Bash: 'run_shell_command',
454
+ Glob: 'glob',
455
+ Grep: 'search_file_content',
456
+ WebSearch: 'google_web_search',
457
+ WebFetch: 'web_fetch',
458
+ TodoWrite: 'write_todos',
459
+ AskUserQuestion: 'ask_user',
460
+ };
461
+ /**
462
+ * Convert a Claude Code tool name to OpenCode format
463
+ * - Applies special mappings (AskUserQuestion -> question, etc.)
464
+ * - Converts to lowercase (except MCP tools which keep their format)
465
+ */
466
+ function convertToolName(claudeTool) {
467
+ // Check for special mapping first
468
+ if (claudeToOpencodeTools[claudeTool]) {
469
+ return claudeToOpencodeTools[claudeTool];
470
+ }
471
+ // MCP tools (mcp__*) keep their format
472
+ if (claudeTool.startsWith('mcp__')) {
473
+ return claudeTool;
474
+ }
475
+ // Default: convert to lowercase
476
+ return claudeTool.toLowerCase();
477
+ }
478
+ /**
479
+ * Convert a Claude Code tool name to Gemini CLI format
480
+ * - Applies Claude→Gemini mapping (Read→read_file, Bash→run_shell_command, etc.)
481
+ * - Filters out MCP tools (mcp__*) — they are auto-discovered at runtime in Gemini
482
+ * - Filters out Task — agents are auto-registered as tools in Gemini
483
+ * @returns {string|null} Gemini tool name, or null if tool should be excluded
484
+ */
485
+ function convertGeminiToolName(claudeTool) {
486
+ // MCP tools: exclude — auto-discovered from mcpServers config at runtime
487
+ if (claudeTool.startsWith('mcp__')) {
488
+ return null;
489
+ }
490
+ // Task: exclude — agents are auto-registered as callable tools
491
+ if (claudeTool === 'Task') {
492
+ return null;
493
+ }
494
+ // Check for explicit mapping
495
+ if (claudeToGeminiTools[claudeTool]) {
496
+ return claudeToGeminiTools[claudeTool];
497
+ }
498
+ // Default: lowercase
499
+ return claudeTool.toLowerCase();
500
+ }
501
+ /**
502
+ * Convert a Claude Code tool name to GitHub Copilot format.
503
+ * - Applies explicit mapping from claudeToCopilotTools
504
+ * - Handles mcp__context7__* prefix → io.github.upstash/context7/*
505
+ * - Falls back to lowercase for unknown tools
506
+ */
507
+ function convertCopilotToolName(claudeTool) {
508
+ // mcp__context7__* wildcard → io.github.upstash/context7/*
509
+ if (claudeTool.startsWith('mcp__context7__')) {
510
+ return 'io.github.upstash/context7/' + claudeTool.slice('mcp__context7__'.length);
511
+ }
512
+ // Check explicit mapping
513
+ if (claudeToCopilotTools[claudeTool]) {
514
+ return claudeToCopilotTools[claudeTool];
515
+ }
516
+ // Default: lowercase
517
+ return claudeTool.toLowerCase();
518
+ }
519
+ /**
520
+ * Apply Copilot-specific content conversion — CONV-06 (paths) + CONV-07 (command names).
521
+ * Path mappings depend on install mode:
522
+ * Global: ~/.claude/ → ~/.copilot/, ./.claude/ → ./.github/
523
+ * Local: ~/.claude/ → ./.github/, ./.claude/ → ./.github/
524
+ * Applied to ALL Copilot content (skills, agents, engine files).
525
+ * @param {string} content - Source content to convert
526
+ * @param {boolean} [isGlobal=false] - Whether this is a global install
527
+ */
528
+ function convertClaudeToCopilotContent(content, isGlobal = false) {
529
+ let c = content;
530
+ // CONV-06: Path replacement — most specific first to avoid substring matches
531
+ if (isGlobal) {
532
+ c = c.replace(/\$HOME\/\.claude\//g, '$HOME/.copilot/');
533
+ c = c.replace(/~\/\.claude\//g, '~/.copilot/');
534
+ }
535
+ else {
536
+ c = c.replace(/\$HOME\/\.claude\//g, '.github/');
537
+ c = c.replace(/~\/\.claude\//g, '.github/');
538
+ }
539
+ c = c.replace(/\.\/\.claude\//g, './.github/');
540
+ c = c.replace(/\.claude\//g, '.github/');
541
+ // CONV-07: Command name conversion (all vector: references → vector-)
542
+ c = c.replace(/vector:/g, 'vector-');
543
+ return c;
544
+ }
545
+ /**
546
+ * Convert a Claude command (.md) to a Copilot skill (SKILL.md).
547
+ * Transforms frontmatter only — body passes through with CONV-06/07 applied.
548
+ * Skills keep original tool names (no mapping) per CONTEXT.md decision.
549
+ */
550
+ function convertClaudeCommandToCopilotSkill(content, skillName, isGlobal = false) {
551
+ const converted = convertClaudeToCopilotContent(content, isGlobal);
552
+ const { frontmatter, body } = extractFrontmatterAndBody(converted);
553
+ if (!frontmatter)
554
+ return converted;
555
+ const description = extractFrontmatterField(frontmatter, 'description') || '';
556
+ const argumentHint = extractFrontmatterField(frontmatter, 'argument-hint');
557
+ const agent = extractFrontmatterField(frontmatter, 'agent');
558
+ // CONV-02: Extract allowed-tools YAML multiline list → comma-separated string
559
+ const toolsMatch = frontmatter.match(/^allowed-tools:\s*\n((?:\s+-\s+.+\n?)*)/m);
560
+ let toolsLine = '';
561
+ if (toolsMatch) {
562
+ const tools = toolsMatch[1].match(/^\s+-\s+(.+)/gm);
563
+ if (tools) {
564
+ toolsLine = tools.map((t) => t.replace(/^\s+-\s+/, '').trim()).join(', ');
565
+ }
566
+ }
567
+ // Reconstruct frontmatter in Copilot format
568
+ let fm = `---\nname: ${skillName}\ndescription: ${description}\n`;
569
+ if (argumentHint)
570
+ fm += `argument-hint: ${yamlQuote(argumentHint)}\n`;
571
+ if (agent)
572
+ fm += `agent: ${agent}\n`;
573
+ if (toolsLine)
574
+ fm += `allowed-tools: ${toolsLine}\n`;
575
+ fm += '---';
576
+ return `${fm}\n${body}`;
577
+ }
578
+ /**
579
+ * Convert a Claude agent (.md) to a Copilot agent (.agent.md).
580
+ * Applies tool mapping + deduplication, formats tools as JSON array.
581
+ * CONV-04: JSON array format. CONV-05: Tool name mapping.
582
+ */
583
+ function convertClaudeAgentToCopilotAgent(content, isGlobal = false) {
584
+ const converted = convertClaudeToCopilotContent(content, isGlobal);
585
+ const { frontmatter, body } = extractFrontmatterAndBody(converted);
586
+ if (!frontmatter)
587
+ return converted;
588
+ const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
589
+ const description = extractFrontmatterField(frontmatter, 'description') || '';
590
+ const color = extractFrontmatterField(frontmatter, 'color');
591
+ const toolsRaw = extractFrontmatterField(frontmatter, 'tools') || '';
592
+ // CONV-04 + CONV-05: Map tools, deduplicate, format as JSON array
593
+ const claudeTools = toolsRaw.split(',').map((t) => t.trim()).filter(Boolean);
594
+ const mappedTools = claudeTools.map((t) => convertCopilotToolName(t));
595
+ const uniqueTools = [...new Set(mappedTools)];
596
+ const toolsArray = uniqueTools.length > 0
597
+ ? "['" + uniqueTools.join("', '") + "']"
598
+ : '[]';
599
+ // Reconstruct frontmatter in Copilot format
600
+ let fm = `---\nname: ${name}\ndescription: ${description}\ntools: ${toolsArray}\n`;
601
+ if (color)
602
+ fm += `color: ${color}\n`;
603
+ fm += '---';
604
+ return `${fm}\n${body}`;
605
+ }
606
+ /**
607
+ * Apply Antigravity-specific content conversion — path replacement + command name conversion.
608
+ * Path mappings depend on install mode:
609
+ * Global: ~/.claude/ → ~/.gemini/antigravity/, ./.claude/ → ./.agent/
610
+ * Local: ~/.claude/ → .agent/, ./.claude/ → ./.agent/
611
+ * Applied to ALL Antigravity content (skills, agents, engine files).
612
+ * @param {string} content - Source content to convert
613
+ * @param {boolean} [isGlobal=false] - Whether this is a global install
614
+ */
615
+ function convertClaudeToAntigravityContent(content, isGlobal = false) {
616
+ let c = content;
617
+ if (isGlobal) {
618
+ c = c.replace(/\$HOME\/\.claude\//g, '$HOME/.gemini/antigravity/');
619
+ c = c.replace(/~\/\.claude\//g, '~/.gemini/antigravity/');
620
+ }
621
+ else {
622
+ c = c.replace(/\$HOME\/\.claude\//g, '.agent/');
623
+ c = c.replace(/~\/\.claude\//g, '.agent/');
624
+ }
625
+ c = c.replace(/\.\/\.claude\//g, './.agent/');
626
+ c = c.replace(/\.claude\//g, '.agent/');
627
+ // Command name conversion (all vector: references → vector-)
628
+ c = c.replace(/vector:/g, 'vector-');
629
+ return c;
630
+ }
631
+ /**
632
+ * Convert a Claude command (.md) to an Antigravity skill (SKILL.md).
633
+ * Transforms frontmatter to minimal name + description only.
634
+ * Body passes through with path/command conversions applied.
635
+ */
636
+ function convertClaudeCommandToAntigravitySkill(content, skillName, isGlobal = false) {
637
+ const converted = convertClaudeToAntigravityContent(content, isGlobal);
638
+ const { frontmatter, body } = extractFrontmatterAndBody(converted);
639
+ if (!frontmatter)
640
+ return converted;
641
+ const name = skillName || extractFrontmatterField(frontmatter, 'name') || 'unknown';
642
+ const description = extractFrontmatterField(frontmatter, 'description') || '';
643
+ const fm = `---\nname: ${name}\ndescription: ${description}\n---`;
644
+ return `${fm}\n${body}`;
645
+ }
646
+ /**
647
+ * Convert a Claude agent (.md) to an Antigravity agent.
648
+ * Uses Gemini tool names since Antigravity runs on Gemini 3 backend.
649
+ */
650
+ function convertClaudeAgentToAntigravityAgent(content, isGlobal = false) {
651
+ const converted = convertClaudeToAntigravityContent(content, isGlobal);
652
+ const { frontmatter, body } = extractFrontmatterAndBody(converted);
653
+ if (!frontmatter)
654
+ return converted;
655
+ const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
656
+ const description = extractFrontmatterField(frontmatter, 'description') || '';
657
+ const color = extractFrontmatterField(frontmatter, 'color');
658
+ const toolsRaw = extractFrontmatterField(frontmatter, 'tools') || '';
659
+ // Map tools to Gemini equivalents (reuse existing convertGeminiToolName)
660
+ const claudeTools = toolsRaw.split(',').map((t) => t.trim()).filter(Boolean);
661
+ const mappedTools = claudeTools.map((t) => convertGeminiToolName(t)).filter(Boolean);
662
+ let fm = `---\nname: ${name}\ndescription: ${description}\ntools: ${mappedTools.join(', ')}\n`;
663
+ if (color)
664
+ fm += `color: ${color}\n`;
665
+ fm += '---';
666
+ return `${fm}\n${body}`;
667
+ }
668
+ function toSingleLine(value) {
669
+ return value.replace(/\s+/g, ' ').trim();
670
+ }
671
+ function yamlQuote(value) {
672
+ return JSON.stringify(value);
673
+ }
674
+ function extractFrontmatterAndBody(content) {
675
+ if (!content.startsWith('---')) {
676
+ return { frontmatter: null, body: content };
677
+ }
678
+ const endIndex = content.indexOf('---', 3);
679
+ if (endIndex === -1) {
680
+ return { frontmatter: null, body: content };
681
+ }
682
+ return {
683
+ frontmatter: content.substring(3, endIndex).trim(),
684
+ body: content.substring(endIndex + 3),
685
+ };
686
+ }
687
+ function extractFrontmatterField(frontmatter, fieldName) {
688
+ const regex = new RegExp(`^${fieldName}:\\s*(.+)$`, 'm');
689
+ const match = frontmatter.match(regex);
690
+ if (!match)
691
+ return null;
692
+ return match[1].trim().replace(/^['"]|['"]$/g, '');
693
+ }
694
+ function convertSlashCommandsToCodexSkillMentions(content) {
695
+ let converted = content.replace(/\/vector:([a-z0-9-]+)/gi, (_, commandName) => {
696
+ return `$vector-${String(commandName).toLowerCase()}`;
697
+ });
698
+ converted = converted.replace(/\/vector-help\b/g, '$vector-help');
699
+ return converted;
700
+ }
701
+ function convertClaudeToCodexMarkdown(content) {
702
+ let converted = convertSlashCommandsToCodexSkillMentions(content);
703
+ converted = converted.replace(/\$ARGUMENTS\b/g, '{{VECTOR_ARGS}}');
704
+ return converted;
705
+ }
706
+ function getCodexSkillAdapterHeader(skillName) {
707
+ const invocation = `$${skillName}`;
708
+ return `<codex_skill_adapter>
709
+ ## A. Skill Invocation
710
+ - This skill is invoked by mentioning \`${invocation}\`.
711
+ - Treat all user text after \`${invocation}\` as \`{{VECTOR_ARGS}}\`.
712
+ - If no arguments are present, treat \`{{VECTOR_ARGS}}\` as empty.
713
+
714
+ ## B. AskUserQuestion → request_user_input Mapping
715
+ Vector workflows use \`AskUserQuestion\` (Claude Code syntax). Translate to Codex \`request_user_input\`:
716
+
717
+ Parameter mapping:
718
+ - \`header\` → \`header\`
719
+ - \`question\` → \`question\`
720
+ - Options formatted as \`"Label" — description\` → \`{label: "Label", description: "description"}\`
721
+ - Generate \`id\` from header: lowercase, replace spaces with underscores
722
+
723
+ Batched calls:
724
+ - \`AskUserQuestion([q1, q2])\` → single \`request_user_input\` with multiple entries in \`questions[]\`
725
+
726
+ Multi-select workaround:
727
+ - Codex has no \`multiSelect\`. Use sequential single-selects, or present a numbered freeform list asking the user to enter comma-separated numbers.
728
+
729
+ Execute mode fallback:
730
+ - When \`request_user_input\` is rejected (Execute mode), present a plain-text numbered list and pick a reasonable default.
731
+
732
+ ## C. Task() → spawn_agent Mapping
733
+ Vector workflows use \`Task(...)\` (Claude Code syntax). Translate to Codex collaboration tools:
734
+
735
+ Direct mapping:
736
+ - \`Task(subagent_type="X", prompt="Y")\` → \`spawn_agent(agent_type="X", message="Y")\`
737
+ - \`Task(model="...")\` → omit (Codex uses per-role config, not inline model selection)
738
+ - \`fork_context: false\` by default — Vector agents load their own context via \`<files_to_read>\` blocks
739
+
740
+ Parallel fan-out:
741
+ - Spawn multiple agents → collect agent IDs → \`wait(ids)\` for all to complete
742
+
743
+ Result parsing:
744
+ - Look for structured markers in agent output: \`CHECKPOINT\`, \`PLAN COMPLETE\`, \`SUMMARY\`, etc.
745
+ - \`close_agent(id)\` after collecting results from each agent
746
+ </codex_skill_adapter>`;
747
+ }
748
+ function convertClaudeCommandToCodexSkill(content, skillName) {
749
+ const converted = convertClaudeToCodexMarkdown(content);
750
+ const { frontmatter, body } = extractFrontmatterAndBody(converted);
751
+ let description = `Run Vector workflow ${skillName}.`;
752
+ if (frontmatter) {
753
+ const maybeDescription = extractFrontmatterField(frontmatter, 'description');
754
+ if (maybeDescription) {
755
+ description = maybeDescription;
756
+ }
757
+ }
758
+ description = toSingleLine(description);
759
+ const shortDescription = description.length > 180 ? `${description.slice(0, 177)}...` : description;
760
+ const adapter = getCodexSkillAdapterHeader(skillName);
761
+ return `---\nname: ${yamlQuote(skillName)}\ndescription: ${yamlQuote(description)}\nmetadata:\n short-description: ${yamlQuote(shortDescription)}\n---\n\n${adapter}\n\n${body.trimStart()}`;
762
+ }
763
+ /**
764
+ * Convert Claude Code agent markdown to Codex agent format.
765
+ * Applies base markdown conversions, then adds a <codex_agent_role> header
766
+ * and cleans up frontmatter (removes tools/color fields).
767
+ */
768
+ function convertClaudeAgentToCodexAgent(content) {
769
+ let converted = convertClaudeToCodexMarkdown(content);
770
+ const { frontmatter, body } = extractFrontmatterAndBody(converted);
771
+ if (!frontmatter)
772
+ return converted;
773
+ const name = extractFrontmatterField(frontmatter, 'name') || 'unknown';
774
+ const description = extractFrontmatterField(frontmatter, 'description') || '';
775
+ const tools = extractFrontmatterField(frontmatter, 'tools') || '';
776
+ const roleHeader = `<codex_agent_role>
777
+ role: ${name}
778
+ tools: ${tools}
779
+ purpose: ${toSingleLine(description)}
780
+ </codex_agent_role>`;
781
+ const cleanFrontmatter = `---\nname: ${yamlQuote(name)}\ndescription: ${yamlQuote(toSingleLine(description))}\n---`;
782
+ return `${cleanFrontmatter}\n\n${roleHeader}\n${body}`;
783
+ }
784
+ /**
785
+ * Generate a per-agent .toml config file for Codex.
786
+ * Sets sandbox_mode and developer_instructions from the agent markdown body.
787
+ */
788
+ function generateCodexAgentToml(agentName, agentContent) {
789
+ const sandboxMode = CODEX_AGENT_SANDBOX[agentName] || 'read-only';
790
+ const { body } = extractFrontmatterAndBody(agentContent);
791
+ const instructions = body.trim();
792
+ const lines = [
793
+ `sandbox_mode = "${sandboxMode}"`,
794
+ // Agent prompts contain raw backslashes in regexes and shell snippets.
795
+ // TOML literal multiline strings preserve them without escape parsing.
796
+ `developer_instructions = '''`,
797
+ instructions,
798
+ `'''`,
799
+ ];
800
+ return lines.join('\n') + '\n';
801
+ }
802
+ /**
803
+ * Generate the Vector config block for Codex config.toml.
804
+ * @param {Array<{name: string, description: string}>} agents
805
+ */
806
+ function generateCodexConfigBlock(agents) {
807
+ const lines = [
808
+ GSD_CODEX_MARKER,
809
+ '',
810
+ ];
811
+ for (const { name, description } of agents) {
812
+ lines.push(`[agents.${name}]`);
813
+ lines.push(`description = ${JSON.stringify(description)}`);
814
+ lines.push(`config_file = "agents/${name}.toml"`);
815
+ lines.push('');
816
+ }
817
+ return lines.join('\n');
818
+ }
819
+ /**
820
+ * Strip Vector sections from Codex config.toml content.
821
+ * Returns cleaned content, or null if file would be empty.
822
+ */
823
+ function stripGsdFromCodexConfig(content) {
824
+ const markerIndex = content.indexOf(GSD_CODEX_MARKER);
825
+ if (markerIndex !== -1) {
826
+ // Has Vector marker — remove everything from marker to EOF
827
+ let before = content.substring(0, markerIndex).trimEnd();
828
+ // Also strip Vector-injected feature keys above the marker (Case 3 inject)
829
+ before = before.replace(/^multi_agent\s*=\s*true\s*\n?/m, '');
830
+ before = before.replace(/^default_mode_request_user_input\s*=\s*true\s*\n?/m, '');
831
+ before = before.replace(/^\[features\]\s*\n(?=\[|$)/m, '');
832
+ before = before.replace(/\n{3,}/g, '\n\n').trim();
833
+ if (!before)
834
+ return null;
835
+ return before + '\n';
836
+ }
837
+ // No marker but may have Vector-injected feature keys
838
+ let cleaned = content;
839
+ cleaned = cleaned.replace(/^multi_agent\s*=\s*true\s*\n?/m, '');
840
+ cleaned = cleaned.replace(/^default_mode_request_user_input\s*=\s*true\s*\n?/m, '');
841
+ // Remove [agents.vector-*] sections (from header to next section or EOF)
842
+ cleaned = cleaned.replace(/^\[agents\.vector-[^\]]+\]\n(?:(?!\[)[^\n]*\n?)*/gm, '');
843
+ // Remove [features] section if now empty (only header, no keys before next section)
844
+ cleaned = cleaned.replace(/^\[features\]\s*\n(?=\[|$)/m, '');
845
+ // Remove [agents] section if now empty
846
+ cleaned = cleaned.replace(/^\[agents\]\s*\n(?=\[|$)/m, '');
847
+ // Clean up excessive blank lines
848
+ cleaned = cleaned.replace(/\n{3,}/g, '\n\n').trim();
849
+ if (!cleaned)
850
+ return null;
851
+ return cleaned + '\n';
852
+ }
853
+ /**
854
+ * Merge Vector config block into an existing or new config.toml.
855
+ * Three cases: new file, existing with Vector marker, existing without marker.
856
+ */
857
+ function mergeCodexConfig(configPath, vectorBlock) {
858
+ // Case 1: No config.toml — create fresh
859
+ if (!fs_1.default.existsSync(configPath)) {
860
+ fs_1.default.writeFileSync(configPath, vectorBlock + '\n');
861
+ return;
862
+ }
863
+ const existing = fs_1.default.readFileSync(configPath, 'utf8');
864
+ const markerIndex = existing.indexOf(GSD_CODEX_MARKER);
865
+ // Case 2: Has Vector marker — truncate and re-append
866
+ if (markerIndex !== -1) {
867
+ let before = existing.substring(0, markerIndex).trimEnd();
868
+ if (before) {
869
+ // Strip any Vector-managed sections that leaked above the marker from previous installs
870
+ before = before.replace(/^\[agents\.vector-[^\]]+\]\n(?:(?!\[)[^\n]*\n?)*/gm, '');
871
+ before = before.replace(/^\[agents\]\n(?:(?!\[)[^\n]*\n?)*/m, '');
872
+ before = before.replace(/\n{3,}/g, '\n\n').trimEnd();
873
+ fs_1.default.writeFileSync(configPath, before + '\n\n' + vectorBlock + '\n');
874
+ }
875
+ else {
876
+ fs_1.default.writeFileSync(configPath, vectorBlock + '\n');
877
+ }
878
+ return;
879
+ }
880
+ // Case 3: No marker — append Vector block
881
+ let content = existing;
882
+ content = content.trimEnd() + '\n\n' + vectorBlock + '\n';
883
+ fs_1.default.writeFileSync(configPath, content);
884
+ }
885
+ /**
886
+ * Merge Vector instructions into copilot-instructions.md.
887
+ * Three cases: new file, existing with markers, existing without markers.
888
+ * @param {string} filePath - Full path to copilot-instructions.md
889
+ * @param {string} vectorContent - Template content (without markers)
890
+ */
891
+ function mergeCopilotInstructions(filePath, vectorContent) {
892
+ const vectorBlock = GSD_COPILOT_INSTRUCTIONS_MARKER + '\n' +
893
+ vectorContent.trim() + '\n' +
894
+ GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER;
895
+ // Case 1: No file — create fresh
896
+ if (!fs_1.default.existsSync(filePath)) {
897
+ fs_1.default.writeFileSync(filePath, vectorBlock + '\n');
898
+ return;
899
+ }
900
+ const existing = fs_1.default.readFileSync(filePath, 'utf8');
901
+ const openIndex = existing.indexOf(GSD_COPILOT_INSTRUCTIONS_MARKER);
902
+ const closeIndex = existing.indexOf(GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER);
903
+ // Case 2: Has Vector markers — replace between markers
904
+ if (openIndex !== -1 && closeIndex !== -1) {
905
+ const before = existing.substring(0, openIndex).trimEnd();
906
+ const after = existing.substring(closeIndex + GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER.length).trimStart();
907
+ let newContent = '';
908
+ if (before)
909
+ newContent += before + '\n\n';
910
+ newContent += vectorBlock;
911
+ if (after)
912
+ newContent += '\n\n' + after;
913
+ newContent += '\n';
914
+ fs_1.default.writeFileSync(filePath, newContent);
915
+ return;
916
+ }
917
+ // Case 3: No markers — append at end
918
+ const content = existing.trimEnd() + '\n\n' + vectorBlock + '\n';
919
+ fs_1.default.writeFileSync(filePath, content);
920
+ }
921
+ /**
922
+ * Strip Vector section from copilot-instructions.md content.
923
+ * Returns cleaned content, or null if file should be deleted (was Vector-only).
924
+ * @param {string} content - File content
925
+ * @returns {string|null} - Cleaned content or null if empty
926
+ */
927
+ function stripGsdFromCopilotInstructions(content) {
928
+ const openIndex = content.indexOf(GSD_COPILOT_INSTRUCTIONS_MARKER);
929
+ const closeIndex = content.indexOf(GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER);
930
+ if (openIndex !== -1 && closeIndex !== -1) {
931
+ const before = content.substring(0, openIndex).trimEnd();
932
+ const after = content.substring(closeIndex + GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER.length).trimStart();
933
+ const cleaned = (before + (before && after ? '\n\n' : '') + after).trim();
934
+ if (!cleaned)
935
+ return null;
936
+ return cleaned + '\n';
937
+ }
938
+ // No markers found — nothing to strip
939
+ return content;
940
+ }
941
+ /**
942
+ * Generate config.toml and per-agent .toml files for Codex.
943
+ * Reads agent .md files from source, extracts metadata, writes .toml configs.
944
+ */
945
+ function installCodexConfig(targetDir, agentsSrc) {
946
+ const configPath = path_1.default.join(targetDir, 'config.toml');
947
+ const agentsTomlDir = path_1.default.join(targetDir, 'agents');
948
+ fs_1.default.mkdirSync(agentsTomlDir, { recursive: true });
949
+ const agentEntries = fs_1.default.readdirSync(agentsSrc).filter(f => f.startsWith('vector-') && f.endsWith('.md'));
950
+ const agents = [];
951
+ // Compute the Codex Vector install path (absolute, so subagents with empty $HOME work — #820)
952
+ const codexGsdPath = `${path_1.default.resolve(targetDir, 'core').replace(/\\/g, '/')}/`;
953
+ for (const file of agentEntries) {
954
+ let content = fs_1.default.readFileSync(path_1.default.join(agentsSrc, file), 'utf8');
955
+ // Replace full .claude/core prefix so path resolves to codex Vector install
956
+ content = content.replace(/~\/\.claude\/core\//g, codexGsdPath);
957
+ content = content.replace(/\$HOME\/\.claude\/core\//g, codexGsdPath);
958
+ const { frontmatter } = extractFrontmatterAndBody(content);
959
+ const name = (frontmatter ? extractFrontmatterField(frontmatter, 'name') : null) || file.replace('.md', '');
960
+ const description = (frontmatter ? extractFrontmatterField(frontmatter, 'description') : null) || '';
961
+ agents.push({ name, description: toSingleLine(description) });
962
+ const tomlContent = generateCodexAgentToml(name, content);
963
+ fs_1.default.writeFileSync(path_1.default.join(agentsTomlDir, `${name}.toml`), tomlContent);
964
+ }
965
+ const vectorBlock = generateCodexConfigBlock(agents);
966
+ mergeCodexConfig(configPath, vectorBlock);
967
+ return agents.length;
968
+ }
969
+ /**
970
+ * Strip HTML <sub> tags for Gemini CLI output
971
+ * Terminals don't support subscript — Gemini renders these as raw HTML.
972
+ * Converts <sub>text</sub> to italic *(text)* for readable terminal output.
973
+ */
974
+ function stripSubTags(content) {
975
+ return content.replace(/<sub>(.*?)<\/sub>/g, '*($1)*');
976
+ }
977
+ /**
978
+ * Convert Claude Code agent frontmatter to Gemini CLI format
979
+ * Gemini agents use .md files with YAML frontmatter, same as Claude,
980
+ * but with different field names and formats:
981
+ * - tools: must be a YAML array (not comma-separated string)
982
+ * - tool names: must use Gemini built-in names (read_file, not Read)
983
+ * - color: must be removed (causes validation error)
984
+ * - skills: must be removed (causes validation error)
985
+ * - mcp__* tools: must be excluded (auto-discovered at runtime)
986
+ */
987
+ function convertClaudeToGeminiAgent(content) {
988
+ if (!content.startsWith('---'))
989
+ return content;
990
+ const endIndex = content.indexOf('---', 3);
991
+ if (endIndex === -1)
992
+ return content;
993
+ const frontmatter = content.substring(3, endIndex).trim();
994
+ const body = content.substring(endIndex + 3);
995
+ const lines = frontmatter.split('\n');
996
+ const newLines = [];
997
+ let inAllowedTools = false;
998
+ let inSkippedArrayField = false;
999
+ const tools = [];
1000
+ for (const line of lines) {
1001
+ const trimmed = line.trim();
1002
+ if (inSkippedArrayField) {
1003
+ if (!trimmed || trimmed.startsWith('- ')) {
1004
+ continue;
1005
+ }
1006
+ inSkippedArrayField = false;
1007
+ }
1008
+ // Convert allowed-tools YAML array to tools list
1009
+ if (trimmed.startsWith('allowed-tools:')) {
1010
+ inAllowedTools = true;
1011
+ continue;
1012
+ }
1013
+ // Handle inline tools: field (comma-separated string)
1014
+ if (trimmed.startsWith('tools:')) {
1015
+ const toolsValue = trimmed.substring(6).trim();
1016
+ if (toolsValue) {
1017
+ const parsed = toolsValue.split(',').map((t) => t.trim()).filter((t) => t);
1018
+ for (const t of parsed) {
1019
+ const mapped = convertGeminiToolName(t);
1020
+ if (mapped)
1021
+ tools.push(mapped);
1022
+ }
1023
+ }
1024
+ else {
1025
+ // tools: with no value means YAML array follows
1026
+ inAllowedTools = true;
1027
+ }
1028
+ continue;
1029
+ }
1030
+ // Strip color field (not supported by Gemini CLI, causes validation error)
1031
+ if (trimmed.startsWith('color:'))
1032
+ continue;
1033
+ // Strip skills field (not supported by Gemini CLI, causes validation error)
1034
+ if (trimmed.startsWith('skills:')) {
1035
+ inSkippedArrayField = true;
1036
+ continue;
1037
+ }
1038
+ // Collect allowed-tools/tools array items
1039
+ if (inAllowedTools) {
1040
+ if (trimmed.startsWith('- ')) {
1041
+ const mapped = convertGeminiToolName(trimmed.substring(2).trim());
1042
+ if (mapped)
1043
+ tools.push(mapped);
1044
+ continue;
1045
+ }
1046
+ else if (trimmed && !trimmed.startsWith('-')) {
1047
+ inAllowedTools = false;
1048
+ }
1049
+ }
1050
+ if (!inAllowedTools) {
1051
+ newLines.push(line);
1052
+ }
1053
+ }
1054
+ // Add tools as YAML array (Gemini requires array format)
1055
+ if (tools.length > 0) {
1056
+ newLines.push('tools:');
1057
+ for (const tool of tools) {
1058
+ newLines.push(` - ${tool}`);
1059
+ }
1060
+ }
1061
+ const newFrontmatter = newLines.join('\n').trim();
1062
+ // Escape ${VAR} patterns in agent body for Gemini CLI compatibility.
1063
+ // Gemini's templateString() treats all ${word} patterns as template variables
1064
+ // and throws "Template validation failed: Missing required input parameters"
1065
+ // when they can't be resolved. Vector agents use ${PHASE}, ${PLAN}, etc. as
1066
+ // shell variables in bash code blocks — convert to $VAR (no braces) which
1067
+ // is equivalent bash and invisible to Gemini's /\$\{(\w+)\}/g regex.
1068
+ const escapedBody = body.replace(/\$\{(\w+)\}/g, '$$$1');
1069
+ return `---\n${newFrontmatter}\n---${stripSubTags(escapedBody)}`;
1070
+ }
1071
+ function convertClaudeToOpencodeFrontmatter(content, { isAgent = false } = {}) {
1072
+ // Replace tool name references in content (applies to all files)
1073
+ let convertedContent = content;
1074
+ convertedContent = convertedContent.replace(/\bAskUserQuestion\b/g, 'question');
1075
+ convertedContent = convertedContent.replace(/\bSlashCommand\b/g, 'skill');
1076
+ convertedContent = convertedContent.replace(/\bTodoWrite\b/g, 'todowrite');
1077
+ // Replace /vector:command with /vector-command for opencode (flat command structure)
1078
+ convertedContent = convertedContent.replace(/\/vector:/g, '/vector-');
1079
+ // Replace ~/.claude and $HOME/.claude with OpenCode's config location
1080
+ convertedContent = convertedContent.replace(/~\/\.claude\b/g, '~/.config/opencode');
1081
+ convertedContent = convertedContent.replace(/\$HOME\/\.claude\b/g, '$HOME/.config/opencode');
1082
+ // Replace general-purpose subagent type with OpenCode's equivalent "general"
1083
+ convertedContent = convertedContent.replace(/subagent_type="general-purpose"/g, 'subagent_type="general"');
1084
+ // Check if content has frontmatter
1085
+ if (!convertedContent.startsWith('---')) {
1086
+ return convertedContent;
1087
+ }
1088
+ // Find the end of frontmatter
1089
+ const endIndex = convertedContent.indexOf('---', 3);
1090
+ if (endIndex === -1) {
1091
+ return convertedContent;
1092
+ }
1093
+ const frontmatter = convertedContent.substring(3, endIndex).trim();
1094
+ const body = convertedContent.substring(endIndex + 3);
1095
+ // Parse frontmatter line by line (simple YAML parsing)
1096
+ const lines = frontmatter.split('\n');
1097
+ const newLines = [];
1098
+ let inAllowedTools = false;
1099
+ let inSkippedArray = false;
1100
+ const allowedTools = [];
1101
+ for (const line of lines) {
1102
+ const trimmed = line.trim();
1103
+ // For agents: skip commented-out lines (e.g. hooks blocks)
1104
+ if (isAgent && trimmed.startsWith('#')) {
1105
+ continue;
1106
+ }
1107
+ // Detect start of allowed-tools array
1108
+ if (trimmed.startsWith('allowed-tools:')) {
1109
+ inAllowedTools = true;
1110
+ continue;
1111
+ }
1112
+ // Detect inline tools: field (comma-separated string)
1113
+ if (trimmed.startsWith('tools:')) {
1114
+ if (isAgent) {
1115
+ // Agents: strip tools entirely (not supported in OpenCode agent frontmatter)
1116
+ inSkippedArray = true;
1117
+ continue;
1118
+ }
1119
+ const toolsValue = trimmed.substring(6).trim();
1120
+ if (toolsValue) {
1121
+ // Parse comma-separated tools
1122
+ const tools = toolsValue.split(',').map((t) => t.trim()).filter((t) => t);
1123
+ allowedTools.push(...tools);
1124
+ }
1125
+ continue;
1126
+ }
1127
+ // For agents: strip skills:, color:, memory:, maxTurns:, permissionMode:, disallowedTools:
1128
+ if (isAgent && /^(skills|color|memory|maxTurns|permissionMode|disallowedTools):/.test(trimmed)) {
1129
+ inSkippedArray = true;
1130
+ continue;
1131
+ }
1132
+ // Skip continuation lines of a stripped array/object field
1133
+ if (inSkippedArray) {
1134
+ if (trimmed.startsWith('- ') || trimmed.startsWith('#') || /^\s/.test(line)) {
1135
+ continue;
1136
+ }
1137
+ inSkippedArray = false;
1138
+ }
1139
+ // For commands: remove name: field (opencode uses filename for command name)
1140
+ // For agents: keep name: (required by OpenCode agents)
1141
+ if (!isAgent && trimmed.startsWith('name:')) {
1142
+ continue;
1143
+ }
1144
+ // Convert color names to hex for opencode (commands only; agents strip color above)
1145
+ if (trimmed.startsWith('color:')) {
1146
+ const colorValue = trimmed.substring(6).trim().toLowerCase();
1147
+ const hexColor = colorNameToHex[colorValue];
1148
+ if (hexColor) {
1149
+ newLines.push(`color: "${hexColor}"`);
1150
+ }
1151
+ else if (colorValue.startsWith('#')) {
1152
+ // Validate hex color format (#RGB or #RRGGBB)
1153
+ if (/^#[0-9a-f]{3}$|^#[0-9a-f]{6}$/i.test(colorValue)) {
1154
+ // Already hex and valid, keep as is
1155
+ newLines.push(line);
1156
+ }
1157
+ // Skip invalid hex colors
1158
+ }
1159
+ // Skip unknown color names
1160
+ continue;
1161
+ }
1162
+ // Collect allowed-tools items
1163
+ if (inAllowedTools) {
1164
+ if (trimmed.startsWith('- ')) {
1165
+ allowedTools.push(trimmed.substring(2).trim());
1166
+ continue;
1167
+ }
1168
+ else if (trimmed && !trimmed.startsWith('-')) {
1169
+ // End of array, new field started
1170
+ inAllowedTools = false;
1171
+ }
1172
+ }
1173
+ // Keep other fields
1174
+ if (!inAllowedTools) {
1175
+ newLines.push(line);
1176
+ }
1177
+ }
1178
+ // For agents: add required OpenCode agent fields
1179
+ if (isAgent) {
1180
+ newLines.push('model: inherit');
1181
+ newLines.push('mode: subagent');
1182
+ }
1183
+ // For commands: add tools object if we had allowed-tools or tools
1184
+ if (!isAgent && allowedTools.length > 0) {
1185
+ newLines.push('tools:');
1186
+ for (const tool of allowedTools) {
1187
+ newLines.push(` ${convertToolName(tool)}: true`);
1188
+ }
1189
+ }
1190
+ // Rebuild frontmatter (body already has tool names converted)
1191
+ const newFrontmatter = newLines.join('\n').trim();
1192
+ return `---\n${newFrontmatter}\n---${body}`;
1193
+ }
1194
+ /**
1195
+ * Convert Claude Code markdown command to Gemini TOML format
1196
+ * @param {string} content - Markdown file content with YAML frontmatter
1197
+ * @returns {string} - TOML content
1198
+ */
1199
+ function convertClaudeToGeminiToml(content) {
1200
+ // Check if content has frontmatter
1201
+ if (!content.startsWith('---')) {
1202
+ return `prompt = ${JSON.stringify(content)}\n`;
1203
+ }
1204
+ const endIndex = content.indexOf('---', 3);
1205
+ if (endIndex === -1) {
1206
+ return `prompt = ${JSON.stringify(content)}\n`;
1207
+ }
1208
+ const frontmatter = content.substring(3, endIndex).trim();
1209
+ const body = content.substring(endIndex + 3).trim();
1210
+ // Extract description from frontmatter
1211
+ let description = '';
1212
+ const lines = frontmatter.split('\n');
1213
+ for (const line of lines) {
1214
+ const trimmed = line.trim();
1215
+ if (trimmed.startsWith('description:')) {
1216
+ description = trimmed.substring(12).trim();
1217
+ break;
1218
+ }
1219
+ }
1220
+ // Construct TOML
1221
+ let toml = '';
1222
+ if (description) {
1223
+ toml += `description = ${JSON.stringify(description)}\n`;
1224
+ }
1225
+ toml += `prompt = ${JSON.stringify(body)}\n`;
1226
+ return toml;
1227
+ }
1228
+ /**
1229
+ * Copy commands to a flat structure for OpenCode
1230
+ * OpenCode expects: command/vector-help.md (invoked as /vector-help)
1231
+ * Source structure: commands/vector/help.md
1232
+ *
1233
+ * @param {string} srcDir - Source directory (e.g., commands/vector/)
1234
+ * @param {string} destDir - Destination directory (e.g., command/)
1235
+ * @param {string} prefix - Prefix for filenames (e.g., 'vector')
1236
+ * @param {string} pathPrefix - Path prefix for file references
1237
+ * @param {string} runtime - Target runtime ('claude' or 'opencode')
1238
+ */
1239
+ function copyFlattenedCommands(srcDir, destDir, prefix, pathPrefix, runtime) {
1240
+ if (!fs_1.default.existsSync(srcDir)) {
1241
+ return;
1242
+ }
1243
+ // Remove old vector-*.md files before copying new ones
1244
+ if (fs_1.default.existsSync(destDir)) {
1245
+ for (const file of fs_1.default.readdirSync(destDir)) {
1246
+ if (file.startsWith(`${prefix}-`) && file.endsWith('.md')) {
1247
+ fs_1.default.unlinkSync(path_1.default.join(destDir, file));
1248
+ }
1249
+ }
1250
+ }
1251
+ else {
1252
+ fs_1.default.mkdirSync(destDir, { recursive: true });
1253
+ }
1254
+ const entries = fs_1.default.readdirSync(srcDir, { withFileTypes: true });
1255
+ for (const entry of entries) {
1256
+ const srcPath = path_1.default.join(srcDir, entry.name);
1257
+ if (entry.isDirectory()) {
1258
+ // Recurse into subdirectories, adding to prefix
1259
+ // e.g., commands/vector/debug/start.md -> command/vector-debug-start.md
1260
+ copyFlattenedCommands(srcPath, destDir, `${prefix}-${entry.name}`, pathPrefix, runtime);
1261
+ }
1262
+ else if (entry.name.endsWith('.md')) {
1263
+ // Flatten: help.md -> vector-help.md
1264
+ const baseName = entry.name.replace('.md', '');
1265
+ const destName = `${prefix}-${baseName}.md`;
1266
+ const destPath = path_1.default.join(destDir, destName);
1267
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1268
+ const globalClaudeRegex = /~\/\.claude\//g;
1269
+ const globalClaudeHomeRegex = /\$HOME\/\.claude\//g;
1270
+ const localClaudeRegex = /\.\/\.claude\//g;
1271
+ const opencodeDirRegex = /~\/\.opencode\//g;
1272
+ content = content.replace(globalClaudeRegex, pathPrefix);
1273
+ content = content.replace(globalClaudeHomeRegex, pathPrefix);
1274
+ content = content.replace(localClaudeRegex, `./${getDirName(runtime)}/`);
1275
+ content = content.replace(opencodeDirRegex, pathPrefix);
1276
+ content = processAttribution(content, getCommitAttribution(runtime));
1277
+ content = convertClaudeToOpencodeFrontmatter(content);
1278
+ fs_1.default.writeFileSync(destPath, content);
1279
+ }
1280
+ }
1281
+ }
1282
+ function listCodexSkillNames(skillsDir, prefix = 'vector-') {
1283
+ if (!fs_1.default.existsSync(skillsDir))
1284
+ return [];
1285
+ const entries = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1286
+ return entries
1287
+ .filter(entry => entry.isDirectory() && entry.name.startsWith(prefix))
1288
+ .filter(entry => fs_1.default.existsSync(path_1.default.join(skillsDir, entry.name, 'SKILL.md')))
1289
+ .map(entry => entry.name)
1290
+ .sort();
1291
+ }
1292
+ function copyCommandsAsCodexSkills(srcDir, skillsDir, prefix, pathPrefix, runtime) {
1293
+ if (!fs_1.default.existsSync(srcDir)) {
1294
+ return;
1295
+ }
1296
+ fs_1.default.mkdirSync(skillsDir, { recursive: true });
1297
+ // Remove previous Vector Codex skills to avoid stale command skills.
1298
+ const existing = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1299
+ for (const entry of existing) {
1300
+ if (entry.isDirectory() && entry.name.startsWith(`${prefix}-`)) {
1301
+ fs_1.default.rmSync(path_1.default.join(skillsDir, entry.name), { recursive: true });
1302
+ }
1303
+ }
1304
+ function recurse(currentSrcDir, currentPrefix) {
1305
+ const entries = fs_1.default.readdirSync(currentSrcDir, { withFileTypes: true });
1306
+ for (const entry of entries) {
1307
+ const srcPath = path_1.default.join(currentSrcDir, entry.name);
1308
+ if (entry.isDirectory()) {
1309
+ recurse(srcPath, `${currentPrefix}-${entry.name}`);
1310
+ continue;
1311
+ }
1312
+ if (!entry.name.endsWith('.md')) {
1313
+ continue;
1314
+ }
1315
+ const baseName = entry.name.replace('.md', '');
1316
+ const skillName = `${currentPrefix}-${baseName}`;
1317
+ const skillDir = path_1.default.join(skillsDir, skillName);
1318
+ fs_1.default.mkdirSync(skillDir, { recursive: true });
1319
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1320
+ const globalClaudeRegex = /~\/\.claude\//g;
1321
+ const globalClaudeHomeRegex = /\$HOME\/\.claude\//g;
1322
+ const localClaudeRegex = /\.\/\.claude\//g;
1323
+ const codexDirRegex = /~\/\.codex\//g;
1324
+ content = content.replace(globalClaudeRegex, pathPrefix);
1325
+ content = content.replace(globalClaudeHomeRegex, pathPrefix);
1326
+ content = content.replace(localClaudeRegex, `./${getDirName(runtime)}/`);
1327
+ content = content.replace(codexDirRegex, pathPrefix);
1328
+ content = processAttribution(content, getCommitAttribution(runtime));
1329
+ content = convertClaudeCommandToCodexSkill(content, skillName);
1330
+ fs_1.default.writeFileSync(path_1.default.join(skillDir, 'SKILL.md'), content);
1331
+ }
1332
+ }
1333
+ recurse(srcDir, prefix);
1334
+ }
1335
+ /**
1336
+ * Copy Claude commands as Copilot skills — one folder per skill with SKILL.md.
1337
+ * Applies CONV-01 (structure), CONV-02 (allowed-tools), CONV-06 (paths), CONV-07 (command names).
1338
+ */
1339
+ function copyCommandsAsCopilotSkills(srcDir, skillsDir, prefix, isGlobal = false) {
1340
+ if (!fs_1.default.existsSync(srcDir)) {
1341
+ return;
1342
+ }
1343
+ fs_1.default.mkdirSync(skillsDir, { recursive: true });
1344
+ // Remove previous Vector Copilot skills
1345
+ const existing = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1346
+ for (const entry of existing) {
1347
+ if (entry.isDirectory() && entry.name.startsWith(`${prefix}-`)) {
1348
+ fs_1.default.rmSync(path_1.default.join(skillsDir, entry.name), { recursive: true });
1349
+ }
1350
+ }
1351
+ function recurse(currentSrcDir, currentPrefix) {
1352
+ const entries = fs_1.default.readdirSync(currentSrcDir, { withFileTypes: true });
1353
+ for (const entry of entries) {
1354
+ const srcPath = path_1.default.join(currentSrcDir, entry.name);
1355
+ if (entry.isDirectory()) {
1356
+ recurse(srcPath, `${currentPrefix}-${entry.name}`);
1357
+ continue;
1358
+ }
1359
+ if (!entry.name.endsWith('.md')) {
1360
+ continue;
1361
+ }
1362
+ const baseName = entry.name.replace('.md', '');
1363
+ const skillName = `${currentPrefix}-${baseName}`;
1364
+ const skillDir = path_1.default.join(skillsDir, skillName);
1365
+ fs_1.default.mkdirSync(skillDir, { recursive: true });
1366
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1367
+ content = convertClaudeCommandToCopilotSkill(content, skillName, isGlobal);
1368
+ content = processAttribution(content, getCommitAttribution('copilot'));
1369
+ fs_1.default.writeFileSync(path_1.default.join(skillDir, 'SKILL.md'), content);
1370
+ }
1371
+ }
1372
+ recurse(srcDir, prefix);
1373
+ }
1374
+ /**
1375
+ * Recursively install Vector commands as Antigravity skills.
1376
+ * Each command becomes a skill-name/ folder containing SKILL.md.
1377
+ * Mirrors copyCommandsAsCopilotSkills but uses Antigravity converters.
1378
+ * @param {string} srcDir - Source commands directory
1379
+ * @param {string} skillsDir - Target skills directory
1380
+ * @param {string} prefix - Skill name prefix (e.g. 'vector')
1381
+ * @param {boolean} isGlobal - Whether this is a global install
1382
+ */
1383
+ function copyCommandsAsAntigravitySkills(srcDir, skillsDir, prefix, isGlobal = false) {
1384
+ if (!fs_1.default.existsSync(srcDir)) {
1385
+ return;
1386
+ }
1387
+ fs_1.default.mkdirSync(skillsDir, { recursive: true });
1388
+ // Remove previous Vector Antigravity skills
1389
+ const existing = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1390
+ for (const entry of existing) {
1391
+ if (entry.isDirectory() && entry.name.startsWith(`${prefix}-`)) {
1392
+ fs_1.default.rmSync(path_1.default.join(skillsDir, entry.name), { recursive: true });
1393
+ }
1394
+ }
1395
+ function recurse(currentSrcDir, currentPrefix) {
1396
+ const entries = fs_1.default.readdirSync(currentSrcDir, { withFileTypes: true });
1397
+ for (const entry of entries) {
1398
+ const srcPath = path_1.default.join(currentSrcDir, entry.name);
1399
+ if (entry.isDirectory()) {
1400
+ recurse(srcPath, `${currentPrefix}-${entry.name}`);
1401
+ continue;
1402
+ }
1403
+ if (!entry.name.endsWith('.md')) {
1404
+ continue;
1405
+ }
1406
+ const baseName = entry.name.replace('.md', '');
1407
+ const skillName = `${currentPrefix}-${baseName}`;
1408
+ const skillDir = path_1.default.join(skillsDir, skillName);
1409
+ fs_1.default.mkdirSync(skillDir, { recursive: true });
1410
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1411
+ content = convertClaudeCommandToAntigravitySkill(content, skillName, isGlobal);
1412
+ content = processAttribution(content, getCommitAttribution('antigravity'));
1413
+ fs_1.default.writeFileSync(path_1.default.join(skillDir, 'SKILL.md'), content);
1414
+ }
1415
+ }
1416
+ recurse(srcDir, prefix);
1417
+ }
1418
+ /**
1419
+ * Recursively copy directory, replacing paths in .md files
1420
+ * Deletes existing destDir first to remove orphaned files from previous versions
1421
+ * @param {string} srcDir - Source directory
1422
+ * @param {string} destDir - Destination directory
1423
+ * @param {string} pathPrefix - Path prefix for file references
1424
+ * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini', 'codex')
1425
+ */
1426
+ function copyWithPathReplacement(srcDir, destDir, pathPrefix, runtime, isCommand = false, isGlobal = false) {
1427
+ const isOpencode = runtime === 'opencode';
1428
+ const isCodex = runtime === 'codex';
1429
+ const isCopilot = runtime === 'copilot';
1430
+ const isAntigravity = runtime === 'antigravity';
1431
+ const dirName = getDirName(runtime);
1432
+ // Clean install: remove existing destination to prevent orphaned files
1433
+ if (fs_1.default.existsSync(destDir)) {
1434
+ fs_1.default.rmSync(destDir, { recursive: true });
1435
+ }
1436
+ fs_1.default.mkdirSync(destDir, { recursive: true });
1437
+ const entries = fs_1.default.readdirSync(srcDir, { withFileTypes: true });
1438
+ for (const entry of entries) {
1439
+ const srcPath = path_1.default.join(srcDir, entry.name);
1440
+ const destPath = path_1.default.join(destDir, entry.name);
1441
+ if (entry.isDirectory()) {
1442
+ copyWithPathReplacement(srcPath, destPath, pathPrefix, runtime, isCommand, isGlobal);
1443
+ }
1444
+ else if (entry.name.endsWith('.md')) {
1445
+ // Replace ~/.claude/ and $HOME/.claude/ and ./.claude/ with runtime-appropriate paths
1446
+ // Skip generic replacement for Copilot — convertClaudeToCopilotContent handles all paths
1447
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1448
+ if (!isCopilot && !isAntigravity) {
1449
+ const globalClaudeRegex = /~\/\.claude\//g;
1450
+ const globalClaudeHomeRegex = /\$HOME\/\.claude\//g;
1451
+ const localClaudeRegex = /\.\/\.claude\//g;
1452
+ content = content.replace(globalClaudeRegex, pathPrefix);
1453
+ content = content.replace(globalClaudeHomeRegex, pathPrefix);
1454
+ content = content.replace(localClaudeRegex, `./${dirName}/`);
1455
+ }
1456
+ content = processAttribution(content, getCommitAttribution(runtime));
1457
+ // Convert frontmatter for opencode compatibility
1458
+ if (isOpencode) {
1459
+ content = convertClaudeToOpencodeFrontmatter(content);
1460
+ fs_1.default.writeFileSync(destPath, content);
1461
+ }
1462
+ else if (runtime === 'gemini') {
1463
+ if (isCommand) {
1464
+ // Convert to TOML for Gemini (strip <sub> tags — terminals can't render subscript)
1465
+ content = stripSubTags(content);
1466
+ const tomlContent = convertClaudeToGeminiToml(content);
1467
+ // Replace extension with .toml
1468
+ const tomlPath = destPath.replace(/\.md$/, '.toml');
1469
+ fs_1.default.writeFileSync(tomlPath, tomlContent);
1470
+ }
1471
+ else {
1472
+ fs_1.default.writeFileSync(destPath, content);
1473
+ }
1474
+ }
1475
+ else if (isCodex) {
1476
+ content = convertClaudeToCodexMarkdown(content);
1477
+ fs_1.default.writeFileSync(destPath, content);
1478
+ }
1479
+ else if (isCopilot) {
1480
+ content = convertClaudeToCopilotContent(content, isGlobal);
1481
+ content = processAttribution(content, getCommitAttribution(runtime));
1482
+ fs_1.default.writeFileSync(destPath, content);
1483
+ }
1484
+ else if (isAntigravity) {
1485
+ content = convertClaudeToAntigravityContent(content, isGlobal);
1486
+ content = processAttribution(content, getCommitAttribution(runtime));
1487
+ fs_1.default.writeFileSync(destPath, content);
1488
+ }
1489
+ else {
1490
+ fs_1.default.writeFileSync(destPath, content);
1491
+ }
1492
+ }
1493
+ else if (isCopilot && (entry.name.endsWith('.cjs') || entry.name.endsWith('.js'))) {
1494
+ // Copilot: also transform .cjs/.js files for CONV-06 and CONV-07
1495
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1496
+ content = convertClaudeToCopilotContent(content, isGlobal);
1497
+ fs_1.default.writeFileSync(destPath, content);
1498
+ }
1499
+ else if (isAntigravity && (entry.name.endsWith('.cjs') || entry.name.endsWith('.js'))) {
1500
+ // Antigravity: also transform .cjs/.js files for path/command conversions
1501
+ let content = fs_1.default.readFileSync(srcPath, 'utf8');
1502
+ content = convertClaudeToAntigravityContent(content, isGlobal);
1503
+ fs_1.default.writeFileSync(destPath, content);
1504
+ }
1505
+ else {
1506
+ fs_1.default.copyFileSync(srcPath, destPath);
1507
+ }
1508
+ }
1509
+ }
1510
+ /**
1511
+ * Clean up orphaned files from previous Vector versions
1512
+ */
1513
+ function cleanupOrphanedFiles(configDir) {
1514
+ const orphanedFiles = [
1515
+ 'hooks/vector-notify.sh', // Removed in v1.6.x
1516
+ 'hooks/statusline.js', // Renamed to vector-statusline.js in v1.9.0
1517
+ ];
1518
+ for (const relPath of orphanedFiles) {
1519
+ const fullPath = path_1.default.join(configDir, relPath);
1520
+ if (fs_1.default.existsSync(fullPath)) {
1521
+ fs_1.default.unlinkSync(fullPath);
1522
+ console.log(` ${green}✓${reset} Removed orphaned ${relPath}`);
1523
+ }
1524
+ }
1525
+ }
1526
+ /**
1527
+ * Clean up orphaned hook registrations from settings.json
1528
+ */
1529
+ function cleanupOrphanedHooks(settings) {
1530
+ const orphanedHookPatterns = [
1531
+ 'vector-notify.sh', // Removed in v1.6.x
1532
+ 'hooks/statusline.js', // Renamed to vector-statusline.js in v1.9.0
1533
+ 'vector-intel-index.js', // Removed in v1.9.2
1534
+ 'vector-intel-session.js', // Removed in v1.9.2
1535
+ 'vector-intel-prune.js', // Removed in v1.9.2
1536
+ ];
1537
+ let cleanedHooks = false;
1538
+ // Check all hook event types (Stop, SessionStart, etc.)
1539
+ if (settings.hooks) {
1540
+ const hooks = settings.hooks;
1541
+ for (const eventType of Object.keys(hooks)) {
1542
+ const hookEntries = hooks[eventType];
1543
+ if (Array.isArray(hookEntries)) {
1544
+ // Filter out entries that contain orphaned hooks
1545
+ const filtered = hookEntries.filter(entry => {
1546
+ const e = entry;
1547
+ if (e.hooks && Array.isArray(e.hooks)) {
1548
+ // Check if any hook in this entry matches orphaned patterns
1549
+ const hasOrphaned = e.hooks.some((h) => h.command && orphanedHookPatterns.some(pattern => h.command.includes(pattern)));
1550
+ if (hasOrphaned) {
1551
+ cleanedHooks = true;
1552
+ return false; // Remove this entry
1553
+ }
1554
+ }
1555
+ return true; // Keep this entry
1556
+ });
1557
+ hooks[eventType] = filtered;
1558
+ }
1559
+ }
1560
+ }
1561
+ if (cleanedHooks) {
1562
+ console.log(` ${green}✓${reset} Removed orphaned hook registrations`);
1563
+ }
1564
+ // Fix #330: Update statusLine if it points to old Vector statusline.js path
1565
+ // Only match the specific old Vector path pattern (hooks/statusline.js),
1566
+ // not third-party statusline scripts that happen to contain 'statusline.js'
1567
+ const statusLine = settings.statusLine;
1568
+ if (statusLine && statusLine.command &&
1569
+ /hooks[\/\\]statusline\.js/.test(statusLine.command)) {
1570
+ statusLine.command = statusLine.command.replace(/hooks([\/\\])statusline\.js/, 'hooks$1vector-statusline.js');
1571
+ console.log(` ${green}✓${reset} Updated statusline path (hooks/statusline.js → hooks/vector-statusline.js)`);
1572
+ }
1573
+ return settings;
1574
+ }
1575
+ /**
1576
+ * Uninstall Vector from the specified directory for a specific runtime
1577
+ * Removes only Vector-specific files/directories, preserves user content
1578
+ * @param {boolean} isGlobal - Whether to uninstall from global or local
1579
+ * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini', 'codex', 'copilot')
1580
+ */
1581
+ function uninstall(isGlobal, runtime = 'claude') {
1582
+ const isOpencode = runtime === 'opencode';
1583
+ const isCodex = runtime === 'codex';
1584
+ const isCopilot = runtime === 'copilot';
1585
+ const isAntigravity = runtime === 'antigravity';
1586
+ const dirName = getDirName(runtime);
1587
+ // Get the target directory based on runtime and install type
1588
+ const targetDir = isGlobal
1589
+ ? getGlobalDir(runtime, explicitConfigDir)
1590
+ : path_1.default.join(process.cwd(), dirName);
1591
+ const locationLabel = isGlobal
1592
+ ? targetDir.replace(os_1.default.homedir(), '~')
1593
+ : targetDir.replace(process.cwd(), '.');
1594
+ let runtimeLabel = 'Claude Code';
1595
+ if (runtime === 'opencode')
1596
+ runtimeLabel = 'OpenCode';
1597
+ if (runtime === 'gemini')
1598
+ runtimeLabel = 'Gemini';
1599
+ if (runtime === 'codex')
1600
+ runtimeLabel = 'Codex';
1601
+ if (runtime === 'copilot')
1602
+ runtimeLabel = 'Copilot';
1603
+ if (runtime === 'antigravity')
1604
+ runtimeLabel = 'Antigravity';
1605
+ console.log(` Uninstalling Vector from ${cyan}${runtimeLabel}${reset} at ${cyan}${locationLabel}${reset}\n`);
1606
+ // Check if target directory exists
1607
+ if (!fs_1.default.existsSync(targetDir)) {
1608
+ console.log(` ${yellow}⚠${reset} Directory does not exist: ${locationLabel}`);
1609
+ console.log(` Nothing to uninstall.\n`);
1610
+ return;
1611
+ }
1612
+ let removedCount = 0;
1613
+ // 1. Remove Vector commands/skills
1614
+ if (isOpencode) {
1615
+ // OpenCode: remove command/vector-*.md files
1616
+ const commandDir = path_1.default.join(targetDir, 'command');
1617
+ if (fs_1.default.existsSync(commandDir)) {
1618
+ const files = fs_1.default.readdirSync(commandDir);
1619
+ for (const file of files) {
1620
+ if (file.startsWith('vector-') && file.endsWith('.md')) {
1621
+ fs_1.default.unlinkSync(path_1.default.join(commandDir, file));
1622
+ removedCount++;
1623
+ }
1624
+ }
1625
+ console.log(` ${green}✓${reset} Removed Vector commands from command/`);
1626
+ }
1627
+ }
1628
+ else if (isCodex) {
1629
+ // Codex: remove skills/vector-*/SKILL.md skill directories
1630
+ const skillsDir = path_1.default.join(targetDir, 'skills');
1631
+ if (fs_1.default.existsSync(skillsDir)) {
1632
+ let skillCount = 0;
1633
+ const entries = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1634
+ for (const entry of entries) {
1635
+ if (entry.isDirectory() && entry.name.startsWith('vector-')) {
1636
+ fs_1.default.rmSync(path_1.default.join(skillsDir, entry.name), { recursive: true });
1637
+ skillCount++;
1638
+ }
1639
+ }
1640
+ if (skillCount > 0) {
1641
+ removedCount++;
1642
+ console.log(` ${green}✓${reset} Removed ${skillCount} Codex skills`);
1643
+ }
1644
+ }
1645
+ // Codex: remove Vector agent .toml config files
1646
+ const codexAgentsDir = path_1.default.join(targetDir, 'agents');
1647
+ if (fs_1.default.existsSync(codexAgentsDir)) {
1648
+ const tomlFiles = fs_1.default.readdirSync(codexAgentsDir);
1649
+ let tomlCount = 0;
1650
+ for (const file of tomlFiles) {
1651
+ if (file.startsWith('vector-') && file.endsWith('.toml')) {
1652
+ fs_1.default.unlinkSync(path_1.default.join(codexAgentsDir, file));
1653
+ tomlCount++;
1654
+ }
1655
+ }
1656
+ if (tomlCount > 0) {
1657
+ removedCount++;
1658
+ console.log(` ${green}✓${reset} Removed ${tomlCount} agent .toml configs`);
1659
+ }
1660
+ }
1661
+ // Codex: clean Vector sections from config.toml
1662
+ const configPath = path_1.default.join(targetDir, 'config.toml');
1663
+ if (fs_1.default.existsSync(configPath)) {
1664
+ const content = fs_1.default.readFileSync(configPath, 'utf8');
1665
+ const cleaned = stripGsdFromCodexConfig(content);
1666
+ if (cleaned === null) {
1667
+ // File is empty after stripping — delete it
1668
+ fs_1.default.unlinkSync(configPath);
1669
+ removedCount++;
1670
+ console.log(` ${green}✓${reset} Removed config.toml (was Vector-only)`);
1671
+ }
1672
+ else if (cleaned !== content) {
1673
+ fs_1.default.writeFileSync(configPath, cleaned);
1674
+ removedCount++;
1675
+ console.log(` ${green}✓${reset} Cleaned Vector sections from config.toml`);
1676
+ }
1677
+ }
1678
+ }
1679
+ else if (isCopilot) {
1680
+ // Copilot: remove skills/vector-/ directories (same layout as Codex skills)
1681
+ const skillsDir = path_1.default.join(targetDir, 'skills');
1682
+ if (fs_1.default.existsSync(skillsDir)) {
1683
+ let skillCount = 0;
1684
+ const entries = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1685
+ for (const entry of entries) {
1686
+ if (entry.isDirectory() && entry.name.startsWith('vector-')) {
1687
+ fs_1.default.rmSync(path_1.default.join(skillsDir, entry.name), { recursive: true });
1688
+ skillCount++;
1689
+ }
1690
+ }
1691
+ if (skillCount > 0) {
1692
+ removedCount++;
1693
+ console.log(` ${green}✓${reset} Removed ${skillCount} Copilot skills`);
1694
+ }
1695
+ }
1696
+ // Copilot: clean Vector section from copilot-instructions.md
1697
+ const instructionsPath = path_1.default.join(targetDir, 'copilot-instructions.md');
1698
+ if (fs_1.default.existsSync(instructionsPath)) {
1699
+ const content = fs_1.default.readFileSync(instructionsPath, 'utf8');
1700
+ const cleaned = stripGsdFromCopilotInstructions(content);
1701
+ if (cleaned === null) {
1702
+ fs_1.default.unlinkSync(instructionsPath);
1703
+ removedCount++;
1704
+ console.log(` ${green}✓${reset} Removed copilot-instructions.md (was Vector-only)`);
1705
+ }
1706
+ else if (cleaned !== content) {
1707
+ fs_1.default.writeFileSync(instructionsPath, cleaned);
1708
+ removedCount++;
1709
+ console.log(` ${green}✓${reset} Cleaned Vector section from copilot-instructions.md`);
1710
+ }
1711
+ }
1712
+ }
1713
+ else if (isAntigravity) {
1714
+ // Antigravity: remove skills/vector-/ directories (same layout as Copilot skills)
1715
+ const skillsDir = path_1.default.join(targetDir, 'skills');
1716
+ if (fs_1.default.existsSync(skillsDir)) {
1717
+ let skillCount = 0;
1718
+ const entries = fs_1.default.readdirSync(skillsDir, { withFileTypes: true });
1719
+ for (const entry of entries) {
1720
+ if (entry.isDirectory() && entry.name.startsWith('vector-')) {
1721
+ fs_1.default.rmSync(path_1.default.join(skillsDir, entry.name), { recursive: true });
1722
+ skillCount++;
1723
+ }
1724
+ }
1725
+ if (skillCount > 0) {
1726
+ removedCount++;
1727
+ console.log(` ${green}✓${reset} Removed ${skillCount} Antigravity skills`);
1728
+ }
1729
+ }
1730
+ }
1731
+ else {
1732
+ const vectorCommandsDir = path_1.default.join(targetDir, 'commands', 'vector');
1733
+ if (fs_1.default.existsSync(vectorCommandsDir)) {
1734
+ fs_1.default.rmSync(vectorCommandsDir, { recursive: true });
1735
+ removedCount++;
1736
+ console.log(` ${green}✓${reset} Removed commands/vector/`);
1737
+ }
1738
+ }
1739
+ // 2. Remove core directory
1740
+ const vectorDir = path_1.default.join(targetDir, 'core');
1741
+ if (fs_1.default.existsSync(vectorDir)) {
1742
+ fs_1.default.rmSync(vectorDir, { recursive: true });
1743
+ removedCount++;
1744
+ console.log(` ${green}✓${reset} Removed core/`);
1745
+ }
1746
+ // 3. Remove Vector agents (vector-*.md files only)
1747
+ const agentsDir = path_1.default.join(targetDir, 'agents');
1748
+ if (fs_1.default.existsSync(agentsDir)) {
1749
+ const files = fs_1.default.readdirSync(agentsDir);
1750
+ let agentCount = 0;
1751
+ for (const file of files) {
1752
+ if (file.startsWith('vector-') && file.endsWith('.md')) {
1753
+ fs_1.default.unlinkSync(path_1.default.join(agentsDir, file));
1754
+ agentCount++;
1755
+ }
1756
+ }
1757
+ if (agentCount > 0) {
1758
+ removedCount++;
1759
+ console.log(` ${green}✓${reset} Removed ${agentCount} Vector agents`);
1760
+ }
1761
+ }
1762
+ // 4. Remove Vector hooks
1763
+ const hooksDir = path_1.default.join(targetDir, 'hooks');
1764
+ if (fs_1.default.existsSync(hooksDir)) {
1765
+ const vectorHooks = ['vector-statusline.js', 'vector-check-update.js', 'vector-check-update.sh', 'vector-context-monitor.js'];
1766
+ let hookCount = 0;
1767
+ for (const hook of vectorHooks) {
1768
+ const hookPath = path_1.default.join(hooksDir, hook);
1769
+ if (fs_1.default.existsSync(hookPath)) {
1770
+ fs_1.default.unlinkSync(hookPath);
1771
+ hookCount++;
1772
+ }
1773
+ }
1774
+ if (hookCount > 0) {
1775
+ removedCount++;
1776
+ console.log(` ${green}✓${reset} Removed ${hookCount} Vector hooks`);
1777
+ }
1778
+ }
1779
+ // 5. Remove Vector package.json (CommonJS mode marker)
1780
+ const pkgJsonPath = path_1.default.join(targetDir, 'package.json');
1781
+ if (fs_1.default.existsSync(pkgJsonPath)) {
1782
+ try {
1783
+ const content = fs_1.default.readFileSync(pkgJsonPath, 'utf8').trim();
1784
+ // Only remove if it's our minimal CommonJS marker
1785
+ if (content === '{"type":"commonjs"}') {
1786
+ fs_1.default.unlinkSync(pkgJsonPath);
1787
+ removedCount++;
1788
+ console.log(` ${green}✓${reset} Removed Vector package.json`);
1789
+ }
1790
+ }
1791
+ catch (e) {
1792
+ // Ignore read errors
1793
+ }
1794
+ }
1795
+ // 6. Clean up settings.json (remove Vector hooks and statusline)
1796
+ const settingsPath = path_1.default.join(targetDir, 'settings.json');
1797
+ if (fs_1.default.existsSync(settingsPath)) {
1798
+ const settings = readSettings(settingsPath);
1799
+ let settingsModified = false;
1800
+ // Remove Vector statusline if it references our hook
1801
+ const settingsStatusLine = settings.statusLine;
1802
+ if (settingsStatusLine && settingsStatusLine.command &&
1803
+ settingsStatusLine.command.includes('vector-statusline')) {
1804
+ delete settings.statusLine;
1805
+ settingsModified = true;
1806
+ console.log(` ${green}✓${reset} Removed Vector statusline from settings`);
1807
+ }
1808
+ // Remove Vector hooks from SessionStart
1809
+ const settingsHooks = settings.hooks;
1810
+ if (settingsHooks && settingsHooks.SessionStart) {
1811
+ const before = settingsHooks.SessionStart.length;
1812
+ settingsHooks.SessionStart = settingsHooks.SessionStart.filter(entry => {
1813
+ const e = entry;
1814
+ if (e.hooks && Array.isArray(e.hooks)) {
1815
+ // Filter out Vector hooks
1816
+ const hasGsdHook = e.hooks.some((h) => h.command && (h.command.includes('vector-check-update') || h.command.includes('vector-statusline')));
1817
+ return !hasGsdHook;
1818
+ }
1819
+ return true;
1820
+ });
1821
+ if (settingsHooks.SessionStart.length < before) {
1822
+ settingsModified = true;
1823
+ console.log(` ${green}✓${reset} Removed Vector hooks from settings`);
1824
+ }
1825
+ // Clean up empty array
1826
+ if (settingsHooks.SessionStart.length === 0) {
1827
+ delete settingsHooks.SessionStart;
1828
+ }
1829
+ }
1830
+ // Remove Vector hooks from PostToolUse and AfterTool (Gemini uses AfterTool)
1831
+ for (const eventName of ['PostToolUse', 'AfterTool']) {
1832
+ if (settingsHooks && settingsHooks[eventName]) {
1833
+ const before = settingsHooks[eventName].length;
1834
+ settingsHooks[eventName] = settingsHooks[eventName].filter(entry => {
1835
+ const e = entry;
1836
+ if (e.hooks && Array.isArray(e.hooks)) {
1837
+ const hasGsdHook = e.hooks.some((h) => h.command && h.command.includes('vector-context-monitor'));
1838
+ return !hasGsdHook;
1839
+ }
1840
+ return true;
1841
+ });
1842
+ if (settingsHooks[eventName].length < before) {
1843
+ settingsModified = true;
1844
+ console.log(` ${green}✓${reset} Removed context monitor hook from settings`);
1845
+ }
1846
+ if (settingsHooks[eventName].length === 0) {
1847
+ delete settingsHooks[eventName];
1848
+ }
1849
+ }
1850
+ }
1851
+ // Clean up empty hooks object
1852
+ if (settingsHooks && Object.keys(settingsHooks).length === 0) {
1853
+ delete settings.hooks;
1854
+ }
1855
+ if (settingsModified) {
1856
+ writeSettings(settingsPath, settings);
1857
+ removedCount++;
1858
+ }
1859
+ }
1860
+ // 6. For OpenCode, clean up permissions from opencode.json or opencode.jsonc
1861
+ if (isOpencode) {
1862
+ const opencodeConfigDir = isGlobal
1863
+ ? getOpencodeGlobalDir()
1864
+ : path_1.default.join(process.cwd(), '.opencode');
1865
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir);
1866
+ if (fs_1.default.existsSync(configPath)) {
1867
+ try {
1868
+ const config = parseJsonc(fs_1.default.readFileSync(configPath, 'utf8'));
1869
+ let modified = false;
1870
+ // Remove Vector permission entries
1871
+ if (config.permission) {
1872
+ const permission = config.permission;
1873
+ for (const permType of ['read', 'external_directory']) {
1874
+ if (permission[permType]) {
1875
+ const keys = Object.keys(permission[permType]);
1876
+ for (const key of keys) {
1877
+ if (key.includes('core')) {
1878
+ delete permission[permType][key];
1879
+ modified = true;
1880
+ }
1881
+ }
1882
+ // Clean up empty objects
1883
+ if (Object.keys(permission[permType]).length === 0) {
1884
+ delete permission[permType];
1885
+ }
1886
+ }
1887
+ }
1888
+ if (Object.keys(permission).length === 0) {
1889
+ delete config.permission;
1890
+ }
1891
+ }
1892
+ if (modified) {
1893
+ fs_1.default.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
1894
+ removedCount++;
1895
+ console.log(` ${green}✓${reset} Removed Vector permissions from ${path_1.default.basename(configPath)}`);
1896
+ }
1897
+ }
1898
+ catch (e) {
1899
+ // Ignore JSON parse errors
1900
+ }
1901
+ }
1902
+ }
1903
+ if (removedCount === 0) {
1904
+ console.log(` ${yellow}⚠${reset} No Vector files found to remove.`);
1905
+ }
1906
+ console.log(`
1907
+ ${green}Done!${reset} Vector has been uninstalled from ${runtimeLabel}.
1908
+ Your other files and settings have been preserved.
1909
+ `);
1910
+ }
1911
+ /**
1912
+ * Parse JSONC (JSON with Comments) by stripping comments and trailing commas.
1913
+ * OpenCode supports JSONC format via jsonc-parser, so users may have comments.
1914
+ * This is a lightweight inline parser to avoid adding dependencies.
1915
+ */
1916
+ function parseJsonc(content) {
1917
+ // Strip BOM if present
1918
+ if (content.charCodeAt(0) === 0xFEFF) {
1919
+ content = content.slice(1);
1920
+ }
1921
+ // Remove single-line and block comments while preserving strings
1922
+ let result = '';
1923
+ let inString = false;
1924
+ let i = 0;
1925
+ while (i < content.length) {
1926
+ const char = content[i];
1927
+ const next = content[i + 1];
1928
+ if (inString) {
1929
+ result += char;
1930
+ // Handle escape sequences
1931
+ if (char === '\\' && i + 1 < content.length) {
1932
+ result += next;
1933
+ i += 2;
1934
+ continue;
1935
+ }
1936
+ if (char === '"') {
1937
+ inString = false;
1938
+ }
1939
+ i++;
1940
+ }
1941
+ else {
1942
+ if (char === '"') {
1943
+ inString = true;
1944
+ result += char;
1945
+ i++;
1946
+ }
1947
+ else if (char === '/' && next === '/') {
1948
+ // Skip single-line comment until end of line
1949
+ while (i < content.length && content[i] !== '\n') {
1950
+ i++;
1951
+ }
1952
+ }
1953
+ else if (char === '/' && next === '*') {
1954
+ // Skip block comment
1955
+ i += 2;
1956
+ while (i < content.length - 1 && !(content[i] === '*' && content[i + 1] === '/')) {
1957
+ i++;
1958
+ }
1959
+ i += 2; // Skip closing */
1960
+ }
1961
+ else {
1962
+ result += char;
1963
+ i++;
1964
+ }
1965
+ }
1966
+ }
1967
+ // Remove trailing commas before } or ]
1968
+ result = result.replace(/,(\s*[}\]])/g, '$1');
1969
+ return JSON.parse(result);
1970
+ }
1971
+ /**
1972
+ * Configure OpenCode permissions to allow reading Vector reference docs
1973
+ * This prevents permission prompts when Vector accesses the core directory
1974
+ * @param {boolean} isGlobal - Whether this is a global or local install
1975
+ */
1976
+ function configureOpencodePermissions(isGlobal = true) {
1977
+ // For local installs, use ./.opencode/
1978
+ // For global installs, use ~/.config/opencode/
1979
+ const opencodeConfigDir = isGlobal
1980
+ ? getOpencodeGlobalDir()
1981
+ : path_1.default.join(process.cwd(), '.opencode');
1982
+ // Ensure config directory exists
1983
+ fs_1.default.mkdirSync(opencodeConfigDir, { recursive: true });
1984
+ const configPath = resolveOpencodeConfigPath(opencodeConfigDir);
1985
+ // Read existing config or create empty object
1986
+ let config = {};
1987
+ if (fs_1.default.existsSync(configPath)) {
1988
+ try {
1989
+ const content = fs_1.default.readFileSync(configPath, 'utf8');
1990
+ config = parseJsonc(content);
1991
+ }
1992
+ catch (e) {
1993
+ // Cannot parse - DO NOT overwrite user's config
1994
+ const configFile = path_1.default.basename(configPath);
1995
+ console.log(` ${yellow}⚠${reset} Could not parse ${configFile} - skipping permission config`);
1996
+ console.log(` ${dim}Reason: ${e.message}${reset}`);
1997
+ console.log(` ${dim}Your config was NOT modified. Fix the syntax manually if needed.${reset}`);
1998
+ return;
1999
+ }
2000
+ }
2001
+ // Ensure permission structure exists
2002
+ if (!config.permission) {
2003
+ config.permission = {};
2004
+ }
2005
+ const permission = config.permission;
2006
+ // Build the Vector path using the actual config directory
2007
+ // Use ~ shorthand if it's in the default location, otherwise use full path
2008
+ const defaultConfigDir = path_1.default.join(os_1.default.homedir(), '.config', 'opencode');
2009
+ const vectorPath = opencodeConfigDir === defaultConfigDir
2010
+ ? '~/.config/opencode/core/*'
2011
+ : `${opencodeConfigDir.replace(/\\/g, '/')}/core/*`;
2012
+ let modified = false;
2013
+ // Configure read permission
2014
+ if (!permission.read || typeof permission.read !== 'object') {
2015
+ permission.read = {};
2016
+ }
2017
+ if (permission.read[vectorPath] !== 'allow') {
2018
+ permission.read[vectorPath] = 'allow';
2019
+ modified = true;
2020
+ }
2021
+ // Configure external_directory permission (the safety guard for paths outside project)
2022
+ if (!permission.external_directory || typeof permission.external_directory !== 'object') {
2023
+ permission.external_directory = {};
2024
+ }
2025
+ if (permission.external_directory[vectorPath] !== 'allow') {
2026
+ permission.external_directory[vectorPath] = 'allow';
2027
+ modified = true;
2028
+ }
2029
+ if (!modified) {
2030
+ return; // Already configured
2031
+ }
2032
+ // Write config back
2033
+ fs_1.default.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
2034
+ console.log(` ${green}✓${reset} Configured read permission for Vector docs`);
2035
+ }
2036
+ /**
2037
+ * Verify a directory exists and contains files
2038
+ */
2039
+ function verifyInstalled(dirPath, description) {
2040
+ if (!fs_1.default.existsSync(dirPath)) {
2041
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: directory not created`);
2042
+ return false;
2043
+ }
2044
+ try {
2045
+ const entries = fs_1.default.readdirSync(dirPath);
2046
+ if (entries.length === 0) {
2047
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: directory is empty`);
2048
+ return false;
2049
+ }
2050
+ }
2051
+ catch (e) {
2052
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: ${e.message}`);
2053
+ return false;
2054
+ }
2055
+ return true;
2056
+ }
2057
+ /**
2058
+ * Verify a file exists
2059
+ */
2060
+ function verifyFileInstalled(filePath, description) {
2061
+ if (!fs_1.default.existsSync(filePath)) {
2062
+ console.error(` ${yellow}✗${reset} Failed to install ${description}: file not created`);
2063
+ return false;
2064
+ }
2065
+ return true;
2066
+ }
2067
+ /**
2068
+ * Install to the specified directory for a specific runtime
2069
+ * @param {boolean} isGlobal - Whether to install globally or locally
2070
+ * @param {string} runtime - Target runtime ('claude', 'opencode', 'gemini', 'codex')
2071
+ */
2072
+ // ──────────────────────────────────────────────────────
2073
+ // Local Patch Persistence
2074
+ // ──────────────────────────────────────────────────────
2075
+ const PATCHES_DIR_NAME = 'vector-local-patches';
2076
+ const MANIFEST_NAME = 'vector-file-manifest.json';
2077
+ /**
2078
+ * Compute SHA256 hash of file contents
2079
+ */
2080
+ function fileHash(filePath) {
2081
+ const content = fs_1.default.readFileSync(filePath);
2082
+ return crypto_1.default.createHash('sha256').update(content).digest('hex');
2083
+ }
2084
+ /**
2085
+ * Recursively collect all files in dir with their hashes
2086
+ */
2087
+ function generateManifest(dir, baseDir) {
2088
+ if (!baseDir)
2089
+ baseDir = dir;
2090
+ const manifest = {};
2091
+ if (!fs_1.default.existsSync(dir))
2092
+ return manifest;
2093
+ const entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
2094
+ for (const entry of entries) {
2095
+ const fullPath = path_1.default.join(dir, entry.name);
2096
+ const relPath = path_1.default.relative(baseDir, fullPath).replace(/\\/g, '/');
2097
+ if (entry.isDirectory()) {
2098
+ Object.assign(manifest, generateManifest(fullPath, baseDir));
2099
+ }
2100
+ else {
2101
+ manifest[relPath] = fileHash(fullPath);
2102
+ }
2103
+ }
2104
+ return manifest;
2105
+ }
2106
+ /**
2107
+ * Write file manifest after installation for future modification detection
2108
+ */
2109
+ function writeManifest(configDir, runtime = 'claude') {
2110
+ const isOpencode = runtime === 'opencode';
2111
+ const isCodex = runtime === 'codex';
2112
+ const isCopilot = runtime === 'copilot';
2113
+ const isAntigravity = runtime === 'antigravity';
2114
+ const vectorDir = path_1.default.join(configDir, 'core');
2115
+ const commandsDir = path_1.default.join(configDir, 'commands', 'vector');
2116
+ const opencodeCommandDir = path_1.default.join(configDir, 'command');
2117
+ const codexSkillsDir = path_1.default.join(configDir, 'skills');
2118
+ const agentsDir = path_1.default.join(configDir, 'agents');
2119
+ const manifest = { version: package_json_1.default.version, timestamp: new Date().toISOString(), files: {} };
2120
+ const vectorHashes = generateManifest(vectorDir);
2121
+ for (const [rel, hash] of Object.entries(vectorHashes)) {
2122
+ manifest.files['core/' + rel] = hash;
2123
+ }
2124
+ if (!isOpencode && !isCodex && !isCopilot && !isAntigravity && fs_1.default.existsSync(commandsDir)) {
2125
+ const cmdHashes = generateManifest(commandsDir);
2126
+ for (const [rel, hash] of Object.entries(cmdHashes)) {
2127
+ manifest.files['commands/vector/' + rel] = hash;
2128
+ }
2129
+ }
2130
+ if (isOpencode && fs_1.default.existsSync(opencodeCommandDir)) {
2131
+ for (const file of fs_1.default.readdirSync(opencodeCommandDir)) {
2132
+ if (file.startsWith('vector-') && file.endsWith('.md')) {
2133
+ manifest.files['command/' + file] = fileHash(path_1.default.join(opencodeCommandDir, file));
2134
+ }
2135
+ }
2136
+ }
2137
+ if ((isCodex || isCopilot || isAntigravity) && fs_1.default.existsSync(codexSkillsDir)) {
2138
+ for (const skillName of listCodexSkillNames(codexSkillsDir)) {
2139
+ const skillRoot = path_1.default.join(codexSkillsDir, skillName);
2140
+ const skillHashes = generateManifest(skillRoot);
2141
+ for (const [rel, hash] of Object.entries(skillHashes)) {
2142
+ manifest.files[`skills/${skillName}/${rel}`] = hash;
2143
+ }
2144
+ }
2145
+ }
2146
+ if (fs_1.default.existsSync(agentsDir)) {
2147
+ for (const file of fs_1.default.readdirSync(agentsDir)) {
2148
+ if (file.startsWith('vector-') && file.endsWith('.md')) {
2149
+ manifest.files['agents/' + file] = fileHash(path_1.default.join(agentsDir, file));
2150
+ }
2151
+ }
2152
+ }
2153
+ fs_1.default.writeFileSync(path_1.default.join(configDir, MANIFEST_NAME), JSON.stringify(manifest, null, 2));
2154
+ return manifest;
2155
+ }
2156
+ /**
2157
+ * Detect user-modified Vector files by comparing against install manifest.
2158
+ * Backs up modified files to vector-local-patches/ for reapply after update.
2159
+ */
2160
+ function saveLocalPatches(configDir) {
2161
+ const manifestPath = path_1.default.join(configDir, MANIFEST_NAME);
2162
+ if (!fs_1.default.existsSync(manifestPath))
2163
+ return [];
2164
+ let manifest;
2165
+ try {
2166
+ manifest = JSON.parse(fs_1.default.readFileSync(manifestPath, 'utf8'));
2167
+ }
2168
+ catch {
2169
+ return [];
2170
+ }
2171
+ const patchesDir = path_1.default.join(configDir, PATCHES_DIR_NAME);
2172
+ const modified = [];
2173
+ for (const [relPath, originalHash] of Object.entries(manifest.files || {})) {
2174
+ const fullPath = path_1.default.join(configDir, relPath);
2175
+ if (!fs_1.default.existsSync(fullPath))
2176
+ continue;
2177
+ const currentHash = fileHash(fullPath);
2178
+ if (currentHash !== originalHash) {
2179
+ const backupPath = path_1.default.join(patchesDir, relPath);
2180
+ fs_1.default.mkdirSync(path_1.default.dirname(backupPath), { recursive: true });
2181
+ fs_1.default.copyFileSync(fullPath, backupPath);
2182
+ modified.push(relPath);
2183
+ }
2184
+ }
2185
+ if (modified.length > 0) {
2186
+ const meta = {
2187
+ backed_up_at: new Date().toISOString(),
2188
+ from_version: manifest.version,
2189
+ files: modified
2190
+ };
2191
+ fs_1.default.writeFileSync(path_1.default.join(patchesDir, 'backup-meta.json'), JSON.stringify(meta, null, 2));
2192
+ console.log(' ' + yellow + 'i' + reset + ' Found ' + modified.length + ' locally modified Vector file(s) — backed up to ' + PATCHES_DIR_NAME + '/');
2193
+ for (const f of modified) {
2194
+ console.log(' ' + dim + f + reset);
2195
+ }
2196
+ }
2197
+ return modified;
2198
+ }
2199
+ /**
2200
+ * After install, report backed-up patches for user to reapply.
2201
+ */
2202
+ function reportLocalPatches(configDir, runtime = 'claude') {
2203
+ const patchesDir = path_1.default.join(configDir, PATCHES_DIR_NAME);
2204
+ const metaPath = path_1.default.join(patchesDir, 'backup-meta.json');
2205
+ if (!fs_1.default.existsSync(metaPath))
2206
+ return [];
2207
+ let meta;
2208
+ try {
2209
+ meta = JSON.parse(fs_1.default.readFileSync(metaPath, 'utf8'));
2210
+ }
2211
+ catch {
2212
+ return [];
2213
+ }
2214
+ if (meta.files && meta.files.length > 0) {
2215
+ const reapplyCommand = (runtime === 'opencode' || runtime === 'copilot')
2216
+ ? '/vector-reapply-patches'
2217
+ : runtime === 'codex'
2218
+ ? '$vector-reapply-patches'
2219
+ : '/vector:reapply-patches';
2220
+ console.log('');
2221
+ console.log(' ' + yellow + 'Local patches detected' + reset + ' (from v' + meta.from_version + '):');
2222
+ for (const f of meta.files) {
2223
+ console.log(' ' + cyan + f + reset);
2224
+ }
2225
+ console.log('');
2226
+ console.log(' Your modifications are saved in ' + cyan + PATCHES_DIR_NAME + '/' + reset);
2227
+ console.log(' Run ' + cyan + reapplyCommand + reset + ' to merge them into the new version.');
2228
+ console.log(' Or manually compare and merge the files.');
2229
+ console.log('');
2230
+ }
2231
+ return meta.files || [];
2232
+ }
2233
+ function install(isGlobal, runtime = 'claude') {
2234
+ const isOpencode = runtime === 'opencode';
2235
+ const isGemini = runtime === 'gemini';
2236
+ const isCodex = runtime === 'codex';
2237
+ const isCopilot = runtime === 'copilot';
2238
+ const isAntigravity = runtime === 'antigravity';
2239
+ const dirName = getDirName(runtime);
2240
+ const src = path_1.default.join(__dirname, '..');
2241
+ // Get the target directory based on runtime and install type
2242
+ const targetDir = isGlobal
2243
+ ? getGlobalDir(runtime, explicitConfigDir)
2244
+ : path_1.default.join(process.cwd(), dirName);
2245
+ const locationLabel = isGlobal
2246
+ ? targetDir.replace(os_1.default.homedir(), '~')
2247
+ : targetDir.replace(process.cwd(), '.');
2248
+ // Path prefix for file references in markdown content (e.g. vector-tools.cjs).
2249
+ // Replaces $HOME/.claude/ or ~/.claude/ so the result is <pathPrefix>core/bin/...
2250
+ // Always use absolute path so: (1) local installs work when Vector is outside $HOME,
2251
+ // (2) spawned subagents with empty $HOME still resolve the path (fixes #820).
2252
+ const pathPrefix = `${path_1.default.resolve(targetDir).replace(/\\/g, '/')}/`;
2253
+ let runtimeLabel = 'Claude Code';
2254
+ if (isOpencode)
2255
+ runtimeLabel = 'OpenCode';
2256
+ if (isGemini)
2257
+ runtimeLabel = 'Gemini';
2258
+ if (isCodex)
2259
+ runtimeLabel = 'Codex';
2260
+ if (isCopilot)
2261
+ runtimeLabel = 'Copilot';
2262
+ if (isAntigravity)
2263
+ runtimeLabel = 'Antigravity';
2264
+ console.log(` Installing for ${cyan}${runtimeLabel}${reset} to ${cyan}${locationLabel}${reset}\n`);
2265
+ // Track installation failures
2266
+ const failures = [];
2267
+ // Save any locally modified Vector files before they get wiped
2268
+ saveLocalPatches(targetDir);
2269
+ // Clean up orphaned files from previous versions
2270
+ cleanupOrphanedFiles(targetDir);
2271
+ // OpenCode uses command/ (flat), Codex uses skills/, Claude/Gemini use commands/vector/
2272
+ if (isOpencode) {
2273
+ // OpenCode: flat structure in command/ directory
2274
+ const commandDir = path_1.default.join(targetDir, 'command');
2275
+ fs_1.default.mkdirSync(commandDir, { recursive: true });
2276
+ // Copy commands/vector/*.md as command/vector-*.md (flatten structure)
2277
+ const vectorSrc = path_1.default.join(src, 'commands', 'vector');
2278
+ copyFlattenedCommands(vectorSrc, commandDir, 'vector', pathPrefix, runtime);
2279
+ if (verifyInstalled(commandDir, 'command/vector-*')) {
2280
+ const count = fs_1.default.readdirSync(commandDir).filter(f => f.startsWith('vector-')).length;
2281
+ console.log(` ${green}✓${reset} Installed ${count} commands to command/`);
2282
+ }
2283
+ else {
2284
+ failures.push('command/vector-*');
2285
+ }
2286
+ }
2287
+ else if (isCodex) {
2288
+ const skillsDir = path_1.default.join(targetDir, 'skills');
2289
+ const vectorSrc = path_1.default.join(src, 'commands', 'vector');
2290
+ copyCommandsAsCodexSkills(vectorSrc, skillsDir, 'vector', pathPrefix, runtime);
2291
+ const installedSkillNames = listCodexSkillNames(skillsDir);
2292
+ if (installedSkillNames.length > 0) {
2293
+ console.log(` ${green}✓${reset} Installed ${installedSkillNames.length} skills to skills/`);
2294
+ }
2295
+ else {
2296
+ failures.push('skills/vector-*');
2297
+ }
2298
+ }
2299
+ else if (isCopilot) {
2300
+ const skillsDir = path_1.default.join(targetDir, 'skills');
2301
+ const vectorSrc = path_1.default.join(src, 'commands', 'vector');
2302
+ copyCommandsAsCopilotSkills(vectorSrc, skillsDir, 'vector', isGlobal);
2303
+ if (fs_1.default.existsSync(skillsDir)) {
2304
+ const count = fs_1.default.readdirSync(skillsDir, { withFileTypes: true })
2305
+ .filter(e => e.isDirectory() && e.name.startsWith('vector-')).length;
2306
+ if (count > 0) {
2307
+ console.log(` ${green}✓${reset} Installed ${count} skills to skills/`);
2308
+ }
2309
+ else {
2310
+ failures.push('skills/vector-*');
2311
+ }
2312
+ }
2313
+ else {
2314
+ failures.push('skills/vector-*');
2315
+ }
2316
+ }
2317
+ else if (isAntigravity) {
2318
+ const skillsDir = path_1.default.join(targetDir, 'skills');
2319
+ const vectorSrc = path_1.default.join(src, 'commands', 'vector');
2320
+ copyCommandsAsAntigravitySkills(vectorSrc, skillsDir, 'vector', isGlobal);
2321
+ if (fs_1.default.existsSync(skillsDir)) {
2322
+ const count = fs_1.default.readdirSync(skillsDir, { withFileTypes: true })
2323
+ .filter(e => e.isDirectory() && e.name.startsWith('vector-')).length;
2324
+ if (count > 0) {
2325
+ console.log(` ${green}✓${reset} Installed ${count} skills to skills/`);
2326
+ }
2327
+ else {
2328
+ failures.push('skills/vector-*');
2329
+ }
2330
+ }
2331
+ else {
2332
+ failures.push('skills/vector-*');
2333
+ }
2334
+ }
2335
+ else {
2336
+ // Claude Code & Gemini: nested structure in commands/ directory
2337
+ const commandsDir = path_1.default.join(targetDir, 'commands');
2338
+ fs_1.default.mkdirSync(commandsDir, { recursive: true });
2339
+ const vectorSrc = path_1.default.join(src, 'commands', 'vector');
2340
+ const vectorDest = path_1.default.join(commandsDir, 'vector');
2341
+ copyWithPathReplacement(vectorSrc, vectorDest, pathPrefix, runtime, true, isGlobal);
2342
+ if (verifyInstalled(vectorDest, 'commands/vector')) {
2343
+ console.log(` ${green}✓${reset} Installed commands/vector`);
2344
+ }
2345
+ else {
2346
+ failures.push('commands/vector');
2347
+ }
2348
+ }
2349
+ // Copy core skill with path replacement
2350
+ const skillSrc = path_1.default.join(src, 'core');
2351
+ const skillDest = path_1.default.join(targetDir, 'core');
2352
+ copyWithPathReplacement(skillSrc, skillDest, pathPrefix, runtime, false, isGlobal);
2353
+ if (verifyInstalled(skillDest, 'core')) {
2354
+ console.log(` ${green}✓${reset} Installed core`);
2355
+ }
2356
+ else {
2357
+ failures.push('core');
2358
+ }
2359
+ // Copy agents to agents directory
2360
+ const agentsSrc = path_1.default.join(src, 'agents');
2361
+ if (fs_1.default.existsSync(agentsSrc)) {
2362
+ const agentsDest = path_1.default.join(targetDir, 'agents');
2363
+ fs_1.default.mkdirSync(agentsDest, { recursive: true });
2364
+ // Remove old Vector agents (vector-*.md) before copying new ones
2365
+ if (fs_1.default.existsSync(agentsDest)) {
2366
+ for (const file of fs_1.default.readdirSync(agentsDest)) {
2367
+ if (file.startsWith('vector-') && file.endsWith('.md')) {
2368
+ fs_1.default.unlinkSync(path_1.default.join(agentsDest, file));
2369
+ }
2370
+ }
2371
+ }
2372
+ // Copy new agents
2373
+ const agentEntries = fs_1.default.readdirSync(agentsSrc, { withFileTypes: true });
2374
+ for (const entry of agentEntries) {
2375
+ if (entry.isFile() && entry.name.endsWith('.md')) {
2376
+ let content = fs_1.default.readFileSync(path_1.default.join(agentsSrc, entry.name), 'utf8');
2377
+ // Replace ~/.claude/ and $HOME/.claude/ as they are the source of truth in the repo
2378
+ const dirRegex = /~\/\.claude\//g;
2379
+ const homeDirRegex = /\$HOME\/\.claude\//g;
2380
+ if (!isCopilot && !isAntigravity) {
2381
+ content = content.replace(dirRegex, pathPrefix);
2382
+ content = content.replace(homeDirRegex, pathPrefix);
2383
+ }
2384
+ content = processAttribution(content, getCommitAttribution(runtime));
2385
+ // Convert frontmatter for runtime compatibility (agents need different handling)
2386
+ if (isOpencode) {
2387
+ content = convertClaudeToOpencodeFrontmatter(content, { isAgent: true });
2388
+ }
2389
+ else if (isGemini) {
2390
+ content = convertClaudeToGeminiAgent(content);
2391
+ }
2392
+ else if (isCodex) {
2393
+ content = convertClaudeAgentToCodexAgent(content);
2394
+ }
2395
+ else if (isCopilot) {
2396
+ content = convertClaudeAgentToCopilotAgent(content, isGlobal);
2397
+ }
2398
+ else if (isAntigravity) {
2399
+ content = convertClaudeAgentToAntigravityAgent(content, isGlobal);
2400
+ }
2401
+ const destName = isCopilot ? entry.name.replace('.md', '.agent.md') : entry.name;
2402
+ fs_1.default.writeFileSync(path_1.default.join(agentsDest, destName), content);
2403
+ }
2404
+ }
2405
+ if (verifyInstalled(agentsDest, 'agents')) {
2406
+ console.log(` ${green}✓${reset} Installed agents`);
2407
+ }
2408
+ else {
2409
+ failures.push('agents');
2410
+ }
2411
+ }
2412
+ // Copy CHANGELOG.md
2413
+ const changelogSrc = path_1.default.join(src, 'CHANGELOG.md');
2414
+ const changelogDest = path_1.default.join(targetDir, 'core', 'CHANGELOG.md');
2415
+ if (fs_1.default.existsSync(changelogSrc)) {
2416
+ fs_1.default.copyFileSync(changelogSrc, changelogDest);
2417
+ if (verifyFileInstalled(changelogDest, 'CHANGELOG.md')) {
2418
+ console.log(` ${green}✓${reset} Installed CHANGELOG.md`);
2419
+ }
2420
+ else {
2421
+ failures.push('CHANGELOG.md');
2422
+ }
2423
+ }
2424
+ // Write VERSION file
2425
+ const versionDest = path_1.default.join(targetDir, 'core', 'VERSION');
2426
+ fs_1.default.writeFileSync(versionDest, package_json_1.default.version);
2427
+ if (verifyFileInstalled(versionDest, 'VERSION')) {
2428
+ console.log(` ${green}✓${reset} Wrote VERSION (${package_json_1.default.version})`);
2429
+ }
2430
+ else {
2431
+ failures.push('VERSION');
2432
+ }
2433
+ if (!isCodex && !isCopilot) {
2434
+ // Write package.json to force CommonJS mode for Vector scripts
2435
+ // Prevents "require is not defined" errors when project has "type": "module"
2436
+ // Node.js walks up looking for package.json - this stops inheritance from project
2437
+ const pkgJsonDest = path_1.default.join(targetDir, 'package.json');
2438
+ fs_1.default.writeFileSync(pkgJsonDest, '{"type":"commonjs"}\n');
2439
+ console.log(` ${green}✓${reset} Wrote package.json (CommonJS mode)`);
2440
+ // Copy hooks from dist/ (bundled with dependencies)
2441
+ // Template paths for the target runtime (replaces '.claude' with correct config dir)
2442
+ const hooksSrc = path_1.default.join(src, 'hooks', 'dist');
2443
+ if (fs_1.default.existsSync(hooksSrc)) {
2444
+ const hooksDest = path_1.default.join(targetDir, 'hooks');
2445
+ fs_1.default.mkdirSync(hooksDest, { recursive: true });
2446
+ const hookEntries = fs_1.default.readdirSync(hooksSrc);
2447
+ const configDirReplacement = getConfigDirFromHome(runtime, isGlobal);
2448
+ for (const entry of hookEntries) {
2449
+ const srcFile = path_1.default.join(hooksSrc, entry);
2450
+ if (fs_1.default.statSync(srcFile).isFile()) {
2451
+ const destFile = path_1.default.join(hooksDest, entry);
2452
+ // Template .js files to replace '.claude' with runtime-specific config dir
2453
+ if (entry.endsWith('.js')) {
2454
+ let content = fs_1.default.readFileSync(srcFile, 'utf8');
2455
+ content = content.replace(/'\.claude'/g, configDirReplacement);
2456
+ fs_1.default.writeFileSync(destFile, content);
2457
+ }
2458
+ else {
2459
+ fs_1.default.copyFileSync(srcFile, destFile);
2460
+ }
2461
+ }
2462
+ }
2463
+ if (verifyInstalled(hooksDest, 'hooks')) {
2464
+ console.log(` ${green}✓${reset} Installed hooks (bundled)`);
2465
+ }
2466
+ else {
2467
+ failures.push('hooks');
2468
+ }
2469
+ }
2470
+ }
2471
+ if (failures.length > 0) {
2472
+ console.error(`\n ${yellow}Installation incomplete!${reset} Failed: ${failures.join(', ')}`);
2473
+ process.exit(1);
2474
+ }
2475
+ // Write file manifest for future modification detection
2476
+ writeManifest(targetDir, runtime);
2477
+ console.log(` ${green}✓${reset} Wrote file manifest (${MANIFEST_NAME})`);
2478
+ // Report any backed-up local patches
2479
+ reportLocalPatches(targetDir, runtime);
2480
+ // Verify no leaked .claude paths in non-Claude runtimes
2481
+ if (runtime !== 'claude') {
2482
+ const leakedPaths = [];
2483
+ function scanForLeakedPaths(dir) {
2484
+ if (!fs_1.default.existsSync(dir))
2485
+ return;
2486
+ let entries;
2487
+ try {
2488
+ entries = fs_1.default.readdirSync(dir, { withFileTypes: true });
2489
+ }
2490
+ catch (err) {
2491
+ if (err.code === 'EPERM' || err.code === 'EACCES') {
2492
+ return; // skip inaccessible directories
2493
+ }
2494
+ throw err;
2495
+ }
2496
+ for (const entry of entries) {
2497
+ const fullPath = path_1.default.join(dir, entry.name);
2498
+ if (entry.isDirectory()) {
2499
+ scanForLeakedPaths(fullPath);
2500
+ }
2501
+ else if ((entry.name.endsWith('.md') || entry.name.endsWith('.toml')) && entry.name !== 'CHANGELOG.md') {
2502
+ let content;
2503
+ try {
2504
+ content = fs_1.default.readFileSync(fullPath, 'utf8');
2505
+ }
2506
+ catch (err) {
2507
+ if (err.code === 'EPERM' || err.code === 'EACCES') {
2508
+ continue; // skip inaccessible files
2509
+ }
2510
+ throw err;
2511
+ }
2512
+ const matches = content.match(/(?:~|\$HOME)\/\.claude\b/g);
2513
+ if (matches) {
2514
+ leakedPaths.push({ file: fullPath.replace(targetDir + '/', ''), count: matches.length });
2515
+ }
2516
+ }
2517
+ }
2518
+ }
2519
+ scanForLeakedPaths(targetDir);
2520
+ if (leakedPaths.length > 0) {
2521
+ const totalLeaks = leakedPaths.reduce((sum, l) => sum + l.count, 0);
2522
+ console.warn(`\n ${yellow}⚠${reset} Found ${totalLeaks} unreplaced .claude path reference(s) in ${leakedPaths.length} file(s):`);
2523
+ for (const leak of leakedPaths.slice(0, 5)) {
2524
+ console.warn(` ${dim}${leak.file}${reset} (${leak.count})`);
2525
+ }
2526
+ if (leakedPaths.length > 5) {
2527
+ console.warn(` ${dim}... and ${leakedPaths.length - 5} more file(s)${reset}`);
2528
+ }
2529
+ console.warn(` ${dim}These paths may not resolve correctly for ${runtimeLabel}.${reset}`);
2530
+ }
2531
+ }
2532
+ if (isCodex) {
2533
+ // Generate Codex config.toml and per-agent .toml files
2534
+ const agentCount = installCodexConfig(targetDir, agentsSrc);
2535
+ console.log(` ${green}✓${reset} Generated config.toml with ${agentCount} agent roles`);
2536
+ console.log(` ${green}✓${reset} Generated ${agentCount} agent .toml config files`);
2537
+ return { settingsPath: null, settings: null, statuslineCommand: null, runtime };
2538
+ }
2539
+ if (isCopilot) {
2540
+ // Generate copilot-instructions.md
2541
+ const templatePath = path_1.default.join(targetDir, 'core', 'templates', 'copilot-instructions.md');
2542
+ const instructionsPath = path_1.default.join(targetDir, 'copilot-instructions.md');
2543
+ if (fs_1.default.existsSync(templatePath)) {
2544
+ const template = fs_1.default.readFileSync(templatePath, 'utf8');
2545
+ mergeCopilotInstructions(instructionsPath, template);
2546
+ console.log(` ${green}✓${reset} Generated copilot-instructions.md`);
2547
+ }
2548
+ // Copilot: no settings.json, no hooks, no statusline (like Codex)
2549
+ return { settingsPath: null, settings: null, statuslineCommand: null, runtime };
2550
+ }
2551
+ // Configure statusline and hooks in settings.json
2552
+ // Gemini and Antigravity use AfterTool instead of PostToolUse for post-tool hooks
2553
+ const postToolEvent = (runtime === 'gemini' || runtime === 'antigravity') ? 'AfterTool' : 'PostToolUse';
2554
+ const settingsPath = path_1.default.join(targetDir, 'settings.json');
2555
+ const settings = cleanupOrphanedHooks(readSettings(settingsPath));
2556
+ const statuslineCommand = isGlobal
2557
+ ? buildHookCommand(targetDir, 'vector-statusline.js')
2558
+ : 'node ' + dirName + '/hooks/vector-statusline.js';
2559
+ const updateCheckCommand = isGlobal
2560
+ ? buildHookCommand(targetDir, 'vector-check-update.js')
2561
+ : 'node ' + dirName + '/hooks/vector-check-update.js';
2562
+ const contextMonitorCommand = isGlobal
2563
+ ? buildHookCommand(targetDir, 'vector-context-monitor.js')
2564
+ : 'node ' + dirName + '/hooks/vector-context-monitor.js';
2565
+ // Enable experimental agents for Gemini CLI (required for custom sub-agents)
2566
+ if (isGemini) {
2567
+ if (!settings.experimental) {
2568
+ settings.experimental = {};
2569
+ }
2570
+ const experimental = settings.experimental;
2571
+ if (!experimental.enableAgents) {
2572
+ experimental.enableAgents = true;
2573
+ console.log(` ${green}✓${reset} Enabled experimental agents`);
2574
+ }
2575
+ }
2576
+ // Configure SessionStart hook for update checking (skip for opencode)
2577
+ if (!isOpencode) {
2578
+ if (!settings.hooks) {
2579
+ settings.hooks = {};
2580
+ }
2581
+ const hooksMap = settings.hooks;
2582
+ if (!hooksMap.SessionStart) {
2583
+ hooksMap.SessionStart = [];
2584
+ }
2585
+ const hasGsdUpdateHook = hooksMap.SessionStart.some((entry) => {
2586
+ const e = entry;
2587
+ return e.hooks && Array.isArray(e.hooks) && e.hooks.some((h) => h.command && h.command.includes('vector-check-update'));
2588
+ });
2589
+ if (!hasGsdUpdateHook) {
2590
+ hooksMap.SessionStart.push({
2591
+ hooks: [
2592
+ {
2593
+ type: 'command',
2594
+ command: updateCheckCommand
2595
+ }
2596
+ ]
2597
+ });
2598
+ console.log(` ${green}✓${reset} Configured update check hook`);
2599
+ }
2600
+ // Configure post-tool hook for context window monitoring
2601
+ if (!hooksMap[postToolEvent]) {
2602
+ hooksMap[postToolEvent] = [];
2603
+ }
2604
+ const hasContextMonitorHook = hooksMap[postToolEvent].some((entry) => {
2605
+ const e = entry;
2606
+ return e.hooks && Array.isArray(e.hooks) && e.hooks.some((h) => h.command && h.command.includes('vector-context-monitor'));
2607
+ });
2608
+ if (!hasContextMonitorHook) {
2609
+ hooksMap[postToolEvent].push({
2610
+ hooks: [
2611
+ {
2612
+ type: 'command',
2613
+ command: contextMonitorCommand
2614
+ }
2615
+ ]
2616
+ });
2617
+ console.log(` ${green}✓${reset} Configured context window monitor hook`);
2618
+ }
2619
+ }
2620
+ return { settingsPath, settings, statuslineCommand, runtime };
2621
+ }
2622
+ /**
2623
+ * Apply statusline config, then print completion message
2624
+ */
2625
+ function finishInstall(settingsPath, settings, statuslineCommand, shouldInstallStatusline, runtime = 'claude', isGlobal = true) {
2626
+ const isOpencode = runtime === 'opencode';
2627
+ const isCodex = runtime === 'codex';
2628
+ const isCopilot = runtime === 'copilot';
2629
+ if (shouldInstallStatusline && !isOpencode && !isCodex && !isCopilot && settings) {
2630
+ settings.statusLine = {
2631
+ type: 'command',
2632
+ command: statuslineCommand
2633
+ };
2634
+ console.log(` ${green}✓${reset} Configured statusline`);
2635
+ }
2636
+ // Write settings when runtime supports settings.json
2637
+ if (!isCodex && !isCopilot && settingsPath && settings) {
2638
+ writeSettings(settingsPath, settings);
2639
+ }
2640
+ // Configure OpenCode permissions
2641
+ if (isOpencode) {
2642
+ configureOpencodePermissions(isGlobal);
2643
+ }
2644
+ let program = 'Claude Code';
2645
+ if (runtime === 'opencode')
2646
+ program = 'OpenCode';
2647
+ if (runtime === 'gemini')
2648
+ program = 'Gemini';
2649
+ if (runtime === 'codex')
2650
+ program = 'Codex';
2651
+ if (runtime === 'copilot')
2652
+ program = 'Copilot';
2653
+ if (runtime === 'antigravity')
2654
+ program = 'Antigravity';
2655
+ let command = '/vector:new-project';
2656
+ if (runtime === 'opencode')
2657
+ command = '/vector-new-project';
2658
+ if (runtime === 'codex')
2659
+ command = '$vector-new-project';
2660
+ if (runtime === 'copilot')
2661
+ command = '/vector-new-project';
2662
+ if (runtime === 'antigravity')
2663
+ command = '/vector-new-project';
2664
+ console.log(`
2665
+ ${green}Done!${reset} Open a blank directory in ${program} and run ${cyan}${command}${reset}.
2666
+
2667
+ ${cyan}Join the community:${reset} https://discord.gg/gsd
2668
+ `);
2669
+ }
2670
+ /**
2671
+ * Handle statusline configuration with optional prompt
2672
+ */
2673
+ function handleStatusline(settings, isInteractive, callback) {
2674
+ const statusLine = settings ? settings.statusLine : undefined;
2675
+ const hasExisting = statusLine != null;
2676
+ if (!hasExisting) {
2677
+ callback(true);
2678
+ return;
2679
+ }
2680
+ if (forceStatusline) {
2681
+ callback(true);
2682
+ return;
2683
+ }
2684
+ if (!isInteractive) {
2685
+ console.log(` ${yellow}⚠${reset} Skipping statusline (already configured)`);
2686
+ console.log(` Use ${cyan}--force-statusline${reset} to replace\n`);
2687
+ callback(false);
2688
+ return;
2689
+ }
2690
+ const existingCmd = (statusLine && (statusLine.command || statusLine.url)) || '(custom)';
2691
+ const rl = readline_1.default.createInterface({
2692
+ input: process.stdin,
2693
+ output: process.stdout
2694
+ });
2695
+ console.log(`
2696
+ ${yellow}⚠${reset} Existing statusline detected\n
2697
+ Your current statusline:
2698
+ ${dim}command: ${existingCmd}${reset}
2699
+
2700
+ Vector includes a statusline showing:
2701
+ • Model name
2702
+ • Current task (from todo list)
2703
+ • Context window usage (color-coded)
2704
+
2705
+ ${cyan}1${reset}) Keep existing
2706
+ ${cyan}2${reset}) Replace with Vector statusline
2707
+ `);
2708
+ rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
2709
+ rl.close();
2710
+ const choice = answer.trim() || '1';
2711
+ callback(choice === '2');
2712
+ });
2713
+ }
2714
+ /**
2715
+ * Prompt for runtime selection
2716
+ */
2717
+ function promptRuntime(callback) {
2718
+ const rl = readline_1.default.createInterface({
2719
+ input: process.stdin,
2720
+ output: process.stdout
2721
+ });
2722
+ let answered = false;
2723
+ rl.on('close', () => {
2724
+ if (!answered) {
2725
+ answered = true;
2726
+ console.log(`\n ${yellow}Installation cancelled${reset}\n`);
2727
+ process.exit(0);
2728
+ }
2729
+ });
2730
+ console.log(` ${yellow}Which runtime(s) would you like to install for?${reset}\n\n ${cyan}1${reset}) Claude Code ${dim}(~/.claude)${reset}
2731
+ ${cyan}2${reset}) OpenCode ${dim}(~/.config/opencode)${reset} - open source, free models
2732
+ ${cyan}3${reset}) Gemini ${dim}(~/.gemini)${reset}
2733
+ ${cyan}4${reset}) Codex ${dim}(~/.codex)${reset}
2734
+ ${cyan}5${reset}) Copilot ${dim}(~/.copilot)${reset}
2735
+ ${cyan}6${reset}) Antigravity ${dim}(~/.gemini/antigravity)${reset}
2736
+ ${cyan}7${reset}) All
2737
+ `);
2738
+ rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
2739
+ answered = true;
2740
+ rl.close();
2741
+ const choice = answer.trim() || '1';
2742
+ if (choice === '7') {
2743
+ callback(['claude', 'opencode', 'gemini', 'codex', 'copilot', 'antigravity']);
2744
+ }
2745
+ else if (choice === '6') {
2746
+ callback(['antigravity']);
2747
+ }
2748
+ else if (choice === '5') {
2749
+ callback(['copilot']);
2750
+ }
2751
+ else if (choice === '4') {
2752
+ callback(['codex']);
2753
+ }
2754
+ else if (choice === '3') {
2755
+ callback(['gemini']);
2756
+ }
2757
+ else if (choice === '2') {
2758
+ callback(['opencode']);
2759
+ }
2760
+ else {
2761
+ callback(['claude']);
2762
+ }
2763
+ });
2764
+ }
2765
+ /**
2766
+ * Prompt for install location
2767
+ */
2768
+ function promptLocation(runtimes) {
2769
+ if (!process.stdin.isTTY) {
2770
+ console.log(` ${yellow}Non-interactive terminal detected, defaulting to global install${reset}\n`);
2771
+ installAllRuntimes(runtimes, true, false);
2772
+ return;
2773
+ }
2774
+ const rl = readline_1.default.createInterface({
2775
+ input: process.stdin,
2776
+ output: process.stdout
2777
+ });
2778
+ let answered = false;
2779
+ rl.on('close', () => {
2780
+ if (!answered) {
2781
+ answered = true;
2782
+ console.log(`\n ${yellow}Installation cancelled${reset}\n`);
2783
+ process.exit(0);
2784
+ }
2785
+ });
2786
+ const pathExamples = runtimes.map(r => {
2787
+ const globalPath = getGlobalDir(r, explicitConfigDir);
2788
+ return globalPath.replace(os_1.default.homedir(), '~');
2789
+ }).join(', ');
2790
+ const localExamples = runtimes.map(r => `./${getDirName(r)}`).join(', ');
2791
+ console.log(` ${yellow}Where would you like to install?${reset}\n\n ${cyan}1${reset}) Global ${dim}(${pathExamples})${reset} - available in all projects
2792
+ ${cyan}2${reset}) Local ${dim}(${localExamples})${reset} - this project only
2793
+ `);
2794
+ rl.question(` Choice ${dim}[1]${reset}: `, (answer) => {
2795
+ answered = true;
2796
+ rl.close();
2797
+ const choice = answer.trim() || '1';
2798
+ const isGlobal = choice !== '2';
2799
+ installAllRuntimes(runtimes, isGlobal, true);
2800
+ });
2801
+ }
2802
+ /**
2803
+ * Install Vector for all selected runtimes
2804
+ */
2805
+ function installAllRuntimes(runtimes, isGlobal, isInteractive) {
2806
+ const results = [];
2807
+ for (const runtime of runtimes) {
2808
+ const result = install(isGlobal, runtime);
2809
+ results.push(result);
2810
+ }
2811
+ const statuslineRuntimes = ['claude', 'gemini'];
2812
+ const primaryStatuslineResult = results.find(r => statuslineRuntimes.includes(r.runtime));
2813
+ const finalize = (shouldInstallStatusline) => {
2814
+ for (const result of results) {
2815
+ const useStatusline = statuslineRuntimes.includes(result.runtime) && shouldInstallStatusline;
2816
+ finishInstall(result.settingsPath, result.settings, result.statuslineCommand, useStatusline, result.runtime, isGlobal);
2817
+ }
2818
+ };
2819
+ if (primaryStatuslineResult) {
2820
+ handleStatusline(primaryStatuslineResult.settings, isInteractive, finalize);
2821
+ }
2822
+ else {
2823
+ finalize(false);
2824
+ }
2825
+ }
2826
+ // Test-only exports — skip main logic when loaded as a module for testing
2827
+ if (process.env.VECTOR_TEST_MODE) {
2828
+ module.exports = {
2829
+ getCodexSkillAdapterHeader,
2830
+ convertClaudeToGeminiAgent,
2831
+ convertClaudeAgentToCodexAgent,
2832
+ generateCodexAgentToml,
2833
+ generateCodexConfigBlock,
2834
+ stripGsdFromCodexConfig,
2835
+ mergeCodexConfig,
2836
+ installCodexConfig,
2837
+ convertClaudeCommandToCodexSkill,
2838
+ convertClaudeToOpencodeFrontmatter,
2839
+ GSD_CODEX_MARKER,
2840
+ CODEX_AGENT_SANDBOX,
2841
+ getDirName,
2842
+ getGlobalDir,
2843
+ getConfigDirFromHome,
2844
+ claudeToCopilotTools,
2845
+ convertCopilotToolName,
2846
+ convertClaudeToCopilotContent,
2847
+ convertClaudeCommandToCopilotSkill,
2848
+ convertClaudeAgentToCopilotAgent,
2849
+ copyCommandsAsCopilotSkills,
2850
+ GSD_COPILOT_INSTRUCTIONS_MARKER,
2851
+ GSD_COPILOT_INSTRUCTIONS_CLOSE_MARKER,
2852
+ mergeCopilotInstructions,
2853
+ stripGsdFromCopilotInstructions,
2854
+ convertClaudeToAntigravityContent,
2855
+ convertClaudeCommandToAntigravitySkill,
2856
+ convertClaudeAgentToAntigravityAgent,
2857
+ copyCommandsAsAntigravitySkills,
2858
+ writeManifest,
2859
+ reportLocalPatches,
2860
+ };
2861
+ }
2862
+ else {
2863
+ // Main logic
2864
+ if (hasGlobal && hasLocal) {
2865
+ console.error(` ${yellow}Cannot specify both --global and --local${reset}`);
2866
+ process.exit(1);
2867
+ }
2868
+ else if (explicitConfigDir && hasLocal) {
2869
+ console.error(` ${yellow}Cannot use --config-dir with --local${reset}`);
2870
+ process.exit(1);
2871
+ }
2872
+ else if (hasUninstall) {
2873
+ if (!hasGlobal && !hasLocal) {
2874
+ console.error(` ${yellow}--uninstall requires --global or --local${reset}`);
2875
+ process.exit(1);
2876
+ }
2877
+ const runtimes = selectedRuntimes.length > 0 ? selectedRuntimes : ['claude'];
2878
+ for (const runtime of runtimes) {
2879
+ uninstall(hasGlobal, runtime);
2880
+ }
2881
+ }
2882
+ else if (selectedRuntimes.length > 0) {
2883
+ if (!hasGlobal && !hasLocal) {
2884
+ promptLocation(selectedRuntimes);
2885
+ }
2886
+ else {
2887
+ installAllRuntimes(selectedRuntimes, hasGlobal, false);
2888
+ }
2889
+ }
2890
+ else if (hasGlobal || hasLocal) {
2891
+ // Default to Claude if no runtime specified but location is
2892
+ installAllRuntimes(['claude'], hasGlobal, false);
2893
+ }
2894
+ else {
2895
+ // Interactive
2896
+ if (!process.stdin.isTTY) {
2897
+ console.log(` ${yellow}Non-interactive terminal detected, defaulting to Claude Code global install${reset}\n`);
2898
+ installAllRuntimes(['claude'], true, false);
2899
+ }
2900
+ else {
2901
+ promptRuntime((runtimes) => {
2902
+ promptLocation(runtimes);
2903
+ });
2904
+ }
2905
+ }
2906
+ } // end of else block for VECTOR_TEST_MODE
2907
+ //# sourceMappingURL=install.cjs.map