@yasaswy.nagavolu/agents 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,132 @@
1
+ 'use strict';
2
+
3
+ const readline = require('node:readline');
4
+
5
+ /**
6
+ * Interactive checkbox picker over `rows` (from menu.describeBundleRow).
7
+ * Renders with raw-mode keypress handling when available (up/down/space/
8
+ * a=all/enter=confirm/q=quit); degrades to a numbered comma-list prompt
9
+ * (readline.question) when raw mode isn't available (e.g. some CI shells,
10
+ * piped stdin that still reports isTTY oddly, or a stdin that doesn't
11
+ * support setRawMode at all).
12
+ *
13
+ * Resolves to an array of selected bundle keys, or null if the user quit.
14
+ */
15
+ function pickBundles(rows, { stdin = process.stdin, stdout = process.stdout } = {}) {
16
+ const canRawMode = !!(stdin.isTTY && typeof stdin.setRawMode === 'function');
17
+ if (canRawMode) {
18
+ return pickWithRawMode(rows, stdin, stdout);
19
+ }
20
+ return pickWithNumberedPrompt(rows, stdin, stdout);
21
+ }
22
+
23
+ function statusLabel(row) {
24
+ if (row.status === 'passthrough') return '[passthrough]';
25
+ return '';
26
+ }
27
+
28
+ function renderRow(row, index, selected, cursor) {
29
+ const box = selected.has(index) ? '[x]' : '[ ]';
30
+ const pointer = cursor === index ? '>' : ' ';
31
+ const depsPart = row.depsHint ? ` (needs: ${row.depsHint})` : '';
32
+ const secretsPart = row.secretsHint ? ` (asks: ${row.secretsHint})` : '';
33
+ const label = statusLabel(row);
34
+ return `${pointer} ${box} ${row.title} — ${row.summary}${depsPart}${secretsPart} ${label}`.trimEnd();
35
+ }
36
+
37
+ function pickWithRawMode(rows, stdin, stdout) {
38
+ return new Promise((resolve) => {
39
+ readline.emitKeypressEvents(stdin);
40
+ stdin.setRawMode(true);
41
+ stdin.resume();
42
+
43
+ let cursor = 0;
44
+ const selected = new Set();
45
+
46
+ function draw() {
47
+ stdout.write('\x1Bc'); // clear screen — simplest robust redraw, no cursor-math bugs
48
+ stdout.write('Select bundles to install (space=toggle, a=all, enter=confirm, q=quit)\n\n');
49
+ rows.forEach((row, i) => {
50
+ stdout.write(`${renderRow(row, i, selected, cursor)}\n`);
51
+ });
52
+ }
53
+
54
+ function cleanup() {
55
+ stdin.setRawMode(false);
56
+ stdin.pause();
57
+ stdin.removeListener('keypress', onKeypress);
58
+ }
59
+
60
+ function toggle(i) {
61
+ if (selected.has(i)) selected.delete(i);
62
+ else selected.add(i);
63
+ }
64
+
65
+ function onKeypress(str, key) {
66
+ if (key && key.ctrl && key.name === 'c') {
67
+ cleanup();
68
+ resolve(null);
69
+ return;
70
+ }
71
+ if (key && key.name === 'q') {
72
+ cleanup();
73
+ resolve(null);
74
+ return;
75
+ }
76
+ if (key && key.name === 'up') {
77
+ cursor = (cursor - 1 + rows.length) % rows.length;
78
+ } else if (key && key.name === 'down') {
79
+ cursor = (cursor + 1) % rows.length;
80
+ } else if (key && key.name === 'space') {
81
+ toggle(cursor);
82
+ } else if (str === 'a') {
83
+ rows.forEach((_, i) => toggle(i));
84
+ } else if (key && key.name === 'return') {
85
+ cleanup();
86
+ resolve(rows.filter((_, i) => selected.has(i)).map((r) => r.key));
87
+ return;
88
+ }
89
+ draw();
90
+ }
91
+
92
+ stdin.on('keypress', onKeypress);
93
+ draw();
94
+ });
95
+ }
96
+
97
+ function pickWithNumberedPrompt(rows, stdin, stdout) {
98
+ return new Promise((resolve) => {
99
+ stdout.write('Available bundles:\n');
100
+ rows.forEach((row, i) => {
101
+ const label = statusLabel(row);
102
+ const depsPart = row.depsHint ? ` (needs: ${row.depsHint})` : '';
103
+ const secretsPart = row.secretsHint ? ` (asks: ${row.secretsHint})` : '';
104
+ stdout.write(` ${i + 1}) ${row.title} — ${row.summary}${depsPart}${secretsPart} ${label}\n`.trimEnd() + '\n');
105
+ });
106
+ const rl = readline.createInterface({ input: stdin, output: stdout });
107
+ rl.question(
108
+ '\nEnter numbers to install (comma-separated), "a" for all, or blank/q to quit: ',
109
+ (answer) => {
110
+ rl.close();
111
+ const trimmed = answer.trim().toLowerCase();
112
+ if (!trimmed || trimmed === 'q') {
113
+ resolve(null);
114
+ return;
115
+ }
116
+ let indices;
117
+ if (trimmed === 'a') {
118
+ indices = rows.map((_, i) => i);
119
+ } else {
120
+ indices = trimmed
121
+ .split(',')
122
+ .map((s) => parseInt(s.trim(), 10) - 1)
123
+ .filter((n) => Number.isInteger(n) && n >= 0 && n < rows.length);
124
+ }
125
+ const keys = indices.map((i) => rows[i].key);
126
+ resolve(keys);
127
+ }
128
+ );
129
+ });
130
+ }
131
+
132
+ module.exports = { pickBundles };
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { loadManifest, findBundle } = require('./manifest');
6
+ const { loadLedger, saveLedger } = require('./ledger');
7
+ const { sha256File, removeEmptyParents } = require('./fsutil');
8
+ const { unwireBundle } = require('./wiring');
9
+ const { unwireMcpBundle } = require('./mcpWiring');
10
+ const { defaultTargetBase } = require('./install');
11
+ const { uninstallComponentsForBundle } = require('./components');
12
+
13
+ class UninstallError extends Error {}
14
+
15
+ /**
16
+ * Remove everything `installBundle` put down for one bundle: files whose
17
+ * on-disk hash still matches the ledger (user-edited files are left in
18
+ * place, reported as `filesKeptUserEdited`), the bundle's ledger entries,
19
+ * and exactly the settings.json hook entries this bundle wired (via
20
+ * wiring.js's `unwireBundle`, scoped to `ledger.wiring[bundleKey]`).
21
+ *
22
+ * Unknown bundle key -> UninstallError listing every bundle the manifest
23
+ * declares (same convention as installBundle's InstallError). A bundle
24
+ * that's valid but was never installed at targetBase (no ledger entries, no
25
+ * recorded wiring) is a no-op, not an error.
26
+ */
27
+ function uninstallBundle({ packageRoot, bundleKey, targetBase, cliVersion, mcpConfigPath }) {
28
+ const { manifest } = loadManifest(packageRoot);
29
+ const bundle = findBundle(manifest, bundleKey);
30
+ if (!bundle) {
31
+ const available = manifest.bundles.map((b) => b.key);
32
+ throw new UninstallError(
33
+ `Unknown bundle "${bundleKey}". Available bundles: ${available.length ? available.join(', ') : '(none defined yet)'}`
34
+ );
35
+ }
36
+
37
+ const resolvedTargetBase = targetBase || defaultTargetBase();
38
+ const ledger = loadLedger(resolvedTargetBase, cliVersion);
39
+
40
+ const filesRemoved = [];
41
+ const filesKeptUserEdited = [];
42
+
43
+ for (const [relTarget, entry] of Object.entries(ledger.entries)) {
44
+ if (entry.bundle !== bundle.key) continue;
45
+
46
+ const destFile = path.join(resolvedTargetBase, ...relTarget.split('/'));
47
+ if (fs.existsSync(destFile)) {
48
+ const currentHash = sha256File(destFile);
49
+ if (currentHash === entry.sha256) {
50
+ fs.unlinkSync(destFile);
51
+ removeEmptyParents(path.dirname(destFile), resolvedTargetBase);
52
+ filesRemoved.push(relTarget);
53
+ } else {
54
+ filesKeptUserEdited.push(relTarget);
55
+ }
56
+ } else {
57
+ // Already gone on disk — nothing to remove, just drop the ledger entry.
58
+ filesRemoved.push(relTarget);
59
+ }
60
+ delete ledger.entries[relTarget];
61
+ }
62
+
63
+ const wiringResult = unwireBundle(bundle.key, { targetBase: resolvedTargetBase, ledger });
64
+ const mcpResult = unwireMcpBundle(bundle.key, { targetBase: resolvedTargetBase, configPath: mcpConfigPath, ledger });
65
+
66
+ // Component cleanup runs last, after this bundle's own entries/wiring/mcp
67
+ // records are gone — remainingDependents() (components.js) derives "is any
68
+ // OTHER bundle still installed" from the ledger, so it must not still see
69
+ // this bundle.
70
+ const componentResults = uninstallComponentsForBundle(bundle, { manifest, targetBase: resolvedTargetBase, ledger });
71
+
72
+ ledger.cliVersion = cliVersion;
73
+ saveLedger(resolvedTargetBase, ledger);
74
+
75
+ return {
76
+ bundle: bundle.key,
77
+ targetBase: resolvedTargetBase,
78
+ filesRemoved,
79
+ filesKeptUserEdited,
80
+ hooksRemoved: wiringResult.removed,
81
+ mcpRemoved: mcpResult.removed,
82
+ mcpKeptUserEdited: mcpResult.keptUserEdited,
83
+ components: componentResults,
84
+ noop:
85
+ filesRemoved.length === 0 &&
86
+ filesKeptUserEdited.length === 0 &&
87
+ wiringResult.removed.length === 0 &&
88
+ mcpResult.removed.length === 0 &&
89
+ mcpResult.keptUserEdited.length === 0 &&
90
+ componentResults.every((c) => c.kept || ((c.removed || []).length === 0 && (c.keptUserEdited || []).length === 0)),
91
+ };
92
+ }
93
+
94
+ module.exports = { uninstallBundle, UninstallError };
package/lib/update.js ADDED
@@ -0,0 +1,363 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { loadManifest, findBundle } = require('./manifest');
6
+ const { loadLedger, saveLedger, bundleKeysInLedger } = require('./ledger');
7
+ const { sha256File, walk, copyFileEnsuringDir, removeEmptyParents } = require('./fsutil');
8
+ const { wireItems, pruneStaleWiring, expectedWiringRecords } = require('./wiring');
9
+ const { wireMcpItems, pruneStaleMcp, expectedMcpNames } = require('./mcpWiring');
10
+ const { unifiedDiff } = require('./diff');
11
+ const { askChoice } = require('./secretsPrompt');
12
+ const { defaultTargetBase } = require('./install');
13
+
14
+ class UpdateError extends Error {}
15
+
16
+ /** Every {relTarget, srcFile} this bundle's non-mcp items currently declare — same walk logic as install.js. */
17
+ function collectBundleFiles(bundle, repoRoot) {
18
+ const files = [];
19
+ for (const item of bundle.items) {
20
+ if (item.kind === 'mcp') continue;
21
+
22
+ const srcRoot = path.join(repoRoot, ...item.path.split('/'));
23
+ if (!fs.existsSync(srcRoot)) {
24
+ throw new UpdateError(
25
+ `Item path "${item.path}" declared by bundle "${bundle.key}" does not exist in the repo at ${srcRoot}`
26
+ );
27
+ }
28
+ const excluded = new Set(item.exclude || []);
29
+ const srcIsFile = fs.statSync(srcRoot).isFile();
30
+ const targetPrefix = item.targetPath || item.path;
31
+
32
+ for (const relFile of walk(srcRoot)) {
33
+ if (excluded.has(relFile)) continue;
34
+ const srcFile = srcIsFile ? srcRoot : path.join(srcRoot, ...relFile.split('/'));
35
+ const sourcePath = srcIsFile ? item.path : `${item.path}/${relFile}`;
36
+ const relTarget = srcIsFile ? targetPrefix : `${targetPrefix}/${relFile}`;
37
+ files.push({ relTarget, srcFile, sourcePath });
38
+ }
39
+ }
40
+ return files;
41
+ }
42
+
43
+ /**
44
+ * Classify every file currently declared by `bundle` (plus every ledger
45
+ * entry for `bundle` no longer declared — "upstream removed") into the
46
+ * update decision table:
47
+ *
48
+ * source == ledger == dest -> upToDate
49
+ * source != ledger, dest == ledger -> overwrite (untouched; silent)
50
+ * dest != ledger, source == ledger -> keepNoSourceChange (user-edited; note)
51
+ * dest != ledger AND source != ledger -> conflicts (needs resolution)
52
+ * dest missing -> reinstall
53
+ * ledger entry, file no longer in source, dest == ledger -> removedUpstream
54
+ * ledger entry, file no longer in source, dest != ledger -> keptUpstreamUserEdited
55
+ *
56
+ * Pure (reads disk, never writes) so it's independently testable and so the
57
+ * caller can decide how to resolve conflicts before anything is mutated.
58
+ */
59
+ function planBundleUpdate(bundle, { repoRoot, targetBase, ledger }) {
60
+ const currentFiles = collectBundleFiles(bundle, repoRoot);
61
+ const currentRelTargets = new Set(currentFiles.map((f) => f.relTarget));
62
+
63
+ const plan = {
64
+ upToDate: [],
65
+ overwrite: [],
66
+ keepNoSourceChange: [],
67
+ reinstall: [],
68
+ conflicts: [],
69
+ removedUpstream: [],
70
+ keptUpstreamUserEdited: [],
71
+ };
72
+
73
+ for (const { relTarget, srcFile, sourcePath } of currentFiles) {
74
+ const destFile = path.join(targetBase, ...relTarget.split('/'));
75
+ const sourceHash = sha256File(srcFile);
76
+ const ledgerEntry = ledger.entries[relTarget];
77
+ const destExists = fs.existsSync(destFile);
78
+ const destHash = destExists ? sha256File(destFile) : null;
79
+ const item = { relTarget, srcFile, destFile, sourceHash, destHash, sourcePath };
80
+
81
+ if (!destExists) {
82
+ plan.reinstall.push(item);
83
+ continue;
84
+ }
85
+ if (!ledgerEntry) {
86
+ // No tracked baseline for this path yet (item newly added to the
87
+ // bundle, or a pre-CLI file happens to sit there). Nothing to compare
88
+ // "user-edited" against, so: already matches -> up to date, otherwise
89
+ // treat it as a fresh install target, same as install.js would.
90
+ if (destHash === sourceHash) {
91
+ plan.upToDate.push(item);
92
+ } else {
93
+ plan.reinstall.push(item);
94
+ }
95
+ continue;
96
+ }
97
+
98
+ const ledgerHash = ledgerEntry.sha256;
99
+ const sourceChanged = sourceHash !== ledgerHash;
100
+ const destChanged = destHash !== ledgerHash;
101
+
102
+ if (!sourceChanged && !destChanged) {
103
+ plan.upToDate.push(item);
104
+ } else if (sourceChanged && !destChanged) {
105
+ plan.overwrite.push(item);
106
+ } else if (!sourceChanged && destChanged) {
107
+ plan.keepNoSourceChange.push(item);
108
+ } else {
109
+ plan.conflicts.push(item);
110
+ }
111
+ }
112
+
113
+ for (const [relTarget, entry] of Object.entries(ledger.entries)) {
114
+ if (entry.bundle !== bundle.key || currentRelTargets.has(relTarget)) continue;
115
+ const destFile = path.join(targetBase, ...relTarget.split('/'));
116
+ if (!fs.existsSync(destFile)) {
117
+ plan.removedUpstream.push({ relTarget, destFile, alreadyGone: true });
118
+ continue;
119
+ }
120
+ if (sha256File(destFile) === entry.sha256) {
121
+ plan.removedUpstream.push({ relTarget, destFile, alreadyGone: false });
122
+ } else {
123
+ plan.keptUpstreamUserEdited.push({ relTarget, destFile });
124
+ }
125
+ }
126
+
127
+ return plan;
128
+ }
129
+
130
+ function applyOverwrite(item, ledger, bundleKey, timestamp) {
131
+ copyFileEnsuringDir(item.srcFile, item.destFile);
132
+ ledger.entries[item.relTarget] = {
133
+ sha256: item.sourceHash,
134
+ bundle: bundleKey,
135
+ installedAt: timestamp,
136
+ sourcePath: item.sourcePath,
137
+ };
138
+ }
139
+
140
+ /**
141
+ * Resolve `conflicts` per the binding decision: a bulk `strategy`
142
+ * ('theirs'/'keep-mine') resolves every conflict without prompting; absent a
143
+ * strategy, an interactive TTY gets a diff + keep/overwrite/backup prompt
144
+ * per file; a non-TTY with no strategy resolves nothing (every conflict
145
+ * comes back `unresolved` — the caller changes nothing for those files and
146
+ * the overall command exits 2).
147
+ */
148
+ async function resolveConflicts(conflicts, { strategy, io, isTTY, log, cliVersion }) {
149
+ const resolved = [];
150
+ if (conflicts.length === 0) {
151
+ return { resolved, unresolved: [] };
152
+ }
153
+
154
+ if (strategy === 'theirs') {
155
+ for (const item of conflicts) resolved.push({ item, action: 'overwrite' });
156
+ return { resolved, unresolved: [] };
157
+ }
158
+ if (strategy === 'keep-mine') {
159
+ for (const item of conflicts) resolved.push({ item, action: 'keep' });
160
+ return { resolved, unresolved: [] };
161
+ }
162
+ if (!isTTY) {
163
+ return { resolved, unresolved: conflicts };
164
+ }
165
+
166
+ for (const item of conflicts) {
167
+ const oldText = fs.readFileSync(item.destFile, 'utf8');
168
+ const newText = fs.readFileSync(item.srcFile, 'utf8');
169
+ log(`\nConflict: ${item.relTarget} was edited locally AND changed upstream.`);
170
+ log(unifiedDiff(oldText, newText, { oldLabel: `${item.relTarget} (yours)`, newLabel: `${item.relTarget} (new)` }));
171
+ // eslint-disable-next-line no-await-in-loop
172
+ const choice = await askChoice({
173
+ input: io.input,
174
+ output: io.output,
175
+ promptText: ' Keep your version, overwrite with the new version, or back up yours then overwrite? [k/o/b] ',
176
+ choices: ['keep', 'overwrite', 'backup'],
177
+ defaultChoice: 'keep',
178
+ });
179
+ if (choice === 'overwrite') {
180
+ resolved.push({ item, action: 'overwrite' });
181
+ } else if (choice === 'backup') {
182
+ const backupFile = `${item.destFile}.bak-${cliVersion}`;
183
+ fs.copyFileSync(item.destFile, backupFile);
184
+ resolved.push({ item, action: 'backup', backupFile });
185
+ } else {
186
+ resolved.push({ item, action: 'keep' });
187
+ }
188
+ }
189
+
190
+ return { resolved, unresolved: [] };
191
+ }
192
+
193
+ async function updateOneBundle(bundle, { repoRoot, targetBase, ledger, timestamp, cliVersion, strategy, io, isTTY, log, pythonChecker, mcpConfigPath }) {
194
+ const plan = planBundleUpdate(bundle, { repoRoot, targetBase, ledger });
195
+
196
+ const summary = {
197
+ bundle: bundle.key,
198
+ upToDate: plan.upToDate.map((i) => i.relTarget),
199
+ overwritten: [],
200
+ kept: plan.keepNoSourceChange.map((i) => i.relTarget),
201
+ reinstalled: [],
202
+ removedUpstream: [],
203
+ keptUpstreamUserEdited: [],
204
+ conflictsResolved: [],
205
+ unresolvedConflicts: [],
206
+ };
207
+
208
+ for (const item of plan.overwrite) {
209
+ applyOverwrite(item, ledger, bundle.key, timestamp);
210
+ summary.overwritten.push(item.relTarget);
211
+ }
212
+ for (const item of plan.reinstall) {
213
+ applyOverwrite(item, ledger, bundle.key, timestamp);
214
+ summary.reinstalled.push(item.relTarget);
215
+ }
216
+
217
+ const { resolved, unresolved } = await resolveConflicts(plan.conflicts, { strategy, io, isTTY, log, cliVersion });
218
+ for (const outcome of resolved) {
219
+ if (outcome.action === 'overwrite' || outcome.action === 'backup') {
220
+ applyOverwrite(outcome.item, ledger, bundle.key, timestamp);
221
+ }
222
+ summary.conflictsResolved.push({
223
+ relTarget: outcome.item.relTarget,
224
+ action: outcome.action,
225
+ backupFile: outcome.backupFile || null,
226
+ });
227
+ }
228
+ summary.unresolvedConflicts = unresolved.map((item) => item.relTarget);
229
+
230
+ for (const item of plan.removedUpstream) {
231
+ if (!item.alreadyGone) {
232
+ fs.unlinkSync(item.destFile);
233
+ removeEmptyParents(path.dirname(item.destFile), targetBase);
234
+ }
235
+ delete ledger.entries[item.relTarget];
236
+ summary.removedUpstream.push(item.relTarget);
237
+ }
238
+ for (const item of plan.keptUpstreamUserEdited) {
239
+ delete ledger.entries[item.relTarget];
240
+ summary.keptUpstreamUserEdited.push(item.relTarget);
241
+ log(
242
+ ` Note: ${item.relTarget} was removed from bundle "${bundle.key}" upstream, but your on-disk copy was ` +
243
+ 'edited since install — left in place (untracked now).'
244
+ );
245
+ }
246
+
247
+ const expectedHooks = expectedWiringRecords(bundle.items, targetBase);
248
+ pruneStaleWiring(bundle.key, { targetBase, ledger, expectedRecords: expectedHooks });
249
+ const wiring = wireItems(bundle.items, { targetBase, bundleKey: bundle.key, ledger, timestamp, pythonChecker });
250
+
251
+ const expectedMcp = expectedMcpNames(bundle.items);
252
+ pruneStaleMcp(bundle.key, { targetBase, configPath: mcpConfigPath, ledger, expectedNames: expectedMcp });
253
+ const mcpWiring = wireMcpItems(bundle.items, { targetBase, bundleKey: bundle.key, ledger, timestamp, configPath: mcpConfigPath });
254
+
255
+ summary.hooksWired = wiring.wired;
256
+ summary.mcpWired = mcpWiring.wired;
257
+ summary.changed =
258
+ summary.overwritten.length > 0 ||
259
+ summary.reinstalled.length > 0 ||
260
+ summary.conflictsResolved.some((c) => c.action !== 'keep') ||
261
+ summary.removedUpstream.length > 0 ||
262
+ wiring.wired.length > 0 ||
263
+ mcpWiring.wired.length > 0;
264
+
265
+ return summary;
266
+ }
267
+
268
+ /**
269
+ * Update every installed bundle (or just `bundleKey`, if given) at
270
+ * `targetBase`: silently overwrite untouched files whose source changed,
271
+ * reinstall missing files, leave user-edited-with-no-source-change files
272
+ * alone, resolve true conflicts (both sides changed) per `strategy`/prompt,
273
+ * remove files the manifest no longer ships (unless user-edited, then warn +
274
+ * untrack), and refresh hook/MCP wiring to match the current manifest.
275
+ *
276
+ * `strategy`: 'theirs' (always take the new source) | 'keep-mine' (always
277
+ * keep the on-disk version) | undefined (interactive prompt in a TTY, or —
278
+ * in a non-TTY — leave every conflict unresolved and report it).
279
+ *
280
+ * Returns `{ targetBase, bundles: [...], unresolvedConflicts, exitCode }` —
281
+ * `exitCode` is 2 when any conflict went unresolved, else 0. The ledger is
282
+ * always saved (matching install.js's convention) even when nothing
283
+ * changed; content is byte-identical to before in that case.
284
+ */
285
+ async function updateBundles({
286
+ packageRoot,
287
+ targetBase,
288
+ cliVersion,
289
+ bundleKey,
290
+ now,
291
+ strategy,
292
+ io,
293
+ isTTY,
294
+ pythonChecker,
295
+ mcpConfigPath,
296
+ log = console.log,
297
+ }) {
298
+ const { manifest, manifestPath } = loadManifest(packageRoot);
299
+ const repoRoot = path.dirname(manifestPath);
300
+ const resolvedTargetBase = targetBase || defaultTargetBase();
301
+ const ledger = loadLedger(resolvedTargetBase, cliVersion);
302
+ const timestamp = now || new Date().toISOString();
303
+
304
+ let bundleKeys;
305
+ if (bundleKey) {
306
+ const bundle = findBundle(manifest, bundleKey);
307
+ if (!bundle) {
308
+ const available = manifest.bundles.map((b) => b.key);
309
+ throw new UpdateError(
310
+ `Unknown bundle "${bundleKey}". Available bundles: ${available.length ? available.join(', ') : '(none defined yet)'}`
311
+ );
312
+ }
313
+ bundleKeys = [bundleKey];
314
+ } else {
315
+ bundleKeys = bundleKeysInLedger(ledger);
316
+ }
317
+
318
+ const resolvedIo = io || { input: process.stdin, output: process.stdout };
319
+ const resolvedIsTTY =
320
+ isTTY !== undefined ? isTTY : !!(resolvedIo.input && resolvedIo.input.isTTY && resolvedIo.output && resolvedIo.output.isTTY);
321
+
322
+ const bundles = [];
323
+ const unresolvedConflicts = [];
324
+
325
+ for (const key of bundleKeys) {
326
+ const bundle = findBundle(manifest, key);
327
+ if (!bundle) {
328
+ log(
329
+ `Bundle "${key}" is recorded in the ledger but no longer exists in the manifest — skipping ` +
330
+ '(its files/wiring are left as-is; use uninstall if you want them removed).'
331
+ );
332
+ continue;
333
+ }
334
+ // eslint-disable-next-line no-await-in-loop
335
+ const result = await updateOneBundle(bundle, {
336
+ repoRoot,
337
+ targetBase: resolvedTargetBase,
338
+ ledger,
339
+ timestamp,
340
+ cliVersion,
341
+ strategy,
342
+ io: resolvedIo,
343
+ isTTY: resolvedIsTTY,
344
+ log,
345
+ pythonChecker,
346
+ mcpConfigPath,
347
+ });
348
+ bundles.push(result);
349
+ unresolvedConflicts.push(...result.unresolvedConflicts.map((relTarget) => ({ bundle: key, relTarget })));
350
+ }
351
+
352
+ ledger.cliVersion = cliVersion;
353
+ saveLedger(resolvedTargetBase, ledger);
354
+
355
+ return {
356
+ targetBase: resolvedTargetBase,
357
+ bundles,
358
+ unresolvedConflicts,
359
+ exitCode: unresolvedConflicts.length > 0 ? 2 : 0,
360
+ };
361
+ }
362
+
363
+ module.exports = { updateBundles, planBundleUpdate, UpdateError };