lean-agents 0.0.0-stage → 0.8.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 (132) hide show
  1. package/LICENSE +21 -0
  2. package/README.es.md +454 -0
  3. package/README.md +453 -2
  4. package/core/AGENTS.es.md +60 -0
  5. package/core/AGENTS.md +60 -0
  6. package/core/README.md +8 -0
  7. package/core/agents/debug.md +14 -0
  8. package/core/agents/explore.md +13 -0
  9. package/core/agents/planner.md +14 -0
  10. package/core/agents/research.md +13 -0
  11. package/core/agents/review.md +13 -0
  12. package/core/copilot-usage-tui.js +186 -0
  13. package/core/mcp.json +38 -0
  14. package/core/pins.json +30 -0
  15. package/core/tiers.json +4 -0
  16. package/node_modules/@clack/core/LICENSE +9 -0
  17. package/node_modules/@clack/core/README.md +22 -0
  18. package/node_modules/@clack/core/dist/index.d.mts +503 -0
  19. package/node_modules/@clack/core/dist/index.mjs +1003 -0
  20. package/node_modules/@clack/core/package.json +63 -0
  21. package/node_modules/@clack/prompts/LICENSE +9 -0
  22. package/node_modules/@clack/prompts/README.md +396 -0
  23. package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
  24. package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
  25. package/node_modules/@clack/prompts/package.json +67 -0
  26. package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
  27. package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
  28. package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
  29. package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
  30. package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
  31. package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
  32. package/node_modules/fast-string-truncated-width/license +21 -0
  33. package/node_modules/fast-string-truncated-width/package.json +35 -0
  34. package/node_modules/fast-string-truncated-width/readme.md +59 -0
  35. package/node_modules/fast-string-width/dist/index.d.ts +4 -0
  36. package/node_modules/fast-string-width/dist/index.js +14 -0
  37. package/node_modules/fast-string-width/license +21 -0
  38. package/node_modules/fast-string-width/package.json +34 -0
  39. package/node_modules/fast-string-width/readme.md +42 -0
  40. package/node_modules/fast-wrap-ansi/LICENSE +23 -0
  41. package/node_modules/fast-wrap-ansi/README.md +26 -0
  42. package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
  43. package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
  44. package/node_modules/fast-wrap-ansi/package.json +51 -0
  45. package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
  46. package/node_modules/jsonc-parser/LICENSE.md +21 -0
  47. package/node_modules/jsonc-parser/README.md +364 -0
  48. package/node_modules/jsonc-parser/SECURITY.md +41 -0
  49. package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
  50. package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
  51. package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
  52. package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
  53. package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
  54. package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
  55. package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
  56. package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
  57. package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
  58. package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
  59. package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
  60. package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
  61. package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
  62. package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
  63. package/node_modules/jsonc-parser/package.json +37 -0
  64. package/node_modules/sisteransi/license +21 -0
  65. package/node_modules/sisteransi/package.json +34 -0
  66. package/node_modules/sisteransi/readme.md +113 -0
  67. package/node_modules/sisteransi/src/index.js +58 -0
  68. package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
  69. package/package.json +29 -4
  70. package/profiles/README.md +10 -0
  71. package/profiles/anthropic-api/gsd-defaults.json +26 -0
  72. package/profiles/anthropic-api.json +18 -0
  73. package/profiles/antigravity.json +12 -0
  74. package/profiles/claude-subscription/gsd-defaults.json +26 -0
  75. package/profiles/claude-subscription.json +17 -0
  76. package/profiles/github-copilot/gsd-defaults.json +26 -0
  77. package/profiles/github-copilot.json +17 -0
  78. package/profiles/openai-api/gsd-defaults.json +26 -0
  79. package/profiles/openai-api.json +17 -0
  80. package/profiles/opencode-go/gsd-defaults.json +26 -0
  81. package/profiles/opencode-go.json +17 -0
  82. package/profiles/vertex-gemini/gsd-defaults.json +26 -0
  83. package/profiles/vertex-gemini.json +18 -0
  84. package/scripts/adhd-skill.mjs +12 -0
  85. package/scripts/bump-pins.mjs +104 -0
  86. package/scripts/check-private.sh +52 -0
  87. package/scripts/check-readme.mjs +131 -0
  88. package/scripts/ci-download.sh +20 -0
  89. package/scripts/ci-install-opencode-v2.sh +6 -0
  90. package/scripts/ci-latest-report.mjs +38 -0
  91. package/scripts/copilot-context-mode.mjs +33 -0
  92. package/scripts/labels.sh +55 -0
  93. package/scripts/lean.mjs +700 -0
  94. package/scripts/lib/adapters/antigravity.mjs +72 -0
  95. package/scripts/lib/adapters/claude.mjs +122 -0
  96. package/scripts/lib/adapters/copilot-cli.mjs +81 -0
  97. package/scripts/lib/adapters/cursor.mjs +60 -0
  98. package/scripts/lib/adapters/opencode-v1.mjs +86 -0
  99. package/scripts/lib/adapters/opencode-v2.mjs +168 -0
  100. package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
  101. package/scripts/lib/adhd.mjs +28 -0
  102. package/scripts/lib/adopt.mjs +474 -0
  103. package/scripts/lib/agent-lifecycle.mjs +163 -0
  104. package/scripts/lib/copilot-usage.mjs +49 -0
  105. package/scripts/lib/doctor.mjs +207 -0
  106. package/scripts/lib/feedback.mjs +30 -0
  107. package/scripts/lib/fsops.mjs +291 -0
  108. package/scripts/lib/gsd.mjs +42 -0
  109. package/scripts/lib/inventory.mjs +195 -0
  110. package/scripts/lib/lean-update.mjs +30 -0
  111. package/scripts/lib/migrate.mjs +407 -0
  112. package/scripts/lib/network.mjs +79 -0
  113. package/scripts/lib/node-runtime.mjs +85 -0
  114. package/scripts/lib/parallel.mjs +265 -0
  115. package/scripts/lib/pins.mjs +47 -0
  116. package/scripts/lib/project.mjs +38 -0
  117. package/scripts/lib/redact.mjs +30 -0
  118. package/scripts/lib/render.mjs +101 -0
  119. package/scripts/lib/system.mjs +178 -0
  120. package/scripts/lib/terminals.mjs +218 -0
  121. package/scripts/lib/ui.mjs +34 -0
  122. package/scripts/lib/unverified.mjs +49 -0
  123. package/scripts/lib/upgrade.mjs +130 -0
  124. package/scripts/lib/verify-commit.mjs +16 -0
  125. package/scripts/lib/verify-sha256.mjs +20 -0
  126. package/scripts/lint-workflows.mjs +25 -0
  127. package/scripts/models-refresh.mjs +58 -0
  128. package/scripts/parallel.mjs +59 -0
  129. package/scripts/pins-latest.mjs +43 -0
  130. package/scripts/release.mjs +46 -0
  131. package/scripts/verify-pins.mjs +36 -0
  132. package/scripts/version-watch.mjs +118 -0
@@ -0,0 +1,407 @@
1
+ // --migrate: copy one harness's rules, agents, skills, prompts and MCP servers to the agents you pick.
2
+ // Hooks are only reported. MCP env and header values are never read into the result, only their names.
3
+ // Source paths and their upstream docs: docs/compatibility.md "Migration sources".
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { parse } from 'jsonc-parser';
7
+ import { OWNED_MARK, hasMark, removeBlock } from './fsops.mjs';
8
+ import { parseAgent } from './render.mjs';
9
+ import { configHome, envDir } from './system.mjs';
10
+ import { configPath, renderOpenCodeAgent } from './adapters/opencode-v2.mjs';
11
+ import { vscodeUserDir } from './adapters/vscode-copilot.mjs';
12
+ import { renderClaudeAgent } from './adapters/claude.mjs';
13
+ import { renderCopilotAgent } from './adapters/copilot-cli.mjs';
14
+ import { renderCursorAgent } from './adapters/cursor.mjs';
15
+ import { renderAntigravityAgent } from './adapters/antigravity.mjs';
16
+
17
+ const j = path.join;
18
+
19
+ // Per harness: where each kind of item lives. `b` is the home (user scope) or the project dir.
20
+ // ruleDirs/agents/prompts are [dir, extension]; mcp is [[file, keyPath]]; hooks is [[file or dir, key]].
21
+ // `verify` paths are unproven upstream: reported when present, never read.
22
+ const SOURCES = {
23
+ claude: (b, user) => {
24
+ const d = j(b, '.claude');
25
+ return {
26
+ rules: [user ? j(d, 'CLAUDE.md') : j(b, 'CLAUDE.md')], ruleDirs: [[j(d, 'rules'), '.md']],
27
+ agents: [j(d, 'agents'), '.md'], skills: j(d, 'skills'), prompts: user ? null : [j(d, 'commands'), '.md'],
28
+ mcp: [[user ? j(b, '.claude.json') : j(b, '.mcp.json'), ['mcpServers']]],
29
+ hooks: [[j(d, 'settings.json'), 'hooks']], verify: user ? [j(d, 'commands')] : [],
30
+ };
31
+ },
32
+ 'vscode-copilot': (b, user) => {
33
+ if (user) {
34
+ const c = envDir(b, 'COPILOT_HOME', j(b, '.copilot'));
35
+ const v = vscodeUserDir(b);
36
+ return { rules: [], ruleDirs: [], agents: null, skills: j(c, 'skills'), prompts: null, mcp: [], hooks: [[j(c, 'hooks'), null]], verify: [j(v, 'prompts'), j(v, 'mcp.json')] };
37
+ }
38
+ const g = j(b, '.github');
39
+ return {
40
+ rules: [j(g, 'copilot-instructions.md'), j(b, 'AGENTS.md')], ruleDirs: [[j(g, 'instructions'), '.instructions.md']],
41
+ agents: [j(g, 'agents'), '.agent.md'], skills: j(g, 'skills'), prompts: [j(g, 'prompts'), '.prompt.md'],
42
+ mcp: [[j(b, '.vscode', 'mcp.json'), ['servers']]], hooks: [[j(g, 'hooks'), null]], verify: [],
43
+ };
44
+ },
45
+ cursor: (b, user) => {
46
+ const d = j(b, '.cursor');
47
+ return {
48
+ rules: user ? [] : [j(b, 'AGENTS.md')], ruleDirs: user ? [] : [[j(d, 'rules'), '.mdc']],
49
+ agents: [j(d, 'agents'), '.md'], skills: j(d, 'skills'), prompts: null,
50
+ mcp: [[j(d, 'mcp.json'), ['mcpServers']]], hooks: [[j(d, 'hooks.json'), null]], verify: [j(d, 'commands')],
51
+ };
52
+ },
53
+ 'copilot-cli': (b, user) => {
54
+ if (user) {
55
+ const c = envDir(b, 'COPILOT_HOME', j(b, '.copilot'));
56
+ return {
57
+ rules: [j(c, 'copilot-instructions.md')], ruleDirs: [[j(c, 'instructions'), '.instructions.md']],
58
+ agents: [j(c, 'agents'), '.agent.md'], skills: j(c, 'skills'), prompts: null,
59
+ mcp: [[j(c, 'mcp-config.json'), ['mcpServers']]], hooks: [[j(c, 'hooks'), null]], verify: [],
60
+ };
61
+ }
62
+ const g = j(b, '.github');
63
+ return {
64
+ rules: [j(g, 'copilot-instructions.md'), j(b, 'AGENTS.md')], ruleDirs: [[j(g, 'instructions'), '.instructions.md']],
65
+ agents: [j(g, 'agents'), '.agent.md'], skills: j(g, 'skills'), prompts: null,
66
+ mcp: [[j(b, '.mcp.json'), ['mcpServers']], [j(g, 'mcp.json'), ['mcpServers']]], hooks: [[j(g, 'hooks'), null]], verify: [j(g, 'prompts')],
67
+ };
68
+ },
69
+ };
70
+ const opencodeSource = (b, user, from) => {
71
+ const cfg = user ? j(configHome(b), 'opencode') : j(b, '.opencode');
72
+ return {
73
+ rules: [j(user ? cfg : b, 'AGENTS.md')], ruleDirs: [],
74
+ agents: [j(cfg, 'agents'), '.md'], skills: j(cfg, 'skills'), prompts: [j(cfg, 'commands'), '.md'],
75
+ mcp: [[configPath(user ? cfg : b), from === 'opencode-v1' ? ['mcp'] : ['mcp', 'servers']]], hooks: [], verify: [],
76
+ };
77
+ };
78
+ // Antigravity: ~/.gemini/config (agy 1.4.12 in CI). Project scope paths are unproven (VERIFY), so there is none.
79
+ // Skills dir and GEMINI.md/AGENTS.md are docs only (VERIFY): GEMINI.md/AGENTS.md are only reported.
80
+ SOURCES.antigravity = (b, user) => {
81
+ if (!user) return { rules: [], ruleDirs: [], agents: null, skills: null, prompts: null, mcp: [], hooks: [], verify: [] };
82
+ const d = j(b, '.gemini', 'config');
83
+ return {
84
+ rules: [], ruleDirs: [[j(d, 'rules'), '.md']], agents: [j(d, 'agents'), '.md'], skills: j(d, 'skills'), prompts: null,
85
+ mcp: [[j(d, 'mcp_config.json'), ['mcpServers']]], hooks: [], verify: [j(b, '.gemini', 'GEMINI.md'), j(b, '.gemini', 'AGENTS.md')],
86
+ };
87
+ };
88
+ SOURCES['opencode-v1'] = opencodeSource;
89
+ SOURCES['opencode-v2'] = opencodeSource;
90
+
91
+ export const MIGRATE_SOURCES = Object.keys(SOURCES);
92
+ export const MIGRATE_TARGETS = MIGRATE_SOURCES;
93
+
94
+ const text = (p) => { try { return fs.readFileSync(p, 'utf8'); } catch { return null; } };
95
+ const isDir = (p) => { try { return fs.statSync(p).isDirectory(); } catch { return false; } };
96
+ const isFile = (p) => { try { return fs.statSync(p).isFile(); } catch { return false; } };
97
+ const list = (dir, ext) => {
98
+ try { return fs.readdirSync(dir).filter((f) => f.endsWith(ext)).sort().map((f) => ({ name: f.slice(0, -ext.length), file: j(dir, f) })); } catch { return []; }
99
+ };
100
+ const SAFE_NAME = /^[A-Za-z0-9][\w.-]*$/;
101
+ const TEXT_LIMIT = 200 * 1024;
102
+
103
+ function frontmatter(t) {
104
+ const m = t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
105
+ return m ? { meta: m[1], body: m[2] } : { meta: '', body: t };
106
+ }
107
+
108
+ function skillFiles(dir) {
109
+ const out = [];
110
+ const walk = (d, rel) => {
111
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
112
+ const p = j(d, e.name);
113
+ if (e.isDirectory()) { walk(p, [...rel, e.name]); continue; }
114
+ if (!e.isFile() || fs.statSync(p).size > TEXT_LIMIT) continue;
115
+ const content = fs.readFileSync(p, 'utf8');
116
+ if (!content.includes('\0')) out.push({ rel: [...rel, e.name], content });
117
+ }
118
+ };
119
+ walk(dir, []);
120
+ return out;
121
+ }
122
+
123
+ // Names of env and header keys only; values never leave this function.
124
+ export function mcpServers(file, keyPath) {
125
+ const raw = text(file);
126
+ const root = raw && parse(raw, [], { allowTrailingComma: true });
127
+ let node = root;
128
+ for (const k of keyPath) node = node && typeof node === 'object' ? node[k] : undefined;
129
+ const out = [];
130
+ for (const [name, s] of Object.entries(node && typeof node === 'object' ? node : {})) {
131
+ if (!s || typeof s !== 'object' || Array.isArray(s)) continue;
132
+ const command = Array.isArray(s.command) ? s.command.map(String) : s.command ? [String(s.command), ...(Array.isArray(s.args) ? s.args.map(String) : [])] : [];
133
+ out.push({
134
+ name, source: file, command, url: typeof s.url === 'string' ? s.url : undefined, transport: s.type === 'sse' ? 'sse' : 'http',
135
+ envNames: Object.keys(s.env ?? s.environment ?? {}), headerNames: Object.keys(s.headers ?? {}),
136
+ });
137
+ }
138
+ return out;
139
+ }
140
+
141
+ export function readSource(from, base, scope) {
142
+ if (!SOURCES[from]) throw new Error(`unknown --migrate source "${from}" (available: ${[...MIGRATE_SOURCES, 'auto'].join(', ')})`);
143
+ const l = SOURCES[from](base, scope === 'user', from);
144
+ const r = { from, rules: [], agents: [], skills: [], prompts: [], mcp: [], hooks: [], unsupported: [] };
145
+
146
+ const addRule = (file, strip) => {
147
+ const raw = text(file);
148
+ if (raw === null || (hasMark(raw) && !raw.includes('lean-agents:start'))) return;
149
+ const { meta, body } = strip ? frontmatter(raw) : { meta: '', body: raw };
150
+ const clean = removeBlock(body).trim();
151
+ if (clean) r.rules.push({ file, text: clean, scoped: /^(applyTo|globs|paths):\s*\S/m.test(meta) });
152
+ };
153
+ for (const f of l.rules) addRule(f, false);
154
+ for (const [dir, ext] of l.ruleDirs) for (const it of list(dir, ext)) addRule(it.file, true);
155
+
156
+ if (l.agents) {
157
+ for (const it of list(...l.agents)) {
158
+ const raw = text(it.file);
159
+ if (raw === null) continue;
160
+ let a;
161
+ // shortcut: parseAgent drops text after "#" in a frontmatter value, so "fix #12" becomes "fix"; upgrade if it bites.
162
+ try { a = parseAgent(raw); } catch { a = { body: raw.trim() }; }
163
+ if (!SAFE_NAME.test(it.name)) continue;
164
+ // The tool list formats differ, so an agent that had one is migrated read-only rather than widened.
165
+ r.agents.push({ name: it.name, description: a.description ?? it.name, body: a.body, restricted: 'tools' in a || 'permission' in a, source: it.file });
166
+ }
167
+ }
168
+ if (isDir(l.skills)) {
169
+ for (const e of fs.readdirSync(l.skills, { withFileTypes: true })) {
170
+ if (e.isDirectory() && SAFE_NAME.test(e.name)) r.skills.push({ name: e.name, source: j(l.skills, e.name), files: skillFiles(j(l.skills, e.name)) });
171
+ }
172
+ }
173
+ if (l.prompts) for (const it of list(...l.prompts)) if (SAFE_NAME.test(it.name) && text(it.file) !== null) r.prompts.push({ name: it.name, source: it.file, text: text(it.file) });
174
+ for (const [file, key] of l.mcp) r.mcp.push(...mcpServers(file, key));
175
+ for (const [p, key] of l.hooks) {
176
+ const files = isDir(p) ? list(p, '.json').map((x) => x.file) : isFile(p) ? [p] : [];
177
+ for (const f of files) {
178
+ const body = key ? parse(text(f) ?? '', [], { allowTrailingComma: true }) : true;
179
+ if (body && (!key || body[key])) r.hooks.push({ source: f });
180
+ }
181
+ }
182
+ for (const p of l.verify) if (fs.existsSync(p)) r.unsupported.push(p);
183
+ return r;
184
+ }
185
+
186
+ export const hasContent = (r) => ['rules', 'agents', 'skills', 'prompts', 'mcp', 'hooks', 'unsupported'].some((k) => r[k].length);
187
+
188
+ // `auto`: every source that has files here, except the ones being written to.
189
+ export function detectSources(base, scope, exclude = []) {
190
+ return MIGRATE_SOURCES.filter((s) => !exclude.includes(s) && hasContent(readSource(s, base, scope)));
191
+ }
192
+
193
+ const refs = { claude: (v) => `\${${v}}`, 'opencode-v1': (v) => `{env:${v}}`, 'opencode-v2': (v) => `{env:${v}}`, cursor: (v) => `\${env:${v}}` };
194
+
195
+ // Where and how each target takes items. `ctx` carries the rules file the engine writes under its state dir.
196
+ const TARGETS = {
197
+ claude: (b, user) => {
198
+ const d = j(b, '.claude');
199
+ return {
200
+ agent: [j(d, 'agents'), '.md', (a) => renderClaudeAgent(a, null, true)], skills: j(d, 'skills'), prompts: [j(d, 'commands'), '.md'],
201
+ mcp: user ? { cli: true } : { file: j(b, '.mcp.json'), key: ['mcpServers'], value: (s, env) => (s.url ? { type: s.transport, url: s.url } : { command: s.command[0], args: s.command.slice(1), ...(env ? { env } : {}) }) },
202
+ rules: user
203
+ ? (rulesFile) => [{ kind: 'block', path: j(d, 'CLAUDE.md'), body: `@${rulesFile.split(path.sep).join('/')}` }]
204
+ : (_f, body) => [{ kind: 'block', path: j(b, 'CLAUDE.md'), body }],
205
+ rulesPath: user ? null : j(b, 'CLAUDE.md'),
206
+ };
207
+ },
208
+ cursor: (b, user) => {
209
+ const d = j(b, '.cursor');
210
+ return {
211
+ agent: [j(d, 'agents'), '.md', renderCursorAgent], skills: j(d, 'skills'), prompts: null,
212
+ mcp: { file: j(d, 'mcp.json'), key: ['mcpServers'], value: (s, env) => (s.url ? { url: s.url } : { command: s.command[0], args: s.command.slice(1), ...(env ? { env } : {}) }) },
213
+ rules: user ? null : (_f, body) => [{ kind: 'block', path: j(b, 'AGENTS.md'), body }],
214
+ rulesPath: user ? null : j(b, 'AGENTS.md'),
215
+ };
216
+ },
217
+ 'vscode-copilot': (b, user) => {
218
+ const c = user ? envDir(b, 'COPILOT_HOME', j(b, '.copilot')) : j(b, '.github');
219
+ return {
220
+ agent: [j(c, 'agents'), '.agent.md', (a) => renderCopilotAgent(a, null, true)], skills: j(c, 'skills'), prompts: user ? null : [j(c, 'prompts'), '.prompt.md'],
221
+ mcp: { file: user ? j(vscodeUserDir(b), 'mcp.json') : j(b, '.vscode', 'mcp.json'), key: ['servers'], value: (s) => (s.url ? { type: s.transport, url: s.url } : { type: 'stdio', command: s.command[0], args: s.command.slice(1) }) },
222
+ rules: (_f, body) => [{ kind: 'block', path: user ? j(c, 'copilot-instructions.md') : j(b, 'AGENTS.md'), body }],
223
+ rulesPath: user ? j(c, 'copilot-instructions.md') : j(b, 'AGENTS.md'),
224
+ };
225
+ },
226
+ 'copilot-cli': (b, user) => {
227
+ const c = user ? envDir(b, 'COPILOT_HOME', j(b, '.copilot')) : j(b, '.github');
228
+ return {
229
+ agent: [j(c, 'agents'), '.agent.md', (a) => renderCopilotAgent(a, null, true)], skills: j(c, 'skills'), prompts: null,
230
+ mcp: { file: user ? j(c, 'mcp-config.json') : j(b, '.mcp.json'), key: ['mcpServers'], value: (s) => (s.url ? { type: s.transport, url: s.url, tools: ['*'] } : { type: 'local', command: s.command[0], args: s.command.slice(1), tools: ['*'] }) },
231
+ rules: (_f, body) => [{ kind: 'block', path: user ? j(c, 'copilot-instructions.md') : j(b, 'AGENTS.md'), body }],
232
+ rulesPath: user ? j(c, 'copilot-instructions.md') : j(b, 'AGENTS.md'),
233
+ };
234
+ },
235
+ };
236
+ TARGETS.antigravity = (b, user) => {
237
+ if (!user) throw new Error('cannot migrate to antigravity with --project: its project paths are unverified, use user scope');
238
+ const d = j(b, '.gemini', 'config');
239
+ return {
240
+ agent: [j(d, 'agents'), '.md', (a) => renderAntigravityAgent(a, null)], skills: j(d, 'skills'), prompts: null,
241
+ // Remote key `serverUrl` is from the docs only (VERIFY). No env syntax is verified, so env names are only reported.
242
+ mcp: { file: j(d, 'mcp_config.json'), key: ['mcpServers'], value: (s) => (s.url ? { serverUrl: s.url } : { command: s.command[0], args: s.command.slice(1) }) },
243
+ rules: (_f, body) => [{ kind: 'file', path: j(d, 'rules', 'migrated-rules.md'), content: body }],
244
+ rulesPath: j(d, 'rules', 'migrated-rules.md'),
245
+ };
246
+ };
247
+ const opencodeTarget = (v2) => (b, user) => {
248
+ const cfg = user ? j(configHome(b), 'opencode') : j(b, '.opencode');
249
+ const file = configPath(user ? cfg : b);
250
+ return {
251
+ agent: [j(cfg, 'agents'), '.md', (a) => renderOpenCodeAgent(a, null)], skills: j(cfg, 'skills'), prompts: [j(cfg, 'commands'), '.md'],
252
+ mcp: {
253
+ file, key: v2 ? ['mcp', 'servers'] : ['mcp'],
254
+ value: (s, env) => (s.url ? { type: 'remote', url: s.url, enabled: true } : { type: 'local', command: s.command, ...(env ? { environment: env } : {}), enabled: true }),
255
+ },
256
+ rules: user
257
+ ? (rulesFile) => [{ kind: 'json', path: file, edits: [{ path: ['instructions'], value: rulesFile.split(path.sep).join('/'), mode: 'arrayAdd' }] }]
258
+ : (_f, body) => [{ kind: 'block', path: j(b, 'AGENTS.md'), body }],
259
+ rulesPath: user ? null : j(b, 'AGENTS.md'),
260
+ };
261
+ };
262
+ TARGETS['opencode-v1'] = opencodeTarget(false);
263
+ TARGETS['opencode-v2'] = opencodeTarget(true);
264
+
265
+ const rulesText = (from, items) => `<!-- ${OWNED_MARK}: migrated from ${from} -->\n${items.map((r) => r.text).join('\n\n')}\n`;
266
+
267
+ // Returns { actions, commands, rows, env, headers }. Rows get their final status from finishRows().
268
+ export function migratePlan({ sources, targets, base, scope, stateDir }) {
269
+ const user = scope === 'user';
270
+ for (const t of targets) {
271
+ if (!TARGETS[t]) throw new Error(`cannot migrate to "${t}" (available: ${MIGRATE_TARGETS.join(', ')})`);
272
+ if (sources.some((s) => s.from === t)) throw new Error(`source and target are both ${t}`);
273
+ }
274
+ const L = Object.fromEntries(targets.map((t) => [t, TARGETS[t](base, user)]));
275
+ const jsonByPath = new Map();
276
+ const actions = [];
277
+ const commands = [];
278
+ const rows = [];
279
+ const env = new Set();
280
+ const headers = new Set();
281
+ const taken = new Map();
282
+ // The first source wins a name; later sources report the clash.
283
+ const claim = (kind, name, s) => {
284
+ const k = `${kind}:${name}`;
285
+ if (taken.has(k)) { rows.push({ item: `${kind} ${name}`, source: s, target: '-', status: 'skipped', note: `already taken from ${taken.get(k)}` }); return false; }
286
+ taken.set(k, s);
287
+ return true;
288
+ };
289
+ const file = (item, source, target, content, note = '') => {
290
+ actions.push({ kind: 'file', path: target, content });
291
+ rows.push({ item, source, target, status: 'migrated', path: target, note });
292
+ };
293
+ const noteTarget = (item, source, t, note) => rows.push({ item, source, target: t, status: 'reported', note });
294
+
295
+ // Rules from every source go into one block per target: a second block would replace the first.
296
+ const seenRules = new Set();
297
+ const allRules = sources.flatMap((x) => x.rules.map((r) => ({ ...r, from: x.from }))).filter((r) => !seenRules.has(path.resolve(r.file)) && seenRules.add(path.resolve(r.file)));
298
+ if (allRules.length) {
299
+ for (const t of targets) {
300
+ const T = L[t];
301
+ if (!T.rules) { noteTarget('rules', allRules[0].from, t, `${t} has no user rules file`); continue; }
302
+ const items = allRules.filter((r) => path.resolve(r.file) !== (T.rulesPath && path.resolve(T.rulesPath)));
303
+ if (!items.length) continue;
304
+ const names = [...new Set(items.map((r) => r.from))].join(', ');
305
+ const body = rulesText(names, items);
306
+ const rulesFile = j(stateDir, 'migrated-rules.md');
307
+ const acts = T.rules(rulesFile, body);
308
+ if (user && ['claude', 'opencode-v1', 'opencode-v2'].includes(t)) acts.unshift({ kind: 'file', path: rulesFile, content: body });
309
+ actions.push(...acts);
310
+ const notes = [`${items.length} file(s)`, ...(items.some((r) => r.scoped) ? ['scope (applyTo/globs) is lost: rules apply everywhere'] : [])];
311
+ rows.push({ item: 'rules', source: items[0].file, target: acts.at(-1).path, status: 'migrated', path: acts.at(-1).path, note: notes.join('; ') });
312
+ }
313
+ }
314
+ for (const src of sources) {
315
+ const from = src.from;
316
+ for (const a of src.agents) {
317
+ if (!claim('agent', a.name, a.source)) continue;
318
+ const agent = { name: a.name, description: a.description, body: a.body, tier: 'migrated', access: a.restricted ? 'read-only' : 'read-write' };
319
+ for (const t of targets) {
320
+ const [dir, ext, render] = L[t].agent;
321
+ file(`agent ${a.name}`, a.source, j(dir, `${a.name}${ext}`), render(agent), a.restricted ? 'tool list not carried over: set to read-only' : '');
322
+ }
323
+ }
324
+ for (const s of src.skills) {
325
+ if (!claim('skill', s.name, s.source)) continue;
326
+ for (const t of targets) {
327
+ const dir = j(L[t].skills, s.name);
328
+ for (const f of s.files) actions.push({ kind: 'file', path: j(dir, ...f.rel), content: f.content });
329
+ // One row per skill; its status follows the first file.
330
+ if (s.files.length) rows.push({ item: `skill ${s.name}`, source: s.source, target: dir, status: 'migrated', path: j(dir, ...s.files[0].rel), note: `${s.files.length} file(s)` });
331
+ }
332
+ }
333
+ for (const p of src.prompts) {
334
+ if (!claim('prompt', p.name, p.source)) continue;
335
+ for (const t of targets) {
336
+ if (!L[t].prompts) { noteTarget(`prompt ${p.name}`, p.source, t, `${t} prompt path is unverified`); continue; }
337
+ const [dir, ext] = L[t].prompts;
338
+ file(`prompt ${p.name}`, p.source, j(dir, `${p.name}${ext}`), p.text);
339
+ }
340
+ }
341
+ for (const s of src.mcp) {
342
+ if (!claim('mcp', s.name, s.source)) continue;
343
+ if (s.url && /[?#]|\/\/[^/]*@/.test(s.url)) { rows.push({ item: `mcp ${s.name}`, source: s.source, target: '-', status: 'skipped', note: 'url has a query or credentials, which may hold a token: add it by hand' }); continue; }
344
+ if (!SAFE_NAME.test(s.name) || (!s.url && !s.command.length)) { rows.push({ item: `mcp ${s.name}`, source: s.source, target: '-', status: 'skipped', note: 'no command or url' }); continue; }
345
+ s.envNames.forEach((n) => env.add(n));
346
+ s.headerNames.forEach((n) => headers.add(`${s.name}: ${n}`));
347
+ const note = s.headerNames.length ? `headers not copied: add ${s.headerNames.join(', ')} by hand` : '';
348
+ for (const t of targets) {
349
+ const m = L[t].mcp;
350
+ if (m.cli) {
351
+ const argv = s.url
352
+ ? ['claude', 'mcp', 'add', '--scope', 'user', '--transport', s.transport, s.name, s.url]
353
+ : ['claude', 'mcp', 'add', '--scope', 'user', s.name, '--', ...s.command];
354
+ commands.push({ tool: 'migrate', desc: `MCP server ${s.name} for Claude Code (user scope)`, run: [argv], undo: [['claude', 'mcp', 'remove', '--scope', 'user', s.name]], skipIfOutput: { cmd: ['claude', 'mcp', 'get', s.name], ok: true } });
355
+ rows.push({ item: `mcp ${s.name}`, source: s.source, target: `claude mcp add (${t})`, status: 'migrated', command: argv.join(' '), note });
356
+ continue;
357
+ }
358
+ const ref = refs[t];
359
+ const envNote = s.envNames.length && !ref ? `env ${s.envNames.join(', ')} not written: export it` : '';
360
+ const vars = ref && s.envNames.length ? Object.fromEntries(s.envNames.map((n) => [n, ref(n)])) : null;
361
+ let a = jsonByPath.get(m.file);
362
+ if (!a) { a = { kind: 'json', path: m.file, edits: [] }; jsonByPath.set(m.file, a); actions.push(a); }
363
+ const key = [...m.key, s.name];
364
+ // Two targets can share a file (.mcp.json): the first server definition wins.
365
+ if (!a.edits.some((e) => e.path.join('.') === key.join('.'))) a.edits.push({ path: key, value: m.value(s, vars), mode: 'setIfAbsent' });
366
+ rows.push({ item: `mcp ${s.name}`, source: s.source, target: m.file, status: 'migrated', path: m.file, key: key.join('.'), note: [note, envNote].filter(Boolean).join('; ') });
367
+ }
368
+ }
369
+ for (const h of src.hooks) rows.push({ item: 'hooks', source: h.source, target: '-', status: 'reported', note: 'hooks are not migrated: formats differ, copy by hand' });
370
+ for (const p of src.unsupported) rows.push({ item: 'unverified path', source: p, target: '-', status: 'reported', note: 'unsupported source path (VERIFY)' });
371
+ }
372
+ return { actions: dedupe(actions), commands, rows, env: [...env].sort(), headers: [...headers].sort() };
373
+ }
374
+
375
+ // Two targets can share a path (Copilot CLI and VS Code both use .github/agents); the first one wins.
376
+ function dedupe(actions) {
377
+ const seen = new Set();
378
+ return actions.filter((a) => {
379
+ const k = a.kind === 'json' ? null : `${a.kind}:${a.path}`;
380
+ if (k === null) return true;
381
+ if (seen.has(k)) return false;
382
+ seen.add(k);
383
+ return true;
384
+ });
385
+ }
386
+
387
+ // Final status per row: what plan() decided, or what --no-exec leaves undone.
388
+ export function finishRows(rows, planned, exec) {
389
+ return rows.map((r) => {
390
+ if (r.command) return exec ? r : { ...r, status: 'reported', note: `run it yourself: ${r.command}` };
391
+ if (!r.path || r.status !== 'migrated') return r;
392
+ const p = planned.find((x) => x.path === r.path);
393
+ if (!p) return r;
394
+ if (p.status === 'skip') return { ...r, status: 'skipped', note: p.note };
395
+ if (p.status === 'unchanged') return { ...r, status: 'skipped', note: 'already there' };
396
+ if (r.key && p.keptKeys?.includes(r.key)) return { ...r, status: 'skipped', note: 'kept your existing server' };
397
+ return r;
398
+ });
399
+ }
400
+
401
+ export function formatTable(rows, rel) {
402
+ const cells = rows.map((r) => [r.item, rel(r.source), rel(r.target), r.status + (r.note ? ` (${r.note})` : '')]);
403
+ const head = ['item', 'source', 'target', 'status'];
404
+ const w = head.map((h, i) => Math.max(h.length, ...cells.map((c) => c[i].length)));
405
+ const line = (c) => ` ${c.map((v, i) => v.padEnd(w[i])).join(' ').trimEnd()}`;
406
+ return [line(head), ...cells.map(line)].join('\n');
407
+ }
@@ -0,0 +1,79 @@
1
+ // Network choices (telemetry, auto-update, other outbound calls) and proxy handling for child commands.
2
+ import os from 'node:os';
3
+ export const CATEGORIES = ['telemetry', 'autoUpdate', 'outbound'];
4
+ export const preset = (value) => Object.fromEntries(CATEGORIES.map((c) => [c, value]));
5
+
6
+ export function onOff(flag, v) {
7
+ if (v !== 'on' && v !== 'off') throw new Error(`${flag} takes on or off`);
8
+ return v;
9
+ }
10
+
11
+ // Old state files and --privacy only know standard/strict.
12
+ export function fromPrivacy(privacy) {
13
+ if (privacy == null) return null;
14
+ if (privacy !== 'strict' && privacy !== 'standard') throw new Error('--privacy takes standard or strict');
15
+ return preset(privacy === 'strict' ? 'off' : 'on');
16
+ }
17
+
18
+ export const privacyOf = (network) => (CATEGORIES.every((c) => network[c] === 'off') ? 'strict' : 'standard');
19
+
20
+ // Env for the commands lean-agents runs, so installers do not phone home when telemetry is off.
21
+ export function childEnv(network) {
22
+ return network.telemetry === 'off' ? { DO_NOT_TRACK: '1', HOMEBREW_NO_ANALYTICS: '1', GH_TELEMETRY: 'false' } : {};
23
+ }
24
+
25
+ export const PROXY_VARS = ['HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY'];
26
+ export const CA_VARS = ['NODE_EXTRA_CA_CERTS', 'NODE_USE_SYSTEM_CA', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'GIT_SSL_CAINFO', 'UV_SYSTEM_CERTS', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'PIP_CERT', 'npm_config_cafile'];
27
+
28
+ export const redactUrl = (v) => v.replace(/(^|\/\/|=)[^/\s=]*@/g, '$1***@');
29
+
30
+ // Names whose values are secrets: redactText scrubs their values, allowedEnv never passes them on.
31
+ export const SECRET_NAME = /TOKEN|SECRET|PASSW|API_?KEY|(^|_)AUTH($|_)|CREDENTIAL|PRIVATE/i;
32
+
33
+ // Light scrub for proxy and CA values the user needs to read: no userinfo, no query string, home as ~.
34
+ export function scrubValue(v, home = os.homedir()) {
35
+ const out = redactUrl(v).replace(/\?\S*/g, '?<redacted>');
36
+ return home ? out.split(home).join('~') : out;
37
+ }
38
+
39
+ // What a child process may inherit. Sources are in docs/compatibility.md; the rest (GH_TOKEN, API keys, ...) stays here.
40
+ const ENV_EXACT = new Set(['PATH', 'HOME', 'USER', 'LOGNAME', 'USERNAME', 'SHELL', 'TERM', 'COLORTERM', 'LANG', 'TZ', 'TMPDIR', 'TMP', 'TEMP', 'CI', 'NODE_OPTIONS', 'NODE_USE_ENV_PROXY', 'OPENSSL_CONF', 'DO_NOT_TRACK', 'COPILOT_HOME', 'CLAUDE_CONFIG_DIR', 'BUN_INSTALL']);
41
+ const ENV_WINDOWS = ['SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'ProgramData', 'ProgramFiles', 'ProgramFiles(x86)', 'ProgramW6432', 'CommonProgramFiles', 'HOMEDRIVE', 'HOMEPATH', 'OS', 'PROCESSOR_ARCHITECTURE', 'NUMBER_OF_PROCESSORS', 'PSModulePath', 'ALLUSERSPROFILE', 'PUBLIC', 'COMPUTERNAME'];
42
+ const ENV_PREFIX = ['LC_', 'XDG_', 'NPM_CONFIG_', 'NODE_', 'NVM_', 'FNM_', 'VOLTA_', 'HOMEBREW_', 'UV_', 'GIT_', 'BUN_', 'OPENCODE_'];
43
+
44
+ export function allowedEnv(env = process.env, platform = process.platform) {
45
+ const exact = new Set([...ENV_EXACT, ...PROXY_VARS, ...CA_VARS, ...(platform === 'win32' ? ENV_WINDOWS : [])].map((n) => n.toUpperCase()));
46
+ const out = {};
47
+ const seen = new Set(); // Windows keeps one key per name in any case; a plain object could hold both
48
+ for (const [name, value] of Object.entries(env)) {
49
+ const up = name.toUpperCase();
50
+ if (value == null || SECRET_NAME.test(name) || seen.has(up)) continue;
51
+ if (exact.has(up) || ENV_PREFIX.some((p) => up.startsWith(p))) { out[name] = value; seen.add(up); }
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // Tools disagree on case (brew and git read lowercase, uv uppercase), so both cases get the value.
57
+ // Only process.env changes: proxy values are never written to disk.
58
+ export function shareProxy(env = process.env) {
59
+ for (const name of PROXY_VARS) {
60
+ const value = env[name] || env[name.toLowerCase()];
61
+ if (!value) continue;
62
+ env[name] ??= value;
63
+ env[name.toLowerCase()] ??= value;
64
+ }
65
+ if ((env.HTTPS_PROXY || env.HTTP_PROXY) && env.NODE_USE_ENV_PROXY == null) env.NODE_USE_ENV_PROXY = '1';
66
+ }
67
+
68
+ // True when a proxy is configured (NO_PROXY alone is not one).
69
+ export const hasProxy = (env = process.env) => PROXY_VARS.slice(0, 3).some((n) => env[n] || env[n.toLowerCase()]);
70
+
71
+ export function proxyReport(env = process.env, home = os.homedir()) {
72
+ const lines = [];
73
+ for (const name of PROXY_VARS) {
74
+ const value = env[name] || env[name.toLowerCase()];
75
+ if (value) lines.push(`${name}=${scrubValue(value, home)}`);
76
+ }
77
+ for (const name of CA_VARS) if (env[name]) lines.push(`${name}=${scrubValue(env[name], home)}`);
78
+ return lines;
79
+ }
@@ -0,0 +1,85 @@
1
+ // Which Node runs each tool. A tool whose `engines.node` (core/pins.json `node`) the active Node fails gets an installed
2
+ // Node of its own, found through nvm, and an absolute command; without nvm it is skipped with one line (#44, #104).
3
+
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+
7
+ // shortcut: only ">=a[.b[.c]]" ranges, which every pinned tool uses today; verify-pins keeps the pins honest. Anything else throws.
8
+ export function minVersion(range) {
9
+ const m = /^>=\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?$/.exec(String(range).trim());
10
+ if (!m) throw new Error(`unsupported node range "${range}" (only >=a.b.c)`);
11
+ return [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)];
12
+ }
13
+
14
+ const parse = (v) => String(v).replace(/^v/, '').split('.').map(Number);
15
+ export function compare(a, b) {
16
+ const [x, y] = [Array.isArray(a) ? a : parse(a), Array.isArray(b) ? b : parse(b)];
17
+ for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) - (y[i] ?? 0);
18
+ return 0;
19
+ }
20
+
21
+ // True when `version` ("22.20.0" or "v22.20.0") meets `range`; a missing range accepts every Node.
22
+ export const satisfies = (version, range) => !range || compare(version, minVersion(range)) >= 0;
23
+
24
+ // nvm (macOS, Linux) or nvm-windows. `env`/`home` are passed in so tests and --home never read the real machine.
25
+ // POSIX: NVM_DIR counts only when it lies inside the target home or the target is the real home; a dev run with --home <temp>
26
+ // must never `nvm install` into the owner's nvm, so it uses <home>/.nvm. nvm-windows is only scanned (never installed into), so NVM_HOME is always used.
27
+ export function findNvm({ env, home, platform, realHome }) {
28
+ const win = platform === 'win32';
29
+ const inside = env.NVM_DIR && (home === realHome || !path.relative(home, env.NVM_DIR).startsWith('..') && !path.isAbsolute(path.relative(home, env.NVM_DIR)));
30
+ const dir = win ? env.NVM_HOME : inside ? env.NVM_DIR : path.join(home, '.nvm');
31
+ if (!dir || !fs.existsSync(win ? dir : path.join(dir, 'nvm.sh'))) return null;
32
+ return { win, dir };
33
+ }
34
+
35
+ // Every installed Node, lowest first. Layouts: POSIX $NVM_DIR/versions/node/vX/{bin/node,lib/node_modules}, Windows %NVM_HOME%\vX\{node.exe,node_modules}.
36
+ export function installedNodes(nvm) {
37
+ const root = nvm.win ? nvm.dir : path.join(nvm.dir, 'versions', 'node');
38
+ if (!fs.existsSync(root)) return [];
39
+ // A folder without its node binary is the rest of a failed install: not a Node to reuse.
40
+ return fs.readdirSync(root).filter((d) => /^v\d+\.\d+\.\d+$/.test(d)).sort(compare).map((d) => nodeAt(nvm, path.join(root, d), d.slice(1))).filter((n) => fs.existsSync(n.node));
41
+ }
42
+
43
+ export function nodeAt(nvm, dir, version) {
44
+ const modules = path.join(dir, nvm.win ? 'node_modules' : path.join('lib', 'node_modules'));
45
+ return { version, dir, node: path.join(dir, nvm.win ? 'node.exe' : path.join('bin', 'node')), pathDir: nvm.win ? dir : path.join(dir, 'bin'), modules, npmCli: path.join(modules, 'npm', 'bin', 'npm-cli.js'), npxCli: path.join(modules, 'npm', 'bin', 'npx-cli.js') };
46
+ }
47
+
48
+ export const nodeSkipLine = (tool, range, found) => `${tool} needs Node ${range}, found ${found}: skipped. Install nvm or Node ${minVersion(range).slice(0, 2).join('.')}+, then run --update.`;
49
+
50
+ // Pins in use whose range the active Node fails -> { toolNode, skipped }. `pins`: { key: { node } } already filtered to the
51
+ // ones in use. `toolNode` is null when none fails or nothing can run them. All failing pins share one Node, the one for the highest floor.
52
+ // A Node that is not installed yet gets `install` (the major) and the version `latest(major)` reports, so configs can name its path.
53
+ export function resolveToolNodes({ pins, active, nvm, latest }) {
54
+ const failing = Object.entries(pins).filter(([, p]) => !satisfies(active, p.node));
55
+ if (!failing.length) return { toolNode: null, skipped: [] };
56
+ const floor = failing.map(([, p]) => minVersion(p.node)).sort(compare).at(-1);
57
+ const range = `>=${floor.join('.')}`;
58
+ const have = nvm && installedNodes(nvm).find((n) => satisfies(n.version, range));
59
+ if (have) return { toolNode: have, tools: failing.map(([k]) => k), skipped: [] };
60
+ const version = nvm && !nvm.win && latest?.(floor[0]);
61
+ if (version && satisfies(version, range)) return { toolNode: { ...nodeAt(nvm, path.join(nvm.dir, 'versions', 'node', `v${version}`), version), install: floor[0] }, tools: failing.map(([k]) => k), skipped: [] };
62
+ return { toolNode: null, skipped: failing.map(([k, p]) => ({ tool: k, line: nodeSkipLine(k, p.node, active) })) };
63
+ }
64
+
65
+ // `env` for a command that must find this Node first: its folder leads PATH (npm starts package bins with the first `node` on PATH).
66
+ export function toolEnv(toolNode, penv = process.env, platform = process.platform) {
67
+ const key = platform === 'win32' ? Object.keys(penv).find((k) => k.toUpperCase() === 'PATH') ?? 'Path' : 'PATH';
68
+ return { [key]: [toolNode.pathDir, penv[key]].filter(Boolean).join(platform === 'win32' ? ';' : ':') };
69
+ }
70
+
71
+ // nvm refuses to work while an npm prefix is set ("nvm is not compatible with the npm_config_prefix environment variable"), and users
72
+ // and throwaway HOMEs often set one. Every nvm command runs with both spellings removed (an undefined value drops the variable from the child env).
73
+ export const nvmEnv = (nvmDir) => ({ NVM_DIR: nvmDir, npm_config_prefix: undefined, NPM_CONFIG_PREFIX: undefined });
74
+
75
+ // nvm installs the newest Node of a major and makes the first one `default`; the user's default stays as it was (none before: none after).
76
+ export const nvmInstallArgv = (major) => ['bash', '-c',
77
+ `had=0; [ -e "$NVM_DIR/alias/default" ] && had=1; . "$NVM_DIR/nvm.sh" --no-use && nvm install ${Number(major)} && { [ $had = 1 ] || rm -f "$NVM_DIR/alias/default"; }`];
78
+
79
+ // Newest published Node of a major through nvm (network). LEAN_AGENTS_NVM_REMOTE fakes it for tests, like LEAN_AGENTS_NODE.
80
+ export function nvmLatest(nvm, major, { env = process.env, run }) {
81
+ if (env.LEAN_AGENTS_NVM_REMOTE) return env.LEAN_AGENTS_NVM_REMOTE;
82
+ const r = run(['bash', '-c', `. "$NVM_DIR/nvm.sh" --no-use && nvm version-remote ${Number(major)}`], 30000, nvmEnv(nvm.dir));
83
+ const v = r.ok && /v(\d+\.\d+\.\d+)\s*$/.exec(r.out.trim());
84
+ return v ? v[1] : null;
85
+ }