@aiwayds/dsh-opentui 0.17.3 → 0.18.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,929 @@
1
+ #!/usr/bin/env node
2
+ // upgrade.mjs — the body of `dsh-opentui upgrade`.
3
+ //
4
+ // Phases (control flow is defined in the implementation plan §6.3):
5
+ // 1. Plan (read-only): resolve the registry, read the opentui profile's
6
+ // dependencies and the versions on disk, query the dist-tag once per
7
+ // upgradable package, print the table. A missing profile is a normal
8
+ // terminal state (exit 0): the launcher provisions it on the next start.
9
+ // 2. Confirmation: skipped by --dry-run and --yes; otherwise an interactive
10
+ // prompt, and a refusal (exit 2) when neither stdin nor CI allows it.
11
+ // 3. Self upgrade: `npm i -g <own name>@<target>`, only when the running
12
+ // copy demonstrably lives under the npm global prefix. Every other
13
+ // install form is skipped with a warning — installing into a different
14
+ // prefix would create a shadow copy that `dsh-opentui` never resolves.
15
+ // A hard failure here aborts BEFORE anything touches the profile.
16
+ // 4. Plugins: `applyPluginUpgrades(ctx)` — back up the profile, run ONE
17
+ // batched `dsh plugin add`, verify each package on disk, and record the
18
+ // landed versions in upgrade-overrides.json. An install failure restores
19
+ // the backup and re-adds the pre-upgrade specs; a version that did not
20
+ // land is reported but never rolls back a successful install.
21
+ //
22
+ // Exit codes: 0 done/nothing to do/dry-run/help; 1 hard failure OR any package
23
+ // whose target version could not be determined (a query failure means the
24
+ // target is unknown, which is not "up to date"; nothing is written in that
25
+ // case); 2 usage refusal; 3 partially applied (some package is not at its
26
+ // planned version, or the override file could not be written).
27
+ //
28
+ // Dependency injection: every child process goes through `run(cmd, args, {
29
+ // timeout })` and every file operation through `fs`, both overridable from the
30
+ // context argument. That is what lets the tests exercise the install, verify
31
+ // and abort paths without npm, a TTY, or a real profile.
32
+ import { execFileSync } from 'node:child_process'
33
+ import {
34
+ copyFileSync,
35
+ existsSync,
36
+ mkdirSync,
37
+ readFileSync,
38
+ readSync,
39
+ realpathSync,
40
+ renameSync,
41
+ rmSync,
42
+ writeFileSync,
43
+ } from 'node:fs'
44
+ import { homedir } from 'node:os'
45
+ import { dirname, join, resolve, sep } from 'node:path'
46
+ import { fileURLToPath } from 'node:url'
47
+ import { formatUpgradeUsage } from '../bin/lib/launcher.mjs'
48
+ import {
49
+ PLUGIN_SET,
50
+ PROFILE,
51
+ compareVersions,
52
+ parseVersion,
53
+ resolveEffectivePin,
54
+ } from './lib/provision-plan.mjs'
55
+ import {
56
+ buildUpgradePlan,
57
+ buildViewArgs,
58
+ isOfficialRegistry,
59
+ isUpgradableDependency,
60
+ parseOverrides,
61
+ resolveRegistry,
62
+ serializeOverrides,
63
+ } from './lib/upgrade-plan.mjs'
64
+
65
+ const PREFIX = 'dsh-opentui upgrade: '
66
+ // Matched to buildViewArgs' `--fetch-timeout 20000` (+ slack for npm startup
67
+ // and DNS): the child enforces its own fetch budget, so this backstop only
68
+ // matters when an argv flag is ignored (an old npm, a wrapper). Without the
69
+ // leftover margin a single dead registry would cost 60s per package.
70
+ const QUERY_TIMEOUT_MS = 25 * 1000
71
+ const PREFIX_TIMEOUT_MS = 10 * 1000
72
+ const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
73
+ const OVERRIDE_FILE = 'upgrade-overrides.json'
74
+ const BACKUP_DIR_NAME = '.upgrade-backup'
75
+ // pnpm-workspace.yaml belongs here because users hand-write allowBuilds in it:
76
+ // a host rollback that restored only the manifest and the lock would leave the
77
+ // rewritten workspace file in place.
78
+ const BACKUP_FILE_NAMES = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', OVERRIDE_FILE]
79
+ const SAVE_EXACT = '--save-exact'
80
+ // The host forwards unknown flags to pnpm, but a future argv parser could
81
+ // reject it; only a rejection of THIS flag earns the one retry without it.
82
+ const SAVE_EXACT_REJECTED = /save-exact|unknown option|unrecognized/i
83
+
84
+ /** The shipped pins, keyed by package name: the only versions provisioning
85
+ * may be raised above, so the only names an override can ever affect. */
86
+ const SHIPPED_PINS = new Map(PLUGIN_SET.map((plugin) => [plugin.name, plugin.version]))
87
+
88
+ const ACTION_LABEL = {
89
+ upgrade: 'upgrade',
90
+ latest: 'up to date',
91
+ 'query-failed': 'query-failed',
92
+ excluded: 'excluded',
93
+ }
94
+
95
+ const say = (message) => console.log(`${PREFIX}${message}`)
96
+ const warn = (message) => console.error(`${PREFIX}warning: ${message}`)
97
+
98
+ function isPlainObject(value) {
99
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // Injected effects — the defaults used by the real CLI
104
+ // ---------------------------------------------------------------------------
105
+
106
+ /**
107
+ * Run a command and NEVER throw on a non-zero exit: the caller inspects
108
+ * `status`. stderr/stdout are strings ('' when absent) so tail printing and
109
+ * JSON parsing need no Buffer handling.
110
+ *
111
+ * `env` is merged over the parent environment (never replaces it): the plugin
112
+ * install must inherit the caller's DSH_HOME, and a spawn that dropped it
113
+ * would operate on the default profile instead of the selected one.
114
+ *
115
+ * @param {string} cmd
116
+ * @param {string[]} args
117
+ * @param {{ timeout?: number, env?: Record<string, string | undefined> }} [options]
118
+ * @returns {{ status: number, stdout: string, stderr: string }}
119
+ */
120
+ export function defaultRun(cmd, args = [], { timeout, env } = {}) {
121
+ const childEnv = {}
122
+ if (env && typeof env === 'object') {
123
+ Object.assign(childEnv, process.env)
124
+ for (const [key, value] of Object.entries(env)) {
125
+ if (typeof value === 'string') childEnv[key] = value
126
+ }
127
+ }
128
+ try {
129
+ const stdout = execFileSync(cmd, args, {
130
+ encoding: 'utf8',
131
+ timeout,
132
+ ...(env && typeof env === 'object' ? { env: childEnv } : {}),
133
+ stdio: ['ignore', 'pipe', 'pipe'],
134
+ })
135
+ return { status: 0, stdout: String(stdout ?? ''), stderr: '' }
136
+ } catch (err) {
137
+ return {
138
+ status: typeof err?.status === 'number' ? err.status : 1,
139
+ stdout: String(err?.stdout ?? ''),
140
+ stderr: String(err?.stderr ?? err?.message ?? ''),
141
+ }
142
+ }
143
+ }
144
+
145
+ /**
146
+ * The file operations the command needs, as an object so a test can replace
147
+ * the whole surface. Path-only helpers (`realpathSync` in canonicalPath) stay
148
+ * on the module import: the injected set deliberately covers reads/writes
149
+ * only, and canonicalPath remembers a path it was already given.
150
+ */
151
+ export const defaultFs = {
152
+ readFileSync: (path, encoding) => readFileSync(path, encoding),
153
+ writeFileSync: (path, data, encoding) => writeFileSync(path, data, encoding),
154
+ existsSync: (path) => existsSync(path),
155
+ mkdirSync: (path, options) => mkdirSync(path, options),
156
+ rmSync: (path, options) => rmSync(path, options),
157
+ copyFileSync: (from, to) => copyFileSync(from, to),
158
+ renameSync: (from, to) => renameSync(from, to),
159
+ }
160
+
161
+ /** A synchronous one-line read from stdin (the confirmation prompt). */
162
+ function defaultReadLine() {
163
+ const buffer = Buffer.alloc(1024)
164
+ try {
165
+ const read = readSync(0, buffer, 0, buffer.length, null)
166
+ return buffer.subarray(0, read).toString('utf8')
167
+ } catch {
168
+ return ''
169
+ }
170
+ }
171
+
172
+ const defaultPrompt = (text) => process.stdout.write(text)
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // Small readers
176
+ // ---------------------------------------------------------------------------
177
+
178
+ /**
179
+ * Absolute path for comparisons. Uses realpathSync when it resolves and falls
180
+ * back to a lexical resolve, so a path that only exists in a test fixture is
181
+ * still comparable (and a broken symlink never throws here).
182
+ */
183
+ function canonicalPath(path) {
184
+ try {
185
+ return realpathSync(path)
186
+ } catch {
187
+ return resolve(path)
188
+ }
189
+ }
190
+
191
+ /** Is `child` the same as `parent` or below it? */
192
+ function isInside(parent, child) {
193
+ const base = canonicalPath(parent).replace(/\/+$/, '')
194
+ const target = canonicalPath(child)
195
+ return target === base || target.startsWith(`${base}${sep}`)
196
+ }
197
+
198
+ /** Parsed JSON, or undefined for a missing/unreadable/malformed file. */
199
+ function readJson(fs, path) {
200
+ try {
201
+ return JSON.parse(fs.readFileSync(path, 'utf8'))
202
+ } catch {
203
+ return undefined
204
+ }
205
+ }
206
+
207
+ /** File contents, or undefined when the file cannot be read. */
208
+ function readText(fs, path) {
209
+ try {
210
+ const text = fs.readFileSync(path, 'utf8')
211
+ return typeof text === 'string' ? text : undefined
212
+ } catch {
213
+ return undefined
214
+ }
215
+ }
216
+
217
+ /**
218
+ * npmrc texts, least specific first (resolveRegistry lets the LAST text win).
219
+ * Only files that exist are passed, so a missing file cannot shadow a present
220
+ * one: profile/.npmrc > $DSH_HOME/.npmrc > ~/.npmrc.
221
+ */
222
+ function collectNpmrcTexts({ fs, dshHome, profileDir, env }) {
223
+ const home = env.HOME || homedir()
224
+ const paths = [join(home, '.npmrc'), join(dshHome, '.npmrc'), join(profileDir, '.npmrc')]
225
+ const texts = []
226
+ for (const path of paths) {
227
+ const text = readText(fs, path)
228
+ if (text !== undefined) texts.push(text)
229
+ }
230
+ return texts
231
+ }
232
+
233
+ /** The version on disk for a profile dependency, when readable. */
234
+ function readInstalledVersion(fs, profileDir, name) {
235
+ const manifest = readJson(fs, join(profileDir, 'node_modules', ...name.split('/'), 'package.json'))
236
+ return isPlainObject(manifest) && typeof manifest.version === 'string' && manifest.version
237
+ ? manifest.version
238
+ : undefined
239
+ }
240
+
241
+ /** The launcher's own name/version — read from ITS manifest, never guessed. */
242
+ function readSelf(fs, pkgRoot) {
243
+ const manifest = readJson(fs, join(pkgRoot, 'package.json'))
244
+ if (!isPlainObject(manifest)) return null
245
+ if (typeof manifest.name !== 'string' || manifest.name === '') return null
246
+ if (typeof manifest.version !== 'string' || manifest.version === '') return null
247
+ return { name: manifest.name, version: manifest.version }
248
+ }
249
+
250
+ /**
251
+ * `npm view <pkg> dist-tags --json` for one package. Returns the version the
252
+ * requested tag points at, or null when the query failed OR the tag is absent.
253
+ * A single package failing is recorded as `query-failed` by the caller.
254
+ */
255
+ function queryDistTag({ run, pkg, registry, tag }) {
256
+ const result = run('npm', buildViewArgs({ pkg, registry }), { timeout: QUERY_TIMEOUT_MS })
257
+ if (!result || result.status !== 0) return null
258
+ let tags
259
+ try {
260
+ tags = JSON.parse(result.stdout)
261
+ } catch {
262
+ return null
263
+ }
264
+ if (!isPlainObject(tags)) return null
265
+ const version = tags[tag]
266
+ return typeof version === 'string' && version !== '' ? version : null
267
+ }
268
+
269
+ /** Plain, ANSI-free table with content-sized columns. */
270
+ function formatPlanTable(rows) {
271
+ const header = ['PACKAGE', 'CURRENT', 'TARGET', 'ACTION']
272
+ const body = rows.map((row) => [
273
+ row.name,
274
+ row.current ?? '-',
275
+ row.target ?? '-',
276
+ ACTION_LABEL[row.action] ?? row.action,
277
+ ])
278
+ const widths = header.map((title, column) =>
279
+ Math.max(title.length, ...body.map((cells) => cells[column].length)),
280
+ )
281
+ const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(' ').trimEnd()
282
+ return [line(header), ...body.map(line)].join('\n')
283
+ }
284
+
285
+ /** The last `count` non-empty lines of a command's stderr. */
286
+ function tailLines(text, count = 10) {
287
+ const lines = String(text ?? '')
288
+ .trimEnd()
289
+ .split(/\r?\n/)
290
+ .filter((line) => line !== '')
291
+ return lines.slice(-count)
292
+ }
293
+
294
+ /** Semver-equal per provision-plan's single comparison rule. */
295
+ function sameVersion(a, b) {
296
+ if (typeof a !== 'string' || typeof b !== 'string') return false
297
+ if (a === b) return true
298
+ return Boolean(parseVersion(a) && parseVersion(b) && compareVersions(a, b) === 0)
299
+ }
300
+
301
+ /** `20261116T142530Z` — sortable and filename-safe. */
302
+ function backupStamp(now = new Date()) {
303
+ return now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
304
+ }
305
+
306
+ // ---------------------------------------------------------------------------
307
+ // Phase: self upgrade
308
+ // ---------------------------------------------------------------------------
309
+
310
+ /**
311
+ * Bring the launcher itself up to `target`, but only when the running copy is
312
+ * the one the npm global prefix owns.
313
+ *
314
+ * @returns {{ kind: 'skipped', form: string } |
315
+ * { kind: 'latest', version: string } |
316
+ * { kind: 'upgraded', from: string, to: string } |
317
+ * { kind: 'failed', exitCode: 1 }}
318
+ */
319
+ function upgradeSelf({ self, target, registry, run, fs, selfPath }) {
320
+ if (!self || typeof target !== 'string' || target === '') {
321
+ say('self: skipped (install form: unknown)')
322
+ warn(
323
+ 'upgrade the launcher first; an older launcher does not read upgrade-overrides and will restore shipped pins',
324
+ )
325
+ return { kind: 'skipped', form: 'unknown' }
326
+ }
327
+
328
+ // Install form: only a copy under `<npm prefix -g>/lib/node_modules/<name>`
329
+ // is ours to replace. Anything else (source tree, a copy in another prefix)
330
+ // must not be upgraded from here.
331
+ const prefixResult = run('npm', ['prefix', '-g'], { timeout: PREFIX_TIMEOUT_MS })
332
+ let form = 'unknown'
333
+ let globalPkgDir = null
334
+ if (prefixResult && prefixResult.status === 0) {
335
+ const prefix = String(prefixResult.stdout ?? '').trim()
336
+ if (prefix !== '') {
337
+ globalPkgDir = join(prefix, 'lib', 'node_modules', ...self.name.split('/'))
338
+ form = isInside(globalPkgDir, selfPath) ? 'global-npm' : 'foreign'
339
+ }
340
+ }
341
+
342
+ if (form !== 'global-npm' || globalPkgDir === null) {
343
+ say(`self: skipped (install form: ${form})`)
344
+ warn(
345
+ 'upgrade the launcher first; an older launcher does not read upgrade-overrides and will restore shipped pins',
346
+ )
347
+ return { kind: 'skipped', form }
348
+ }
349
+
350
+ if (sameVersion(self.version, target)) {
351
+ say(`self: already up to date (${self.version})`)
352
+ return { kind: 'latest', version: self.version }
353
+ }
354
+
355
+ const install = run('npm', ['i', '-g', `${self.name}@${target}`, '--registry', registry], {
356
+ timeout: INSTALL_TIMEOUT_MS,
357
+ })
358
+ if (!install || install.status !== 0) {
359
+ const tail = tailLines(install?.stderr, 10)
360
+ if (tail.length > 0) console.error(tail.join('\n'))
361
+ if (/EACCES|permission denied/i.test(String(install?.stderr ?? ''))) {
362
+ say(`try npm i -g ${self.name}@${target} with a writable prefix`)
363
+ }
364
+ say('upgrade aborted; profile untouched')
365
+ return { kind: 'failed', exitCode: 1 }
366
+ }
367
+
368
+ // Landing check reads the INSTALLED copy, never the running pkgRoot: npm may
369
+ // have replaced the directory this process was loaded from.
370
+ const landed = readJson(fs, join(globalPkgDir, 'package.json'))
371
+ const actual = isPlainObject(landed) && typeof landed.version === 'string' ? landed.version : undefined
372
+ if (actual !== target) {
373
+ say(`installed ${actual ?? 'nothing'}, expected ${target}`)
374
+ say('upgrade aborted; profile untouched')
375
+ return { kind: 'failed', exitCode: 1 }
376
+ }
377
+
378
+ say(`upgraded ${self.name} ${self.version} -> ${target}`)
379
+ say(`this process still runs the old code; quit and re-run \`dsh-opentui\` to start on ${target}`)
380
+ return { kind: 'upgraded', from: self.version, to: target }
381
+ }
382
+
383
+ // ---------------------------------------------------------------------------
384
+ // Phase: plugins
385
+ //
386
+ // The install is deliberately ONE `dsh plugin ... add` for every target: the
387
+ // host takes the profile lock once, saves/restores package.json + lock around
388
+ // the run, and pnpm resolves the batch as a whole. Per-package calls would
389
+ // turn one bad version into "3 landed, 1 failed" and leave the profile
390
+ // inconsistent, so a failure rolls the whole batch back instead.
391
+ // ---------------------------------------------------------------------------
392
+
393
+ /** Numeric exit status of an injected run result; missing results count as 1. */
394
+ function runStatus(result) {
395
+ return result && typeof result.status === 'number' ? result.status : 1
396
+ }
397
+
398
+ /** argv tail for the batched install (and for the rollback convergence). */
399
+ function pluginAddArgs(specs, { saveExact = true } = {}) {
400
+ const args = ['plugin', '--profile', PROFILE, 'add']
401
+ if (saveExact) args.push(SAVE_EXACT)
402
+ return [...args, ...specs]
403
+ }
404
+
405
+ /**
406
+ * Copy the files a rollback needs. Only files that EXIST are copied: a file
407
+ * that was never there must be re-absent after a rollback, which the caller
408
+ * infers from the missing key (it deletes the override path in that case).
409
+ *
410
+ * @returns {Record<string, string>} original file name -> backup copy path
411
+ */
412
+ function createBackup({ fs, profileDir, backupDir }) {
413
+ fs.mkdirSync(backupDir, { recursive: true })
414
+ const copies = {}
415
+ for (const name of BACKUP_FILE_NAMES) {
416
+ const source = join(profileDir, name)
417
+ if (!fs.existsSync(source)) continue
418
+ const target = join(backupDir, name)
419
+ fs.copyFileSync(source, target)
420
+ copies[name] = target
421
+ }
422
+ return copies
423
+ }
424
+
425
+ /**
426
+ * Put the profile back the way the backup found it. `package.json` and the
427
+ * lock are copy-restored; `upgrade-overrides.json` is restored when it was
428
+ * backed up, and REMOVED when it was not (a rollback must not leave behind a
429
+ * file the user never had).
430
+ */
431
+ function restoreBackup({ fs, profileDir, overridePath, copies }) {
432
+ for (const [name, copy] of Object.entries(copies)) {
433
+ fs.copyFileSync(copy, join(profileDir, name))
434
+ }
435
+ if (!Object.prototype.hasOwnProperty.call(copies, OVERRIDE_FILE)) {
436
+ fs.rmSync(overridePath, { force: true })
437
+ }
438
+ }
439
+
440
+ /** The specs of the pre-upgrade manifest, read from its BACKUP copy (the live
441
+ * manifest may already have been rewritten by the host). Local and host
442
+ * specs are skipped: they are not installable from the registry. */
443
+ function originalSpecs({ fs, copies, manifestPath }) {
444
+ const manifest = readJson(fs, copies['package.json'] ?? manifestPath)
445
+ const dependencies = isPlainObject(manifest?.dependencies) ? manifest.dependencies : {}
446
+ return Object.entries(dependencies)
447
+ .filter(([name, spec]) => isUpgradableDependency(name, spec))
448
+ .map(([name, spec]) => `${name}@${spec}`)
449
+ }
450
+
451
+ /**
452
+ * One batched install. A host that rejects `--save-exact` gets exactly one
453
+ * retry without it; every other failure is final (no per-package retry).
454
+ *
455
+ * @returns {{ status: number, args: string[], stderr: string }}
456
+ */
457
+ function installPlugins({ run, env, specs, warn }) {
458
+ let args = pluginAddArgs(specs)
459
+ let result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
460
+ let status = runStatus(result)
461
+ if (status === 0) return { status, args, stderr: '' }
462
+
463
+ const stderr = String(result?.stderr ?? '')
464
+ if (SAVE_EXACT_REJECTED.test(stderr)) {
465
+ warn('--save-exact not supported by host; relying on upgrade-overrides')
466
+ args = pluginAddArgs(specs, { saveExact: false })
467
+ result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
468
+ status = runStatus(result)
469
+ if (status === 0) return { status, args, stderr: '' }
470
+ }
471
+ return { status, args, stderr }
472
+ }
473
+
474
+ /** Strict per-package check: only an exact string match counts as landed. */
475
+ function verifyPlugins({ fs, profileDir, rows }) {
476
+ const landed = []
477
+ const mismatched = []
478
+ for (const row of rows) {
479
+ const actual = readInstalledVersion(fs, profileDir, row.name)
480
+ if (actual !== undefined && actual === row.target) {
481
+ landed.push({ name: row.name, version: actual, from: row.current })
482
+ } else {
483
+ mismatched.push({ name: row.name, expected: row.target, actual: actual ?? null })
484
+ }
485
+ }
486
+ return { landed, mismatched }
487
+ }
488
+
489
+ /**
490
+ * Merge the landed packages into the override document.
491
+ *
492
+ * An entry is only added when `resolveEffectivePin` — the single authority
493
+ * provisioning also uses — agrees the entry would take effect. That one check
494
+ * covers all the ways an entry is useless: a package outside PLUGIN_SET, a
495
+ * version that is not newer than the shipped pin (stale or downgrade), and a
496
+ * version that does not parse.
497
+ *
498
+ * @returns {{
499
+ * packages: Record<string, unknown>,
500
+ * written: string[],
501
+ * atPin: string[],
502
+ * ineffective: Array<{ name: string, reason: string }>,
503
+ * }}
504
+ */
505
+ function planOverrides({ packages, landed, updatedAt }) {
506
+ const next = { ...packages }
507
+ const written = []
508
+ const atPin = []
509
+ const ineffective = []
510
+
511
+ for (const entry of landed) {
512
+ const shippedPin = SHIPPED_PINS.get(entry.name)
513
+ if (shippedPin !== undefined && entry.version === shippedPin) {
514
+ // The profile is already on the shipped pin: an override would restate
515
+ // it, so the package counts as up to date instead of upgraded.
516
+ atPin.push(entry.name)
517
+ continue
518
+ }
519
+
520
+ const candidate = {
521
+ ...next,
522
+ [entry.name]: { version: entry.version, shippedPin: shippedPin ?? null, updatedAt },
523
+ }
524
+ const effective = resolveEffectivePin({ name: entry.name, shippedPin, overrides: candidate })
525
+ if (effective !== entry.version) {
526
+ ineffective.push({ name: entry.name, version: entry.version, shippedPin: shippedPin ?? null })
527
+ continue
528
+ }
529
+ next[entry.name] = candidate[entry.name]
530
+ written.push(entry.name)
531
+ }
532
+
533
+ return { packages: next, written, atPin, ineffective }
534
+ }
535
+
536
+ /** The rollback's second half: re-add the pre-upgrade specs so node_modules
537
+ * matches the restored manifest again. A failure here is reported with the
538
+ * exact command the user can run by hand. */
539
+ function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
540
+ const specs = originalSpecs({ fs, copies, manifestPath })
541
+ if (specs.length === 0) return
542
+
543
+ const result = run('dsh', pluginAddArgs(specs), { timeout: INSTALL_TIMEOUT_MS, env })
544
+ const status = runStatus(result)
545
+ if (status === 0) {
546
+ log(`restored the previous plugin versions (${specs.length} spec(s))`)
547
+ return
548
+ }
549
+ warn(`could not restore the previous plugin versions (dsh plugin add exit ${status})`)
550
+ warn(`run this by hand to restore them: dsh plugin --profile ${PROFILE} add ${specs.join(' ')}`)
551
+ }
552
+
553
+ /**
554
+ * Phase 4: install every planned plugin upgrade, verify it landed, and record
555
+ * the landed versions in `upgrade-overrides.json`.
556
+ *
557
+ * Outcomes (they map 1:1 to the process exit code, see exitCodeAfterPlugins):
558
+ * - all landed, overrides written or unnecessary -> backup deleted, code 0
559
+ * - install failed -> rollback, backup kept, code 1
560
+ * - install ok, some version did not land -> no rollback, code 3
561
+ * - override write failed -> code 3
562
+ *
563
+ * @param {{
564
+ * profileDir: string, manifestPath: string, overridePath: string,
565
+ * backupDir: string, pluginRows: Array<{name: string, current: string|null, target: string}>,
566
+ * rows: Array<{name: string, action: string}>,
567
+ * counts: {latest: number, excluded: number}, selfName: string|null,
568
+ * env: Record<string, string|undefined>,
569
+ * run: Function, fs: typeof defaultFs,
570
+ * log: (message: string) => void, warn: (message: string) => void,
571
+ * }} ctx
572
+ * @returns {{
573
+ * landed: Array<{name: string, version: string, from: string|null}>,
574
+ * mismatched: Array<{name: string, expected: string, actual: string|null}>,
575
+ * failed: Array<{reason: string, status?: number}>,
576
+ * overridesError?: boolean,
577
+ * upgraded?: number,
578
+ * upToDate?: number,
579
+ * }}
580
+ */
581
+ function applyPluginUpgrades(ctx) {
582
+ const { profileDir, manifestPath, overridePath, backupDir, rows, pluginRows, counts, selfName, env, run, fs, log, warn } =
583
+ ctx
584
+
585
+ if (pluginRows.length === 0) {
586
+ log('plugins: already up to date')
587
+ return { landed: [], mismatched: [], failed: [] }
588
+ }
589
+
590
+ const specs = pluginRows.map((row) => `${row.name}@${row.target}`)
591
+ const copies = createBackup({ fs, profileDir, backupDir })
592
+ log(`backup: ${backupDir}`)
593
+ log(`plugins: installing ${specs.length} package(s)`)
594
+
595
+ const install = installPlugins({ run, env, specs, warn })
596
+ if (install.status !== 0) {
597
+ const tail = tailLines(install.stderr, 10)
598
+ if (tail.length > 0) console.error(tail.join('\n'))
599
+ restoreBackup({ fs, profileDir, overridePath, copies })
600
+ convergeProfile({ fs, run, env, copies, manifestPath, log, warn })
601
+ log(`upgrade failed at plugin install; profile restored from ${backupDir}`)
602
+ log('if the profile still looks wrong, fix it by hand before starting the TUI')
603
+ return { landed: [], mismatched: [], failed: [{ reason: 'install', status: install.status }] }
604
+ }
605
+
606
+ const { landed, mismatched } = verifyPlugins({ fs, profileDir, rows: pluginRows })
607
+ for (const item of mismatched) {
608
+ log(`mismatch: ${item.name} expected ${item.expected}, installed ${item.actual ?? 'nothing'}`)
609
+ }
610
+
611
+ // --- overrides: read, merge, assert, write -------------------------------
612
+ // A file that is not a usable override document is left UNTOUCHED: it may
613
+ // hold hand-edited entries this module would silently drop. Nothing is
614
+ // recorded in that case (the run reports a partial result), and the file is
615
+ // in the backup if the user wants it back.
616
+ const existingText = readText(fs, overridePath)
617
+ const parsed = existingText === undefined ? null : parseOverrides(existingText)
618
+ const unusable = existingText !== undefined && parsed === null
619
+ if (unusable) {
620
+ warn(
621
+ `${overridePath} is not a usable override document; leaving it untouched — fix or delete it and re-run, or the next start will reinstall the shipped pins`,
622
+ )
623
+ }
624
+
625
+ let overridesError = unusable
626
+ let written = []
627
+ let atPin = []
628
+ if (!unusable) {
629
+ const document = parsed ?? { version: 1, packages: {} }
630
+ const updatedAt = new Date().toISOString()
631
+ const plan = planOverrides({ packages: document.packages ?? {}, landed, updatedAt })
632
+ written = plan.written
633
+ atPin = plan.atPin
634
+
635
+ for (const item of plan.ineffective) {
636
+ if (item.shippedPin === null) {
637
+ // The package is not in PLUGIN_SET, so provisioning never installs or
638
+ // converges it: an override would be dead data, not a lost upgrade.
639
+ warn(`${item.name}: not managed by provisioning; no override recorded`)
640
+ continue
641
+ }
642
+ warn(
643
+ `${item.name}: an override at ${item.version} would be ignored by provisioning (shipped pin ${item.shippedPin}); not recorded — the next start will reinstall the shipped pin`,
644
+ )
645
+ }
646
+
647
+ if (written.length > 0) {
648
+ const nextDocument = { ...document, version: document.version ?? 1, updatedAt, packages: plan.packages }
649
+ // Write-then-rename in the SAME directory: a crash mid-write cannot leave
650
+ // a torn upgrade-overrides.json that provisioning would silently ignore.
651
+ const tmpPath = `${overridePath}.tmp`
652
+ try {
653
+ fs.writeFileSync(tmpPath, serializeOverrides(nextDocument), 'utf8')
654
+ fs.renameSync(tmpPath, overridePath)
655
+ log(`wrote ${written.length} override(s) to ${overridePath}`)
656
+ } catch (err) {
657
+ overridesError = true
658
+ warn(`could not write ${overridePath}: ${err?.message ?? err}`)
659
+ warn('the next start may reinstall the shipped pins and downgrade these plugins')
660
+ log(`override write failed; backup kept at ${backupDir}`)
661
+ }
662
+ }
663
+ }
664
+
665
+ // --- summary + exit-code material ---------------------------------------
666
+ // The launcher has its own row and its own report, so it never counts here.
667
+ const latestPlugins = rows.filter(
668
+ (row) => row.action === 'latest' && (selfName === null || row.name !== selfName),
669
+ ).length
670
+ const upgraded = landed.length - atPin.length
671
+ const upToDate = latestPlugins + atPin.length
672
+ log(
673
+ `${upgraded} upgraded, ${upToDate} up to date, ${mismatched.length} mismatched, ${counts.excluded} excluded`,
674
+ )
675
+ log('restart required: exit the TUI and run dsh-opentui again')
676
+
677
+ if (mismatched.length > 0) {
678
+ log(
679
+ 'packages without an override will be reinstalled at the shipped pin on the next start (possible downgrade)',
680
+ )
681
+ }
682
+
683
+ if (mismatched.length === 0 && !overridesError) {
684
+ fs.rmSync(backupDir, { recursive: true, force: true })
685
+ log(`upgraded ${upgraded} plugin(s)`)
686
+ } else {
687
+ log(`backup kept at ${backupDir}`)
688
+ }
689
+
690
+ return { landed, mismatched, failed: [], overridesError, upgraded, upToDate }
691
+ }
692
+
693
+ /**
694
+ * Exit code after the plugin phase (plan §1.3):
695
+ * 1 - the batched install failed and the profile was rolled back;
696
+ * 3 - partially applied: the install exited 0 but a package is not at its
697
+ * target version, or the override file could not be written;
698
+ * 0 - every target is on disk at its planned version.
699
+ */
700
+ function exitCodeAfterPlugins({ pluginResult } = {}) {
701
+ if (!pluginResult) return 0
702
+ if (Array.isArray(pluginResult.failed) && pluginResult.failed.length > 0) return 1
703
+ if (pluginResult.overridesError) return 3
704
+ if (Array.isArray(pluginResult.mismatched) && pluginResult.mismatched.length > 0) return 3
705
+ return 0
706
+ }
707
+
708
+ // ---------------------------------------------------------------------------
709
+ // Entry point
710
+ // ---------------------------------------------------------------------------
711
+
712
+ /**
713
+ * Run the upgrade command and return the process exit code.
714
+ *
715
+ * @param {{
716
+ * dryRun?: boolean, yes?: boolean, tag?: string, noSelf?: boolean,
717
+ * noPlugins?: boolean, resetOverrides?: boolean, help?: boolean,
718
+ * }} [opts]
719
+ * @param {{
720
+ * pkgRoot?: string,
721
+ * env?: Record<string, string | undefined>,
722
+ * run?: (cmd: string, args: string[], options?: { timeout?: number }) =>
723
+ * { status: number, stdout: string, stderr: string },
724
+ * fs?: typeof defaultFs,
725
+ * selfPath?: string,
726
+ * isTTY?: boolean,
727
+ * readLine?: () => string,
728
+ * prompt?: (text: string) => void,
729
+ * }} [context]
730
+ * @returns {number} 0 done / nothing to do / --dry-run / --help,
731
+ * 1 hard failure or an undetermined target version, 2 non-interactive
732
+ * refusal (the bin owns the other usage errors), 3 partially applied
733
+ */
734
+ export function runUpgrade(
735
+ opts = {},
736
+ {
737
+ pkgRoot = defaultPkgRoot(),
738
+ env = process.env,
739
+ run = defaultRun,
740
+ fs = defaultFs,
741
+ selfPath = fileURLToPath(import.meta.url),
742
+ isTTY = Boolean(process.stdin.isTTY),
743
+ readLine = defaultReadLine,
744
+ prompt = defaultPrompt,
745
+ } = {},
746
+ ) {
747
+ if (opts.help) {
748
+ console.log(formatUpgradeUsage())
749
+ return 0
750
+ }
751
+
752
+ const dshHome = env.DSH_HOME || join(homedir(), '.dsh')
753
+ const profileDir = join(dshHome, 'profiles', PROFILE)
754
+ const manifestPath = join(profileDir, 'package.json')
755
+ const overridePath = join(profileDir, OVERRIDE_FILE)
756
+
757
+ // --- --reset-overrides: a terminal action, never a step of the upgrade ---
758
+ if (opts.resetOverrides) {
759
+ if (!fs.existsSync(overridePath)) {
760
+ say('no overrides to reset')
761
+ return 0
762
+ }
763
+ if (opts.dryRun) {
764
+ say(`would remove ${overridePath}`)
765
+ return 0
766
+ }
767
+ fs.rmSync(overridePath, { force: true })
768
+ say(`removed ${overridePath}`)
769
+ warn('next provisioning will restore shipped pins; plugins may be downgraded')
770
+ return 0
771
+ }
772
+
773
+ if (!fs.existsSync(profileDir)) {
774
+ say(`no opentui profile at ${profileDir}; run dsh-opentui once to provision it`)
775
+ return 0
776
+ }
777
+
778
+ // --- 1. Plan (read-only) -------------------------------------------------
779
+ const manifest = readJson(fs, manifestPath)
780
+ if (!isPlainObject(manifest)) {
781
+ warn(`could not read ${manifestPath}; treating the profile as having no plugin dependencies`)
782
+ }
783
+
784
+ const { registry, source } = resolveRegistry({
785
+ env,
786
+ npmrcTexts: collectNpmrcTexts({ fs, dshHome, profileDir, env }),
787
+ })
788
+
789
+ const tag = opts.tag ?? 'latest'
790
+ say(`dsh home ${dshHome} · profile ${PROFILE} · tag ${tag}`)
791
+ say(`registry ${registry} (source: ${source})`)
792
+ if (!isOfficialRegistry(registry)) {
793
+ say(`note: resolved via ${registry}; "${tag}" may lag behind npmjs`)
794
+ }
795
+
796
+ // `deps` keeps the excluded entries too: buildUpgradePlan must report them
797
+ // as `excluded` rather than silently dropping them from the table.
798
+ const deps = {}
799
+ const installedVersions = {}
800
+
801
+ if (!opts.noPlugins) {
802
+ const dependencies = isPlainObject(manifest?.dependencies) ? manifest.dependencies : {}
803
+ for (const [name, spec] of Object.entries(dependencies)) {
804
+ deps[name] = spec
805
+ const installed = readInstalledVersion(fs, profileDir, name)
806
+ if (installed !== undefined) installedVersions[name] = installed
807
+ }
808
+ }
809
+
810
+ const self = opts.noSelf ? null : readSelf(fs, pkgRoot)
811
+ if (self !== null && !Object.prototype.hasOwnProperty.call(deps, self.name)) {
812
+ // The launcher is not a profile dependency; give it a row of its own so
813
+ // "the launcher is already up to date" is visible instead of implied.
814
+ deps[self.name] = self.version
815
+ installedVersions[self.name] = self.version
816
+ }
817
+
818
+ // Excluded entries (`@deepseek-ai/*`, local specs) are never queried: their
819
+ // target is meaningless by definition.
820
+ const latestByPkg = {}
821
+ for (const [name, spec] of Object.entries(deps)) {
822
+ if (!isUpgradableDependency(name, spec)) continue
823
+ const target = queryDistTag({ run, pkg: name, registry, tag })
824
+ if (target !== null) latestByPkg[name] = target
825
+ }
826
+
827
+ const { rows, counts } = buildUpgradePlan({ deps, installedVersions, latestByPkg, tag })
828
+
829
+ console.log(formatPlanTable(rows))
830
+ console.log(
831
+ `${counts.upgrade} to upgrade, ${counts.latest} up to date, ${counts.queryFailed} failed, ${counts.excluded} excluded`,
832
+ )
833
+
834
+ // An undetermined target is not a satisfied package: without a target there
835
+ // is nothing to install, so the run must not claim success — and it writes
836
+ // nothing, --dry-run included.
837
+ if (counts.queryFailed > 0) {
838
+ say(`could not determine target version for ${counts.queryFailed} package(s); nothing changed`)
839
+ return 1
840
+ }
841
+ if (opts.dryRun) return 0
842
+ if (counts.upgrade === 0) {
843
+ // No target needs work: there is nothing to back up and nothing to spawn.
844
+ say(opts.noPlugins ? 'plugins: skipped (--no-plugins)' : 'plugins: already up to date')
845
+ say('nothing to do')
846
+ return 0
847
+ }
848
+
849
+ // --- 2. Confirmation -----------------------------------------------------
850
+ if (!opts.yes) {
851
+ if (env.CI || !isTTY) {
852
+ console.error(`${PREFIX}refusing to run non-interactively; pass --yes`)
853
+ return 2
854
+ }
855
+ prompt('Proceed with upgrade? [y/N] ')
856
+ const answer = String(readLine() ?? '').trim().toLowerCase()
857
+ if (answer !== 'y' && answer !== 'yes') {
858
+ say('aborted')
859
+ return 0
860
+ }
861
+ }
862
+
863
+ // --- 3. Self upgrade -----------------------------------------------------
864
+ const selfRow = self === null ? undefined : rows.find((row) => row.name === self.name)
865
+ let selfResult
866
+ if (opts.noSelf) {
867
+ say('self: skipped (--no-self)')
868
+ selfResult = { kind: 'skipped', form: 'skipped-by-flag' }
869
+ } else {
870
+ selfResult = upgradeSelf({
871
+ self,
872
+ target: selfRow?.target ?? null,
873
+ registry,
874
+ run,
875
+ fs,
876
+ selfPath,
877
+ })
878
+ if (selfResult.kind === 'failed') return selfResult.exitCode
879
+ }
880
+
881
+ // --- 4. Plugins ----------------------------------------------------------
882
+ const pluginRows = rows.filter(
883
+ (row) => row.action === 'upgrade' && (self === null || row.name !== self.name),
884
+ )
885
+
886
+ if (opts.noPlugins) {
887
+ say('plugins: skipped (--no-plugins)')
888
+ return 0
889
+ }
890
+ if (pluginRows.length === 0) {
891
+ say('plugins: already up to date')
892
+ return 0
893
+ }
894
+
895
+ const ctx = {
896
+ // Locations
897
+ dshHome,
898
+ profileDir,
899
+ manifestPath,
900
+ overridePath,
901
+ // Plan
902
+ registry,
903
+ tag,
904
+ rows,
905
+ counts,
906
+ pluginRows,
907
+ installedVersions,
908
+ latestByPkg,
909
+ // Self result
910
+ selfName: self?.name ?? null,
911
+ selfResult,
912
+ // Where the plugin phase writes its backup (created there, not here):
913
+ // $DSH_HOME/profiles/opentui/.upgrade-backup/<UTC stamp>-<pid>/
914
+ backupDir: join(profileDir, BACKUP_DIR_NAME, `${backupStamp()}-${process.pid}`),
915
+ // Injected effects + logging
916
+ env,
917
+ run,
918
+ fs,
919
+ log: say,
920
+ warn,
921
+ }
922
+
923
+ const pluginResult = applyPluginUpgrades(ctx)
924
+ return exitCodeAfterPlugins({ pluginResult })
925
+ }
926
+
927
+ function defaultPkgRoot() {
928
+ return dirname(dirname(fileURLToPath(import.meta.url)))
929
+ }