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,203 @@
|
|
|
1
|
+
// `opencode1`: OpenCode 1.x side by side with 2.x (#80 part 2, P4): `--upgrade-agent opencode --opencode1`.
|
|
2
|
+
// Copies the 1.x binary to `<data>/lean-agents/opencode1/<version>/`, writes an owned shim `opencode1` (+ `opencode1.cmd` on Windows)
|
|
3
|
+
// that points XDG_DATA_HOME + XDG_STATE_HOME at the frozen copy (proven by the P1 spike) and XDG_CONFIG_HOME at its own copy of the
|
|
4
|
+
// 1.x config (the upgrade rewrites ~/.config/opencode to 2.x keys, which 1.x may reject), and puts the shim folder on PATH: a marked
|
|
5
|
+
// block in the shell rc file, or the HKCU user PATH on Windows. Files and blocks go through the engine's fsops actions; the copied
|
|
6
|
+
// binary and the HKCU entry are recorded in state.json (`opencode1`) and removed by `--uninstall`. The backup, the frozen copy and
|
|
7
|
+
// `opencode1/state` (what 1.x writes while it runs) and `opencode1/config` (the 1.x config copy) are never removed.
|
|
8
|
+
// `which`, `probe`, `winPath` and `shell` are passed in so tests never read the real machine or the registry.
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { rcFiles } from './shell-path.mjs';
|
|
13
|
+
import { execFileSync } from 'node:child_process';
|
|
14
|
+
import { backupLayout, sha256File } from './opencode-backup.mjs';
|
|
15
|
+
import { which as findOnPath } from './system.mjs';
|
|
16
|
+
import { plan as planActions, renameRetry } from './fsops.mjs';
|
|
17
|
+
|
|
18
|
+
const j = path.join;
|
|
19
|
+
const MIN_BINARY = 1 << 20; // npm ships a ~0.5 KB launcher in bin/ until its postinstall swaps in the native binary
|
|
20
|
+
|
|
21
|
+
export function layout(home) {
|
|
22
|
+
const { lean, frozen } = backupLayout(home, 'x');
|
|
23
|
+
const root = j(lean, 'opencode1');
|
|
24
|
+
return { root, frozen, state: j(root, 'state'), config: j(root, 'config'), bin: j(root, 'bin') };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const sq = (s) => `'${s.replace(/'/g, "'\\''")}'`;
|
|
28
|
+
const MARK = 'managed by lean-agents: OpenCode 1.x on its own frozen copy of the data (#80); removed by --uninstall';
|
|
29
|
+
|
|
30
|
+
export function shimText(kind, { data, state, binary, config }) {
|
|
31
|
+
if (kind === 'cmd') {
|
|
32
|
+
const lines = ['@echo off', `rem ${MARK}`, 'setlocal', `set "XDG_DATA_HOME=${data}"`, `set "XDG_STATE_HOME=${state}"`, ...(config ? [`set "XDG_CONFIG_HOME=${config}"`] : []), `"${binary}" %*`, 'exit /b %errorlevel%'];
|
|
33
|
+
return `${lines.join('\r\n')}\r\n`;
|
|
34
|
+
}
|
|
35
|
+
const fwd = (p) => p.replace(/\\/g, '/'); // Git Bash on Windows reads D:/x
|
|
36
|
+
return `#!/bin/sh\n# ${MARK}\nexport XDG_DATA_HOME=${sq(fwd(data))}\nexport XDG_STATE_HOME=${sq(fwd(state))}\n${config ? `export XDG_CONFIG_HOME=${sq(fwd(config))}\n` : ''}exec ${sq(fwd(binary))} "$@"\n`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Where an `opencode` 1.x binary may be: the 2.x installer's folder (same path on Windows), what is on PATH, and npm's platform packages.
|
|
40
|
+
export function candidates({ home, platform = process.platform, whichPath = null, fsx = fs }) {
|
|
41
|
+
const ext = platform === 'win32' ? '.exe' : '';
|
|
42
|
+
const out = [j(home, '.opencode', 'bin', `opencode${ext}`)];
|
|
43
|
+
if (whichPath) {
|
|
44
|
+
let real = whichPath;
|
|
45
|
+
try { real = fsx.realpathSync(whichPath); } catch { /* keep the path as found */ }
|
|
46
|
+
out.push(real);
|
|
47
|
+
const dir = path.dirname(real);
|
|
48
|
+
for (const pkg of [j(dir, 'node_modules', 'opencode-ai'), path.dirname(dir)]) {
|
|
49
|
+
out.push(j(pkg, 'bin', `opencode${ext}`));
|
|
50
|
+
for (const base of [j(pkg, 'node_modules'), path.dirname(pkg)]) {
|
|
51
|
+
let names = [];
|
|
52
|
+
try { names = fsx.readdirSync(base); } catch { /* no such folder */ }
|
|
53
|
+
for (const n of names) if (/^opencode-/.test(n) && n !== 'opencode-ai') out.push(j(base, n, 'bin', `opencode${ext}`));
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const big = (f) => { try { const s = fsx.statSync(f); return s.isFile() && s.size >= MIN_BINARY; } catch { return false; } };
|
|
58
|
+
return [...new Set(out)].filter((f) => !/\.(cmd|bat|ps1)$/i.test(f) && big(f));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function probeVersion(bin, env) {
|
|
62
|
+
const out = execFileSync(bin, ['--version'], { env, encoding: 'utf8', timeout: 30000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
63
|
+
return out.trim().split(/\r?\n/).pop().trim();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// First candidate that runs and reports a 1.x version: { path, version }, or { tried: [...] }.
|
|
67
|
+
export function findBinary({ home, platform, whichPath, probe, env, fsx = fs }) {
|
|
68
|
+
const tried = [];
|
|
69
|
+
for (const c of candidates({ home, platform, whichPath, fsx })) {
|
|
70
|
+
try {
|
|
71
|
+
const v = probe(c, env);
|
|
72
|
+
if (/^1\.\d+\.\d+$/.test(v)) return { path: c, version: v };
|
|
73
|
+
tried.push(`${c} (version ${v || '?'}, not 1.x)`);
|
|
74
|
+
} catch (e) { tried.push(`${c} (does not run: ${String(e.message).split('\n')[0]})`); }
|
|
75
|
+
}
|
|
76
|
+
return { tried };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// User PATH on Windows, read and written unexpanded like install.ps1 does. Prints present | absent | changed.
|
|
80
|
+
const WIN_PATH_PS = `
|
|
81
|
+
$ErrorActionPreference = 'Stop'
|
|
82
|
+
$dir = $env:LEAN_PATH_DIR
|
|
83
|
+
function Open-Env($w) { [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $w) }
|
|
84
|
+
function Get-Norm($p) { [Environment]::ExpandEnvironmentVariables($p).TrimEnd('\\') }
|
|
85
|
+
$k = Open-Env $false
|
|
86
|
+
try { $raw = [string]$k.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) } finally { $k.Close() }
|
|
87
|
+
$parts = @($raw -split ';' | Where-Object { $_ })
|
|
88
|
+
$has = @($parts | Where-Object { (Get-Norm $_) -eq (Get-Norm $dir) }).Count -gt 0
|
|
89
|
+
if ($env:LEAN_PATH_OP -eq 'has') { if ($has) { 'present' } else { 'absent' }; exit 0 }
|
|
90
|
+
if ($env:LEAN_PATH_OP -eq 'add' -or $env:LEAN_PATH_OP -eq 'prepend') {
|
|
91
|
+
if ($has) { 'present'; exit 0 }
|
|
92
|
+
if ($env:LEAN_PATH_OP -eq 'prepend') {
|
|
93
|
+
if (-not $raw) { $new = $dir } else { $new = "$dir;" + $raw.TrimStart(';') }
|
|
94
|
+
} else {
|
|
95
|
+
if (-not $raw) { $new = $dir } elseif ($raw.EndsWith(';')) { $new = "$raw$dir" } else { $new = "$raw;$dir" }
|
|
96
|
+
}
|
|
97
|
+
} else {
|
|
98
|
+
if (-not $has) { 'absent'; exit 0 }
|
|
99
|
+
$new = @($parts | Where-Object { (Get-Norm $_) -ne (Get-Norm $dir) }) -join ';'
|
|
100
|
+
}
|
|
101
|
+
$k = Open-Env $true
|
|
102
|
+
try { $k.SetValue('Path', $new, [Microsoft.Win32.RegistryValueKind]::ExpandString) } finally { $k.Close() }
|
|
103
|
+
[Environment]::SetEnvironmentVariable('LEAN_AGENTS_PATH_REFRESH', '1', 'User')
|
|
104
|
+
[Environment]::SetEnvironmentVariable('LEAN_AGENTS_PATH_REFRESH', $null, 'User')
|
|
105
|
+
'changed'
|
|
106
|
+
`;
|
|
107
|
+
export const winPathDefault = (op, dir) => execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', WIN_PATH_PS], {
|
|
108
|
+
encoding: 'utf8', windowsHide: true, env: { ...process.env, LEAN_PATH_DIR: dir, LEAN_PATH_OP: op },
|
|
109
|
+
}).trim().split(/\r?\n/).pop();
|
|
110
|
+
|
|
111
|
+
// Read-only. Returns { ok, problems, version, source, binary, actions, pathDir } for `installOpencode1`.
|
|
112
|
+
// `configSnapshot`: the 1.x config folder saved by --backup (copied for the shim); without one the shim gets an empty config folder.
|
|
113
|
+
export function planOpencode1({ home, configSnapshot = null, exec = true, platform = process.platform, env = process.env, which = findOnPath, probe = probeVersion, shell = process.env.SHELL, fsx = fs }) {
|
|
114
|
+
const L = layout(home);
|
|
115
|
+
const win = platform === 'win32';
|
|
116
|
+
const problems = [];
|
|
117
|
+
if (!fsx.existsSync(j(L.frozen, 'opencode', 'opencode.db'))) problems.push(`no frozen copy at ${L.frozen}: run --upgrade-agent opencode --backup --yes first`);
|
|
118
|
+
// The binary is run once (`--version`) to name its folder and to prove the copy works: not under --no-exec.
|
|
119
|
+
if (!exec) problems.push('--no-exec: the 1.x binary has to run `--version`, so this step needs commands enabled');
|
|
120
|
+
if (problems.length) return { ok: false, problems };
|
|
121
|
+
// Candidates may be 2.x (it migrates a db it finds): probe them on an empty throwaway data dir, never on the frozen copy.
|
|
122
|
+
const scratch = fsx.mkdtempSync(j(os.tmpdir(), 'lean-probe-'));
|
|
123
|
+
let found;
|
|
124
|
+
try { found = findBinary({ home, platform, whichPath: which('opencode'), probe, env: { ...env, XDG_DATA_HOME: scratch, XDG_STATE_HOME: scratch }, fsx }); } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
|
|
125
|
+
if (!found.path) problems.push(`no OpenCode 1.x binary found${found.tried.length ? `; tried:\n ${found.tried.join('\n ')}` : ' (none on PATH or in ~/.opencode/bin)'}`);
|
|
126
|
+
if (problems.length) return { ok: false, problems };
|
|
127
|
+
|
|
128
|
+
const binary = j(L.root, found.version, `opencode${win ? '.exe' : ''}`);
|
|
129
|
+
const text = { data: L.frozen, state: L.state, binary, config: L.config };
|
|
130
|
+
const actions = win
|
|
131
|
+
? [{ kind: 'file', path: j(L.bin, 'opencode1.cmd'), content: shimText('cmd', text) }, { kind: 'file', path: j(L.bin, 'opencode1'), content: shimText('sh', text) }]
|
|
132
|
+
: [{ kind: 'file', path: j(L.bin, 'opencode1'), content: shimText('sh', text) },
|
|
133
|
+
...rcFiles(home, shell, fsx).map((p) => ({ kind: 'block', id: 'opencode1', path: p, body: `export PATH=${sq(L.bin)}:"$PATH"` }))];
|
|
134
|
+
return { ok: true, problems, version: found.version, source: found.path, binary, actions, pathDir: L.bin, root: L.root, configSnapshot, configDir: j(L.config, 'opencode') };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Writes. `files` collects the fsops entries (the caller saves them in state.json); `onRecord(record)` fires after each step that
|
|
138
|
+
// `--uninstall` must undo, so an error midway still leaves a state to undo. Returns the record (state.json `opencode1`).
|
|
139
|
+
export function installOpencode1(p, { home, roots, backupDir, apply, files = [], platform = process.platform, probe = probeVersion, env = process.env, winPath = winPathDefault, onRecord = () => {} }) {
|
|
140
|
+
const win = platform === 'win32';
|
|
141
|
+
const record = { version: p.version, dir: path.dirname(p.binary), binary: p.binary, binDir: p.pathDir, pathEntry: false };
|
|
142
|
+
const planned = planActions(p.actions, roots);
|
|
143
|
+
const refused = planned.filter((a) => a.status === 'skip');
|
|
144
|
+
if (refused.length) throw new Error(refused.map((a) => `${a.path}: ${a.note}`).join('; '));
|
|
145
|
+
|
|
146
|
+
if (fs.existsSync(p.binary)) {
|
|
147
|
+
if (sha256File(p.binary) !== sha256File(p.source)) throw new Error(`${p.binary} exists and differs from ${p.source}: not overwritten`);
|
|
148
|
+
} else {
|
|
149
|
+
fs.mkdirSync(record.dir, { recursive: true, mode: 0o700 });
|
|
150
|
+
const part = `${p.binary}.partial`;
|
|
151
|
+
fs.copyFileSync(p.source, part);
|
|
152
|
+
if (!win) fs.chmodSync(part, 0o755);
|
|
153
|
+
if (sha256File(part) !== sha256File(p.source)) throw new Error('sha256 differs after copying the binary');
|
|
154
|
+
const scratch = fs.mkdtempSync(j(os.tmpdir(), 'lean-probe-'));
|
|
155
|
+
let v;
|
|
156
|
+
try { v = probe(part, { ...env, XDG_DATA_HOME: scratch, XDG_STATE_HOME: scratch }); } finally { fs.rmSync(scratch, { recursive: true, force: true }); }
|
|
157
|
+
if (v !== p.version) throw new Error(`the copied binary reports "${v}", expected ${p.version}`);
|
|
158
|
+
renameRetry(part, p.binary);
|
|
159
|
+
}
|
|
160
|
+
// 1.x gets its own copy of the config it knew; an existing copy (the user may have edited it) is never overwritten.
|
|
161
|
+
const cfg = p.configDir ?? j(layout(home).config, 'opencode');
|
|
162
|
+
if (!fs.existsSync(cfg)) {
|
|
163
|
+
// Copy beside it and rename: a copy that fails midway must not leave a partial folder that later runs would keep.
|
|
164
|
+
const part = `${cfg}.partial`;
|
|
165
|
+
fs.rmSync(part, { recursive: true, force: true });
|
|
166
|
+
fs.mkdirSync(part, { recursive: true, mode: 0o700 });
|
|
167
|
+
if (p.configSnapshot && fs.existsSync(p.configSnapshot)) fs.cpSync(p.configSnapshot, part, { recursive: true, filter: (f) => path.basename(f) !== 'node_modules' });
|
|
168
|
+
renameRetry(part, cfg);
|
|
169
|
+
}
|
|
170
|
+
onRecord(record);
|
|
171
|
+
try { apply(planned, backupDir, home, roots, files); } finally { onRecord(record); }
|
|
172
|
+
if (!win) fs.chmodSync(p.actions[0].path, 0o755);
|
|
173
|
+
if (win) {
|
|
174
|
+
// Recorded before the registry write (a kill in between must not leave an HKCU entry --uninstall does not know about), but
|
|
175
|
+
// only when the entry was absent: removing one the user already had would be ours to answer for.
|
|
176
|
+
record.pathEntry = winPath('has', p.pathDir) === 'absent';
|
|
177
|
+
onRecord(record);
|
|
178
|
+
if (record.pathEntry) {
|
|
179
|
+
record.pathEntry = winPath('add', p.pathDir) === 'changed';
|
|
180
|
+
onRecord(record);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return record;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Undo what `record` holds (the shim files and rc blocks are undone by fsops from state.files). Returns [what, path] lines.
|
|
187
|
+
export function removeOpencode1(record, { home, winPath = winPathDefault, platform = process.platform } = {}) {
|
|
188
|
+
const report = [];
|
|
189
|
+
const L = layout(home);
|
|
190
|
+
// Only ever inside <data>/lean-agents/opencode1: a hand-edited state.json cannot point this at anything else.
|
|
191
|
+
const inside = (p) => path.dirname(p) === L.root && p !== L.frozen && p !== L.state && p !== L.config && p !== L.bin;
|
|
192
|
+
// Only the copied binary, then the folder if nothing else is in it.
|
|
193
|
+
if (record.dir && inside(record.dir) && record.binary && path.dirname(record.binary) === record.dir && fs.existsSync(record.binary)) {
|
|
194
|
+
fs.rmSync(record.binary);
|
|
195
|
+
report.push(['removed', record.binary]);
|
|
196
|
+
try { fs.rmdirSync(record.dir); report.push(['removed', record.dir]); } catch { /* not empty: left */ }
|
|
197
|
+
}
|
|
198
|
+
try { if (fs.readdirSync(L.bin).length === 0) { fs.rmdirSync(L.bin); report.push(['removed', L.bin]); } } catch { /* absent or not empty */ }
|
|
199
|
+
if (record.pathEntry && platform === 'win32' && record.binDir === L.bin) {
|
|
200
|
+
if (winPath('remove', L.bin) === 'changed') report.push(['removed from user PATH', L.bin]);
|
|
201
|
+
}
|
|
202
|
+
return report;
|
|
203
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Parallel agent sessions: one git worktree per task, one worker agent in each, merged one at a time.
|
|
2
|
+
// Commands are argv arrays, never shell strings. State lives in <git common dir>/lean-agents/.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
7
|
+
import { loadProfile, modelFor } from './render.mjs';
|
|
8
|
+
import { which } from './system.mjs';
|
|
9
|
+
|
|
10
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
11
|
+
const LOG_TAIL_BYTES = 2000;
|
|
12
|
+
|
|
13
|
+
const NAME_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
14
|
+
// User-facing tier names; profiles call the cheapest one "fast".
|
|
15
|
+
export const TIERS = { cheap: 'fast', balanced: 'balanced', strong: 'strong' };
|
|
16
|
+
const ROLE_TIER = { plan: 'strong', build: 'balanced', explore: 'cheap', research: 'cheap' };
|
|
17
|
+
const DEFAULT_PROFILE = { claude: 'claude-subscription', orca: 'claude-subscription' };
|
|
18
|
+
|
|
19
|
+
export function git(cwd, args) {
|
|
20
|
+
const r = spawnSync('git', args, { cwd, encoding: 'utf8' });
|
|
21
|
+
return { ok: r.status === 0, out: (r.stdout ?? '').trim(), err: (r.stderr ?? '').trim() };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function gitOrThrow(cwd, args) {
|
|
25
|
+
const r = git(cwd, args);
|
|
26
|
+
if (!r.ok) throw new Error(`git ${args.join(' ')}: ${r.err || r.out}`);
|
|
27
|
+
return r.out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Task file: optional `---` front matter (role, tier, agent, check), then the prompt body.
|
|
31
|
+
export function parseTask(file) {
|
|
32
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
33
|
+
const name = path.basename(file).replace(/\.md$/, '');
|
|
34
|
+
if (!NAME_RE.test(name)) throw new Error(`task file name "${name}" must be lowercase letters, digits and dashes`);
|
|
35
|
+
const meta = {};
|
|
36
|
+
let body = text;
|
|
37
|
+
const m = text.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
|
|
38
|
+
if (m) {
|
|
39
|
+
for (const line of m[1].split(/\r?\n/)) {
|
|
40
|
+
const kv = line.match(/^(\w+):\s*(.*)$/);
|
|
41
|
+
if (kv) meta[kv[1]] = kv[2].trim();
|
|
42
|
+
}
|
|
43
|
+
body = text.slice(m[0].length);
|
|
44
|
+
}
|
|
45
|
+
return { name, role: meta.role ?? 'build', tier: meta.tier, agent: meta.agent, check: meta.check, body };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function tierOf(task, override) {
|
|
49
|
+
const tier = override ?? task.tier ?? ROLE_TIER[task.role];
|
|
50
|
+
if (!tier) throw new Error(`task ${task.name}: unknown role "${task.role}" (use plan, build, explore or research, or set tier)`);
|
|
51
|
+
if (!TIERS[tier]) throw new Error(`task ${task.name}: unknown tier "${tier}" (use cheap, balanced or strong)`);
|
|
52
|
+
return tier;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Model for a tier through a profile; Claude aliases (haiku, sonnet, opus) come from claude-subscription.
|
|
56
|
+
export function tierModel(agent, tier, profileName) {
|
|
57
|
+
const profile = loadProfile(ROOT, profileName ?? DEFAULT_PROFILE[agent]);
|
|
58
|
+
return modelFor(profile, TIERS[tier])?.model ?? null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Only `Read <path> and follow it.` goes on the command line; the task text stays in the file.
|
|
62
|
+
export const instruction = (promptFile) => `Read ${promptFile} and follow it.`;
|
|
63
|
+
|
|
64
|
+
export function buildWorkerCommand({ agent, name, model, promptFile, dir, base }) {
|
|
65
|
+
const instr = instruction(promptFile);
|
|
66
|
+
if (agent === 'claude') {
|
|
67
|
+
return ['claude', '--bg', '-n', name, '--permission-mode', 'plan', ...(model ? ['--model', model] : []), instr];
|
|
68
|
+
}
|
|
69
|
+
if (agent === 'opencode') {
|
|
70
|
+
return ['opencode', 'run', '--title', name, '--agent', 'plan', ...(model ? ['-m', model] : []), '-f', promptFile, instr];
|
|
71
|
+
}
|
|
72
|
+
if (agent === 'orca') {
|
|
73
|
+
return ['orca', 'worktree', 'create', '--name', name, '--agent', 'claude', ...(model ? ['--model', model] : []),
|
|
74
|
+
'--prompt', instr, '--surface', 'terminal', '--base-branch', base, '--json'];
|
|
75
|
+
}
|
|
76
|
+
throw new Error(`no command for agent "${agent}"`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export const orcaAvailable = () => Boolean(which('orca')) && spawnSync('orca', ['agent-context', '--json'], { stdio: 'ignore' }).status === 0;
|
|
80
|
+
|
|
81
|
+
export function pickAgent(requested) {
|
|
82
|
+
if (requested && requested !== 'auto') return requested;
|
|
83
|
+
if (orcaAvailable()) return 'orca';
|
|
84
|
+
if (which('claude')) return 'claude';
|
|
85
|
+
if (which('opencode')) return 'opencode';
|
|
86
|
+
return 'print';
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Quoted for display only, so the user can paste it into a terminal.
|
|
90
|
+
export const display = (argv) => argv.map((a) => (/^[\w./:=@%+-]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`)).join(' ');
|
|
91
|
+
|
|
92
|
+
export function repoInfo(cwd) {
|
|
93
|
+
const top = gitOrThrow(cwd, ['rev-parse', '--show-toplevel']);
|
|
94
|
+
const common = path.resolve(top, gitOrThrow(top, ['rev-parse', '--git-common-dir']));
|
|
95
|
+
return { top, stateDir: path.join(common, 'lean-agents') };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const workersFile = (stateDir) => path.join(stateDir, 'workers.json');
|
|
99
|
+
|
|
100
|
+
// A worker name becomes a path (clean removes stateDir/<name>), so a hand-edited workers.json is checked like a task file name.
|
|
101
|
+
export function loadWorkers(stateDir) {
|
|
102
|
+
let data;
|
|
103
|
+
try { data = JSON.parse(fs.readFileSync(workersFile(stateDir), 'utf8')); } catch { return { base: null, workers: [] }; }
|
|
104
|
+
if (!Array.isArray(data?.workers) || data.workers.some((w) => typeof w?.name !== 'string' || !NAME_RE.test(w.name))) throw new Error(`${workersFile(stateDir)} is not a valid worker list (names are lowercase letters, digits and dashes); fix or delete the file`);
|
|
105
|
+
return data;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function saveWorkers(stateDir, data) {
|
|
109
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
110
|
+
fs.writeFileSync(workersFile(stateDir), `${JSON.stringify(data, null, 2)}\n`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export const statusOf = (stateDir, name) => {
|
|
114
|
+
try { return fs.readFileSync(path.join(stateDir, name, 'status'), 'utf8').trim() || 'running'; } catch { return 'running'; }
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
function logTail(stateDir, name) {
|
|
118
|
+
const file = path.join(stateDir, name, 'log');
|
|
119
|
+
if (!fs.existsSync(file)) return '';
|
|
120
|
+
const buf = fs.readFileSync(file);
|
|
121
|
+
return buf.subarray(Math.max(0, buf.length - LOG_TAIL_BYTES)).toString('utf8').trim().split('\n').slice(-5).join('\n');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function writePrompt(stateDir, task, statusFile) {
|
|
125
|
+
const dir = path.join(stateDir, task.name);
|
|
126
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
127
|
+
const promptFile = path.join(dir, 'task.md');
|
|
128
|
+
fs.writeFileSync(promptFile, [
|
|
129
|
+
task.body.trim(),
|
|
130
|
+
'',
|
|
131
|
+
'## Rules from the coordinator',
|
|
132
|
+
'- Work only in this worktree. Do not push. Commit your work on this branch.',
|
|
133
|
+
`- Report by writing one line to ${statusFile}: \`running\`, \`blocked: <question>\` or \`done\`.`,
|
|
134
|
+
'',
|
|
135
|
+
].join('\n'));
|
|
136
|
+
fs.writeFileSync(statusFile, 'running\n');
|
|
137
|
+
return promptFile;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Orca prefixes the branch with the user's handle; find it by suffix and rename it to lean/<name>.
|
|
141
|
+
function adoptOrcaBranch(top, name, branch) {
|
|
142
|
+
const list = gitOrThrow(top, ['worktree', 'list', '--porcelain']).split('\n\n').map((b) => ({
|
|
143
|
+
dir: (b.match(/^worktree (.*)$/m) ?? [])[1], branch: ((b.match(/^branch refs\/heads\/(.*)$/m) ?? [])[1]),
|
|
144
|
+
}));
|
|
145
|
+
const hit = list.find((w) => w.branch && (w.branch === name || w.branch.endsWith(`/${name}`)));
|
|
146
|
+
if (!hit) throw new Error(`Orca created no worktree for "${name}" (VERIFY the Orca output)`);
|
|
147
|
+
if (hit.branch !== branch) gitOrThrow(hit.dir, ['branch', '-m', hit.branch, branch]);
|
|
148
|
+
return hit.dir;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function start(cwd, files, opts = {}) {
|
|
152
|
+
const { top, stateDir } = repoInfo(cwd);
|
|
153
|
+
const data = loadWorkers(stateDir);
|
|
154
|
+
const base = opts.base ?? data.base ?? gitOrThrow(top, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
155
|
+
data.base = base;
|
|
156
|
+
const out = [];
|
|
157
|
+
for (const file of files) {
|
|
158
|
+
const task = parseTask(file);
|
|
159
|
+
if (data.workers.some((w) => w.name === task.name)) throw new Error(`worker "${task.name}" already exists; run clean first`);
|
|
160
|
+
const agent = pickAgent(task.agent ?? opts.agent);
|
|
161
|
+
const tier = tierOf(task, opts.tier);
|
|
162
|
+
const modelAgent = agent === 'print' ? 'claude' : agent;
|
|
163
|
+
const model = opts.model ?? tierModel(modelAgent, tier, opts.profile);
|
|
164
|
+
const branch = `lean/${task.name}`;
|
|
165
|
+
const promptFile = writePrompt(stateDir, task, path.join(stateDir, task.name, 'status'));
|
|
166
|
+
const logFile = path.join(stateDir, task.name, 'log');
|
|
167
|
+
const worker = { name: task.name, branch, base, agent, tier, model, check: task.check ?? null, dir: null };
|
|
168
|
+
let argv;
|
|
169
|
+
if (agent === 'orca') {
|
|
170
|
+
argv = buildWorkerCommand({ agent, name: task.name, model, promptFile, base });
|
|
171
|
+
const r = spawnSync(argv[0], argv.slice(1), { cwd: top, encoding: 'utf8' });
|
|
172
|
+
fs.writeFileSync(logFile, `${r.stdout ?? ''}${r.stderr ?? ''}`);
|
|
173
|
+
if (r.status !== 0) throw new Error(`orca worktree create failed: ${(r.stderr ?? '').trim()}`);
|
|
174
|
+
worker.dir = adoptOrcaBranch(top, task.name, branch);
|
|
175
|
+
} else {
|
|
176
|
+
worker.dir = path.join(`${top}.lean`, task.name);
|
|
177
|
+
if (agent === 'custom' && !opts.cmd) throw new Error('--agent custom needs --cmd <program>');
|
|
178
|
+
gitOrThrow(top, ['worktree', 'add', '-b', branch, worker.dir, base]);
|
|
179
|
+
data.workers.push(worker);
|
|
180
|
+
saveWorkers(stateDir, data);
|
|
181
|
+
if (agent === 'custom') {
|
|
182
|
+
argv = [opts.cmd, promptFile];
|
|
183
|
+
} else if (agent !== 'print') {
|
|
184
|
+
argv = buildWorkerCommand({ agent, name: task.name, model, promptFile, dir: worker.dir });
|
|
185
|
+
}
|
|
186
|
+
if (agent === 'print' || (agent !== 'custom' && !which(argv[0]))) {
|
|
187
|
+
argv = buildWorkerCommand({ agent: 'claude', name: task.name, model, promptFile, dir: worker.dir });
|
|
188
|
+
worker.agent = 'print';
|
|
189
|
+
worker.command = `cd ${display([worker.dir])} && ${display(argv)}`;
|
|
190
|
+
} else {
|
|
191
|
+
const fd = fs.openSync(logFile, 'a');
|
|
192
|
+
// OpenCode has no --dir flag in 2.1.4, so the worker's working directory is the worktree.
|
|
193
|
+
spawn(argv[0], argv.slice(1), { cwd: worker.dir, detached: true, stdio: ['ignore', fd, fd] }).unref();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (!data.workers.includes(worker)) data.workers.push(worker);
|
|
197
|
+
saveWorkers(stateDir, data);
|
|
198
|
+
out.push(worker);
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export function status(cwd) {
|
|
204
|
+
const { stateDir } = repoInfo(cwd);
|
|
205
|
+
return loadWorkers(stateDir).workers.map((w) => ({
|
|
206
|
+
...w,
|
|
207
|
+
status: statusOf(stateDir, w.name),
|
|
208
|
+
tail: logTail(stateDir, w.name),
|
|
209
|
+
}));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Merges one finished worker, in start order, then rebases the others onto the new base.
|
|
213
|
+
export function merge(cwd, name) {
|
|
214
|
+
const { top, stateDir } = repoInfo(cwd);
|
|
215
|
+
const data = loadWorkers(stateDir);
|
|
216
|
+
const w = data.workers.find((x) => x.name === name);
|
|
217
|
+
if (!w) throw new Error(`no worker "${name}"`);
|
|
218
|
+
if (w.merged) throw new Error(`worker "${name}" is already merged`);
|
|
219
|
+
const next = data.workers.find((x) => !x.merged);
|
|
220
|
+
if (next.name !== name) throw new Error(`merge "${next.name}" first (start order)`);
|
|
221
|
+
const st = statusOf(stateDir, name);
|
|
222
|
+
if (st !== 'done') throw new Error(`worker "${name}" is "${st}", not done`);
|
|
223
|
+
if (git(w.dir, ['status', '--porcelain']).out) throw new Error(`worker "${name}" has uncommitted changes in ${w.dir}`);
|
|
224
|
+
if (git(top, ['rev-parse', '--abbrev-ref', 'HEAD']).out !== data.base) throw new Error(`check out ${data.base} in ${top} first`);
|
|
225
|
+
if (git(top, ['status', '--porcelain', '--untracked-files=no']).out) throw new Error(`${top} has uncommitted changes`);
|
|
226
|
+
if (w.check) {
|
|
227
|
+
const [bin, ...args] = w.check.split(/\s+/);
|
|
228
|
+
const r = spawnSync(bin, args, { cwd: w.dir, encoding: 'utf8' });
|
|
229
|
+
if (r.status !== 0) throw new Error(`check "${w.check}" failed:\n${(r.stdout ?? '').slice(-LOG_TAIL_BYTES)}${(r.stderr ?? '').slice(-LOG_TAIL_BYTES)}`);
|
|
230
|
+
}
|
|
231
|
+
const m = git(top, ['merge', '--no-ff', '--no-edit', w.branch]);
|
|
232
|
+
if (!m.ok) { git(top, ['merge', '--abort']); throw new Error(`merge of "${name}" failed: ${m.err || m.out}\nIf it conflicts, rebase it on ${data.base} in ${w.dir} and retry`); }
|
|
233
|
+
w.merged = true;
|
|
234
|
+
saveWorkers(stateDir, data);
|
|
235
|
+
const rebased = [];
|
|
236
|
+
const skipped = [];
|
|
237
|
+
for (const o of data.workers) {
|
|
238
|
+
if (o.merged) continue;
|
|
239
|
+
// A running worker has a dirty tree and would be disturbed; it rebases itself or at its own merge.
|
|
240
|
+
if (statusOf(stateDir, o.name) !== 'done' || git(o.dir, ['status', '--porcelain']).out) { skipped.push(o.name); continue; }
|
|
241
|
+
if (git(o.dir, ['rebase', data.base]).ok) rebased.push(o.name);
|
|
242
|
+
else { git(o.dir, ['rebase', '--abort']); skipped.push(o.name); }
|
|
243
|
+
}
|
|
244
|
+
if (skipped.length) console.error(`not rebased (running, dirty or conflicting): ${skipped.join(', ')}; rebase them in their worktree before their merge`);
|
|
245
|
+
return rebased;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Removes only workers this helper created, only when merged; never --force.
|
|
249
|
+
export function clean(cwd) {
|
|
250
|
+
const { top, stateDir } = repoInfo(cwd);
|
|
251
|
+
const data = loadWorkers(stateDir);
|
|
252
|
+
const kept = [];
|
|
253
|
+
const removed = [];
|
|
254
|
+
for (const w of data.workers) {
|
|
255
|
+
if (!w.merged) { kept.push(w); continue; }
|
|
256
|
+
if (fs.existsSync(w.dir)) gitOrThrow(top, ['worktree', 'remove', w.dir]);
|
|
257
|
+
if (git(top, ['rev-parse', '--verify', '-q', w.branch]).ok) gitOrThrow(top, ['branch', '-d', w.branch]);
|
|
258
|
+
fs.rmSync(path.join(stateDir, w.name), { recursive: true, force: true });
|
|
259
|
+
removed.push(w.name);
|
|
260
|
+
}
|
|
261
|
+
if (kept.length) saveWorkers(stateDir, { ...data, workers: kept });
|
|
262
|
+
else fs.rmSync(workersFile(stateDir), { force: true });
|
|
263
|
+
try { fs.rmdirSync(`${top}.lean`); } catch { /* not empty or absent */ }
|
|
264
|
+
return { removed, kept: kept.map((w) => w.name) };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// For --doctor: workers left in the repo at `cwd`, if it is one.
|
|
268
|
+
export function leftovers(cwd) {
|
|
269
|
+
try { return loadWorkers(repoInfo(cwd).stateDir).workers.map((w) => w.name); } catch { return []; }
|
|
270
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Diffs two core/pins.json documents for the release notes. Pure: no I/O, no network.
|
|
2
|
+
|
|
3
|
+
const MARKS = { added: 'new', removed: 'removed' };
|
|
4
|
+
|
|
5
|
+
// Rows for every pin whose version changed, appeared or disappeared, sorted by name. `prev` may be null (no earlier release).
|
|
6
|
+
export function diffPins(prev, next) {
|
|
7
|
+
if (!prev?.pins) return [];
|
|
8
|
+
const a = prev.pins;
|
|
9
|
+
const b = next.pins ?? {};
|
|
10
|
+
return [...new Set([...Object.keys(a), ...Object.keys(b)])].sort().flatMap((name) => {
|
|
11
|
+
const was = a[name];
|
|
12
|
+
const now = b[name];
|
|
13
|
+
if (was && now && was.version === now.version) return [];
|
|
14
|
+
const p = now ?? was;
|
|
15
|
+
return [{
|
|
16
|
+
name,
|
|
17
|
+
from: was?.version ?? null,
|
|
18
|
+
to: now?.version ?? null,
|
|
19
|
+
kind: p.kind,
|
|
20
|
+
change: !was ? 'added' : !now ? 'removed' : 'bumped',
|
|
21
|
+
held: Boolean(p.hold),
|
|
22
|
+
ciOnly: Boolean(p.ciOnly),
|
|
23
|
+
}];
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Markdown table, or '' when nothing changed.
|
|
28
|
+
export function toolVersionsTable(rows) {
|
|
29
|
+
if (!rows.length) return '';
|
|
30
|
+
const note = (r) => [MARKS[r.change], r.held && 'held', r.ciOnly && 'CI only'].filter(Boolean).join(', ');
|
|
31
|
+
const lines = rows.map((r) => `| ${r.name} | ${r.from ?? '-'} | ${r.to ?? '-'} | ${note(r)} |`);
|
|
32
|
+
return ['| Tool | From | To | Note |', '| --- | --- | --- | --- |', ...lines].join('\n');
|
|
33
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// Known-good versions of everything fetched at run time (core/pins.json).
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'core', 'pins.json');
|
|
7
|
+
export const PINS = JSON.parse(fs.readFileSync(FILE, 'utf8')).pins;
|
|
8
|
+
|
|
9
|
+
function pin(key) {
|
|
10
|
+
const p = PINS[key];
|
|
11
|
+
if (!p) throw new Error(`no pin for ${key} in core/pins.json`);
|
|
12
|
+
return p;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const npmSpec = (key) => `${pin(key).source}@${pin(key).version}`;
|
|
16
|
+
// owner/repo#ref: `skills add` ignores a trailing @tag (installs HEAD) but honors #tag and #<commit sha> (verified skills 1.5.18 and 1.7.4).
|
|
17
|
+
// A pin without `sha` (lean-update until its tag exists) falls back to the tag.
|
|
18
|
+
export const skillSource = (key) => `${pin(key).source}#${pin(key).sha ?? pin(key).version}`;
|
|
19
|
+
// `claude plugin marketplace add owner/repo#<sha>` fails (checked 2026-11-10), so marketplaces pin by tag only.
|
|
20
|
+
export const marketplaceSource = (key) => `${pin(key).source}#${pin(key).version}`;
|
|
21
|
+
// What `uvx --from` takes: the commit SHA, so a moved tag cannot change what runs.
|
|
22
|
+
export const gitSpec = (key) => `git+https://github.com/${pin(key).source}@${pin(key).sha}`;
|
|
23
|
+
// npm or git spec for a {pin:key} placeholder in core/mcp.json.
|
|
24
|
+
export const pinSpec = (key) => (pin(key).kind === 'git' ? gitSpec(key) : npmSpec(key));
|
|
25
|
+
// The `engines.node` range the pinned npm version declares (">=24.15.0"), or undefined when it declares none.
|
|
26
|
+
export const nodeRange = (key) => pin(key).node;
|
|
27
|
+
export const bunPin = () => pin('bun');
|
|
28
|
+
export const rtkPin = () => pin('rtk');
|
|
29
|
+
export const skillsCli = () => npmSpec('skills-cli');
|
|
30
|
+
// `download` pins (Bun) are verified by SHA256 at install time; `tool` (rtk, uv, gh) and `cask` (Antigravity) pins are
|
|
31
|
+
// package-manager installs we cannot pin, so they are a minimum and a known-good version, not something state.json records.
|
|
32
|
+
const tracked = (p) => !p.ciOnly && !['download', 'tool', 'cask'].includes(p.kind);
|
|
33
|
+
// [{ key, source, via, version, min }] for the tools the update plan reports against: rtk, uv, gh, the Antigravity cask and Bun.
|
|
34
|
+
export const toolPins = () => Object.entries(PINS).filter(([, p]) => ['tool', 'cask'].includes(p.kind) || p.tagPrefix)
|
|
35
|
+
.map(([key, p]) => ({ key, source: p.source, via: p.via ?? p.kind, version: p.version, min: p.min ?? null }));
|
|
36
|
+
export const pinVersions = () => Object.fromEntries(Object.entries(PINS).filter(([, p]) => tracked(p)).map(([k, p]) => [k, p.version]));
|
|
37
|
+
|
|
38
|
+
// Pin keys that differ from the tool name lean-agents saves in state.json options.tools.
|
|
39
|
+
const PIN_TOOL = { 'playwright-mcp': 'playwright', 'gsd-core': 'gsd', 'opencode-dcp': 'dcp', 'ponytail-plugin': 'ponytail', 'context-mode-plugin': 'context-mode' };
|
|
40
|
+
export const pinTool = (key) => PIN_TOOL[key] ?? key;
|
|
41
|
+
// True when the saved options use this pin; the Skills CLI and the lean-update skill ride along with every install.
|
|
42
|
+
export const pinInUse = (key, options) => key === 'skills-cli' || key === 'lean-update'
|
|
43
|
+
|| (key === 'orca-cli' ? (options.terminals ?? []).includes('orca')
|
|
44
|
+
: key === 'warp-opencode' ? (options.terminals ?? []).includes('warp')
|
|
45
|
+
: (options.tools ?? []).includes(PIN_TOOL[key] ?? key));
|
|
46
|
+
|
|
47
|
+
// [{ tool, installed, pinned }] for pins in use whose saved version differs from core/pins.json now.
|
|
48
|
+
export function behindPins(saved) {
|
|
49
|
+
return Object.entries(saved.pins ?? {})
|
|
50
|
+
.filter(([k, v]) => PINS[k] && tracked(PINS[k]) && PINS[k].version !== v && pinInUse(k, saved.options))
|
|
51
|
+
.map(([tool, installed]) => ({ tool, installed, pinned: PINS[tool].version }));
|
|
52
|
+
}
|