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.
- package/LICENSE +21 -0
- package/README.es.md +454 -0
- package/README.md +453 -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 +186 -0
- package/core/mcp.json +38 -0
- package/core/pins.json +30 -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 +29 -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/bump-pins.mjs +104 -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/copilot-context-mode.mjs +33 -0
- package/scripts/labels.sh +55 -0
- package/scripts/lean.mjs +700 -0
- package/scripts/lib/adapters/antigravity.mjs +72 -0
- package/scripts/lib/adapters/claude.mjs +122 -0
- package/scripts/lib/adapters/copilot-cli.mjs +81 -0
- package/scripts/lib/adapters/cursor.mjs +60 -0
- package/scripts/lib/adapters/opencode-v1.mjs +86 -0
- package/scripts/lib/adapters/opencode-v2.mjs +168 -0
- package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
- package/scripts/lib/adhd.mjs +28 -0
- package/scripts/lib/adopt.mjs +474 -0
- package/scripts/lib/agent-lifecycle.mjs +163 -0
- package/scripts/lib/copilot-usage.mjs +49 -0
- package/scripts/lib/doctor.mjs +207 -0
- package/scripts/lib/feedback.mjs +30 -0
- package/scripts/lib/fsops.mjs +291 -0
- package/scripts/lib/gsd.mjs +42 -0
- package/scripts/lib/inventory.mjs +195 -0
- package/scripts/lib/lean-update.mjs +30 -0
- package/scripts/lib/migrate.mjs +407 -0
- package/scripts/lib/network.mjs +79 -0
- package/scripts/lib/node-runtime.mjs +85 -0
- package/scripts/lib/parallel.mjs +265 -0
- package/scripts/lib/pins.mjs +47 -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/system.mjs +178 -0
- package/scripts/lib/terminals.mjs +218 -0
- package/scripts/lib/ui.mjs +34 -0
- package/scripts/lib/unverified.mjs +49 -0
- package/scripts/lib/upgrade.mjs +130 -0
- package/scripts/lib/verify-commit.mjs +16 -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 +43 -0
- package/scripts/release.mjs +46 -0
- package/scripts/verify-pins.mjs +36 -0
- package/scripts/version-watch.mjs +118 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// i-have-adhd ships with disable-model-invocation: true, so an agent cannot load it when a
|
|
2
|
+
// prompt asks for it; only a typed /i-have-adhd or the always-on hook can. The owner wants
|
|
3
|
+
// agents to load it, so lean-agents flips the flag in the installed copies.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const SCRIPT = fileURLToPath(new URL('../adhd-skill.mjs', import.meta.url));
|
|
9
|
+
|
|
10
|
+
export function adhdCommand(home) {
|
|
11
|
+
return {
|
|
12
|
+
tool: 'i-have-adhd',
|
|
13
|
+
desc: 'Let agents load the i-have-adhd skill',
|
|
14
|
+
run: [['node', SCRIPT, 'on', home]],
|
|
15
|
+
undo: [['node', SCRIPT, 'off', home]],
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const setInvocable = (text, on) => text.replace(/^disable-model-invocation: (true|false)$/m, `disable-model-invocation: ${on ? 'false' : 'true'}`);
|
|
20
|
+
|
|
21
|
+
// Every installed copy. Claude Code keeps one folder per plugin version.
|
|
22
|
+
export function adhdSkillFiles(home) {
|
|
23
|
+
const cache = path.join(home, '.claude', 'plugins', 'cache', 'i-have-adhd', 'i-have-adhd');
|
|
24
|
+
const versions = fs.existsSync(cache) ? fs.readdirSync(cache).map((v) => path.join(cache, v, 'skills', 'i-have-adhd', 'SKILL.md')) : [];
|
|
25
|
+
// skills 1.7.x writes ~/.agents/skills; 1.8 writes Antigravity's copy to ~/.gemini/config/skills.
|
|
26
|
+
const shared = [['.agents', 'skills'], ['.gemini', 'config', 'skills']].map((p) => path.join(home, ...p, 'i-have-adhd', 'SKILL.md'));
|
|
27
|
+
return [...versions, ...shared].filter((f) => fs.existsSync(f));
|
|
28
|
+
}
|
|
@@ -0,0 +1,474 @@
|
|
|
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 { parse } from 'jsonc-parser';
|
|
10
|
+
import { hasMark, plan as planFiles, revertJsonEdits, sha, writePrivate, privateDir, dropBackups, unsafe } from './fsops.mjs';
|
|
11
|
+
import { PINS, npmSpec, pinVersions } from './pins.mjs';
|
|
12
|
+
import { configHome, envDir } from './system.mjs';
|
|
13
|
+
import { configPath } from './adapters/opencode-v2.mjs';
|
|
14
|
+
import { mcpServers } from './migrate.mjs';
|
|
15
|
+
import { findNvm, resolveToolNodes, minVersion, installedNodes, toolEnv } from './node-runtime.mjs';
|
|
16
|
+
import { run } from './system.mjs';
|
|
17
|
+
import { doctor } from './doctor.mjs';
|
|
18
|
+
import { clients, launchOf, pinOf, classify, npmCopies, skillDirs, duplicateSkills, treeSha, probeInitialize } from './inventory.mjs';
|
|
19
|
+
|
|
20
|
+
const j = path.join;
|
|
21
|
+
const MANAGED_SKILLS = new Set(Object.entries(PINS).filter(([, p]) => p.kind === 'skill').map(([k]) => k));
|
|
22
|
+
const MANAGED_HOOK = /\b(rtk|context-mode|gsd)\b/;
|
|
23
|
+
const MANAGED_PLUGIN = /context-mode|opencode-dcp|opencode-warp|lean-agents/;
|
|
24
|
+
|
|
25
|
+
const readJson = (file) => { try { return parse(fs.readFileSync(file, 'utf8'), [], { allowTrailingComma: true }) ?? null; } catch { return null; } };
|
|
26
|
+
const pinVersion = (argv, pin) => {
|
|
27
|
+
const m = argv.map((a) => new RegExp(`${PINS[pin].source.replace(/[/.]/g, '\\$&')}@(\\d[^\\s/]*)$`).exec(a)).find(Boolean);
|
|
28
|
+
return m?.[1] ?? null;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// Hand-made stopgaps from the original machine (issue #123 last comment, #78, #132): path under home → what replaces them.
|
|
32
|
+
// `needs`: what state.json must record before the replacement counts as installed (a tool or a terminal integration).
|
|
33
|
+
const CUSAGE = 'the managed `copilot-usage` tool (--tools copilot-usage)';
|
|
34
|
+
const STOPGAPS = [
|
|
35
|
+
{ rel: ['.local', 'bin', 'copilot-usage'], by: CUSAGE, needs: { tools: 'copilot-usage' } },
|
|
36
|
+
{ rel: ['.local', 'bin', 'copilot-usage.ps1'], by: CUSAGE, needs: { tools: 'copilot-usage' } },
|
|
37
|
+
{ rel: ['.config', 'opencode', 'plugins', 'copilot-usage-tui'], by: CUSAGE, needs: { tools: 'copilot-usage' } },
|
|
38
|
+
{ rel: ['.config', 'opencode', 'plugins', 'orca-status-tui-shim.js'], by: 'the managed Orca integration (--terminal orca)', needs: { terminals: 'orca' } },
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
// 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.
|
|
42
|
+
export async function opencodeInfo(home, env, fsx = fs) {
|
|
43
|
+
const cfgFile = configPath(j(configHome(home), 'opencode'));
|
|
44
|
+
const cfg = readJson(cfgFile);
|
|
45
|
+
const major = !cfg ? null : cfg.mcp?.servers || cfg.plugins ? 2 : 1; // VERIFY with `opencode --version` in real-adopt
|
|
46
|
+
const dataDir = j(envDir(home, 'XDG_DATA_HOME', j(home, '.local', 'share')), 'opencode');
|
|
47
|
+
const dbs = fsx.existsSync(dataDir) ? fsx.readdirSync(dataDir).filter((f) => /^opencode\.db(-wal|-shm)?$/.test(f)) : [];
|
|
48
|
+
const dbBytes = dbs.reduce((n, f) => n + fsx.statSync(j(dataDir, f)).size, 0);
|
|
49
|
+
const out = { major, dataDir, dbBytes, sessions: null };
|
|
50
|
+
if (!dbs.includes('opencode.db')) return { ...out, note: 'no opencode.db' };
|
|
51
|
+
let sqlite;
|
|
52
|
+
try { sqlite = await import('node:sqlite'); } catch { return { ...out, note: 'node:sqlite is not available on this Node: sessions not counted' }; }
|
|
53
|
+
const tmp = fs.mkdtempSync(j(os.tmpdir(), 'lean-adopt-'));
|
|
54
|
+
try {
|
|
55
|
+
for (const f of dbs) fs.copyFileSync(j(dataDir, f), j(tmp, f));
|
|
56
|
+
const db = new sqlite.DatabaseSync(j(tmp, 'opencode.db'), { readOnly: true });
|
|
57
|
+
try { out.sessions = Number(db.prepare('SELECT count(*) AS n FROM session').get().n); } finally { db.close(); }
|
|
58
|
+
} catch (e) { out.note = `sessions not counted: ${String(e.message).split('\n')[0]}`; } finally { fs.rmSync(tmp, { recursive: true, force: true }); }
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function inventory({ home, env = process.env, platform = process.platform, realHome = os.homedir(), fsx = fs }) {
|
|
63
|
+
const rel = (p) => (p && p.startsWith(home) ? `~${p.slice(home.length)}` : p);
|
|
64
|
+
const items = [];
|
|
65
|
+
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 ?? {}) });
|
|
66
|
+
const shape = (l) => ({ style: l.style, node: rel(l.node), nodeVersion: l.nodeVersion });
|
|
67
|
+
const seen = new Set();
|
|
68
|
+
|
|
69
|
+
// --- MCP servers (names only; args and env stay unread)
|
|
70
|
+
const names = new Set();
|
|
71
|
+
for (const { client, file, keyPath } of clients(home)) {
|
|
72
|
+
for (const s of mcpServers(file, keyPath)) {
|
|
73
|
+
const id = `${file}\0${s.name}`;
|
|
74
|
+
if (seen.has(id)) continue;
|
|
75
|
+
seen.add(id);
|
|
76
|
+
const pin = s.command.length ? pinOf(s.command) : null;
|
|
77
|
+
const managed = Boolean(pin) || (s.name === 'serena' && s.command.includes('start-mcp-server'));
|
|
78
|
+
const status = [];
|
|
79
|
+
const launch = s.command.length ? launchOf(s.command, { env, platform, fsx }) : null;
|
|
80
|
+
let wanted = null;
|
|
81
|
+
if (launch && pin && classify(launch, pin).status === 'wrong-node') status.push('wrong-node');
|
|
82
|
+
if (pin) {
|
|
83
|
+
const v = pinVersion(s.command, pin);
|
|
84
|
+
wanted = PINS[pin].version;
|
|
85
|
+
if (v && v !== wanted) status.push('drift');
|
|
86
|
+
}
|
|
87
|
+
const abs = s.command[0] && path.isAbsolute(s.command[0]);
|
|
88
|
+
if (abs && !fsx.existsSync(s.command[0])) status.push('stale');
|
|
89
|
+
names.add(`${client}\0${s.name}`);
|
|
90
|
+
add({ client, kind: 'mcp', name: s.name, file, keyPath, launch: launch && shape(launch), owner: managed ? 'managed' : 'user', status, pin, wanted });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// --- Claude: hooks, enabledPlugins
|
|
95
|
+
const settings = j(home, '.claude', 'settings.json');
|
|
96
|
+
const cs = readJson(settings) ?? {};
|
|
97
|
+
for (const [event, groups] of Object.entries(cs.hooks ?? {})) {
|
|
98
|
+
for (const g of Array.isArray(groups) ? groups : []) {
|
|
99
|
+
for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
|
|
100
|
+
if (typeof h?.command !== 'string') continue;
|
|
101
|
+
const argv = h.command.split(/\s+/).filter(Boolean);
|
|
102
|
+
// Inline `VAR=value` prefixes can hold secrets: never use them as the name.
|
|
103
|
+
while (argv.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(argv[0])) argv.shift();
|
|
104
|
+
if (!argv.length) continue;
|
|
105
|
+
const pin = pinOf(argv);
|
|
106
|
+
const launch = launchOf(argv, { env, platform, fsx });
|
|
107
|
+
const status = [];
|
|
108
|
+
if (pin && classify(launch, pin).status === 'wrong-node') status.push('wrong-node');
|
|
109
|
+
if (path.isAbsolute(argv[0] ?? '') && !fsx.existsSync(argv[0])) status.push('stale');
|
|
110
|
+
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 });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const installed = readJson(j(home, '.claude', 'plugins', 'installed_plugins.json')); // VERIFY: name and shape, proven in real-adopt
|
|
115
|
+
const have = installed && typeof installed.plugins === 'object' ? installed.plugins : null;
|
|
116
|
+
for (const [key, on] of Object.entries(cs.enabledPlugins ?? {})) {
|
|
117
|
+
const stale = have && typeof have === 'object' && !(key in have);
|
|
118
|
+
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) } });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// --- OpenCode: plugin / plugins, tui.json plugin, plugins/ folder
|
|
122
|
+
const ocDir = j(configHome(home), 'opencode');
|
|
123
|
+
const ocCfg = configPath(ocDir);
|
|
124
|
+
const pluginEntry = (file, key, e) => {
|
|
125
|
+
const spec = Array.isArray(e) ? String(e[0]) : String(e);
|
|
126
|
+
const status = [];
|
|
127
|
+
let target = null;
|
|
128
|
+
try { target = spec.startsWith('file://') ? fileURLToPath(spec) : null; } catch { /* not a local file URL */ }
|
|
129
|
+
if (target && !fsx.existsSync(target)) status.push('stale');
|
|
130
|
+
if (/context-mode/.test(spec) && names.has('opencode\0context-mode')) status.push('duplicate'); // plugin and MCP; the MCP row gets the same mark below
|
|
131
|
+
add({ client: 'opencode', kind: 'plugin', name: spec.replace(/^file:\/\/.*[\\/]/, 'file:').replace(/\/\/[^/@\s]*@/, '//').replace(/[?#].*$/, ''), file, keyPath: [key], owner: !target && MANAGED_PLUGIN.test(spec) ? 'managed' : 'user', status });
|
|
132
|
+
};
|
|
133
|
+
for (const [file, keys] of [[ocCfg, ['plugin', 'plugins']], [j(ocDir, 'tui.json'), ['plugin']], [j(ocDir, 'tui.jsonc'), ['plugin']]]) {
|
|
134
|
+
const c = readJson(file);
|
|
135
|
+
for (const k of keys) for (const e of Array.isArray(c?.[k]) ? c[k] : []) pluginEntry(file, k, e);
|
|
136
|
+
}
|
|
137
|
+
const pdir = j(ocDir, 'plugins');
|
|
138
|
+
for (const e of fsx.existsSync(pdir) ? fsx.readdirSync(pdir, { withFileTypes: true }) : []) {
|
|
139
|
+
const f = j(pdir, e.name);
|
|
140
|
+
let owned = false;
|
|
141
|
+
if (e.isFile()) { try { owned = hasMark(fs.readFileSync(f, 'utf8')); } catch { /* unreadable: user */ } }
|
|
142
|
+
add({ client: 'opencode', kind: 'plugin', name: `plugins/${e.name}`, file: f, owner: owned ? 'managed' : 'user' });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (items.some((i) => i.client === 'opencode' && i.kind === 'plugin' && i.status.includes('duplicate'))) {
|
|
146
|
+
const mcp = items.find((i) => i.client === 'opencode' && i.kind === 'mcp' && i.name === 'context-mode');
|
|
147
|
+
if (mcp) mcp.status.push('duplicate');
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// --- Skills in every folder some agent reads
|
|
151
|
+
const dirs = [...new Set(['claude', 'opencode', 'cursor', 'copilot'].flatMap((a) => skillDirs(a, home)))];
|
|
152
|
+
const dupDirs = new Map();
|
|
153
|
+
for (const a of ['claude', 'opencode', 'cursor', 'copilot']) for (const d of duplicateSkills(skillDirs(a, home), fsx)) dupDirs.set(d.name, d);
|
|
154
|
+
for (const d of dirs) {
|
|
155
|
+
let list = [];
|
|
156
|
+
try { list = fsx.readdirSync(d).filter((n) => fsx.existsSync(j(d, n, 'SKILL.md'))); } catch { continue; }
|
|
157
|
+
for (const name of list) {
|
|
158
|
+
const dup = dupDirs.get(name);
|
|
159
|
+
add({ client: 'skills', kind: 'skill', name, file: j(d, name), owner: MANAGED_SKILLS.has(name) ? 'managed' : 'user', status: dup ? ['duplicate'] : [], extra: dup ? { copies: dup.dirs.map(rel), differs: dup.differs } : {} });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// --- npm copies under each nvm Node, and the one Node the tools should use
|
|
164
|
+
const nvm = findNvm({ env, home, platform, realHome });
|
|
165
|
+
const copies = nvm ? npmCopies(nvm) : [];
|
|
166
|
+
const toolPins = Object.fromEntries([...new Set(items.map((i) => i.pin).filter(Boolean))].map((k) => [k, PINS[k]]));
|
|
167
|
+
// active '0.0.0': the question is which Node the tools should run on, whatever Node runs this command.
|
|
168
|
+
const r = resolveToolNodes({ pins: toolPins, active: '0.0.0', nvm, latest: null });
|
|
169
|
+
const ranges = Object.values(toolPins).map((p) => p.node).filter(Boolean);
|
|
170
|
+
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;
|
|
171
|
+
const tn = r.toolNode;
|
|
172
|
+
const toolNode = tn
|
|
173
|
+
? { version: tn.version, node: rel(tn.node), range: `>=${floor}`, source: tn.install ? 'install' : 'reuse' }
|
|
174
|
+
: { version: null, node: null, range: floor ? `>=${floor}` : null, source: null };
|
|
175
|
+
const byPin = new Map();
|
|
176
|
+
for (const c of copies) byPin.set(c.pin, [...(byPin.get(c.pin) ?? []), c]);
|
|
177
|
+
for (const c of copies) {
|
|
178
|
+
const status = [];
|
|
179
|
+
if (PINS[c.pin].version !== c.version) status.push('drift');
|
|
180
|
+
if (byPin.get(c.pin).length > 1) status.push('duplicate');
|
|
181
|
+
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 } });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// --- Known hand-made stopgaps: listed with their managed replacement
|
|
185
|
+
const stopgaps = STOPGAPS.filter((s) => fsx.existsSync(j(home, ...s.rel))).map((s) => ({ file: rel(j(home, ...s.rel)), replaceWith: s.by }));
|
|
186
|
+
|
|
187
|
+
// --- Actions
|
|
188
|
+
for (const it of items) {
|
|
189
|
+
const s = it.status;
|
|
190
|
+
if (it.owner === 'user') it.action = s.includes('stale') || s.includes('duplicate') ? 'ask' : 'keep';
|
|
191
|
+
else if (s.includes('wrong-node')) it.action = 'reinstall';
|
|
192
|
+
else if (s.includes('drift')) it.action = 'upgrade';
|
|
193
|
+
else if (s.includes('stale')) it.action = 'remove';
|
|
194
|
+
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';
|
|
195
|
+
}
|
|
196
|
+
const oc = await opencodeInfo(home, env, fsx);
|
|
197
|
+
const plan = items.filter((i) => i.action !== 'keep').map((i) => `${i.action} ${i.client} ${i.kind} ${i.name} (${i.status.join(', ') || i.owner})`);
|
|
198
|
+
for (const s of stopgaps) if (s.replaceWith) plan.push(`ask ${s.file}: replace with ${s.replaceWith}`);
|
|
199
|
+
return { version: 1, os: platform, toolNode, items, opencode: { ...oc, dataDir: rel(oc.dataDir) }, stopgaps, plan, ok: !items.some((i) => i.action !== 'keep') };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export async function adopt(o) {
|
|
203
|
+
if (o.undo) return adoptUndo(o);
|
|
204
|
+
if (o.yes && !o.dryRun && !o.json) return adoptApply(o);
|
|
205
|
+
const r = await inventory(o);
|
|
206
|
+
if (o.json) { process.stdout.write(`${JSON.stringify(r, null, 2)}\n`); return true; }
|
|
207
|
+
const by = {};
|
|
208
|
+
for (const i of r.items) by[`${i.kind}`] = (by[`${i.kind}`] ?? 0) + 1;
|
|
209
|
+
console.log(`--adopt (dry run: nothing is changed; --yes applies). Found: ${Object.entries(by).map(([k, n]) => `${n} ${k}`).join(', ') || 'nothing'}`);
|
|
210
|
+
console.log(`tool Node: ${r.toolNode.range ? `${r.toolNode.range} -> ${r.toolNode.node ?? 'no matching Node installed, nvm not found'} (${r.toolNode.source ?? 'none'})` : 'not needed'}`);
|
|
211
|
+
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})` : ''}`);
|
|
212
|
+
for (const i of r.items.filter((x) => x.action !== 'keep' || x.owner === 'managed')) console.log(` ${i.action.padEnd(9)} ${i.owner.padEnd(8)} ${i.client} ${i.kind} ${i.name}${i.status.length ? ` [${i.status.join(', ')}]` : ''}`);
|
|
213
|
+
console.log(` user-owned items kept untouched: ${r.items.filter((i) => i.owner === 'user' && i.action === 'keep').length}`);
|
|
214
|
+
for (const s of r.stopgaps) console.log(` stopgap ${s.file}${s.replaceWith ? `: replace with ${s.replaceWith}` : `: ${s.note}`}`);
|
|
215
|
+
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.');
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
220
|
+
// Apply and undo (#106). Everything below writes, and only inside `home` and `stateDir`.
|
|
221
|
+
const ROOT = fileURLToPath(new URL('../../', import.meta.url));
|
|
222
|
+
const absOf = (home, f) => (f === '~' || f.startsWith('~/') || f.startsWith('~\\') ? home + f.slice(1) : f);
|
|
223
|
+
const walk = (obj, p) => p.reduce((v, k) => (v && typeof v === 'object' ? v[k] : undefined), obj);
|
|
224
|
+
const stamp = () => new Date().toISOString().replace(/[:.]/g, '-');
|
|
225
|
+
const bytes = (f) => fs.readFileSync(f);
|
|
226
|
+
const relIn = (home, f) => (f.startsWith(home + path.sep) ? path.relative(home, f) : f.replace(/^[A-Za-z]:/, '').replace(/^[\\/]+/, ''));
|
|
227
|
+
|
|
228
|
+
// State file: --adopt adds `adopt` to an existing state.json, or creates one that only holds it (`adoptOnly`).
|
|
229
|
+
const stateFile = (stateDir) => j(stateDir, 'state.json');
|
|
230
|
+
const readState = (stateDir) => readJson(stateFile(stateDir));
|
|
231
|
+
function saveState(stateDir, adoptState) {
|
|
232
|
+
const st = readState(stateDir) ?? {
|
|
233
|
+
version: JSON.parse(fs.readFileSync(j(ROOT, 'package.json'), 'utf8')).version, installedAt: new Date().toISOString(), pins: pinVersions(), adoptOnly: true,
|
|
234
|
+
options: { migrateOnly: true, agents: [], tools: [], privacy: 'standard', gh: false, terminals: [], unverified: {}, lang: 'en', profile: null, adhdAlways: false, ponytailMode: null, bun: false, shell: 'git-bash' },
|
|
235
|
+
files: [], commands: [],
|
|
236
|
+
};
|
|
237
|
+
st.updatedAt = new Date().toISOString();
|
|
238
|
+
st.adopt = adoptState;
|
|
239
|
+
privateDir(stateDir, stateDir);
|
|
240
|
+
writePrivate(stateFile(stateDir), `${JSON.stringify(st, null, 2)}\n`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// What to change, from one inventory. Pure: no writes. `state`: the saved state.json (tells which managed replacements exist).
|
|
244
|
+
export function adoptPlan(r, { home, env, platform, realHome, state, fsx = fs }) {
|
|
245
|
+
const nvm = findNvm({ env, home, platform, realHome });
|
|
246
|
+
const nodes = nvm ? installedNodes(nvm) : [];
|
|
247
|
+
const tn = r.toolNode.version ? nodes.find((n) => n.version === r.toolNode.version) ?? null : null;
|
|
248
|
+
const out = { tn, nodes, edits: new Map(), rewritten: [], install: null, oldCopies: [], dupSkills: [], stopgaps: [], notes: [] };
|
|
249
|
+
const addEdit = (file, e) => out.edits.set(file, [...(out.edits.get(file) ?? []), e]);
|
|
250
|
+
|
|
251
|
+
// 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.
|
|
252
|
+
const pin = 'context-mode';
|
|
253
|
+
const cli = tn && j(tn.modules, 'context-mode', 'cli.mjs');
|
|
254
|
+
const seen = new Set();
|
|
255
|
+
for (const it of r.items) {
|
|
256
|
+
if (it.kind !== 'mcp' || it.owner !== 'managed' || it.pin !== pin || !['reinstall', 'upgrade'].includes(it.action)) continue;
|
|
257
|
+
const file = absOf(home, it.file);
|
|
258
|
+
const id = `${file}\0${it.keyPath.join('.')}\0${it.name}`;
|
|
259
|
+
if (seen.has(id)) continue;
|
|
260
|
+
seen.add(id);
|
|
261
|
+
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; }
|
|
262
|
+
const entry = walk(readJson(file), [...it.keyPath, it.name]);
|
|
263
|
+
const base = [...it.keyPath, it.name];
|
|
264
|
+
if (Array.isArray(entry?.command)) addEdit(file, { path: [...base, 'command'], mode: 'set', value: [tn.node, cli, 'server'] });
|
|
265
|
+
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'] }); }
|
|
266
|
+
else continue;
|
|
267
|
+
out.rewritten.push({ client: it.client, name: it.name, file, path: base, argv: [tn.node, cli, 'server'] });
|
|
268
|
+
}
|
|
269
|
+
// 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.
|
|
270
|
+
for (const it of r.items) {
|
|
271
|
+
if (it.owner !== 'managed' || it.action !== 'remove' || !it.status.includes('stale')) continue;
|
|
272
|
+
const p = it.kind === 'mcp' ? [...it.keyPath, it.name] : it.kind === 'plugin' && it.keyPath[0] === 'enabledPlugins' ? it.keyPath : null;
|
|
273
|
+
if (p) addEdit(absOf(home, it.file), { path: p, mode: 'remove' });
|
|
274
|
+
}
|
|
275
|
+
// The pinned package in the tool Node's prefix.
|
|
276
|
+
if (tn && out.rewritten.length) {
|
|
277
|
+
let have = null;
|
|
278
|
+
try { have = JSON.parse(fsx.readFileSync(j(tn.modules, 'context-mode', 'package.json'), 'utf8')).version; } catch { /* not installed there */ }
|
|
279
|
+
if (have !== PINS[pin].version) out.install = { have, node: tn };
|
|
280
|
+
}
|
|
281
|
+
// (a) old npm copies under another Node; (b) a skill in both folders; stopgaps with their managed replacement installed.
|
|
282
|
+
if (tn) for (const it of r.items) if (it.kind === 'npm' && it.status.includes('duplicate') && it.node !== tn.version) { 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(/^.*@/, '') }); }
|
|
283
|
+
const shared = j(home, '.agents', 'skills');
|
|
284
|
+
const claude = j(home, '.claude', 'skills');
|
|
285
|
+
const otherAgents = fsx.existsSync(j(home, '.cursor')) || fsx.existsSync(envDir(home, 'COPILOT_HOME', j(home, '.copilot')));
|
|
286
|
+
for (const name of new Set(r.items.filter((i) => i.kind === 'skill' && i.status.includes('duplicate')).map((i) => i.name))) {
|
|
287
|
+
const drop = j(shared, name);
|
|
288
|
+
// 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.
|
|
289
|
+
if (fsx.existsSync(j(claude, name, 'SKILL.md')) && fsx.existsSync(j(drop, 'SKILL.md')) && !otherAgents) out.dupSkills.push(drop);
|
|
290
|
+
else out.notes.push(`skill ${name} stays in both folders (${otherAgents ? 'Cursor or Copilot read only ~/.agents/skills' : 'the copies are not the ~/.agents and ~/.claude pair'}); keep one by hand`);
|
|
291
|
+
}
|
|
292
|
+
const have = (need) => Object.entries(need).every(([k, v]) => (state?.options?.[k] ?? []).includes(v));
|
|
293
|
+
for (const sg of STOPGAPS) {
|
|
294
|
+
const f = j(home, ...sg.rel);
|
|
295
|
+
if (!fsx.existsSync(f)) continue;
|
|
296
|
+
if (have(sg.needs)) out.stopgaps.push(f);
|
|
297
|
+
else out.notes.push(`${path.relative(home, f)}: kept (${sg.by} is not installed yet)`);
|
|
298
|
+
}
|
|
299
|
+
return out;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// 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.
|
|
303
|
+
function userSnapshot(r, home, skip) {
|
|
304
|
+
const snap = new Map();
|
|
305
|
+
for (const it of r.items) {
|
|
306
|
+
if (it.owner !== 'user') continue;
|
|
307
|
+
const f = absOf(home, it.file);
|
|
308
|
+
if (skip.has(f)) continue;
|
|
309
|
+
try {
|
|
310
|
+
if (it.kind === 'skill') snap.set(`${f}`, treeSha(f, fs));
|
|
311
|
+
else if (it.kind === 'plugin' && !it.keyPath.length) snap.set(f, sha(bytes(f)));
|
|
312
|
+
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));
|
|
313
|
+
else if (it.kind === 'plugin' && it.keyPath[0] === 'enabledPlugins') snap.set(`${f}\0${it.name}`, JSON.stringify(walk(readJson(f), it.keyPath) ?? null));
|
|
314
|
+
} catch { /* unreadable: nothing to compare */ }
|
|
315
|
+
}
|
|
316
|
+
return snap;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export async function adoptApply(o) {
|
|
320
|
+
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;
|
|
321
|
+
const r = await inventory(o);
|
|
322
|
+
const state = readState(stateDir);
|
|
323
|
+
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; }
|
|
324
|
+
const p = adoptPlan(r, { home, env, platform, realHome, state });
|
|
325
|
+
const nothing = !p.edits.size && !p.install && !p.oldCopies.length && !p.dupSkills.length && !p.stopgaps.length;
|
|
326
|
+
for (const n of p.notes) console.log(` note: ${n}`);
|
|
327
|
+
if (nothing) { console.log('--adopt: nothing to change.'); return true; }
|
|
328
|
+
|
|
329
|
+
// Removals outside the JSON edits need a yes (menu on a terminal, --confirm-removals without one); else they are listed and kept.
|
|
330
|
+
const rel = (f) => `~${f.slice(home.length)}`;
|
|
331
|
+
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; };
|
|
332
|
+
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)'));
|
|
333
|
+
if (!exec && p.oldCopies.length) console.log(' kept: old npm copies need a run without --no-exec');
|
|
334
|
+
const okSkills = await ask(p.dupSkills.map((d) => `delete ${rel(d)} (copied to the backup first)`), 'Delete these duplicate skill folders?');
|
|
335
|
+
const okStops = await ask(p.stopgaps.map((d) => `delete the hand-made ${rel(d)} (copied to the backup first)`), 'Delete these hand-made stopgaps?');
|
|
336
|
+
|
|
337
|
+
const user = userSnapshot(r, home, new Set([...(okSkills ? p.dupSkills : []), ...(okStops ? p.stopgaps : [])]));
|
|
338
|
+
const sessions = r.opencode.sessions;
|
|
339
|
+
const backupDir = j(stateDir, `adopt-${stamp()}`);
|
|
340
|
+
privateDir(backupDir, stateDir);
|
|
341
|
+
const adoptState = { backupDir, files: [], dirs: [], npm: [] };
|
|
342
|
+
saveState(stateDir, adoptState);
|
|
343
|
+
const env2 = { ...env };
|
|
344
|
+
const fail = async (why) => { console.log(`! ${why}\nRolling back from the backup.`); await adoptUndo({ ...o, undo: true }); return false; };
|
|
345
|
+
|
|
346
|
+
// 1. npm into the tool Node's prefix
|
|
347
|
+
if (p.install && exec) {
|
|
348
|
+
const { node: n, have } = p.install;
|
|
349
|
+
const prefix = ['--prefix', n.dir];
|
|
350
|
+
const argv = [n.node, n.npmCli, 'install', '-g', ...prefix, npmSpec('context-mode')];
|
|
351
|
+
const undoArgv = have ? [n.node, n.npmCli, 'install', '-g', ...prefix, `${PINS['context-mode'].source}@${have}`] : [n.node, n.npmCli, 'uninstall', '-g', ...prefix, 'context-mode'];
|
|
352
|
+
adoptState.npm.push({ desc: `context-mode ${PINS['context-mode'].version} in Node ${n.version}`, undo: [undoArgv], env: toolEnv(n, env, platform) });
|
|
353
|
+
saveState(stateDir, adoptState);
|
|
354
|
+
if (!run(argv, { dryRun: false, log: console.log, env: toolEnv(n, env, platform) })) return fail('npm install failed');
|
|
355
|
+
} else if (p.install) console.log(` --no-exec: install context-mode ${PINS['context-mode'].version} into ${p.install.node.dir} by hand`);
|
|
356
|
+
|
|
357
|
+
// 2. JSON edits: the old bytes go to the backup first
|
|
358
|
+
const actions = [...p.edits].map(([file, edits]) => ({ kind: 'json', path: file, edits }));
|
|
359
|
+
for (const pl of planFiles(actions, [home, configHome(home), envDir(home, 'COPILOT_HOME', null)].filter(Boolean))) {
|
|
360
|
+
if (pl.status !== 'modify') { if (pl.status === 'skip') console.log(` skipped ${rel(pl.path)}: ${pl.note}`); continue; }
|
|
361
|
+
const backup = j(backupDir, 'files', relIn(home, pl.path));
|
|
362
|
+
privateDir(path.dirname(backup), stateDir);
|
|
363
|
+
fs.copyFileSync(pl.path, backup);
|
|
364
|
+
fs.chmodSync(backup, 0o600);
|
|
365
|
+
adoptState.files.push({ path: pl.path, before: sha(bytes(pl.path)), after: sha(pl.after), backup, applied: pl.applied });
|
|
366
|
+
saveState(stateDir, adoptState);
|
|
367
|
+
fs.writeFileSync(pl.path, pl.after);
|
|
368
|
+
console.log(` edited ${rel(pl.path)}`);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// 3. removals: copy into the backup, then delete
|
|
372
|
+
const drop = (list, label) => {
|
|
373
|
+
for (const d of list) {
|
|
374
|
+
const why = unsafe(d, [home]);
|
|
375
|
+
if (why) { console.log(` kept ${label} ${rel(d)}: ${why}`); continue; }
|
|
376
|
+
const backup = j(backupDir, 'dirs', relIn(home, d));
|
|
377
|
+
privateDir(path.dirname(backup), stateDir);
|
|
378
|
+
fs.cpSync(d, backup, { recursive: true });
|
|
379
|
+
adoptState.dirs.push({ path: d, backup });
|
|
380
|
+
saveState(stateDir, adoptState);
|
|
381
|
+
fs.rmSync(d, { recursive: true, force: true });
|
|
382
|
+
console.log(` removed ${label} ${rel(d)}`);
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
if (okSkills) drop(p.dupSkills, 'duplicate skill');
|
|
386
|
+
if (okStops) drop(p.stopgaps, 'stopgap');
|
|
387
|
+
if (okCopies) {
|
|
388
|
+
for (const c of p.oldCopies) {
|
|
389
|
+
const e = toolEnv(c.node, env, platform);
|
|
390
|
+
const prefix = ['--prefix', c.node.dir];
|
|
391
|
+
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 });
|
|
392
|
+
saveState(stateDir, adoptState);
|
|
393
|
+
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}`);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// 4. verify: each rewritten MCP answers initialize with the current PATH first (the default or symlink Node), user files unchanged, sessions equal
|
|
398
|
+
const bad = [];
|
|
399
|
+
if (exec) {
|
|
400
|
+
for (const m of p.rewritten) {
|
|
401
|
+
const pr = await probeInitialize(m.argv, { env: env2, expect: 'context-mode' });
|
|
402
|
+
console.log(` ${pr.ok ? 'ok ' : 'FAIL'} initialize ${m.client} ${m.name}${pr.error ? ` (${pr.error})` : ''}`);
|
|
403
|
+
if (!pr.ok) bad.push(`${m.client} ${m.name} did not answer initialize`);
|
|
404
|
+
}
|
|
405
|
+
} else console.log(' verify: initialize skipped (--no-exec)');
|
|
406
|
+
const after = userSnapshot(r, home, new Set());
|
|
407
|
+
for (const [k, v] of user) if (after.get(k) !== v) bad.push(`a user-owned item changed: ${k.split('\0')[0].replace(home, '~')}`);
|
|
408
|
+
const oc = await opencodeInfo(home, env, fs);
|
|
409
|
+
if (oc.sessions !== sessions) bad.push(`OpenCode sessions ${sessions} -> ${oc.sessions}`);
|
|
410
|
+
if (bad.length) return fail(bad.join('; '));
|
|
411
|
+
const dr = doctor({ home, state: readState(stateDir), exec: false, env, platform, json: false });
|
|
412
|
+
if (!dr) return fail('--doctor reports problems after the change');
|
|
413
|
+
|
|
414
|
+
// Read back what is on disk: a skipped write (symlinked or unparsable file) must not pass on the value we meant to write.
|
|
415
|
+
for (const m of p.rewritten) {
|
|
416
|
+
const e = walk(readJson(m.file), m.path);
|
|
417
|
+
const now = Array.isArray(e?.command) ? e.command : [e?.command, ...(e?.args ?? [])];
|
|
418
|
+
if (JSON.stringify(now) !== JSON.stringify(m.argv)) return fail(`${rel(m.file)} still has the old ${m.name} command (the file was skipped)`);
|
|
419
|
+
}
|
|
420
|
+
// A deleted folder comes back only from the backup, so one that removed a folder keeps it.
|
|
421
|
+
if (keepBackup || adoptState.dirs.length) console.log(`Done. Backup kept: ${backupDir}\nUndo: --adopt --undo`);
|
|
422
|
+
else {
|
|
423
|
+
// The backup is the undo: without it --adopt --undo can only revert our keys.
|
|
424
|
+
dropBackups(backupDir);
|
|
425
|
+
adoptState.backupDir = null;
|
|
426
|
+
for (const f of adoptState.files) f.backup = null;
|
|
427
|
+
for (const d of adoptState.dirs) d.backup = null;
|
|
428
|
+
saveState(stateDir, adoptState);
|
|
429
|
+
console.log('Done. Verified; backup deleted (--keep-backup keeps it for --adopt --undo).');
|
|
430
|
+
}
|
|
431
|
+
return true;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export async function adoptUndo(o) {
|
|
435
|
+
const { home, stateDir = j(home, '.config', 'lean-agents'), exec = true, env = process.env } = o;
|
|
436
|
+
const st = readState(stateDir);
|
|
437
|
+
const a = st?.adopt;
|
|
438
|
+
if (!a) { console.log('Nothing to undo: no --adopt run is recorded.'); return true; }
|
|
439
|
+
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; }
|
|
440
|
+
let ok = true;
|
|
441
|
+
for (const c of [...a.npm].reverse()) {
|
|
442
|
+
if (!exec) { console.log(` by hand: ${c.undo.map((u) => u.join(' ')).join(' && ')}`); continue; }
|
|
443
|
+
for (const argv of c.undo) {
|
|
444
|
+
// An offline reinstall of an old copy must not stop the byte restore: it is listed instead.
|
|
445
|
+
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})`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
for (const d of a.dirs) {
|
|
449
|
+
if (!d.backup || !fs.existsSync(d.backup)) { console.log(` ! no backup for ${d.path}; nothing restored`); ok = false; continue; }
|
|
450
|
+
// Keep the backup: it is the only copy of this folder.
|
|
451
|
+
if (fs.existsSync(d.path)) { console.log(` left ${d.path} (it exists again); its copy stays in the backup`); ok = false; continue; }
|
|
452
|
+
fs.mkdirSync(path.dirname(d.path), { recursive: true });
|
|
453
|
+
fs.cpSync(d.backup, d.path, { recursive: true });
|
|
454
|
+
console.log(` restored ${d.path}`);
|
|
455
|
+
}
|
|
456
|
+
for (const f of [...a.files].reverse()) {
|
|
457
|
+
let now = null;
|
|
458
|
+
try { now = bytes(f.path); } catch { /* gone */ }
|
|
459
|
+
if (now === null) { console.log(` ! ${f.path} is gone; left`); continue; }
|
|
460
|
+
const why = unsafe(f.path, [home, configHome(home)]);
|
|
461
|
+
if (why) { console.log(` ! ${f.path}: ${why}`); ok = false; continue; }
|
|
462
|
+
if (sha(now) === f.after && f.backup && fs.existsSync(f.backup)) { fs.writeFileSync(f.path, bytes(f.backup)); console.log(` restored ${f.path}`); continue; }
|
|
463
|
+
// Edited since (or no backup kept): take back only our keys.
|
|
464
|
+
fs.writeFileSync(f.path, revertJsonEdits(now.toString('utf8'), f.applied ?? []));
|
|
465
|
+
console.log(` reverted our keys in ${f.path}${sha(now) === f.after ? ' (no backup kept)' : ' (you edited it since)'}`);
|
|
466
|
+
}
|
|
467
|
+
if (!ok) { console.log(`Undone with problems; the record and backup stay so you can retry: ${a.backupDir ?? '(no backup)'}`); return false; }
|
|
468
|
+
if (a.backupDir) dropBackups(a.backupDir);
|
|
469
|
+
if (st.adoptOnly) fs.rmSync(stateFile(stateDir));
|
|
470
|
+
else { delete st.adopt; writePrivate(stateFile(stateDir), `${JSON.stringify(st, null, 2)}\n`); }
|
|
471
|
+
try { fs.rmdirSync(stateDir); } catch { /* other lean-agents files live there */ }
|
|
472
|
+
console.log(ok ? 'Undone.' : 'Undone, with the problems above.');
|
|
473
|
+
return ok;
|
|
474
|
+
}
|