lean-agents 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +407 -0
- package/LICENSE +21 -0
- package/README.es.md +560 -0
- package/README.md +559 -2
- package/core/AGENTS.es.md +60 -0
- package/core/AGENTS.md +60 -0
- package/core/README.md +8 -0
- package/core/agents/debug.md +14 -0
- package/core/agents/explore.md +13 -0
- package/core/agents/planner.md +14 -0
- package/core/agents/research.md +13 -0
- package/core/agents/review.md +13 -0
- package/core/copilot-usage-tui.js +189 -0
- package/core/mcp.json +38 -0
- package/core/pins.json +39 -0
- package/core/tiers.json +4 -0
- package/node_modules/@clack/core/LICENSE +9 -0
- package/node_modules/@clack/core/README.md +22 -0
- package/node_modules/@clack/core/dist/index.d.mts +503 -0
- package/node_modules/@clack/core/dist/index.mjs +1003 -0
- package/node_modules/@clack/core/package.json +63 -0
- package/node_modules/@clack/prompts/LICENSE +9 -0
- package/node_modules/@clack/prompts/README.md +396 -0
- package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
- package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
- package/node_modules/@clack/prompts/package.json +67 -0
- package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
- package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
- package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
- package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
- package/node_modules/fast-string-truncated-width/license +21 -0
- package/node_modules/fast-string-truncated-width/package.json +35 -0
- package/node_modules/fast-string-truncated-width/readme.md +59 -0
- package/node_modules/fast-string-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-width/dist/index.js +14 -0
- package/node_modules/fast-string-width/license +21 -0
- package/node_modules/fast-string-width/package.json +34 -0
- package/node_modules/fast-string-width/readme.md +42 -0
- package/node_modules/fast-wrap-ansi/LICENSE +23 -0
- package/node_modules/fast-wrap-ansi/README.md +26 -0
- package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
- package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
- package/node_modules/fast-wrap-ansi/package.json +51 -0
- package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
- package/node_modules/jsonc-parser/LICENSE.md +21 -0
- package/node_modules/jsonc-parser/README.md +364 -0
- package/node_modules/jsonc-parser/SECURITY.md +41 -0
- package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
- package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
- package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
- package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
- package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
- package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
- package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
- package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
- package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
- package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
- package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
- package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
- package/node_modules/jsonc-parser/package.json +37 -0
- package/node_modules/sisteransi/license +21 -0
- package/node_modules/sisteransi/package.json +34 -0
- package/node_modules/sisteransi/readme.md +113 -0
- package/node_modules/sisteransi/src/index.js +58 -0
- package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
- package/package.json +30 -4
- package/profiles/README.md +10 -0
- package/profiles/anthropic-api/gsd-defaults.json +26 -0
- package/profiles/anthropic-api.json +18 -0
- package/profiles/antigravity.json +12 -0
- package/profiles/claude-subscription/gsd-defaults.json +26 -0
- package/profiles/claude-subscription.json +17 -0
- package/profiles/github-copilot/gsd-defaults.json +26 -0
- package/profiles/github-copilot.json +17 -0
- package/profiles/openai-api/gsd-defaults.json +26 -0
- package/profiles/openai-api.json +17 -0
- package/profiles/opencode-go/gsd-defaults.json +26 -0
- package/profiles/opencode-go.json +17 -0
- package/profiles/vertex-gemini/gsd-defaults.json +26 -0
- package/profiles/vertex-gemini.json +18 -0
- package/scripts/adhd-skill.mjs +12 -0
- package/scripts/behavior-diff.sh +47 -0
- package/scripts/bump-pins.mjs +115 -0
- package/scripts/check-private.sh +52 -0
- package/scripts/check-readme.mjs +131 -0
- package/scripts/ci-download.sh +20 -0
- package/scripts/ci-install-opencode-v2.sh +6 -0
- package/scripts/ci-latest-report.mjs +38 -0
- package/scripts/ci-timing.mjs +61 -0
- package/scripts/copilot-context-mode.mjs +33 -0
- package/scripts/labels.sh +56 -0
- package/scripts/lean.mjs +1319 -0
- package/scripts/lib/adapters/antigravity.mjs +83 -0
- package/scripts/lib/adapters/claude.mjs +127 -0
- package/scripts/lib/adapters/copilot-cli.mjs +82 -0
- package/scripts/lib/adapters/cursor.mjs +60 -0
- package/scripts/lib/adapters/opencode-v1.mjs +79 -0
- package/scripts/lib/adapters/opencode-v2.mjs +216 -0
- package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
- package/scripts/lib/adhd.mjs +28 -0
- package/scripts/lib/adopt.mjs +619 -0
- package/scripts/lib/agent-lifecycle.mjs +280 -0
- package/scripts/lib/backup-stamp.mjs +25 -0
- package/scripts/lib/copilot-usage.mjs +49 -0
- package/scripts/lib/doctor.mjs +279 -0
- package/scripts/lib/feedback.mjs +48 -0
- package/scripts/lib/fsops.mjs +319 -0
- package/scripts/lib/gsd.mjs +42 -0
- package/scripts/lib/inventory.mjs +196 -0
- package/scripts/lib/lean-update.mjs +30 -0
- package/scripts/lib/logins.mjs +28 -0
- package/scripts/lib/migrate.mjs +407 -0
- package/scripts/lib/network.mjs +119 -0
- package/scripts/lib/node-runtime.mjs +85 -0
- package/scripts/lib/opencode-backup.mjs +204 -0
- package/scripts/lib/opencode-upgrade.mjs +441 -0
- package/scripts/lib/opencode1.mjs +203 -0
- package/scripts/lib/parallel.mjs +270 -0
- package/scripts/lib/pins-diff.mjs +33 -0
- package/scripts/lib/pins.mjs +52 -0
- package/scripts/lib/plugin-health.mjs +191 -0
- package/scripts/lib/prereqs.mjs +203 -0
- package/scripts/lib/project.mjs +38 -0
- package/scripts/lib/redact.mjs +30 -0
- package/scripts/lib/render.mjs +101 -0
- package/scripts/lib/shell-path.mjs +22 -0
- package/scripts/lib/summary-data.mjs +30 -0
- package/scripts/lib/summary-html.mjs +159 -0
- package/scripts/lib/system.mjs +269 -0
- package/scripts/lib/terminals.mjs +316 -0
- package/scripts/lib/ui.mjs +34 -0
- package/scripts/lib/unverified.mjs +49 -0
- package/scripts/lib/update-plan.mjs +60 -0
- package/scripts/lib/upgrade.mjs +231 -0
- package/scripts/lib/verify-commit.mjs +16 -0
- package/scripts/lib/verify-prompt.mjs +46 -0
- package/scripts/lib/verify-sha256.mjs +20 -0
- package/scripts/lint-workflows.mjs +25 -0
- package/scripts/models-refresh.mjs +58 -0
- package/scripts/parallel.mjs +59 -0
- package/scripts/pins-latest.mjs +66 -0
- package/scripts/release.mjs +71 -0
- package/scripts/verify-pins.mjs +36 -0
- package/scripts/version-watch.mjs +124 -0
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
// --adopt: inventory of a hand-built machine, each item classified and given the action a later
|
|
2
|
+
// apply would take. Read-only: nothing is written, env and header values are never read, the OpenCode database is only
|
|
3
|
+
// read through a copy (#106, #132). `home`, `env`, `platform` and `fsx` are passed in so tests never read the real machine.
|
|
4
|
+
// With --yes it applies the plan (adoptApply: backup, edits, verify, automatic undo on failure); --adopt --undo restores from the backup.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { execFileSync } from 'node:child_process';
|
|
10
|
+
import { parse } from 'jsonc-parser';
|
|
11
|
+
import { hasMark, plan as planFiles, revertJsonEdits, sha, writePrivate, privateDir, dropBackups, unsafe } from './fsops.mjs';
|
|
12
|
+
import { PINS, npmSpec, pinVersions } from './pins.mjs';
|
|
13
|
+
import { configHome, envDir, antigravityFootprint } from './system.mjs';
|
|
14
|
+
import { configPath } from './adapters/opencode-v2.mjs';
|
|
15
|
+
import { mcpServers } from './migrate.mjs';
|
|
16
|
+
import { findNvm, resolveToolNodes, minVersion, compare, satisfies, installedNodes, toolEnv } from './node-runtime.mjs';
|
|
17
|
+
import { run } from './system.mjs';
|
|
18
|
+
import { doctor } from './doctor.mjs';
|
|
19
|
+
import { pluginHealth, probePlugins } from './plugin-health.mjs';
|
|
20
|
+
import { orcaHooksFound } from './terminals.mjs';
|
|
21
|
+
import { clients, launchOf, pinOf, classify, npmCopies, skillDirs, duplicateSkills, treeSha, probeInitialize } from './inventory.mjs';
|
|
22
|
+
|
|
23
|
+
const j = path.join;
|
|
24
|
+
const MANAGED_SKILLS = new Set(Object.entries(PINS).filter(([, p]) => p.kind === 'skill').map(([k]) => k));
|
|
25
|
+
const MANAGED_HOOK = /\b(rtk|context-mode|gsd)\b/;
|
|
26
|
+
// A pre-release sorts below its release (#204). shortcut: two pre-releases of one core compare equal, no -beta.2 vs -beta.10 order; upgrade when a pinned tool ships two.
|
|
27
|
+
export const cmpVersion = (a, b) => compare(String(a).split(/[-+]/)[0], String(b).split(/[-+]/)[0]) || (String(b).split('+')[0].includes('-') - String(a).split('+')[0].includes('-')); // build metadata (+x) is ignored (#219)
|
|
28
|
+
// Shell syntax (GSD's `$(for n in ...; done) file.js`) is named after the first script it runs (#202).
|
|
29
|
+
const SHELL_HEAD = /^(\$\(|\(|\{)|^(for|if|while)$/;
|
|
30
|
+
const SCRIPT_PATH = /[^\s"'();|&]+\.(?:[cm]?js|ts|ps1|sh)(?![\w.])/;
|
|
31
|
+
// win32.basename splits both separators, so a Windows path never leaks into a name on macOS or Linux.
|
|
32
|
+
export const cursorHookLabel = (command, argv) => {
|
|
33
|
+
if (!(SHELL_HEAD.test(argv[0]) || (/^(sh|bash)$/.test(argv[0]) && argv[1] === '-c'))) return path.win32.basename(argv[0]);
|
|
34
|
+
const script = command.match(SCRIPT_PATH);
|
|
35
|
+
return script ? path.win32.basename(script[0]) : 'shell';
|
|
36
|
+
};
|
|
37
|
+
// PowerShell -e, -ec, -enc...: the payload is never named or matched; `--encoding` is not one.
|
|
38
|
+
// Bare `-e`/`-ec` only count next to powershell/pwsh: `node -e 1` is not a payload.
|
|
39
|
+
export const cursorEncoded = (command) => /(^|\s)-enc\w*(\s|$)/i.test(command) || (/\b(powershell|pwsh)(\.exe)?\b/i.test(command) && /(^|\s)-ec?(\s|$)/i.test(command));
|
|
40
|
+
// The basename of any argument counts (`npx -y context-mode hook cursor`, `env FOO=1 rtk hook cursor`); a folder never does: `node /opt/rtk-fork/hook.js` is the user's.
|
|
41
|
+
// Flags, URLs and whitespace tokens (`sh -c "echo rtk"`) are arguments, not program names (#235).
|
|
42
|
+
const nameToken = (a) => !/^[A-Za-z_]\w*=/.test(a) && !a.startsWith('-') && !a.includes('://') && !/\s/.test(a);
|
|
43
|
+
export const cursorNameManaged = (command, argv) => argv.some((a) => nameToken(a) && MANAGED_HOOK.test(path.win32.basename(a))) || MANAGED_HOOK.test(cursorHookLabel(command, argv));
|
|
44
|
+
const MANAGED_PLUGIN = /context-mode|opencode-dcp|opencode-warp|lean-agents/;
|
|
45
|
+
|
|
46
|
+
const readJson = (file) => { try { return parse(fs.readFileSync(file, 'utf8'), [], { allowTrailingComma: true }) ?? null; } catch { return null; } };
|
|
47
|
+
const readJsonText = (file) => { try { return fs.readFileSync(file, 'utf8'); } catch { return null; } };
|
|
48
|
+
const pinVersion = (argv, pin) => {
|
|
49
|
+
const m = argv.map((a) => new RegExp(`${PINS[pin].source.replace(/[/.]/g, '\\$&')}@(\\d[^\\s/]*)$`).exec(a)).find(Boolean);
|
|
50
|
+
return m?.[1] ?? null;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Hand-made stopgaps from the original machine (issue #123 last comment, #78, #132): path under home → what replaces them.
|
|
54
|
+
// `needs`: what state.json must record before the replacement counts as installed (a tool or a terminal integration).
|
|
55
|
+
const CUSAGE = 'the managed `copilot-usage` tool (--tools copilot-usage)';
|
|
56
|
+
const STOPGAPS = [
|
|
57
|
+
{ rel: ['.local', 'bin', 'copilot-usage'], by: CUSAGE, needs: { tools: 'copilot-usage' } },
|
|
58
|
+
{ rel: ['.local', 'bin', 'copilot-usage.ps1'], by: CUSAGE, needs: { tools: 'copilot-usage' } },
|
|
59
|
+
{ rel: ['.config', 'opencode', 'plugins', 'copilot-usage-tui'], by: CUSAGE, needs: { tools: 'copilot-usage' } },
|
|
60
|
+
{ rel: ['.config', 'opencode', 'plugins', 'orca-status-tui-shim.js'], by: 'the managed Orca integration (--terminal orca)', needs: { terminals: 'orca' } },
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
// node:sqlite needs no flag from Node 22.13 and 23.4 (24.x too); a tool Node older than that is not tried.
|
|
64
|
+
export const sqliteOk = (v) => { const [a, b] = minVersion(`>=${v}`); return a >= 24 || (a === 23 && b >= 4) || (a === 22 && b >= 13); };
|
|
65
|
+
const COUNT_SCRIPT = "const{DatabaseSync}=require('node:sqlite');const d=new DatabaseSync(process.argv[1],{readOnly:true});console.log(d.prepare('SELECT count(*) AS n FROM session').get().n)";
|
|
66
|
+
|
|
67
|
+
// Count in a child Node when this one lacks node:sqlite (#201): the tool Node first, then this Node with the flag. null when neither answers.
|
|
68
|
+
export function countInChild(dbCopy, toolNode) {
|
|
69
|
+
const tried = [];
|
|
70
|
+
const cands = [
|
|
71
|
+
...(toolNode?.node && sqliteOk(toolNode.version) ? [{ node: toolNode.node, flags: [], label: `Node ${toolNode.version}` }] : []),
|
|
72
|
+
{ node: process.execPath, flags: ['--experimental-sqlite'], label: `Node ${process.version} --experimental-sqlite` },
|
|
73
|
+
];
|
|
74
|
+
for (const c of cands) {
|
|
75
|
+
tried.push(c.label);
|
|
76
|
+
try {
|
|
77
|
+
// A real 7 GB db took 6 s to count (#179 PC run): 5 s made backup and --undo refuse. 10 min covers far larger dbs.
|
|
78
|
+
const out = execFileSync(c.node, [...c.flags, '-e', COUNT_SCRIPT, dbCopy], { encoding: 'utf8', timeout: 600000, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
79
|
+
if (/^\d+$/.test(out)) return { sessions: Number(out) }; // empty output is a failure, not 0
|
|
80
|
+
} catch (e) { if (e.code === 'ETIMEDOUT') tried[tried.length - 1] += ' (timed out)'; }
|
|
81
|
+
}
|
|
82
|
+
return { tried };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// OpenCode: major from the config shape (2.x: mcp.servers / plugins; 1.x: flat mcp / plugin), data folder, db size, session count read from a COPY.
|
|
86
|
+
// `opts.toolNode` ({version, node}): where the count runs when this Node lacks node:sqlite; `opts.sqliteImport` lets tests hide node:sqlite.
|
|
87
|
+
export async function opencodeInfo(home, env, fsx = fs, { toolNode = null, sqliteImport = () => import('node:sqlite') } = {}) {
|
|
88
|
+
const cfgFile = configPath(j(configHome(home), 'opencode'));
|
|
89
|
+
const cfg = readJson(cfgFile);
|
|
90
|
+
const major = !cfg ? null : cfg.mcp?.servers || cfg.plugins ? 2 : 1; // VERIFY with `opencode --version` in real-adopt
|
|
91
|
+
const dataDir = j(envDir(home, 'XDG_DATA_HOME', j(home, '.local', 'share')), 'opencode');
|
|
92
|
+
const dbs = fsx.existsSync(dataDir) ? fsx.readdirSync(dataDir).filter((f) => /^opencode\.db(-wal|-shm)?$/.test(f)) : [];
|
|
93
|
+
const dbBytes = dbs.reduce((n, f) => n + fsx.statSync(j(dataDir, f)).size, 0);
|
|
94
|
+
const out = { major, dataDir, dbBytes, sessions: null };
|
|
95
|
+
if (!dbs.includes('opencode.db')) return { ...out, note: 'no opencode.db' };
|
|
96
|
+
let sqlite = null;
|
|
97
|
+
try { sqlite = await sqliteImport(); } catch { /* counted in a child below */ }
|
|
98
|
+
const tmp = fs.mkdtempSync(j(os.tmpdir(), 'lean-adopt-'));
|
|
99
|
+
try {
|
|
100
|
+
for (const f of dbs) fs.copyFileSync(j(dataDir, f), j(tmp, f));
|
|
101
|
+
if (!sqlite) {
|
|
102
|
+
const c = countInChild(j(tmp, 'opencode.db'), toolNode);
|
|
103
|
+
if (c.tried) out.note = `node:sqlite is not available on this Node: sessions not counted (tried ${c.tried.join(', ')})`;
|
|
104
|
+
else out.sessions = c.sessions;
|
|
105
|
+
return out;
|
|
106
|
+
}
|
|
107
|
+
const db = new sqlite.DatabaseSync(j(tmp, 'opencode.db'), { readOnly: true });
|
|
108
|
+
try { out.sessions = Number(db.prepare('SELECT count(*) AS n FROM session').get().n); } finally { db.close(); }
|
|
109
|
+
} catch (e) { out.note = `sessions not counted: ${String(e.message).split('\n')[0]}`; } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export async function inventory({ home, env = process.env, platform = process.platform, realHome = os.homedir(), fsx = fs }) {
|
|
114
|
+
const rel = (p) => (p && p.startsWith(home) ? `~${p.slice(home.length)}` : p);
|
|
115
|
+
const items = [];
|
|
116
|
+
const add = (it) => items.push({ client: it.client, kind: it.kind, name: it.name, file: rel(it.file), keyPath: it.keyPath ?? [], launch: it.launch ?? null, owner: it.owner, status: it.status ?? [], pin: it.pin ?? null, wanted: it.wanted ?? null, action: 'keep', ...(it.extra ?? {}) });
|
|
117
|
+
const shape = (l) => ({ style: l.style, node: rel(l.node), nodeVersion: l.nodeVersion });
|
|
118
|
+
const seen = new Set();
|
|
119
|
+
|
|
120
|
+
// --- MCP servers (names only; args and env stay unread)
|
|
121
|
+
const names = new Set();
|
|
122
|
+
for (const { client, file, keyPath } of clients(home)) {
|
|
123
|
+
for (const s of mcpServers(file, keyPath)) {
|
|
124
|
+
const id = `${file}\0${s.name}`;
|
|
125
|
+
if (seen.has(id)) continue;
|
|
126
|
+
seen.add(id);
|
|
127
|
+
const pin = s.command.length ? pinOf(s.command) : null;
|
|
128
|
+
const managed = Boolean(pin) || (s.name === 'serena' && s.command.includes('start-mcp-server'));
|
|
129
|
+
const status = [];
|
|
130
|
+
const launch = s.command.length ? launchOf(s.command, { env, platform, fsx }) : null;
|
|
131
|
+
let wanted = null;
|
|
132
|
+
if (launch && pin && classify(launch, pin).status === 'wrong-node') status.push('wrong-node');
|
|
133
|
+
if (pin) {
|
|
134
|
+
const v = pinVersion(s.command, pin);
|
|
135
|
+
wanted = PINS[pin].version;
|
|
136
|
+
if (v && v !== wanted) status.push('drift');
|
|
137
|
+
}
|
|
138
|
+
const abs = s.command[0] && path.isAbsolute(s.command[0]);
|
|
139
|
+
if (abs && !fsx.existsSync(s.command[0])) status.push('stale');
|
|
140
|
+
names.add(`${client}\0${s.name}`);
|
|
141
|
+
add({ client, kind: 'mcp', name: s.name, file, keyPath, launch: launch && shape(launch), owner: managed ? 'managed' : 'user', status, pin, wanted });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// --- Claude: hooks, enabledPlugins
|
|
146
|
+
const settings = j(home, '.claude', 'settings.json');
|
|
147
|
+
const cs = readJson(settings) ?? {};
|
|
148
|
+
for (const [event, groups] of Object.entries(cs.hooks ?? {})) {
|
|
149
|
+
for (const g of Array.isArray(groups) ? groups : []) {
|
|
150
|
+
for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
|
|
151
|
+
if (typeof h?.command !== 'string') continue;
|
|
152
|
+
const argv = h.command.split(/\s+/).filter(Boolean);
|
|
153
|
+
// Inline `VAR=value` prefixes can hold secrets: never use them as the name.
|
|
154
|
+
while (argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0])) argv.shift();
|
|
155
|
+
if (!argv.length) continue;
|
|
156
|
+
const pin = pinOf(argv);
|
|
157
|
+
const launch = launchOf(argv, { env, platform, fsx });
|
|
158
|
+
const status = [];
|
|
159
|
+
if (pin && classify(launch, pin).status === 'wrong-node') status.push('wrong-node');
|
|
160
|
+
if (path.isAbsolute(argv[0] ?? '') && !fsx.existsSync(argv[0])) status.push('stale');
|
|
161
|
+
add({ client: 'claude', kind: 'hook', name: `${event}:${path.basename(argv[0])}`, file: settings, keyPath: ['hooks', event], launch: shape(launch), owner: MANAGED_HOOK.test(h.command) ? 'managed' : 'user', status, pin });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// --- Cursor: hooks.json, {version, hooks: {event: [{command}]}} (cursor.com/docs/hooks, read 2026-11-13). Encoded payloads are never printed.
|
|
166
|
+
const cursorHooks = j(home, '.cursor', 'hooks.json');
|
|
167
|
+
const ch = readJson(cursorHooks);
|
|
168
|
+
const orcaFile = orcaHooksFound(home).includes(cursorHooks);
|
|
169
|
+
const seenCursor = new Map();
|
|
170
|
+
for (const [event, hooks] of Object.entries(ch?.hooks && typeof ch.hooks === 'object' ? ch.hooks : {})) {
|
|
171
|
+
for (const h of Array.isArray(hooks) ? hooks : []) {
|
|
172
|
+
if (typeof h?.command !== 'string') continue;
|
|
173
|
+
const argv = (h.command.match(/"[^"]*"|'[^']*'|\S+/g) ?? []).map((a) => a.replace(/^(["'])(.*)\1$/, '$2'));
|
|
174
|
+
while (argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0])) argv.shift();
|
|
175
|
+
if (!argv.length) continue;
|
|
176
|
+
const encoded = cursorEncoded(h.command);
|
|
177
|
+
// Only an absolute path can carry the mark: a bare `rtk` would resolve against the cwd.
|
|
178
|
+
const script = !encoded && path.isAbsolute(argv[0]) ? argv[0] : null;
|
|
179
|
+
// RTK and GSD write their own Cursor hooks without the mark, so the name match counts too (#199).
|
|
180
|
+
const managed = !encoded && (cursorNameManaged(h.command, argv) || (Boolean(script) && fsx.existsSync(script) && hasMark(readJsonText(script) ?? '')));
|
|
181
|
+
const base = `${event}:${encoded ? 'powershell' : cursorHookLabel(h.command, argv)}`;
|
|
182
|
+
// Same event and label twice (#198): the second gets `#2`, the third `#3`.
|
|
183
|
+
const n = seenCursor.get(base) ?? 0;
|
|
184
|
+
seenCursor.set(base, n + 1);
|
|
185
|
+
add({ client: 'cursor', kind: 'hook', name: n ? `${base}#${n + 1}` : base, file: cursorHooks, keyPath: ['hooks', event], owner: managed ? 'managed' : 'user', extra: encoded && orcaFile ? { note: 'Orca agent status hook' } : undefined });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const installed = readJson(j(home, '.claude', 'plugins', 'installed_plugins.json')); // VERIFY: name and shape, proven in real-adopt
|
|
189
|
+
const have = installed && typeof installed.plugins === 'object' ? installed.plugins : null;
|
|
190
|
+
for (const [key, on] of Object.entries(cs.enabledPlugins ?? {})) {
|
|
191
|
+
const stale = have && typeof have === 'object' && !(key in have);
|
|
192
|
+
add({ client: 'claude', kind: 'plugin', name: key, file: settings, keyPath: ['enabledPlugins', key], owner: /^(context-mode|ponytail)@/.test(key) ? 'managed' : 'user', status: stale ? ['stale'] : [], extra: { enabled: Boolean(on) } });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// --- OpenCode: plugin / plugins, tui.json plugin, plugins/ folder
|
|
196
|
+
const ocDir = j(configHome(home), 'opencode');
|
|
197
|
+
const ocCfg = configPath(ocDir);
|
|
198
|
+
const pluginEntry = (file, key, e) => {
|
|
199
|
+
const spec = Array.isArray(e) ? String(e[0]) : String(e);
|
|
200
|
+
const status = [];
|
|
201
|
+
let target = null;
|
|
202
|
+
try { target = spec.startsWith('file://') ? fileURLToPath(spec) : null; } catch { /* not a local file URL */ }
|
|
203
|
+
if (target && !fsx.existsSync(target)) status.push('stale');
|
|
204
|
+
if (/context-mode/.test(spec) && names.has('opencode\0context-mode')) status.push('duplicate'); // plugin and MCP; the MCP row gets the same mark below
|
|
205
|
+
// a local plugin is named `<folder>/<file>`: two `tui.js` in different folders stay distinct
|
|
206
|
+
const name = target ? `${path.basename(path.dirname(target))}/${path.basename(target)}` : spec.replace(/\/\/[^/@\s]*@/, '//').replace(/[?#].*$/, '');
|
|
207
|
+
add({ client: 'opencode', kind: 'plugin', name, file, keyPath: [key], owner: !target && MANAGED_PLUGIN.test(spec) ? 'managed' : 'user', status, extra: target ? { source: rel(target) } : {} });
|
|
208
|
+
};
|
|
209
|
+
for (const [file, keys] of [[ocCfg, ['plugin', 'plugins']], [j(ocDir, 'tui.json'), ['plugin']], [j(ocDir, 'tui.jsonc'), ['plugin']]]) {
|
|
210
|
+
const c = readJson(file);
|
|
211
|
+
for (const k of keys) for (const e of Array.isArray(c?.[k]) ? c[k] : []) pluginEntry(file, k, e);
|
|
212
|
+
}
|
|
213
|
+
const pdir = j(ocDir, 'plugins');
|
|
214
|
+
for (const e of fsx.existsSync(pdir) ? fsx.readdirSync(pdir, { withFileTypes: true }) : []) {
|
|
215
|
+
if (e.name.startsWith('.') || e.name === 'node_modules' || (!e.isDirectory() && !/\.[cm]?[jt]s$/.test(e.name))) continue; // package.json and friends are not plugins
|
|
216
|
+
const f = j(pdir, e.name);
|
|
217
|
+
let owned = false;
|
|
218
|
+
if (e.isFile()) { try { owned = hasMark(fs.readFileSync(f, 'utf8')); } catch { /* unreadable: user */ } }
|
|
219
|
+
add({ client: 'opencode', kind: 'plugin', name: `plugins/${e.name}`, file: f, owner: owned ? 'managed' : 'user' });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (items.some((i) => i.client === 'opencode' && i.kind === 'plugin' && i.status.includes('duplicate'))) {
|
|
223
|
+
const mcp = items.find((i) => i.client === 'opencode' && i.kind === 'mcp' && i.name === 'context-mode');
|
|
224
|
+
if (mcp) mcp.status.push('duplicate');
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// --- Skills in every folder some agent reads
|
|
228
|
+
const dirs = [...new Set(['claude', 'opencode', 'cursor', 'copilot'].flatMap((a) => skillDirs(a, home)))];
|
|
229
|
+
// A skill is a duplicate only in the folders one client reads together (#176); links count, a client scanning both paths meets it twice.
|
|
230
|
+
const dupRows = new Map(); // `${folder}\0${name}` -> { clients, copies: { folder: short sha }, differs, linked }
|
|
231
|
+
for (const a of ['claude', 'opencode', 'cursor', 'copilot']) {
|
|
232
|
+
for (const d of duplicateSkills(skillDirs(a, home), fsx, { links: true })) {
|
|
233
|
+
const group = d.dirs.map((x, i) => ({ dir: x, sha: d.shas[i] }));
|
|
234
|
+
for (const g of group) {
|
|
235
|
+
const row = dupRows.get(`${g.dir}\0${d.name}`) ?? { clients: [], copies: {}, differs: false, linked: false };
|
|
236
|
+
if (!row.clients.includes(a)) row.clients.push(a);
|
|
237
|
+
for (const x of group) row.copies[rel(x.dir)] = x.sha === 'unreadable' ? x.sha : x.sha.slice(0, 8);
|
|
238
|
+
row.differs ||= d.differs; row.linked ||= d.linked;
|
|
239
|
+
dupRows.set(`${g.dir}\0${d.name}`, row);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
for (const d of dirs) {
|
|
244
|
+
let list = [];
|
|
245
|
+
try { list = fsx.readdirSync(d).filter((n) => fsx.existsSync(j(d, n, 'SKILL.md'))); } catch { continue; }
|
|
246
|
+
for (const name of list) {
|
|
247
|
+
const dup = dupRows.get(`${d}\0${name}`);
|
|
248
|
+
const fix = dup && `keep one folder (e.g. ~/.agents/skills) and delete the other copy after a backup${dup.linked ? '; the copies are links, so remove the extra link, not the folder it points to' : ''}${Object.keys(dup.copies).includes('~/.claude/skills') ? '; Claude Code reads only ~/.claude/skills' : ''}`;
|
|
249
|
+
add({ client: 'skills', kind: 'skill', name, file: j(d, name), owner: MANAGED_SKILLS.has(name) ? 'managed' : 'user', status: dup ? ['duplicate'] : [], extra: dup ? { copies: Object.keys(dup.copies), hashes: dup.copies, clients: dup.clients.sort(), differs: dup.differs, linked: dup.linked, fix } : {} });
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// --- Antigravity IDE folders and VS Code extension: listed, never changed (#216)
|
|
254
|
+
for (const f of antigravityFootprint(home, fsx)) add({ client: 'antigravity', kind: 'ide', name: f.name, file: f.file, owner: 'user' });
|
|
255
|
+
|
|
256
|
+
// --- npm copies under each nvm Node, and the one Node the tools should use
|
|
257
|
+
const nvm = findNvm({ env, home, platform, realHome });
|
|
258
|
+
const copies = nvm ? npmCopies(nvm) : [];
|
|
259
|
+
// The npm copies count too: a context-mode copy with no context-mode MCP still needs its Node floor (#179 PC run).
|
|
260
|
+
const toolPins = Object.fromEntries([...new Set([...items.map((i) => i.pin), ...copies.map((c) => c.pin)].filter(Boolean))].map((k) => [k, PINS[k]]));
|
|
261
|
+
// active '0.0.0': the question is which Node the tools should run on, whatever Node runs this command.
|
|
262
|
+
const r = resolveToolNodes({ pins: toolPins, active: '0.0.0', nvm, latest: null });
|
|
263
|
+
const ranges = Object.values(toolPins).map((p) => p.node).filter(Boolean);
|
|
264
|
+
const floor = ranges.length ? ranges.map((x) => minVersion(x)).sort((a, b) => b[0] - a[0] || b[1] - a[1] || b[2] - a[2])[0].join('.') : null;
|
|
265
|
+
const tn = r.toolNode;
|
|
266
|
+
const toolNode = tn
|
|
267
|
+
? { version: tn.version, node: rel(tn.node), range: `>=${floor}`, source: tn.install ? 'install' : 'reuse' }
|
|
268
|
+
: { version: null, node: null, range: floor ? `>=${floor}` : null, source: null };
|
|
269
|
+
const byPin = new Map();
|
|
270
|
+
for (const c of copies) byPin.set(c.pin, [...(byPin.get(c.pin) ?? []), c]);
|
|
271
|
+
for (const c of copies) {
|
|
272
|
+
const status = [];
|
|
273
|
+
const cmp = cmpVersion(c.version, PINS[c.pin].version);
|
|
274
|
+
if (cmp < 0) status.push('drift');
|
|
275
|
+
else if (cmp > 0) status.push('newer'); // newer than the pin: nothing to upgrade
|
|
276
|
+
const dup = byPin.get(c.pin).length > 1;
|
|
277
|
+
if (dup) status.push('duplicate');
|
|
278
|
+
if (dup && !satisfies(c.node, PINS[c.pin].node)) status.push('below-floor'); // this copy cannot run: it is a removal, not an upgrade
|
|
279
|
+
add({ client: 'npm', kind: 'npm', name: `${c.name}@${c.version}`, file: c.prefix, owner: 'managed', status, pin: c.pin, wanted: PINS[c.pin].version, extra: { node: c.node } });
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// --- Known hand-made stopgaps: listed with their managed replacement
|
|
283
|
+
const stopgaps = STOPGAPS.filter((s) => fsx.existsSync(j(home, ...s.rel))).map((s) => ({ file: rel(j(home, ...s.rel)), replaceWith: s.by }));
|
|
284
|
+
|
|
285
|
+
// --- Actions
|
|
286
|
+
for (const it of items) {
|
|
287
|
+
const s = it.status;
|
|
288
|
+
if (it.owner === 'user') it.action = s.includes('stale') || s.includes('duplicate') ? 'ask' : 'keep';
|
|
289
|
+
else if (s.includes('wrong-node')) it.action = 'reinstall';
|
|
290
|
+
else if (s.includes('below-floor')) it.action = 'remove';
|
|
291
|
+
else if (s.includes('drift')) it.action = 'upgrade';
|
|
292
|
+
else if (s.includes('stale')) it.action = 'remove';
|
|
293
|
+
else if (s.includes('duplicate')) it.action = it.kind === 'skill' || it.kind === 'plugin' || it.kind === 'mcp' ? 'ask' : it.kind === 'npm' ? (tn && it.node !== tn.version ? 'remove' : 'keep') : 'remove';
|
|
294
|
+
}
|
|
295
|
+
const oc = await opencodeInfo(home, env, fsx, { toolNode: tn });
|
|
296
|
+
// Linked skill copies: --yes skips them (it never deletes a link target), so they are not plan steps (#226).
|
|
297
|
+
const byLink = (i) => i.kind === 'skill' && i.linked && i.status.includes('duplicate');
|
|
298
|
+
const plan = items.filter((i) => i.action !== 'keep' && !byLink(i)).map((i) => `${i.action} ${i.client} ${i.kind} ${i.name} (${i.status.join(', ') || i.owner})`);
|
|
299
|
+
for (const s of stopgaps) if (s.replaceWith) plan.push(`ask ${s.file}: replace with ${s.replaceWith}`);
|
|
300
|
+
const links = {};
|
|
301
|
+
for (const i of items.filter(byLink)) for (const c of i.copies) (links[i.name] ??= new Set()).add(c);
|
|
302
|
+
const byHand = Object.entries(links).map(([n, c]) => `skill ${n}: remove the extra link, keep one folder (${[...c].join(', ')})`);
|
|
303
|
+
return { version: 1, os: platform, toolNode, items, opencode: { ...oc, dataDir: rel(oc.dataDir) }, stopgaps, plan, byHand, health: pluginHealth(home, { fsx }), ok: !items.some((i) => i.action !== 'keep') };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export async function adopt(o) {
|
|
307
|
+
if (o.undo) return adoptUndo(o);
|
|
308
|
+
if (o.yes && !o.dryRun && !o.json) return adoptApply(o);
|
|
309
|
+
const r = await inventory(o);
|
|
310
|
+
if (o.probePlugins) r.health.push(...await probePlugins(o.home)); // opt-in: starts a short-lived opencode serve
|
|
311
|
+
// What --yes does (the apply plan, not only the inventory rows): the pin's target Node and the removals, which need a yes (#179 PC run).
|
|
312
|
+
const ap = adoptPlan(r, { home: o.home, env: o.env ?? process.env, platform: o.platform ?? process.platform, realHome: o.realHome ?? os.homedir(), state: readState(o.stateDir ?? j(o.home, '.config', 'lean-agents')) });
|
|
313
|
+
r.apply = applyLines(ap, o.home);
|
|
314
|
+
if (o.json) { process.stdout.write(`${JSON.stringify(r, null, 2)}\n`); return true; }
|
|
315
|
+
const by = {};
|
|
316
|
+
for (const i of r.items) by[`${i.kind}`] = (by[`${i.kind}`] ?? 0) + 1;
|
|
317
|
+
console.log(`--adopt (dry run: nothing is changed; --yes applies). Found: ${Object.entries(by).map(([k, n]) => `${n} ${k}`).join(', ') || 'nothing'}`);
|
|
318
|
+
console.log(`tool Node: ${r.toolNode.range ? `${r.toolNode.range} -> ${r.toolNode.node ?? 'no installed Node meets it (install one with nvm)'} (${r.toolNode.source ?? 'none'})` : 'not needed'}`);
|
|
319
|
+
console.log(`OpenCode: major ${r.opencode.major ?? 'none'}, ${r.opencode.dbBytes} bytes of db, sessions ${r.opencode.sessions ?? 'unknown'}${r.opencode.note ? ` (${r.opencode.note})` : ''}`);
|
|
320
|
+
for (const i of r.items.filter((x) => x.action !== 'keep' || x.owner === 'managed' || x.kind === 'hook' || x.kind === 'ide')) {
|
|
321
|
+
console.log(` ${i.action.padEnd(9)} ${i.owner.padEnd(8)} ${i.client} ${i.kind} ${i.name}${i.status.length ? ` [${i.status.join(', ')}]` : ''}${i.note ? ` (${i.note})` : ''} (${i.file})`);
|
|
322
|
+
if (i.kind === 'skill' && i.fix) console.log(` ${i.clients.join(' and ')} loads it twice: ${Object.entries(i.hashes).map(([d, h]) => `${d} ${h}`).join(', ')} (${i.differs ? 'differs' : 'identical'}); ${i.fix}`);
|
|
323
|
+
}
|
|
324
|
+
console.log(` user-owned items kept untouched: ${r.items.filter((i) => i.owner === 'user' && i.action === 'keep').length}`);
|
|
325
|
+
for (const f of r.health) console.log(` health ${f.plugin || 'probe'} [${f.id}] ${f.line}\n fix: ${f.fix}`);
|
|
326
|
+
for (const s of r.stopgaps) console.log(` stopgap ${s.file}${s.replaceWith ? `: replace with ${s.replaceWith}` : `: ${s.note}`}`);
|
|
327
|
+
console.log(r.plan.length ? `Plan (${r.plan.length} steps; add --yes to apply, --confirm-removals to allow the removals):\n${r.plan.map((l) => ` - ${l}`).join('\n')}` : 'Plan: nothing to change.');
|
|
328
|
+
if (r.byHand.length) console.log(`Fix by hand (--yes leaves these):\n${r.byHand.map((l) => ` - ${l}`).join('\n')}`);
|
|
329
|
+
if (r.apply.length) console.log(`--yes does:\n${r.apply.map((l) => ` - ${l}`).join('\n')}`);
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// One line per action adoptApply takes, in its order.
|
|
334
|
+
function applyLines(p, home) {
|
|
335
|
+
const rel = (f) => (f.startsWith(home) ? `~${f.slice(home.length)}` : f);
|
|
336
|
+
const yes = ' (needs a yes, or --confirm-removals)';
|
|
337
|
+
return [
|
|
338
|
+
...(p.install ? [`install ${PINS['context-mode'].source}@${PINS['context-mode'].version} into Node ${p.install.node.version}${p.install.have ? ` (now ${p.install.have})` : ''}`] : []),
|
|
339
|
+
...p.rewritten.map((w) => `re-register ${w.client} ${w.name} on Node ${p.tn.version} (${rel(w.file)})`),
|
|
340
|
+
...[...p.edits.keys()].filter((f) => !p.rewritten.some((w) => w.file === f)).map((f) => `edit ${rel(f)} (remove stale keys of ours)`),
|
|
341
|
+
...p.oldCopies.map((c) => `npm uninstall the old ${c.name}@${c.version} under Node ${c.node.version}${yes}`),
|
|
342
|
+
...p.dupSkills.map((d) => `remove the duplicate skill folder ${rel(d)}${yes}`),
|
|
343
|
+
...p.stopgaps.map((f) => `remove the stopgap ${rel(f)}${yes}`),
|
|
344
|
+
...p.notes.map((n) => `note: ${n}`),
|
|
345
|
+
];
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
349
|
+
// Apply and undo (#106). Everything below writes, and only inside `home` and `stateDir`.
|
|
350
|
+
const ROOT = fileURLToPath(new URL('../../', import.meta.url));
|
|
351
|
+
const absOf = (home, f) => (f === '~' || f.startsWith('~/') || f.startsWith('~\\') ? home + f.slice(1) : f);
|
|
352
|
+
const walk = (obj, p) => p.reduce((v, k) => (v && typeof v === 'object' ? v[k] : undefined), obj);
|
|
353
|
+
const stamp = () => new Date().toISOString().replace(/[:.]/g, '-');
|
|
354
|
+
const bytes = (f) => fs.readFileSync(f);
|
|
355
|
+
const relIn = (home, f) => (f.startsWith(home + path.sep) ? path.relative(home, f) : f.replace(/^[A-Za-z]:/, '').replace(/^[\\/]+/, ''));
|
|
356
|
+
|
|
357
|
+
// State file: --adopt adds `adopt` to an existing state.json, or creates one that only holds it (`adoptOnly`).
|
|
358
|
+
const stateFile = (stateDir) => j(stateDir, 'state.json');
|
|
359
|
+
const readState = (stateDir) => readJson(stateFile(stateDir));
|
|
360
|
+
export function saveState(stateDir, adoptState) {
|
|
361
|
+
const st = readState(stateDir) ?? {
|
|
362
|
+
version: JSON.parse(fs.readFileSync(j(ROOT, 'package.json'), 'utf8')).version, installedAt: new Date().toISOString(), pins: pinVersions(), adoptOnly: true,
|
|
363
|
+
options: { migrateOnly: true, agents: [], tools: [], privacy: 'standard', gh: false, terminals: [], unverified: {}, lang: 'en', profile: null, adhdAlways: false, ponytailMode: null, bun: false, shell: 'git-bash' },
|
|
364
|
+
files: [], commands: [],
|
|
365
|
+
};
|
|
366
|
+
st.updatedAt = new Date().toISOString();
|
|
367
|
+
st.adopt = adoptState;
|
|
368
|
+
privateDir(stateDir, stateDir);
|
|
369
|
+
writePrivate(stateFile(stateDir), `${JSON.stringify(st, null, 2)}\n`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// What to change, from one inventory. Pure: no writes. `state`: the saved state.json (tells which managed replacements exist).
|
|
373
|
+
export function adoptPlan(r, { home, env, platform, realHome, state, fsx = fs }) {
|
|
374
|
+
const nvm = findNvm({ env, home, platform, realHome });
|
|
375
|
+
const nodes = nvm ? installedNodes(nvm) : [];
|
|
376
|
+
const tn = r.toolNode.version ? nodes.find((n) => n.version === r.toolNode.version) ?? null : null;
|
|
377
|
+
const out = { tn, nodes, edits: new Map(), rewritten: [], install: null, oldCopies: [], dupSkills: [], stopgaps: [], notes: [] };
|
|
378
|
+
const addEdit = (file, e) => out.edits.set(file, [...(out.edits.get(file) ?? []), e]);
|
|
379
|
+
|
|
380
|
+
// Managed MCPs on the wrong or a moving Node -> `<tool Node> <entry>` (plan-106 section 2). `set`, not `upgradeIf`: the old value is recorded, so a key revert writes it back.
|
|
381
|
+
const pin = 'context-mode';
|
|
382
|
+
const cli = tn && j(tn.modules, 'context-mode', 'cli.mjs');
|
|
383
|
+
const seen = new Set();
|
|
384
|
+
for (const it of r.items) {
|
|
385
|
+
if (it.kind !== 'mcp' || it.owner !== 'managed' || it.pin !== pin || !['reinstall', 'upgrade'].includes(it.action)) continue;
|
|
386
|
+
const file = absOf(home, it.file);
|
|
387
|
+
const id = `${file}\0${it.keyPath.join('.')}\0${it.name}`;
|
|
388
|
+
if (seen.has(id)) continue;
|
|
389
|
+
seen.add(id);
|
|
390
|
+
if (!tn) { out.notes.push(`${it.client} ${it.name}: no installed Node meets ${r.toolNode.range}; install one with nvm, then run --adopt again`); continue; }
|
|
391
|
+
const entry = walk(readJson(file), [...it.keyPath, it.name]);
|
|
392
|
+
const base = [...it.keyPath, it.name];
|
|
393
|
+
if (Array.isArray(entry?.command)) addEdit(file, { path: [...base, 'command'], mode: 'set', value: [tn.node, cli, 'server'] });
|
|
394
|
+
else if (typeof entry?.command === 'string') { addEdit(file, { path: [...base, 'command'], mode: 'set', value: tn.node }); addEdit(file, { path: [...base, 'args'], mode: 'set', value: [cli, 'server'] }); }
|
|
395
|
+
else continue;
|
|
396
|
+
out.rewritten.push({ client: it.client, name: it.name, file, path: base, argv: [tn.node, cli, 'server'] });
|
|
397
|
+
}
|
|
398
|
+
// Stale keys of ours (a managed MCP whose command is gone, an enabledPlugins entry of ours without its plugin): removed, the old value recorded. A user's own stale key is only listed.
|
|
399
|
+
for (const it of r.items) {
|
|
400
|
+
if (it.owner !== 'managed' || it.action !== 'remove' || !it.status.includes('stale')) continue;
|
|
401
|
+
const p = it.kind === 'mcp' ? [...it.keyPath, it.name] : it.kind === 'plugin' && it.keyPath[0] === 'enabledPlugins' ? it.keyPath : null;
|
|
402
|
+
if (p) addEdit(absOf(home, it.file), { path: p, mode: 'remove' });
|
|
403
|
+
}
|
|
404
|
+
// The pinned package in the tool Node's prefix: needed by a rewritten MCP, or by a drift copy planned as `upgrade` (a copy on another Node is then removed below).
|
|
405
|
+
if (tn && (out.rewritten.length || r.items.some((i) => i.kind === 'npm' && i.pin === pin && i.action === 'upgrade'))) {
|
|
406
|
+
let have = null;
|
|
407
|
+
try { have = JSON.parse(fsx.readFileSync(j(tn.modules, 'context-mode', 'package.json'), 'utf8')).version; } catch { /* not installed there */ }
|
|
408
|
+
if (have !== PINS[pin].version) out.install = { have, node: tn };
|
|
409
|
+
}
|
|
410
|
+
if (!tn && r.toolNode.range && r.items.some((i) => i.kind === 'npm' && i.pin === pin && i.action === 'upgrade')) out.notes.push(`context-mode: no installed Node meets ${r.toolNode.range}; install one with nvm, then run --adopt again`);
|
|
411
|
+
// (a) old npm copies under another Node; (b) a skill in both folders; stopgaps with their managed replacement installed.
|
|
412
|
+
// A copy on another Node becomes a duplicate once this run installs the pin into the tool Node: removed now, a second --adopt --yes is refused (#179 PC run).
|
|
413
|
+
// Not a newer copy, and not one a user's own MCP or hook still runs on.
|
|
414
|
+
const userOn = (v) => r.items.find((i) => i.owner === 'user' && i.launch?.nodeVersion === v);
|
|
415
|
+
if (tn) for (const it of r.items) {
|
|
416
|
+
if (it.kind !== 'npm' || it.node === tn.version) continue;
|
|
417
|
+
const replaced = out.install && it.pin === pin && !it.status.includes('newer');
|
|
418
|
+
if (!it.status.includes('duplicate') && !replaced) continue;
|
|
419
|
+
const u = !it.status.includes('duplicate') && userOn(it.node);
|
|
420
|
+
if (u) { out.notes.push(`${it.name} under Node ${it.node} stays: your ${u.client} ${u.name} runs on that Node`); continue; }
|
|
421
|
+
const n = nodes.find((x) => x.version === it.node); if (n) out.oldCopies.push({ node: n, pin: it.pin, name: PINS[it.pin].source, version: it.name.replace(/^.*@/, '') });
|
|
422
|
+
}
|
|
423
|
+
const shared = j(home, '.agents', 'skills');
|
|
424
|
+
const claude = j(home, '.claude', 'skills');
|
|
425
|
+
const otherAgents = fsx.existsSync(j(home, '.cursor')) || fsx.existsSync(envDir(home, 'COPILOT_HOME', j(home, '.copilot')));
|
|
426
|
+
for (const name of new Set(r.items.filter((i) => i.kind === 'skill' && i.status.includes('duplicate')).map((i) => i.name))) {
|
|
427
|
+
const drop = j(shared, name);
|
|
428
|
+
// Keep the copy in ~/.claude/skills (Claude reads only that folder, OpenCode reads both); Cursor and Copilot read only ~/.agents/skills, so with them present nothing is removed.
|
|
429
|
+
const linked = r.items.some((i) => i.kind === 'skill' && i.name === name && i.linked);
|
|
430
|
+
if (fsx.existsSync(j(claude, name, 'SKILL.md')) && fsx.existsSync(j(drop, 'SKILL.md')) && !otherAgents && !linked) out.dupSkills.push(drop);
|
|
431
|
+
else out.notes.push(`skill ${name} stays in both folders (${linked ? 'the copies are links to one folder' : otherAgents ? 'Cursor or Copilot read only ~/.agents/skills' : 'the copies are not the ~/.agents and ~/.claude pair'}); keep one by hand`);
|
|
432
|
+
}
|
|
433
|
+
const have = (need) => Object.entries(need).every(([k, v]) => (state?.options?.[k] ?? []).includes(v));
|
|
434
|
+
for (const sg of STOPGAPS) {
|
|
435
|
+
const f = j(home, ...sg.rel);
|
|
436
|
+
if (!fsx.existsSync(f)) continue;
|
|
437
|
+
if (have(sg.needs)) out.stopgaps.push(f);
|
|
438
|
+
else out.notes.push(`${path.relative(home, f)}: kept (${sg.by} is not installed yet)`);
|
|
439
|
+
}
|
|
440
|
+
return out;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// A snapshot of everything of the user's that must not change: whole files and folders by hash, entries of shared JSON files by value.
|
|
444
|
+
function userSnapshot(r, home, skip) {
|
|
445
|
+
const snap = new Map();
|
|
446
|
+
for (const it of r.items) {
|
|
447
|
+
if (it.owner !== 'user') continue;
|
|
448
|
+
const f = absOf(home, it.file);
|
|
449
|
+
if (skip.has(f)) continue;
|
|
450
|
+
try {
|
|
451
|
+
if (it.kind === 'skill') snap.set(`${f}`, treeSha(f, fs));
|
|
452
|
+
else if (it.kind === 'plugin' && !it.keyPath.length) snap.set(f, sha(bytes(f)));
|
|
453
|
+
else if (it.kind === 'mcp') snap.set(`${f}\0${it.keyPath.join('.')}\0${it.name}`, JSON.stringify(walk(readJson(f), [...it.keyPath, it.name]) ?? null));
|
|
454
|
+
else if (it.kind === 'plugin' && it.keyPath[0] === 'enabledPlugins') snap.set(`${f}\0${it.name}`, JSON.stringify(walk(readJson(f), it.keyPath) ?? null));
|
|
455
|
+
} catch { /* unreadable: nothing to compare */ }
|
|
456
|
+
}
|
|
457
|
+
return snap;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
export async function adoptApply(o) {
|
|
461
|
+
const { home, env = process.env, platform = process.platform, realHome = os.homedir(), stateDir = j(home, '.config', 'lean-agents'), exec = true, keepBackup = false, confirm = async () => false } = o;
|
|
462
|
+
const r = await inventory(o);
|
|
463
|
+
const state = readState(stateDir);
|
|
464
|
+
if (state?.adopt) { console.log('An earlier --adopt run is still recorded. Run --adopt --undo first (or delete its backup and the "adopt" key by hand).'); return false; }
|
|
465
|
+
const p = adoptPlan(r, { home, env, platform, realHome, state });
|
|
466
|
+
const nothing = !p.edits.size && !p.install && !p.oldCopies.length && !p.dupSkills.length && !p.stopgaps.length;
|
|
467
|
+
for (const n of p.notes) console.log(` note: ${n}`);
|
|
468
|
+
if (nothing) { console.log('--adopt: nothing to change.'); return true; }
|
|
469
|
+
|
|
470
|
+
// Removals outside the JSON edits need a yes (menu on a terminal, --confirm-removals without one); else they are listed and kept.
|
|
471
|
+
const rel = (f) => `~${f.slice(home.length)}`;
|
|
472
|
+
const ask = async (list, q) => { if (!list.length) return false; for (const l of list) console.log(` ask: ${l}`); const ok = await confirm(q); if (!ok) console.log(' kept (not confirmed; pass --confirm-removals to allow)'); return ok; };
|
|
473
|
+
const okCopies = exec && (await ask(p.oldCopies.map((c) => `npm uninstall the old ${c.name}@${c.version} under Node ${c.node.version}`), 'Remove these old npm copies? (undo reinstalls them from the network)'));
|
|
474
|
+
if (!exec && p.oldCopies.length) console.log(' kept: old npm copies need a run without --no-exec');
|
|
475
|
+
const okSkills = await ask(p.dupSkills.map((d) => `delete ${rel(d)} (copied to the backup first)`), 'Delete these duplicate skill folders?');
|
|
476
|
+
const okStops = await ask(p.stopgaps.map((d) => `delete the hand-made ${rel(d)} (copied to the backup first)`), 'Delete these hand-made stopgaps?');
|
|
477
|
+
|
|
478
|
+
const user = userSnapshot(r, home, new Set([...(okSkills ? p.dupSkills : []), ...(okStops ? p.stopgaps : [])]));
|
|
479
|
+
const sessions = r.opencode.sessions;
|
|
480
|
+
const backupDir = j(stateDir, `adopt-${stamp()}`);
|
|
481
|
+
privateDir(backupDir, stateDir);
|
|
482
|
+
const adoptState = { backupDir, files: [], dirs: [], npm: [] };
|
|
483
|
+
saveState(stateDir, adoptState);
|
|
484
|
+
const env2 = { ...env };
|
|
485
|
+
const fail = async (why) => { console.log(`! ${why}\nRolling back from the backup.`); await adoptUndo({ ...o, undo: true }); return false; };
|
|
486
|
+
|
|
487
|
+
// 1. npm into the tool Node's prefix
|
|
488
|
+
if (p.install && exec) {
|
|
489
|
+
const { node: n, have } = p.install;
|
|
490
|
+
const prefix = ['--prefix', n.dir];
|
|
491
|
+
const argv = [n.node, n.npmCli, 'install', '-g', ...prefix, npmSpec('context-mode')];
|
|
492
|
+
const undoArgv = have ? [n.node, n.npmCli, 'install', '-g', ...prefix, `${PINS['context-mode'].source}@${have}`] : [n.node, n.npmCli, 'uninstall', '-g', ...prefix, 'context-mode'];
|
|
493
|
+
adoptState.npm.push({ desc: `context-mode ${PINS['context-mode'].version} in Node ${n.version}`, undo: [undoArgv], env: toolEnv(n, env, platform) });
|
|
494
|
+
saveState(stateDir, adoptState);
|
|
495
|
+
if (!run(argv, { dryRun: false, log: console.log, env: toolEnv(n, env, platform) })) return fail('npm install failed');
|
|
496
|
+
} else if (p.install) console.log(` --no-exec: install context-mode ${PINS['context-mode'].version} into ${p.install.node.dir} by hand`);
|
|
497
|
+
|
|
498
|
+
// 2. JSON edits: the old bytes go to the backup first
|
|
499
|
+
const actions = [...p.edits].map(([file, edits]) => ({ kind: 'json', path: file, edits }));
|
|
500
|
+
for (const pl of planFiles(actions, [home, configHome(home), envDir(home, 'COPILOT_HOME', null)].filter(Boolean))) {
|
|
501
|
+
if (pl.status !== 'modify') { if (pl.status === 'skip') console.log(` skipped ${rel(pl.path)}: ${pl.note}`); continue; }
|
|
502
|
+
const backup = j(backupDir, 'files', relIn(home, pl.path));
|
|
503
|
+
privateDir(path.dirname(backup), stateDir);
|
|
504
|
+
fs.copyFileSync(pl.path, backup);
|
|
505
|
+
fs.chmodSync(backup, 0o600);
|
|
506
|
+
adoptState.files.push({ path: pl.path, before: sha(bytes(pl.path)), after: sha(pl.after), backup, applied: pl.applied });
|
|
507
|
+
saveState(stateDir, adoptState);
|
|
508
|
+
fs.writeFileSync(pl.path, pl.after);
|
|
509
|
+
console.log(` edited ${rel(pl.path)}`);
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// 3. removals: copy into the backup, then delete
|
|
513
|
+
const drop = (list, label) => {
|
|
514
|
+
for (const d of list) {
|
|
515
|
+
const why = unsafe(d, [home]);
|
|
516
|
+
if (why) { console.log(` kept ${label} ${rel(d)}: ${why}`); continue; }
|
|
517
|
+
const backup = j(backupDir, 'dirs', relIn(home, d));
|
|
518
|
+
privateDir(path.dirname(backup), stateDir);
|
|
519
|
+
fs.cpSync(d, backup, { recursive: true });
|
|
520
|
+
adoptState.dirs.push({ path: d, backup });
|
|
521
|
+
saveState(stateDir, adoptState);
|
|
522
|
+
fs.rmSync(d, { recursive: true, force: true });
|
|
523
|
+
console.log(` removed ${label} ${rel(d)}`);
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
if (okSkills) drop(p.dupSkills, 'duplicate skill');
|
|
527
|
+
if (okStops) drop(p.stopgaps, 'stopgap');
|
|
528
|
+
if (okCopies) {
|
|
529
|
+
for (const c of p.oldCopies) {
|
|
530
|
+
const e = toolEnv(c.node, env, platform);
|
|
531
|
+
const prefix = ['--prefix', c.node.dir];
|
|
532
|
+
adoptState.npm.push({ desc: `old ${c.name}@${c.version} in Node ${c.node.version}`, undo: [[c.node.node, c.node.npmCli, 'install', '-g', ...prefix, `${c.name}@${c.version}`]], env: e });
|
|
533
|
+
saveState(stateDir, adoptState);
|
|
534
|
+
if (!run([c.node.node, c.node.npmCli, 'uninstall', '-g', ...prefix, c.name], { dryRun: false, log: console.log, env: e })) return fail(`could not remove the old ${c.name} under Node ${c.node.version}`);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// 4. verify: each rewritten MCP answers initialize with the current PATH first (the default or symlink Node), user files unchanged, sessions equal
|
|
539
|
+
const bad = [];
|
|
540
|
+
if (exec) {
|
|
541
|
+
for (const m of p.rewritten) {
|
|
542
|
+
const pr = await probeInitialize(m.argv, { env: env2, expect: 'context-mode' });
|
|
543
|
+
console.log(` ${pr.ok ? 'ok ' : 'FAIL'} initialize ${m.client} ${m.name}${pr.error ? ` (${pr.error})` : ''}`);
|
|
544
|
+
if (!pr.ok) bad.push(`${m.client} ${m.name} did not answer initialize`);
|
|
545
|
+
}
|
|
546
|
+
} else console.log(' verify: initialize skipped (--no-exec)');
|
|
547
|
+
const after = userSnapshot(r, home, new Set());
|
|
548
|
+
for (const [k, v] of user) if (after.get(k) !== v) bad.push(`a user-owned item changed: ${k.split('\0')[0].replace(home, '~')}`);
|
|
549
|
+
const oc = await opencodeInfo(home, env, fs, { toolNode: p.tn });
|
|
550
|
+
if (oc.sessions !== sessions) bad.push(`OpenCode sessions ${sessions} -> ${oc.sessions}`);
|
|
551
|
+
if (bad.length) return fail(bad.join('; '));
|
|
552
|
+
const dr = doctor({ home, state: readState(stateDir), exec: false, env, platform, json: false });
|
|
553
|
+
if (!dr) return fail('--doctor reports problems after the change');
|
|
554
|
+
|
|
555
|
+
// Read back what is on disk: a skipped write (symlinked or unparsable file) must not pass on the value we meant to write.
|
|
556
|
+
for (const m of p.rewritten) {
|
|
557
|
+
const e = walk(readJson(m.file), m.path);
|
|
558
|
+
const now = Array.isArray(e?.command) ? e.command : [e?.command, ...(e?.args ?? [])];
|
|
559
|
+
if (JSON.stringify(now) !== JSON.stringify(m.argv)) return fail(`${rel(m.file)} still has the old ${m.name} command (the file was skipped)`);
|
|
560
|
+
}
|
|
561
|
+
// A deleted folder comes back only from the backup, so one that removed a folder keeps it.
|
|
562
|
+
if (keepBackup || adoptState.dirs.length) console.log(`Done. Backup kept: ${backupDir}\nUndo: --adopt --undo`);
|
|
563
|
+
else {
|
|
564
|
+
// The backup is the undo: without it --adopt --undo can only revert our keys.
|
|
565
|
+
dropBackups(backupDir);
|
|
566
|
+
adoptState.backupDir = null;
|
|
567
|
+
for (const f of adoptState.files) f.backup = null;
|
|
568
|
+
for (const d of adoptState.dirs) d.backup = null;
|
|
569
|
+
saveState(stateDir, adoptState);
|
|
570
|
+
console.log('Done. Verified; backup deleted (--keep-backup keeps it for --adopt --undo).');
|
|
571
|
+
}
|
|
572
|
+
return true;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
export async function adoptUndo(o) {
|
|
576
|
+
const { home, stateDir = j(home, '.config', 'lean-agents'), exec = true, env = process.env } = o;
|
|
577
|
+
const st = readState(stateDir);
|
|
578
|
+
const a = st?.adopt;
|
|
579
|
+
if (!a) { console.log('Nothing to undo: no --adopt run is recorded.'); return true; }
|
|
580
|
+
if (o.dryRun) { console.log(`--adopt --undo --dry-run: would restore ${a.files.length} files, ${a.dirs.length} folders and undo ${a.npm.length} npm steps; nothing was changed.`); return true; }
|
|
581
|
+
let ok = true;
|
|
582
|
+
for (const c of [...a.npm].reverse()) {
|
|
583
|
+
if (!exec) { console.log(` by hand: ${c.undo.map((u) => u.join(' ')).join(' && ')}`); continue; }
|
|
584
|
+
for (const argv of c.undo) {
|
|
585
|
+
// An offline reinstall of an old copy must not stop the byte restore: it is listed instead.
|
|
586
|
+
if (!run(argv, { dryRun: false, log: console.log, env: c.env })) console.log(` ! could not run it; run the command above by hand (${c.desc})`);
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
for (const d of a.dirs) {
|
|
590
|
+
if (!d.backup || !fs.existsSync(d.backup)) { console.log(` ! no backup for ${d.path}; nothing restored`); ok = false; continue; }
|
|
591
|
+
// Keep the backup: it is the only copy of this folder.
|
|
592
|
+
if (fs.existsSync(d.path)) { console.log(` left ${d.path} (it exists again); its copy stays in the backup`); ok = false; continue; }
|
|
593
|
+
fs.mkdirSync(path.dirname(d.path), { recursive: true });
|
|
594
|
+
fs.cpSync(d.backup, d.path, { recursive: true });
|
|
595
|
+
console.log(` restored ${d.path}`);
|
|
596
|
+
}
|
|
597
|
+
for (const f of [...a.files].reverse()) {
|
|
598
|
+
let now = null;
|
|
599
|
+
try { now = bytes(f.path); } catch { /* gone */ }
|
|
600
|
+
if (now === null) { console.log(` ! ${f.path} is gone; left`); continue; }
|
|
601
|
+
const why = unsafe(f.path, [home, configHome(home)]);
|
|
602
|
+
if (why) { console.log(` ! ${f.path}: ${why}`); ok = false; continue; }
|
|
603
|
+
if (sha(now) === f.after && f.backup && fs.existsSync(f.backup)) { fs.writeFileSync(f.path, bytes(f.backup)); console.log(` restored ${f.path}`); continue; }
|
|
604
|
+
// Edited since (or no backup kept): take back only our keys.
|
|
605
|
+
fs.writeFileSync(f.path, revertJsonEdits(now.toString('utf8'), f.applied ?? []));
|
|
606
|
+
console.log(` reverted our keys in ${f.path}${sha(now) === f.after ? ' (no backup kept)' : ' (you edited it since)'}`);
|
|
607
|
+
}
|
|
608
|
+
if (!ok) { console.log(`Undone with problems; the record and backup stay so you can retry: ${a.backupDir ?? '(no backup)'}`); return false; }
|
|
609
|
+
if (a.backupDir) dropBackups(a.backupDir);
|
|
610
|
+
delete st.adopt;
|
|
611
|
+
const isBare = st.adoptOnly && (!st.files || st.files.length === 0) && (!st.commands || st.commands.length === 0) && !st.opencode1 && !st.upgrade;
|
|
612
|
+
if (isBare) fs.rmSync(stateFile(stateDir));
|
|
613
|
+
else {
|
|
614
|
+
writePrivate(stateFile(stateDir), `${JSON.stringify(st, null, 2)}\n`);
|
|
615
|
+
}
|
|
616
|
+
try { fs.rmdirSync(stateDir); } catch { /* other lean-agents files live there */ }
|
|
617
|
+
console.log(ok ? 'Undone.' : 'Undone, with the problems above.');
|
|
618
|
+
return ok;
|
|
619
|
+
}
|