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.
Files changed (148) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/LICENSE +21 -0
  3. package/README.es.md +560 -0
  4. package/README.md +559 -2
  5. package/core/AGENTS.es.md +60 -0
  6. package/core/AGENTS.md +60 -0
  7. package/core/README.md +8 -0
  8. package/core/agents/debug.md +14 -0
  9. package/core/agents/explore.md +13 -0
  10. package/core/agents/planner.md +14 -0
  11. package/core/agents/research.md +13 -0
  12. package/core/agents/review.md +13 -0
  13. package/core/copilot-usage-tui.js +189 -0
  14. package/core/mcp.json +38 -0
  15. package/core/pins.json +39 -0
  16. package/core/tiers.json +4 -0
  17. package/node_modules/@clack/core/LICENSE +9 -0
  18. package/node_modules/@clack/core/README.md +22 -0
  19. package/node_modules/@clack/core/dist/index.d.mts +503 -0
  20. package/node_modules/@clack/core/dist/index.mjs +1003 -0
  21. package/node_modules/@clack/core/package.json +63 -0
  22. package/node_modules/@clack/prompts/LICENSE +9 -0
  23. package/node_modules/@clack/prompts/README.md +396 -0
  24. package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
  25. package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
  26. package/node_modules/@clack/prompts/package.json +67 -0
  27. package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
  28. package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
  29. package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
  30. package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
  31. package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
  32. package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
  33. package/node_modules/fast-string-truncated-width/license +21 -0
  34. package/node_modules/fast-string-truncated-width/package.json +35 -0
  35. package/node_modules/fast-string-truncated-width/readme.md +59 -0
  36. package/node_modules/fast-string-width/dist/index.d.ts +4 -0
  37. package/node_modules/fast-string-width/dist/index.js +14 -0
  38. package/node_modules/fast-string-width/license +21 -0
  39. package/node_modules/fast-string-width/package.json +34 -0
  40. package/node_modules/fast-string-width/readme.md +42 -0
  41. package/node_modules/fast-wrap-ansi/LICENSE +23 -0
  42. package/node_modules/fast-wrap-ansi/README.md +26 -0
  43. package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
  44. package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
  45. package/node_modules/fast-wrap-ansi/package.json +51 -0
  46. package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
  47. package/node_modules/jsonc-parser/LICENSE.md +21 -0
  48. package/node_modules/jsonc-parser/README.md +364 -0
  49. package/node_modules/jsonc-parser/SECURITY.md +41 -0
  50. package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
  51. package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
  52. package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
  53. package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
  54. package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
  55. package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
  56. package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
  57. package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
  58. package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
  59. package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
  60. package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
  61. package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
  62. package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
  63. package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
  64. package/node_modules/jsonc-parser/package.json +37 -0
  65. package/node_modules/sisteransi/license +21 -0
  66. package/node_modules/sisteransi/package.json +34 -0
  67. package/node_modules/sisteransi/readme.md +113 -0
  68. package/node_modules/sisteransi/src/index.js +58 -0
  69. package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
  70. package/package.json +30 -4
  71. package/profiles/README.md +10 -0
  72. package/profiles/anthropic-api/gsd-defaults.json +26 -0
  73. package/profiles/anthropic-api.json +18 -0
  74. package/profiles/antigravity.json +12 -0
  75. package/profiles/claude-subscription/gsd-defaults.json +26 -0
  76. package/profiles/claude-subscription.json +17 -0
  77. package/profiles/github-copilot/gsd-defaults.json +26 -0
  78. package/profiles/github-copilot.json +17 -0
  79. package/profiles/openai-api/gsd-defaults.json +26 -0
  80. package/profiles/openai-api.json +17 -0
  81. package/profiles/opencode-go/gsd-defaults.json +26 -0
  82. package/profiles/opencode-go.json +17 -0
  83. package/profiles/vertex-gemini/gsd-defaults.json +26 -0
  84. package/profiles/vertex-gemini.json +18 -0
  85. package/scripts/adhd-skill.mjs +12 -0
  86. package/scripts/behavior-diff.sh +47 -0
  87. package/scripts/bump-pins.mjs +115 -0
  88. package/scripts/check-private.sh +52 -0
  89. package/scripts/check-readme.mjs +131 -0
  90. package/scripts/ci-download.sh +20 -0
  91. package/scripts/ci-install-opencode-v2.sh +6 -0
  92. package/scripts/ci-latest-report.mjs +38 -0
  93. package/scripts/ci-timing.mjs +61 -0
  94. package/scripts/copilot-context-mode.mjs +33 -0
  95. package/scripts/labels.sh +56 -0
  96. package/scripts/lean.mjs +1319 -0
  97. package/scripts/lib/adapters/antigravity.mjs +83 -0
  98. package/scripts/lib/adapters/claude.mjs +127 -0
  99. package/scripts/lib/adapters/copilot-cli.mjs +82 -0
  100. package/scripts/lib/adapters/cursor.mjs +60 -0
  101. package/scripts/lib/adapters/opencode-v1.mjs +79 -0
  102. package/scripts/lib/adapters/opencode-v2.mjs +216 -0
  103. package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
  104. package/scripts/lib/adhd.mjs +28 -0
  105. package/scripts/lib/adopt.mjs +619 -0
  106. package/scripts/lib/agent-lifecycle.mjs +280 -0
  107. package/scripts/lib/backup-stamp.mjs +25 -0
  108. package/scripts/lib/copilot-usage.mjs +49 -0
  109. package/scripts/lib/doctor.mjs +279 -0
  110. package/scripts/lib/feedback.mjs +48 -0
  111. package/scripts/lib/fsops.mjs +319 -0
  112. package/scripts/lib/gsd.mjs +42 -0
  113. package/scripts/lib/inventory.mjs +196 -0
  114. package/scripts/lib/lean-update.mjs +30 -0
  115. package/scripts/lib/logins.mjs +28 -0
  116. package/scripts/lib/migrate.mjs +407 -0
  117. package/scripts/lib/network.mjs +119 -0
  118. package/scripts/lib/node-runtime.mjs +85 -0
  119. package/scripts/lib/opencode-backup.mjs +204 -0
  120. package/scripts/lib/opencode-upgrade.mjs +441 -0
  121. package/scripts/lib/opencode1.mjs +203 -0
  122. package/scripts/lib/parallel.mjs +270 -0
  123. package/scripts/lib/pins-diff.mjs +33 -0
  124. package/scripts/lib/pins.mjs +52 -0
  125. package/scripts/lib/plugin-health.mjs +191 -0
  126. package/scripts/lib/prereqs.mjs +203 -0
  127. package/scripts/lib/project.mjs +38 -0
  128. package/scripts/lib/redact.mjs +30 -0
  129. package/scripts/lib/render.mjs +101 -0
  130. package/scripts/lib/shell-path.mjs +22 -0
  131. package/scripts/lib/summary-data.mjs +30 -0
  132. package/scripts/lib/summary-html.mjs +159 -0
  133. package/scripts/lib/system.mjs +269 -0
  134. package/scripts/lib/terminals.mjs +316 -0
  135. package/scripts/lib/ui.mjs +34 -0
  136. package/scripts/lib/unverified.mjs +49 -0
  137. package/scripts/lib/update-plan.mjs +60 -0
  138. package/scripts/lib/upgrade.mjs +231 -0
  139. package/scripts/lib/verify-commit.mjs +16 -0
  140. package/scripts/lib/verify-prompt.mjs +46 -0
  141. package/scripts/lib/verify-sha256.mjs +20 -0
  142. package/scripts/lint-workflows.mjs +25 -0
  143. package/scripts/models-refresh.mjs +58 -0
  144. package/scripts/parallel.mjs +59 -0
  145. package/scripts/pins-latest.mjs +66 -0
  146. package/scripts/release.mjs +71 -0
  147. package/scripts/verify-pins.mjs +36 -0
  148. package/scripts/version-watch.mjs +124 -0
@@ -0,0 +1,231 @@
1
+ // --upgrade-agent opencode (#80 PR A): the --adopt inventory plus, per OpenCode 1.x item, what a move to 2.x would do with it.
2
+ // Read-only: only key names are printed, never env or header values. `home`, `fsx` and `binary` are passed in so tests never read the real machine.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { parse } from 'jsonc-parser';
6
+ import { hasMark, plan, apply, describe } from './fsops.mjs';
7
+ import { configHome } from './system.mjs';
8
+ import { configPath } from './adapters/opencode-v2.mjs';
9
+ import { readBackupStamp } from './backup-stamp.mjs';
10
+
11
+ const j = path.join;
12
+
13
+ // The translation table. `verified: false` rows are VERIFY (docs/compatibility.md): their items stay user-manual until proven.
14
+ export const TRANSLATIONS = [
15
+ { key: 'agent', from: 'agent.<name>', to: 'agents.<name>', source: 'SPEC 0, real 2.2.5', verified: true },
16
+ { key: 'plugin', from: 'plugin[] (npm spec)', to: 'plugins[]', source: 'SPEC 0, tests/real-opencode.sh', verified: true },
17
+ { key: 'mcp', from: 'mcp.<name>', to: 'mcp.servers.<name>', source: 'SPEC 0, real 2.2.5 (tests/real-opencode.sh)', verified: true },
18
+ { key: 'compaction.auto', from: 'compaction.auto', to: 'compaction.auto', source: 'SPEC 0', verified: true },
19
+ { key: 'compaction.reserved', from: 'compaction.reserved', to: 'compaction.buffer', source: 'SPEC 0', verified: true },
20
+ { key: 'autoupdate', from: 'autoupdate: false', to: 'update: "disable"', source: 'opencode.ai/docs/migrate-v1, 2026-11-12 (docs only)', verified: true },
21
+ { key: 'autoupdate-true', from: 'autoupdate: true', to: 'update: "auto"', source: 'opencode.ai/docs/migrate-v1, 2026-11-12 (docs only)', verified: true },
22
+ { key: 'disabled_providers', from: 'disabled_providers[]', to: 'policies: deny provider.use', source: 'real 2.1.4 accepts `policies` (tests/real-opencode.sh)', verified: true },
23
+ ...['instructions', 'default_agent', 'model', 'share', 'shell'].map((k) => ({ key: k, from: k, to: k, source: 'real 2.2.5, #124b', verified: true })),
24
+ { key: 'tui-plugin', from: 'tui.json(c) plugin[] (file://)', to: 'cli.json plugins[]', source: 'VERIFY: opencode.ai/docs/plugins says cli.json `plugins`, tui docs still say tui.json; no binary proof', verified: false },
25
+ { key: 'keybinds', from: 'keybinds', to: '?', source: 'VERIFY: docs name no 2.x file for keybinds (tui.json vs cli.json)', verified: false },
26
+ { key: 'dir', from: 'agent/ agents/ command/ commands/ folders', to: 'same folders', source: 'opencode.ai/docs/migrate-v1, 2026-11-12 (docs only)', verified: true },
27
+ { key: 'skills', from: '~/.config/opencode/skills, ~/.agents/skills, ~/.claude/skills', to: 'same folders', source: 'opencode.ai/docs/skills, 2026-11-12 (docs only)', verified: true },
28
+ ];
29
+ const row = (key) => TRANSLATIONS.find((t) => t.key === key);
30
+
31
+ // Keys with no verified 2.x equivalent, and so no row.
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
+ };
38
+ const SAME = new Set(['instructions', 'default_agent', 'model', 'share', 'shell']);
39
+ const HANDLED = new Set(['$schema', 'mcp', 'plugin']); // mcp and plugin come from the adopt items
40
+
41
+ const readJson = (file, fsx) => { try { return parse(fsx.readFileSync(file, 'utf8'), [], { allowTrailingComma: true }) ?? null; } catch { return null; } };
42
+
43
+ const translate = (t, name, before = t.from.replace('<name>', name)) => ({ class: 'user-translatable', before, after: t.to.replace('<name>', name), reason: 'row in the translation table', source: t.source });
44
+ const verifyRow = (t, before) => ({ class: 'user-manual', before, after: null, reason: `${t.source}: no proven 2.x equivalent`, source: t.source });
45
+ const manual = (before, reason) => ({ class: 'user-manual', before, after: null, reason, source: null });
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' });
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
+
63
+ // Classify one adopt item of the OpenCode 1.x config (mcp, plugin, plugins/ file) or a skill.
64
+ function classifyItem(it, stopgaps, home, fsx) {
65
+ if (it.owner === 'managed') return managed(`${it.kind} ${it.name}`, it.kind === 'plugin' ? 'plugins[]' : it.kind === 'mcp' ? `mcp.servers.${it.name}` : it.file);
66
+ if (it.kind === 'mcp') return translate(row('mcp'), it.name);
67
+ if (it.kind === 'skill') { const t = row('skills'); return t.verified ? translate(t, it.name, `skill ${it.name}`) : verifyRow(t, `skill ${it.name}`); }
68
+ if (it.kind === 'plugin' && it.keyPath.length) {
69
+ const tui = /tui\.jsonc?$/.test(it.file);
70
+ const t = row(tui ? 'tui-plugin' : 'plugin');
71
+ if (!t.verified) return verifyRow(t, `${tui ? 'tui.json ' : ''}plugin ${it.name}`);
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
+
78
+ return translate(t, it.name, `plugin ${it.name}`);
79
+ }
80
+ const sg = stopgaps.find((s) => s.file === it.file);
81
+ if (sg) return manual(`plugin ${it.name}`, `leftover stopgap: replace with ${sg.replaceWith}`);
82
+ return manual(`plugin ${it.name}`, localPluginReason(pluginSource(it, home, fsx)));
83
+ }
84
+
85
+ // Top-level keys of the 1.x config and the files in its agent/command folders, as new items (key names only).
86
+ function configItems(home, ocDir, fsx, rel) {
87
+ const out = [];
88
+ const file = configPath(ocDir);
89
+ const mk = (kind, name, f, keyPath, owner, upgrade) => out.push({ client: 'opencode', kind, name, file: rel(f), keyPath, launch: null, owner, status: [], pin: null, wanted: null, action: 'keep', upgrade });
90
+ const cfg = readJson(file, fsx);
91
+ for (const [k, v] of Object.entries(cfg && typeof cfg === 'object' ? cfg : {})) {
92
+ if (HANDLED.has(k)) continue;
93
+ const at = (name, u) => mk('config', name, file, [k], 'user', u);
94
+ if (k === 'agent') for (const n of Object.keys(v ?? {})) at(`agent.${n}`, translate(row('agent'), n));
95
+ else if (k === 'compaction') for (const s of Object.keys(v ?? {})) at(`compaction.${s}`, ['auto', 'reserved'].includes(s) ? translate(row(`compaction.${s}`), s) : manual(`compaction.${s}`, 'no verified 2.x key'));
96
+ else if (k === 'autoupdate') at(k, typeof v === 'boolean' ? translate(row(v ? 'autoupdate-true' : 'autoupdate'), k) : manual(k, 'no verified 2.x value (autoupdate "notify" is not in the table)'));
97
+ else if (k === 'disabled_providers') at(k, translate(row(k), k));
98
+ else if (SAME.has(k)) at(k, translate(row(k), k));
99
+ else if (k === 'keybinds') at(k, verifyRow(row(k), k));
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')));
101
+ }
102
+ for (const d of ['agent', 'agents', 'command', 'commands']) {
103
+ let list = [];
104
+ try { list = fsx.readdirSync(j(ocDir, d), { withFileTypes: true }).filter((e) => e.isFile()); } catch { continue; }
105
+ for (const e of list) {
106
+ const f = j(ocDir, d, e.name);
107
+ let owned = false;
108
+ try { owned = hasMark(fsx.readFileSync(f, 'utf8')); } catch { /* unreadable: user */ }
109
+ mk('file', `${d}/${e.name}`, f, [], owned ? 'managed' : 'user', owned ? managed(`${d}/${e.name}`, 'rewritten by the 2.x adapter') : row('dir').verified ? { ...translate(row('dir'), d), before: `${d}/${e.name}`, after: `${d}/${e.name}` } : verifyRow(row('dir'), `${d}/${e.name}`));
110
+ }
111
+ }
112
+ return out;
113
+ }
114
+
115
+ // Where the `opencode` binary came from, by its path. Unknown paths stay unknown.
116
+ export const installVia = (p) => (!p ? null : /node_modules|[\\/]\.nvm[\\/]|[\\/]npm[\\/]/.test(p) ? 'npm' : /[\\/]\.opencode[\\/]bin/.test(p) ? 'script' : /homebrew|Cellar|linuxbrew/i.test(p) ? 'brew' : /scoop/i.test(p) ? 'scoop' : 'unknown');
117
+
118
+ export function upgradeInventory(inv, { home, fsx = fs, binary = { path: null, version: null } }) {
119
+ const rel = (p) => (p && p.startsWith(home) ? `~${p.slice(home.length)}` : p);
120
+ const ocDir = j(configHome(home), 'opencode');
121
+ const items = inv.items.map((it) => {
122
+ if (!(it.client === 'opencode' || it.kind === 'skill')) return it;
123
+ return { ...it, upgrade: classifyItem(it, inv.stopgaps, home, fsx) };
124
+ });
125
+ items.push(...configItems(home, ocDir, fsx, rel));
126
+ const mine = items.filter((i) => i.upgrade);
127
+ const counts = { managed: 0, 'user-translatable': 0, 'user-manual': 0 };
128
+ for (const i of mine) counts[i.upgrade.class]++;
129
+ const plan = [
130
+ ...(counts.managed ? [`reinstall ${counts.managed} managed items through the 2.x adapter`] : []),
131
+ ...mine.filter((i) => i.upgrade.class === 'user-translatable').map((i) => `translate ${i.upgrade.before} -> ${i.upgrade.after}`),
132
+ ...mine.filter((i) => i.upgrade.class === 'user-manual').map((i) => `manual ${i.upgrade.before}: ${i.upgrade.reason}`),
133
+ ];
134
+ const stamp = readBackupStamp(home, fsx); // shown as ~ like the other paths: reports get pasted into issues
135
+ return {
136
+ ...inv,
137
+ items,
138
+ upgrade: {
139
+ from: 'opencode-v1', to: 'opencode-v2',
140
+ binary: { path: rel(binary.path), version: binary.version, via: installVia(binary.path) },
141
+ layout: { configDir: rel(ocDir), dataDir: inv.opencode.dataDir, sessions: inv.opencode.sessions, major: inv.opencode.major },
142
+ backup: stamp && { ...stamp, dir: rel(stamp.dir), frozen: rel(stamp.frozen) },
143
+ counts, plan,
144
+ },
145
+ };
146
+ }
147
+
148
+ export function formatUpgrade(r) {
149
+ const u = r.upgrade;
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.',
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'}`,
153
+ `${u.counts.managed} managed, ${u.counts['user-translatable']} translatable, ${u.counts['user-manual']} manual`];
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})` : ''}`);
155
+ out.push('Translation table:', ...TRANSLATIONS.map((t) => ` ${t.from} -> ${t.to} [${t.source}]`));
156
+ return out.join('\n');
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,16 @@
1
+ // Refuses a git checkout whose HEAD is not the pinned commit: `node verify-commit.mjs <dir> <sha>`.
2
+ // A moved tag removes the checkout and exits 1. A script file, not `node -e`, so no shell can split its arguments.
3
+ import fs from 'node:fs';
4
+ import { execFileSync } from 'node:child_process';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
8
+ const [dir, want] = process.argv.slice(2);
9
+ const got = execFileSync('git', ['-C', dir, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();
10
+ if (got !== want) {
11
+ fs.rmSync(dir, { recursive: true, force: true });
12
+ console.error(`${dir}: tag moved, HEAD is ${got}, pinned ${want}. The checkout was removed.`);
13
+ process.exit(1);
14
+ }
15
+ console.log(`commit ok: ${dir}`);
16
+ }
@@ -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
+ }
@@ -0,0 +1,20 @@
1
+ // Refuses a download whose SHA256 differs from the pinned one: `node verify-sha256.mjs <file> <hex>`.
2
+ // A mismatch deletes the file and exits 1, so the install command chain stops before extracting it.
3
+ import fs from 'node:fs';
4
+ import crypto from 'node:crypto';
5
+ import { pathToFileURL } from 'node:url';
6
+
7
+ export function sha256(file) {
8
+ return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
9
+ }
10
+
11
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
12
+ const [file, want] = process.argv.slice(2);
13
+ const got = sha256(file);
14
+ if (got !== want.toLowerCase()) {
15
+ fs.rmSync(file, { force: true });
16
+ console.error(`SHA256 mismatch for ${file}: got ${got}, pinned ${want}. Nothing was installed.`);
17
+ process.exit(1);
18
+ }
19
+ console.log(`SHA256 ok: ${file}`);
20
+ }
@@ -0,0 +1,25 @@
1
+ // Fails on a download piped straight into a shell in a workflow or composite action (#75):
2
+ // `curl ... | bash`, `wget ... | sh`, `irm ... | iex`. Download to a file, check its SHA256, then run it (scripts/ci-download.sh).
3
+ // node scripts/lint-workflows.mjs [files...] (default: .github/workflows and .github/actions)
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { pathToFileURL } from 'node:url';
7
+
8
+ const PIPE = /\b(curl|wget|irm|iwr|Invoke-RestMethod|Invoke-WebRequest)\b[^\n]*\|\s*(sudo\s+)?(bash|sh|zsh|iex|Invoke-Expression)\b/i;
9
+
10
+ export function findPipes(text) {
11
+ return text.split('\n').map((l, i) => [i + 1, l]).filter(([, l]) => !l.trim().startsWith('#') && PIPE.test(l)).map(([n, l]) => `${n}: ${l.trim()}`);
12
+ }
13
+
14
+ function listFiles(dir) {
15
+ if (!fs.existsSync(dir)) return [];
16
+ return fs.readdirSync(dir, { withFileTypes: true, recursive: true }).filter((e) => e.isFile() && /\.ya?ml$/.test(e.name)).map((e) => path.join(e.parentPath, e.name));
17
+ }
18
+
19
+ if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
20
+ const files = process.argv.length > 2 ? process.argv.slice(2) : [...listFiles('.github/workflows'), ...listFiles('.github/actions')];
21
+ let bad = 0;
22
+ for (const f of files) for (const hit of findPipes(fs.readFileSync(f, 'utf8'))) { console.log(`::error file=${f}::download piped into a shell, line ${hit}`); bad++; }
23
+ console.log(bad ? `${bad} piped download(s)` : 'no piped downloads');
24
+ process.exit(bad ? 1 : 0);
25
+ }
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ // Compares the model IDs in profiles/ with the public models.dev catalog.
3
+ // Prints a Markdown report. --check exits 1 when a profile uses an ID the catalog lacks.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const ROOT = fileURLToPath(new URL('..', import.meta.url));
9
+ const CATALOG = 'https://models.dev/api.json';
10
+
11
+ // Unknown outputs on either side count as the same, so a catalog gap never hides an upgrade.
12
+ const outputs = (m) => (m.modalities?.output ? JSON.stringify([...m.modalities.output].sort()) : null);
13
+ const sameOutputs = (a, b) => !outputs(a) || !outputs(b) || outputs(a) === outputs(b);
14
+
15
+ // profiles: [{ name, tiers }]. IDs without a provider prefix are aliases and are skipped.
16
+ export function diffModels(profiles, catalog) {
17
+ const missing = [];
18
+ const newer = [];
19
+ for (const { name, tiers } of profiles) {
20
+ const used = new Set(Object.values(tiers).map((t) => t.model));
21
+ for (const { model } of Object.values(tiers)) {
22
+ if (!model.includes('/')) continue;
23
+ const [provider, id] = model.split(/\/(.*)/);
24
+ const models = catalog[provider]?.models ?? {};
25
+ const current = models[id];
26
+ if (!current) {
27
+ missing.push({ profile: name, model });
28
+ continue;
29
+ }
30
+ const latest = Object.values(models)
31
+ // A model the profile already uses, or one with other outputs (an image model in a text family), is not an upgrade.
32
+ .filter((m) => m.family === current.family && m.release_date > current.release_date)
33
+ .filter((m) => !used.has(`${provider}/${m.id}`) && sameOutputs(m, current))
34
+ .sort((a, b) => b.release_date.localeCompare(a.release_date))[0];
35
+ if (latest) newer.push({ profile: name, model, latest: `${provider}/${latest.id}` });
36
+ }
37
+ }
38
+ return { missing, newer };
39
+ }
40
+
41
+ function report({ missing, newer }) {
42
+ const lines = ['## Model IDs not in models.dev', ''];
43
+ lines.push(...(missing.length ? missing.map((m) => `- \`${m.profile}\`: \`${m.model}\``) : ['None.']));
44
+ lines.push('', '## Newer models in the same family', '');
45
+ lines.push(...(newer.length ? newer.map((m) => `- \`${m.profile}\`: \`${m.model}\`, newer: \`${m.latest}\``) : ['None.']));
46
+ lines.push('', `Source: ${CATALOG}. Check price and training terms before changing a profile.`);
47
+ return lines.join('\n');
48
+ }
49
+
50
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
51
+ const dir = path.join(ROOT, 'profiles');
52
+ const profiles = fs.readdirSync(dir).filter((f) => f.endsWith('.json')).map((f) => JSON.parse(fs.readFileSync(path.join(dir, f), 'utf8')));
53
+ const res = await fetch(CATALOG);
54
+ if (!res.ok) throw new Error(`${CATALOG}: HTTP ${res.status}`);
55
+ const diff = diffModels(profiles, await res.json());
56
+ console.log(report(diff));
57
+ if (process.argv.includes('--check') && diff.missing.length) process.exitCode = 1;
58
+ }
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ // Parallel agent sessions helper: start <task.md>…, status, merge <task> --yes, clean.
3
+ // Run it inside the repo whose work you want to split (or pass --repo <dir>).
4
+ import { start, status, merge, clean } from './lib/parallel.mjs';
5
+
6
+ const VALUE_FLAGS = ['repo', 'base', 'agent', 'tier', 'profile', 'model', 'cmd'];
7
+
8
+ function parse(argv) {
9
+ const opts = {};
10
+ const rest = [];
11
+ for (let i = 0; i < argv.length; i++) {
12
+ const m = argv[i].match(/^--(\w+)$/);
13
+ if (!m) rest.push(argv[i]);
14
+ else if (VALUE_FLAGS.includes(m[1])) opts[m[1]] = argv[++i];
15
+ else opts[m[1]] = true;
16
+ }
17
+ return { opts, rest };
18
+ }
19
+
20
+ const USAGE = `usage: parallel.mjs <command> [options]
21
+ start <task.md>… [--agent auto|orca|claude|opencode|print|custom] [--tier cheap|balanced|strong]
22
+ [--profile <name>] [--model <id>] [--base <branch>] [--cmd <program>]
23
+ status
24
+ merge <task> --yes merge one finished worker (start order), rebase the rest
25
+ clean remove merged worktrees and branches
26
+ --repo <dir> repository to work in (default: current directory)`;
27
+
28
+ const { opts, rest } = parse(process.argv.slice(2));
29
+ const [cmd, ...args] = rest;
30
+ const cwd = opts.repo ?? process.cwd();
31
+
32
+ try {
33
+ if (cmd === 'start' && args.length) {
34
+ for (const w of start(cwd, args, opts)) {
35
+ console.log(`${w.name}: ${w.agent}, tier ${w.tier}${w.model ? ` (${w.model})` : ''}, branch ${w.branch}, ${w.dir}`);
36
+ if (w.command) console.log(` run in a new terminal: ${w.command}`);
37
+ }
38
+ } else if (cmd === 'status') {
39
+ const rows = status(cwd);
40
+ if (!rows.length) console.log('no workers');
41
+ for (const w of rows) {
42
+ console.log(`${w.name}\t${w.merged ? 'merged' : w.status}\t${w.agent}\t${w.tier}\t${w.branch}`);
43
+ if (w.tail && !w.merged) console.log(w.tail.replace(/^/gm, ' '));
44
+ }
45
+ } else if (cmd === 'merge' && args.length === 1) {
46
+ if (!opts.yes) { console.log(`dry run: would merge ${args[0]}; ask the user, then add --yes`); process.exit(0); }
47
+ const rebased = merge(cwd, args[0]);
48
+ console.log(`merged ${args[0]}${rebased.length ? `; rebased ${rebased.join(', ')}; rerun their checks` : ''}`);
49
+ } else if (cmd === 'clean') {
50
+ const r = clean(cwd);
51
+ console.log(`removed: ${r.removed.join(', ') || 'none'}${r.kept.length ? `; kept (not merged): ${r.kept.join(', ')}` : ''}`);
52
+ } else {
53
+ console.log(USAGE);
54
+ process.exit(cmd ? 1 : 0);
55
+ }
56
+ } catch (e) {
57
+ console.error(`error: ${e.message}`);
58
+ process.exit(1);
59
+ }
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // Rewrites core/pins.json in the current checkout to the newest upstream versions, so the daily CI run tests `latest`.
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';
5
+ import fs from 'node:fs';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ import { isNewer, latestVersion, tagSha } from './version-watch.mjs';
8
+
9
+ const FILE = fileURLToPath(new URL('../core/pins.json', import.meta.url));
10
+
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) {
30
+ const moved = [];
31
+ for (const [key, p] of Object.entries(pins)) {
32
+ let next = null;
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
39
+ try {
40
+ next = await latestVersion(p, get);
41
+ if (next && isNewer(p.version, next)) {
42
+ const sha = p.sha ? await tagSha(p.source, next, get) : null;
43
+ const integrity = p.integrity ? (await get(`https://registry.npmjs.org/${p.source.replace('/', '%2F')}/${next}`)).dist.integrity : null;
44
+ moved.push({ key, from: p.version, to: next }); p.version = next;
45
+ if (sha) p.sha = sha;
46
+ if (integrity) p.integrity = integrity;
47
+ }
48
+ } catch (e) { console.log(`! ${key}: ${e.message}`); }
49
+ }
50
+ return moved;
51
+ }
52
+
53
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
54
+ const { GITHUB_TOKEN } = process.env;
55
+ const get = async (url) => {
56
+ const r = await fetch(url, { headers: { accept: 'application/json', ...(url.includes('api.github.com') && GITHUB_TOKEN ? { authorization: `Bearer ${GITHUB_TOKEN}` } : {}) } });
57
+ if (!r.ok) throw new Error(`${url}: ${r.status}`);
58
+ return r.json();
59
+ };
60
+ const file = JSON.parse(fs.readFileSync(FILE, 'utf8'));
61
+ const moved = await bump(file.pins, get, hashUrl);
62
+ fs.writeFileSync(FILE, `${JSON.stringify(file, null, 2)}\n`);
63
+ const lines = moved.length ? moved.map((m) => `- ${m.key}: ${m.from} -> ${m.to}`) : ['- no pin has a newer version'];
64
+ console.log(lines.join('\n'));
65
+ if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Latest versions under test\n${lines.join('\n')}\n`);
66
+ }
@@ -0,0 +1,71 @@
1
+ #!/usr/bin/env node
2
+ // Builds dist/notes.md, the source archives, the npm tarball and SHA256SUMS for a release. Used by release.yml and CI.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { execFileSync } from 'node:child_process';
6
+ import crypto from 'node:crypto';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { diffPins, toolVersionsTable } from './lib/pins-diff.mjs';
9
+
10
+ const ROOT = fileURLToPath(new URL('..', import.meta.url));
11
+
12
+ export function releaseNotes(changelog, version) {
13
+ const lines = changelog.split('\n');
14
+ const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
15
+ if (start < 0) return '';
16
+ const rest = lines.slice(start + 1);
17
+ const end = rest.findIndex((l) => l.startsWith('## ['));
18
+ return rest.slice(0, end < 0 ? undefined : end).join('\n').trim();
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
+
43
+ // Needs `npm ci --omit=dev` first: the tarball bundles node_modules.
44
+ export function packDist(dist, version) {
45
+ const name = `lean-agents-${version}`;
46
+ execFileSync('npm', ['pack', '--pack-destination', dist, '--silent'], { cwd: ROOT });
47
+ for (const f of ['install.sh', 'install.ps1']) fs.copyFileSync(path.join(ROOT, f), path.join(dist, f));
48
+ const files = [`${name}.tgz`, `${name}.tar.gz`, `${name}.zip`, 'install.sh', 'install.ps1'];
49
+ const sums = files.map((f) => `${crypto.createHash('sha256').update(fs.readFileSync(path.join(dist, f))).digest('hex')} ${f}\n`);
50
+ fs.writeFileSync(path.join(dist, 'SHA256SUMS'), sums.join(''));
51
+ return files;
52
+ }
53
+
54
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
55
+ const version = process.argv[2];
56
+ const current = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
57
+ if (version !== current) throw new Error(`version ${version} does not match package.json ${current}`);
58
+ const notes = releaseNotes(fs.readFileSync(path.join(ROOT, 'CHANGELOG.md'), 'utf8'), version);
59
+ if (!notes) throw new Error(`CHANGELOG.md has no notes for ${version}`);
60
+ const dist = path.join(ROOT, 'dist');
61
+ fs.mkdirSync(dist, { recursive: true });
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`);
65
+ const name = `lean-agents-${version}`;
66
+ for (const ext of ['tar.gz', 'zip']) {
67
+ execFileSync('git', ['archive', '--format', ext, '--prefix', `${name}/`, '-o', path.join(dist, `${name}.${ext}`), 'HEAD'], { cwd: ROOT });
68
+ }
69
+ const packed = packDist(dist, version);
70
+ console.log(`dist: notes.md, SHA256SUMS, ${packed.join(', ')}`);
71
+ }
@@ -0,0 +1,36 @@
1
+ // Checks core/pins.json against the real upstream: npm `dist.integrity` and the commit a tag points at.
2
+ // A mismatch means the registry or the tag changed after the pin was recorded (a republish or a moved tag).
3
+ // node scripts/verify-pins.mjs (GITHUB_TOKEN raises the GitHub API rate limit)
4
+ import fs from 'node:fs';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { tagSha } from './version-watch.mjs';
7
+
8
+ const FILE = fileURLToPath(new URL('../core/pins.json', import.meta.url));
9
+
10
+ // Returns one message per pin whose recorded integrity or sha differs from upstream.
11
+ export async function verify(pins, get) {
12
+ const bad = [];
13
+ for (const [key, p] of Object.entries(pins)) {
14
+ try {
15
+ if (p.integrity) {
16
+ const meta = await get(`https://registry.npmjs.org/${p.source.replace('/', '%2F')}/${p.version}`);
17
+ if (meta.dist.integrity !== p.integrity) bad.push(`${key}: integrity ${meta.dist.integrity} != pinned ${p.integrity}`);
18
+ if (meta.engines?.node !== p.node) bad.push(`${key}: engines.node ${meta.engines?.node} != pinned ${p.node}`);
19
+ }
20
+ if (p.sha) {
21
+ const got = await tagSha(p.source, p.version, get);
22
+ if (got !== p.sha) bad.push(`${key}: ${p.version} is ${got}, pinned ${p.sha}`);
23
+ }
24
+ } catch (e) { bad.push(`${key}: ${e.message}`); }
25
+ }
26
+ return bad;
27
+ }
28
+
29
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
30
+ const headers = { 'User-Agent': 'lean-agents', ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}) };
31
+ const get = async (url) => { const r = await fetch(url, { headers }); if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`); return r.json(); };
32
+ const bad = await verify(JSON.parse(fs.readFileSync(FILE, 'utf8')).pins, get);
33
+ for (const m of bad) console.log(`! ${m}`);
34
+ console.log(bad.length ? `${bad.length} pin(s) do not match upstream` : 'every pin matches upstream');
35
+ process.exit(bad.length ? 1 : 0);
36
+ }