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