lean-agents 0.8.0 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/README.es.md +130 -24
  3. package/README.md +130 -24
  4. package/core/copilot-usage-tui.js +5 -2
  5. package/core/pins.json +18 -9
  6. package/package.json +3 -2
  7. package/scripts/behavior-diff.sh +47 -0
  8. package/scripts/bump-pins.mjs +14 -3
  9. package/scripts/ci-timing.mjs +61 -0
  10. package/scripts/labels.sh +1 -0
  11. package/scripts/lean.mjs +695 -76
  12. package/scripts/lib/adapters/antigravity.mjs +20 -9
  13. package/scripts/lib/adapters/claude.mjs +7 -2
  14. package/scripts/lib/adapters/copilot-cli.mjs +4 -3
  15. package/scripts/lib/adapters/opencode-v1.mjs +6 -13
  16. package/scripts/lib/adapters/opencode-v2.mjs +51 -3
  17. package/scripts/lib/adopt.mjs +172 -27
  18. package/scripts/lib/agent-lifecycle.mjs +140 -23
  19. package/scripts/lib/backup-stamp.mjs +25 -0
  20. package/scripts/lib/doctor.mjs +86 -14
  21. package/scripts/lib/feedback.mjs +22 -4
  22. package/scripts/lib/fsops.mjs +42 -14
  23. package/scripts/lib/inventory.mjs +5 -4
  24. package/scripts/lib/logins.mjs +28 -0
  25. package/scripts/lib/network.mjs +53 -13
  26. package/scripts/lib/opencode-backup.mjs +204 -0
  27. package/scripts/lib/opencode-upgrade.mjs +441 -0
  28. package/scripts/lib/opencode1.mjs +203 -0
  29. package/scripts/lib/parallel.mjs +7 -2
  30. package/scripts/lib/pins-diff.mjs +33 -0
  31. package/scripts/lib/pins.mjs +7 -2
  32. package/scripts/lib/plugin-health.mjs +191 -0
  33. package/scripts/lib/prereqs.mjs +203 -0
  34. package/scripts/lib/shell-path.mjs +22 -0
  35. package/scripts/lib/summary-data.mjs +30 -0
  36. package/scripts/lib/summary-html.mjs +159 -0
  37. package/scripts/lib/system.mjs +107 -16
  38. package/scripts/lib/terminals.mjs +101 -3
  39. package/scripts/lib/update-plan.mjs +60 -0
  40. package/scripts/lib/upgrade.mjs +112 -11
  41. package/scripts/lib/verify-prompt.mjs +46 -0
  42. package/scripts/pins-latest.mjs +27 -4
  43. package/scripts/release.mjs +26 -1
  44. package/scripts/version-watch.mjs +8 -2
@@ -3,9 +3,10 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { parse } from 'jsonc-parser';
6
- import { hasMark } from './fsops.mjs';
6
+ import { hasMark, plan, apply, describe } from './fsops.mjs';
7
7
  import { configHome } from './system.mjs';
8
8
  import { configPath } from './adapters/opencode-v2.mjs';
9
+ import { readBackupStamp } from './backup-stamp.mjs';
9
10
 
10
11
  const j = path.join;
11
12
 
@@ -28,7 +29,12 @@ export const TRANSLATIONS = [
28
29
  const row = (key) => TRANSLATIONS.find((t) => t.key === key);
29
30
 
30
31
  // Keys with no verified 2.x equivalent, and so no row.
31
- const MANUAL_KEYS = new Set(['provider', 'permission', 'experimental']);
32
+ const MANUAL_KEYS = new Set(['provider']);
33
+ // Keys the docs name but whose value conversion they do not state as a rule (opencode.ai/docs/migrate-v1, permissions, config; 2026-11-13, docs only).
34
+ const MANUAL_WHY = {
35
+ permission: 'VERIFY: 2.x renames it to `permissions` (array of {action, resource, effect}; bash -> shell, task -> subagent); the docs show no general rule to convert the 1.x values',
36
+ experimental: 'VERIFY: 2.x keeps `experimental` but only `mcp_timeout` and `subagent_depth` have a documented mapping; `batch_tool`, `openTelemetry`, `primary_tools` and `continue_loop_on_deny` are ignored in 2.x',
37
+ };
32
38
  const SAME = new Set(['instructions', 'default_agent', 'model', 'share', 'shell']);
33
39
  const HANDLED = new Set(['$schema', 'mcp', 'plugin']); // mcp and plugin come from the adopt items
34
40
 
@@ -39,22 +45,41 @@ const verifyRow = (t, before) => ({ class: 'user-manual', before, after: null, r
39
45
  const manual = (before, reason) => ({ class: 'user-manual', before, after: null, reason, source: null });
40
46
  const managed = (before, after) => ({ class: 'managed', before, after, reason: 'lean-agents owns it; the 2.x adapter reinstalls it', source: 'adapters/opencode-v2.mjs' });
41
47
 
48
+ // The source text of a local plugin (a file, or the entry file of a folder), or null when unreadable.
49
+ function pluginSource(it, home, fsx) {
50
+ const p = (x) => (x.startsWith('~') ? home + x.slice(1) : x);
51
+ const f = p(it.source ?? it.file);
52
+ try {
53
+ if (!fsx.statSync(f).isDirectory()) return fsx.readFileSync(f, 'utf8');
54
+ const entry = ['tui.js', 'index.js', 'index.ts'].find((n) => fsx.existsSync(j(f, n)));
55
+ return entry ? fsx.readFileSync(j(f, entry), 'utf8') : null;
56
+ } catch { return null; }
57
+ }
58
+ // Only a file that calls `api.command` gets the 1.x -> 2.x API reason; for the rest nothing is proven either way.
59
+ const localPluginReason = (text) => (text !== null && /\bapi\.command\b/.test(text)
60
+ ? 'JS/TS plugin uses 1.x API `api.command`; 2.x uses `api.keymap`'
61
+ : 'local plugin file: the 2.x plugin API is not proven for it');
62
+
42
63
  // Classify one adopt item of the OpenCode 1.x config (mcp, plugin, plugins/ file) or a skill.
43
- function classifyItem(it, stopgaps) {
64
+ function classifyItem(it, stopgaps, home, fsx) {
44
65
  if (it.owner === 'managed') return managed(`${it.kind} ${it.name}`, it.kind === 'plugin' ? 'plugins[]' : it.kind === 'mcp' ? `mcp.servers.${it.name}` : it.file);
45
66
  if (it.kind === 'mcp') return translate(row('mcp'), it.name);
46
67
  if (it.kind === 'skill') { const t = row('skills'); return t.verified ? translate(t, it.name, `skill ${it.name}`) : verifyRow(t, `skill ${it.name}`); }
47
68
  if (it.kind === 'plugin' && it.keyPath.length) {
48
69
  const tui = /tui\.jsonc?$/.test(it.file);
49
70
  const t = row(tui ? 'tui-plugin' : 'plugin');
50
- const local = it.name.startsWith('file:');
51
71
  if (!t.verified) return verifyRow(t, `${tui ? 'tui.json ' : ''}plugin ${it.name}`);
52
- if (local) return manual(`plugin ${it.name}`, 'local plugin file: the 2.x plugin API is not proven for it');
72
+ if (it.source) return manual(`plugin ${it.name}`, localPluginReason(pluginSource(it, home, fsx)));
73
+
74
+ // A path or a bare file name is a local plugin; npm names (also @scope/name) are not.
75
+ const isLocalPath = /^([./~\\]|file:|[a-zA-Z]:[\\/])/.test(it.name) || (!it.name.startsWith('@') && /\.(js|mjs|cjs|ts)$/.test(it.name));
76
+ if (isLocalPath) return manual(`plugin ${it.name}`, localPluginReason(null));
77
+
53
78
  return translate(t, it.name, `plugin ${it.name}`);
54
79
  }
55
80
  const sg = stopgaps.find((s) => s.file === it.file);
56
81
  if (sg) return manual(`plugin ${it.name}`, `leftover stopgap: replace with ${sg.replaceWith}`);
57
- return manual(`plugin ${it.name}`, 'JS/TS plugin uses 1.x API `api.command`; 2.x uses `api.keymap`');
82
+ return manual(`plugin ${it.name}`, localPluginReason(pluginSource(it, home, fsx)));
58
83
  }
59
84
 
60
85
  // Top-level keys of the 1.x config and the files in its agent/command folders, as new items (key names only).
@@ -72,7 +97,7 @@ function configItems(home, ocDir, fsx, rel) {
72
97
  else if (k === 'disabled_providers') at(k, translate(row(k), k));
73
98
  else if (SAME.has(k)) at(k, translate(row(k), k));
74
99
  else if (k === 'keybinds') at(k, verifyRow(row(k), k));
75
- else at(k, manual(k, MANUAL_KEYS.has(k) ? 'no verified 2.x key' : 'unknown 1.x key: no verified 2.x key'));
100
+ else at(k, manual(k, MANUAL_WHY[k] ?? (MANUAL_KEYS.has(k) ? 'no verified 2.x key' : 'unknown 1.x key: no verified 2.x key')));
76
101
  }
77
102
  for (const d of ['agent', 'agents', 'command', 'commands']) {
78
103
  let list = [];
@@ -95,7 +120,7 @@ export function upgradeInventory(inv, { home, fsx = fs, binary = { path: null, v
95
120
  const ocDir = j(configHome(home), 'opencode');
96
121
  const items = inv.items.map((it) => {
97
122
  if (!(it.client === 'opencode' || it.kind === 'skill')) return it;
98
- return { ...it, upgrade: classifyItem(it, inv.stopgaps) };
123
+ return { ...it, upgrade: classifyItem(it, inv.stopgaps, home, fsx) };
99
124
  });
100
125
  items.push(...configItems(home, ocDir, fsx, rel));
101
126
  const mine = items.filter((i) => i.upgrade);
@@ -106,6 +131,7 @@ export function upgradeInventory(inv, { home, fsx = fs, binary = { path: null, v
106
131
  ...mine.filter((i) => i.upgrade.class === 'user-translatable').map((i) => `translate ${i.upgrade.before} -> ${i.upgrade.after}`),
107
132
  ...mine.filter((i) => i.upgrade.class === 'user-manual').map((i) => `manual ${i.upgrade.before}: ${i.upgrade.reason}`),
108
133
  ];
134
+ const stamp = readBackupStamp(home, fsx); // shown as ~ like the other paths: reports get pasted into issues
109
135
  return {
110
136
  ...inv,
111
137
  items,
@@ -113,7 +139,7 @@ export function upgradeInventory(inv, { home, fsx = fs, binary = { path: null, v
113
139
  from: 'opencode-v1', to: 'opencode-v2',
114
140
  binary: { path: rel(binary.path), version: binary.version, via: installVia(binary.path) },
115
141
  layout: { configDir: rel(ocDir), dataDir: inv.opencode.dataDir, sessions: inv.opencode.sessions, major: inv.opencode.major },
116
- backup: null, // PR B: the permanent session backup
142
+ backup: stamp && { ...stamp, dir: rel(stamp.dir), frozen: rel(stamp.frozen) },
117
143
  counts, plan,
118
144
  },
119
145
  };
@@ -121,10 +147,85 @@ export function upgradeInventory(inv, { home, fsx = fs, binary = { path: null, v
121
147
 
122
148
  export function formatUpgrade(r) {
123
149
  const u = r.upgrade;
124
- const out = [`--upgrade-agent opencode (dry run: nothing is changed; apply is not in this release yet)`,
150
+ const out = [`--upgrade-agent opencode (dry run: nothing is changed; --yes applies once --backup --yes made a verified backup)`,
151
+ 'OpenCode 2 migrates your sessions the first time it starts: --backup --yes keeps a 1.x copy first, and --undo --yes goes back to it.',
125
152
  `OpenCode: ${u.binary.version ?? 'version unknown'} at ${u.binary.path ?? 'not on PATH'} (${u.binary.via ?? 'n/a'}), major ${u.layout.major ?? 'none'}, sessions ${u.layout.sessions ?? 'unknown'}`,
126
153
  `${u.counts.managed} managed, ${u.counts['user-translatable']} translatable, ${u.counts['user-manual']} manual`];
127
- for (const i of r.items.filter((x) => x.upgrade)) out.push(` ${i.upgrade.class.padEnd(16)} ${i.upgrade.before}${i.upgrade.after ? ` -> ${i.upgrade.after}` : ''}${i.upgrade.class === 'user-manual' ? ` (${i.upgrade.reason})` : ''}`);
154
+ for (const i of r.items.filter((x) => x.upgrade)) out.push(` ${i.upgrade.class.padEnd(16)} ${i.upgrade.before}${i.upgrade.after ? ` -> ${i.upgrade.after}` : ''}${i.upgrade.class === 'user-manual' ? ` (${i.upgrade.reason})` : ''}${i.file ? ` (${i.file})` : ''}`);
128
155
  out.push('Translation table:', ...TRANSLATIONS.map((t) => ` ${t.from} -> ${t.to} [${t.source}]`));
129
156
  return out.join('\n');
130
157
  }
158
+
159
+ // Edits that turn the 1.x config into 2.x keys, from `managed` and `user-translatable` rows only. Whole keys are set or removed
160
+ // (never single array slots), so each edit undoes exactly. `user-manual` keys and entries are left where they are.
161
+ // `inv.items` come from upgradeInventory; `cfg` is the parsed live config. A 2.x-shaped file (mcp.servers) yields no edits.
162
+ export function translateEdits(cfg, items) {
163
+ const edits = [];
164
+ const mine = items.filter((i) => i.upgrade && i.client === 'opencode' && i.kind !== 'file' && /opencode\.jsonc?$/.test(i.file ?? ''));
165
+ const cls = (kind, name) => mine.find((i) => i.kind === kind && i.name === name)?.upgrade.class;
166
+ const c = cfg && typeof cfg === 'object' ? cfg : {};
167
+ const set = (p, value) => edits.push({ path: p, value, mode: 'setIfAbsent' });
168
+ const drop = (p) => edits.push({ path: p, mode: 'remove' });
169
+
170
+ for (const [n, v] of Object.entries(c.agent ?? {})) if (cls('config', `agent.${n}`) === 'user-translatable') set(['agents', n], v);
171
+ // A 2.x value already there wins (setIfAbsent), so the 1.x source is dropped only when nothing of it would be lost.
172
+ if (c.agent && Object.entries(c.agent).every(([n, v]) => cls('config', `agent.${n}`) === 'user-translatable' && (c.agents?.[n] === undefined || JSON.stringify(c.agents[n]) === JSON.stringify(v)))) drop(['agent']);
173
+
174
+ // Managed MCPs are dropped here: the 2.x adapter writes them again under mcp.servers.
175
+ if (c.mcp && !c.mcp.servers) {
176
+ const servers = {};
177
+ for (const [n, v] of Object.entries(c.mcp)) if (cls('mcp', n) === 'user-translatable') servers[n] = v;
178
+ const left = Object.keys(c.mcp).filter((n) => !['user-translatable', 'managed'].includes(cls('mcp', n)));
179
+ if (!left.length) edits.push({ path: ['mcp'], value: { servers }, mode: 'set' });
180
+ }
181
+
182
+ if (Array.isArray(c.plugin)) {
183
+ const rest = [];
184
+ for (const spec of c.plugin) {
185
+ const k = typeof spec === 'string' ? cls('plugin', spec) : null;
186
+ if (k === 'user-translatable') edits.push({ path: ['plugins'], value: spec, mode: 'arrayAdd' });
187
+ else if (k !== 'managed') rest.push(spec);
188
+ }
189
+ if (rest.length !== c.plugin.length) edits.push(rest.length ? { path: ['plugin'], value: rest, mode: 'set' } : { path: ['plugin'], mode: 'remove' });
190
+ }
191
+
192
+ if (cls('config', 'compaction.reserved') === 'user-translatable' && c.compaction?.reserved !== undefined) {
193
+ set(['compaction', 'buffer'], c.compaction.reserved);
194
+ if (c.compaction.buffer === undefined) drop(['compaction', 'reserved']);
195
+ }
196
+ if (typeof c.autoupdate === 'boolean' && cls('config', 'autoupdate') === 'user-translatable') {
197
+ set(['update'], c.autoupdate ? 'auto' : 'disable');
198
+ if (c.update === undefined) drop(['autoupdate']);
199
+ }
200
+ if (Array.isArray(c.disabled_providers) && cls('config', 'disabled_providers') === 'user-translatable') {
201
+ for (const resource of c.disabled_providers) edits.push({ path: ['policies'], value: { effect: 'deny', action: 'provider.use', resource }, mode: 'arrayAdd' });
202
+ drop(['disabled_providers']);
203
+ }
204
+ return edits;
205
+ }
206
+
207
+ // Apply gate: a verified backup stamp. `stamp` is injectable; the default reader is the P3 stub (never verified until P3 merges).
208
+ export const backupVerified = (stamp) => Boolean(stamp && stamp.verified === true);
209
+
210
+ // Apply the translation to the live 2.x config dir. `adapter` is the v2 adapter plan ({ actions }); its config action is merged
211
+ // with the translation edits so the file is written once. Writes only under the XDG config home, never the 1.x data folder.
212
+ // Returns { planned, entries } (entries are the fsops state records an undo needs).
213
+ export function upgradeApply({ home, inv, adapter, backupDir, stamp = readBackupStamp(home), dryRun = false, fsx = fs, entries = [] }) {
214
+ if (!backupVerified(stamp)) throw new Error('refusing to apply: no verified session backup (run --upgrade-agent opencode --backup first)');
215
+ const ocDir = j(configHome(home), 'opencode');
216
+ const file = configPath(ocDir);
217
+ const cfg = readJson(file, fsx);
218
+ const errors = [];
219
+ if (fsx.existsSync(file)) parse(fsx.readFileSync(file, 'utf8'), errors, { allowTrailingComma: true });
220
+ if (errors.length) throw new Error(`refusing to apply: ${file} could not be parsed; fix it by hand first`);
221
+ const tr = translateEdits(cfg, inv.items);
222
+ const actions = adapter.actions.map((a) => (a.kind === 'json' && a.path === file ? { ...a, edits: [...tr, ...a.edits] } : a));
223
+ if (!actions.some((a) => a.path === file) && tr.length) actions.push({ kind: 'json', path: file, edits: tr });
224
+ const cfgHome = configHome(home);
225
+ const stray = actions.find((a) => !path.resolve(a.path).startsWith(path.resolve(cfgHome) + path.sep));
226
+ if (stray) throw new Error(`refusing to write outside ${cfgHome}: ${stray.path}`);
227
+ const planned = plan(actions, [cfgHome]);
228
+ if (dryRun) return { planned, entries: [], text: describe(planned, home) };
229
+ // `entries` is filled as files are written, so a caller that passes it still holds what an error midway wrote.
230
+ return { planned, entries: apply(planned, backupDir, home, [cfgHome], entries), text: describe(planned, home) };
231
+ }
@@ -0,0 +1,46 @@
1
+ // The verify prompt the user pastes into their agent after an install (#181). Text only: the engine never calls the network
2
+ // or `gh issue`; the agent does, and only after a per-issue yes. Strict or offline presets get no filing text at all.
3
+ import { feedbackAllowed } from './feedback.mjs';
4
+
5
+ const REPO = 'estebanmr99/lean-agents';
6
+ const DOCTOR = 'npx -y lean-agents@latest --doctor --json';
7
+ const DRAFT = 'npx -y lean-agents@latest --feedback-draft --feedback-kind verify --failed-command "<item>"';
8
+ const SUMMARY = 'npx -y lean-agents@latest --summary --filed-issue "<item>=<issue url>"';
9
+
10
+ const TEXT = {
11
+ en: {
12
+ head: 'Verify my lean-agents install. Ask before every change. Never read, print or store my keys or tokens.',
13
+ doctor: `Run \`${DOCTOR}\` and read the rows. Report every row whose status is not \`ok\`.`,
14
+ fix: 'For each problem, propose a fix that stays inside the install plan we agreed on. Ask me before each change. Stop when no fix fits the plan.',
15
+ copy: 'For each problem you could not fix, show me its doctor row (item, status, detail) as text I can copy myself. Do not send it anywhere.',
16
+ draft: `For each problem you could not fix, run \`${DRAFT}\` with the row's \`status: detail\` on stdin. It prints a redacted draft.`,
17
+ dupes: `Only after my yes, search open issues for a duplicate with the redacted draft title, never the raw item name: \`gh issue list --repo ${REPO} --state open --search "<draft title>"\`. If one matches, show me its link and skip it.`,
18
+ show: 'Show me the full redacted draft.',
19
+ ask: 'Ask me "File this issue? yes/no" for each draft separately. File nothing without my yes. One yes covers one issue only. On no, keep the draft as text I can copy.',
20
+ file: `Only after my yes, run \`gh issue create --repo ${REPO} --title "<title>" --body-file <draft file>\`, then delete the draft file.`,
21
+ link: `Write each issue link back with \`${SUMMARY}\`, then re-run \`npx -y lean-agents@latest --summary\`.`,
22
+ done: 'Finish with one line per problem: fixed, filed (link) or copied.',
23
+ },
24
+ es: {
25
+ head: 'Verifica mi instalación de lean-agents. Pregunta antes de cada cambio. Nunca leas, muestres ni guardes mis claves o tokens.',
26
+ doctor: `Ejecuta \`${DOCTOR}\` y lee las filas. Informa cada fila cuyo estado no sea \`ok\`.`,
27
+ fix: 'Para cada problema, propón una solución que quede dentro del plan de instalación acordado. Pregúntame antes de cada cambio. Detente cuando ninguna solución encaje en el plan.',
28
+ copy: 'Para cada problema que no pudiste resolver, muéstrame su fila de doctor (item, status, detail) como texto que yo mismo pueda copiar. No la envíes a ningún sitio.',
29
+ draft: `Para cada problema que no pudiste resolver, ejecuta \`${DRAFT}\` con el \`status: detail\` de la fila por stdin. Imprime un borrador redactado.`,
30
+ dupes: `Solo después de mi sí, busca un duplicado entre los issues abiertos con el título redactado del borrador, nunca el nombre sin redactar: \`gh issue list --repo ${REPO} --state open --search "<título del borrador>"\`. Si hay uno, muéstrame su enlace y sáltalo.`,
31
+ show: 'Muéstrame el borrador redactado completo.',
32
+ ask: 'Pregúntame "¿Crear este issue? sí/no" por cada borrador, por separado. No crees nada sin mi sí. Un sí cubre un solo issue. Si digo no, deja el borrador como texto que yo pueda copiar.',
33
+ file: `Solo después de mi sí, ejecuta \`gh issue create --repo ${REPO} --title "<título>" --body-file <archivo del borrador>\` y borra el archivo del borrador.`,
34
+ link: `Guarda cada enlace con \`${SUMMARY}\` y vuelve a ejecutar \`npx -y lean-agents@latest --summary\`.`,
35
+ done: 'Termina con una línea por problema: resuelto, creado (enlace) o copiado.',
36
+ },
37
+ };
38
+
39
+ // `network` is the saved or chosen preset; without outbound on, the prompt has no filing steps.
40
+ export function verifyPrompt({ lang = 'en', network } = {}) {
41
+ const t = TEXT[lang] ?? TEXT.en;
42
+ const steps = feedbackAllowed(network)
43
+ ? [t.doctor, t.fix, t.draft, t.show, t.ask, t.dupes, t.file, t.link, t.done]
44
+ : [t.doctor, t.fix, t.copy, t.done];
45
+ return [t.head, ...steps.map((s, i) => `${i + 1}. ${s}`)].join('\n');
46
+ }
@@ -1,18 +1,41 @@
1
1
  #!/usr/bin/env node
2
2
  // Rewrites core/pins.json in the current checkout to the newest upstream versions, so the daily CI run tests `latest`.
3
3
  // Only the runner's copy changes; nothing is committed. Pins never move backwards. Deliberately no 14-day quarantine: the point is to see a brand-new release break before anyone bumps to it.
4
+ import crypto from 'node:crypto';
4
5
  import fs from 'node:fs';
5
6
  import { fileURLToPath, pathToFileURL } from 'node:url';
6
7
  import { isNewer, latestVersion, tagSha } from './version-watch.mjs';
7
8
 
8
9
  const FILE = fileURLToPath(new URL('../core/pins.json', import.meta.url));
9
10
 
10
- // Returns the pins that moved as [{ key, from, to }] and edits `pins` in place.
11
- export async function bump(pins, get) {
11
+ export async function hashUrl(url) {
12
+ const r = await fetch(url);
13
+ if (!r.ok) throw new Error(`${url}: ${r.status}`);
14
+ return crypto.createHash('sha256').update(Buffer.from(await r.arrayBuffer())).digest('hex');
15
+ }
16
+
17
+ // An installer script at a fixed URL changes without a version number: its sha256 is the version (#245).
18
+ // Returns { key, from, to } when the hash moved and edits `p` in place; null when it did not.
19
+ export async function rehash(key, p, hash) {
20
+ const s = await hash(p.url);
21
+ if (s === p.sha256) return null;
22
+ const m = { key, from: `sha256 ${p.sha256.slice(0, 12)}`, to: `sha256 ${s.slice(0, 12)}` };
23
+ p.sha256 = s;
24
+ return m;
25
+ }
26
+
27
+ // Returns the pins that moved as [{ key, from, to }] and edits `pins` in place. `hash` (url -> sha256) re-hashes
28
+ // the `version: "script"` installer pins; without it they are skipped like the other download pins.
29
+ export async function bump(pins, get, hash) {
12
30
  const moved = [];
13
31
  for (const [key, p] of Object.entries(pins)) {
14
32
  let next = null;
15
- if (p.kind === 'download') continue; // Bun: the sha256 map is copied by hand from SHASUMS256.txt
33
+ if (p.version === 'script' && hash) {
34
+ try { const m = await rehash(key, p, hash); if (m) moved.push(m); } catch (e) { console.log(`! ${key}: ${e.message}`); }
35
+ continue;
36
+ }
37
+ if (p.kind === 'download' || p.sha256) continue; // a sha256 map (Bun, RTK's Linux tarball) only fits its own version (tool and cask pins move in the runner copy too, so the nightly shows the newest rtk/uv/gh/Antigravity)
38
+ // Bun: the sha256 map is copied by hand from SHASUMS256.txt
16
39
  try {
17
40
  next = await latestVersion(p, get);
18
41
  if (next && isNewer(p.version, next)) {
@@ -35,7 +58,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
35
58
  return r.json();
36
59
  };
37
60
  const file = JSON.parse(fs.readFileSync(FILE, 'utf8'));
38
- const moved = await bump(file.pins, get);
61
+ const moved = await bump(file.pins, get, hashUrl);
39
62
  fs.writeFileSync(FILE, `${JSON.stringify(file, null, 2)}\n`);
40
63
  const lines = moved.length ? moved.map((m) => `- ${m.key}: ${m.from} -> ${m.to}`) : ['- no pin has a newer version'];
41
64
  console.log(lines.join('\n'));
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import crypto from 'node:crypto';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { diffPins, toolVersionsTable } from './lib/pins-diff.mjs';
8
9
 
9
10
  const ROOT = fileURLToPath(new URL('..', import.meta.url));
10
11
 
@@ -17,6 +18,28 @@ export function releaseNotes(changelog, version) {
17
18
  return rest.slice(0, end < 0 ? undefined : end).join('\n').trim();
18
19
  }
19
20
 
21
+ const nums = (v) => v.replace(/^v/, '').split('-')[0].split('.').map(Number);
22
+
23
+ // Highest `v<x.y.z>` tag below `version`, or null (first release, or a shallow clone without tags).
24
+ export function previousTag(tags, version) {
25
+ const cmp = (a, b) => { const x = nums(a), y = nums(b); return (x[0] - y[0]) || (x[1] - y[1]) || (x[2] - y[2]); };
26
+ return tags.filter((t) => /^v\d+\.\d+\.\d+$/.test(t) && cmp(t, version) < 0).sort(cmp).pop() ?? null;
27
+ }
28
+
29
+ // "Tool versions" section from the pins at the previous tag; '' when there is no earlier pins file or nothing changed.
30
+ export function toolVersionsSection(prevPins, nextPins) {
31
+ const table = toolVersionsTable(diffPins(prevPins, nextPins));
32
+ return table ? `## Tool versions\n\n${table}` : '';
33
+ }
34
+
35
+ function pinsAtPreviousTag(version) {
36
+ const git = (args) => execFileSync('git', args, { cwd: ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
37
+ try {
38
+ const tag = previousTag(git(['tag', '--list', 'v*']).split('\n'), version);
39
+ return tag ? JSON.parse(git(['show', `${tag}:core/pins.json`])) : null;
40
+ } catch { return null; } // a tag from before core/pins.json existed, or no git: the notes just skip the table
41
+ }
42
+
20
43
  // Needs `npm ci --omit=dev` first: the tarball bundles node_modules.
21
44
  export function packDist(dist, version) {
22
45
  const name = `lean-agents-${version}`;
@@ -36,7 +59,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
36
59
  if (!notes) throw new Error(`CHANGELOG.md has no notes for ${version}`);
37
60
  const dist = path.join(ROOT, 'dist');
38
61
  fs.mkdirSync(dist, { recursive: true });
39
- fs.writeFileSync(path.join(dist, 'notes.md'), `${notes}\n`);
62
+ const nextPins = JSON.parse(fs.readFileSync(path.join(ROOT, 'core', 'pins.json'), 'utf8'));
63
+ const versions = toolVersionsSection(pinsAtPreviousTag(version), nextPins);
64
+ fs.writeFileSync(path.join(dist, 'notes.md'), `${[notes, versions].filter(Boolean).join('\n\n')}\n`);
40
65
  const name = `lean-agents-${version}`;
41
66
  for (const ext of ['tar.gz', 'zip']) {
42
67
  execFileSync('git', ['archive', '--format', ext, '--prefix', `${name}/`, '-o', path.join(dist, `${name}.${ext}`), 'HEAD'], { cwd: ROOT });
@@ -19,7 +19,9 @@ export function isNewer(current, next) {
19
19
  }
20
20
 
21
21
  export function notesUrl(p, version) {
22
- return p.kind === 'npm' ? `https://www.npmjs.com/package/${p.source}/v/${version}` : `https://github.com/${p.source}/releases/tag/${version}`;
22
+ if (p.kind === 'npm') return `https://www.npmjs.com/package/${p.source}/v/${version}`;
23
+ if (p.kind === 'cask') return `https://formulae.brew.sh/cask/${p.source}`;
24
+ return `https://github.com/${p.source}/releases/tag/${p.tagPrefix ?? ''}${version}`;
23
25
  }
24
26
 
25
27
  function render(key, p, version) {
@@ -55,8 +57,12 @@ export function plan(pins, latest, issues) {
55
57
 
56
58
  export async function latestVersion(p, get) {
57
59
  if (p.kind === 'npm') return (await get(`https://registry.npmjs.org/${p.source.replace('/', '%2F')}/latest`)).version;
60
+ // Homebrew cask (Antigravity): its version is "1.5.11,<build>"; only the part before the comma is the release.
61
+ if (p.kind === 'cask') return (await get(`https://formulae.brew.sh/api/cask/${p.source}.json`)).version.split(',')[0];
58
62
  // shortcut: first 100 tags only, enough for repos that tag per release; page if a repo outgrows that.
59
- const tags = (await get(`https://api.github.com/repos/${p.source}/tags?per_page=100`)).map((t) => t.name).filter((n) => STABLE.test(n));
63
+ // tagPrefix: Bun tags `bun-v1.4.4`; the prefix is dropped so versions compare as x.y.z.
64
+ const pre = p.tagPrefix ?? '';
65
+ const tags = (await get(`https://api.github.com/repos/${p.source}/tags?per_page=100`)).map((t) => t.name).filter((n) => n.startsWith(pre)).map((n) => n.slice(pre.length)).filter((n) => STABLE.test(n));
60
66
  return tags.reduce((best, n) => (!best || isNewer(best, n) ? n : best), null);
61
67
  }
62
68