@aiwayds/dsh-opentui 0.18.1 → 0.18.3

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.
@@ -13,17 +13,19 @@
13
13
  // install form is skipped with a warning — installing into a different
14
14
  // prefix would create a shadow copy that `dsh-opentui` never resolves.
15
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.
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.
21
22
  //
22
23
  // Exit codes: 0 done/nothing to do/dry-run/help; 1 hard failure OR any package
23
24
  // whose target version could not be determined (a query failure means the
24
25
  // 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).
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).
27
29
  //
28
30
  // Dependency injection: every child process goes through `run(cmd, args, {
29
31
  // timeout })` and every file operation through `fs`, both overridable from the
@@ -31,16 +33,20 @@
31
33
  // and abort paths without npm, a TTY, or a real profile.
32
34
  import { execFileSync } from 'node:child_process'
33
35
  import {
36
+ closeSync,
34
37
  copyFileSync,
35
38
  existsSync,
36
39
  mkdirSync,
40
+ openSync,
37
41
  readFileSync,
38
42
  readSync,
39
43
  realpathSync,
40
44
  renameSync,
41
45
  rmdirSync,
42
46
  rmSync,
47
+ statSync,
43
48
  writeFileSync,
49
+ writeSync,
44
50
  } from 'node:fs'
45
51
  import { homedir } from 'node:os'
46
52
  import { dirname, join, resolve, sep } from 'node:path'
@@ -54,6 +60,10 @@ import {
54
60
  resolveEffectivePin,
55
61
  } from './lib/provision-plan.mjs'
56
62
  import {
63
+ NPMRC_DSH_HOME,
64
+ NPMRC_HOME,
65
+ NPMRC_PROFILE,
66
+ buildSelfInstallArgs,
57
67
  buildUpgradePlan,
58
68
  buildViewArgs,
59
69
  isOfficialRegistry,
@@ -73,6 +83,19 @@ const PREFIX_TIMEOUT_MS = 10 * 1000
73
83
  const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
74
84
  const OVERRIDE_FILE = 'upgrade-overrides.json'
75
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: '
76
99
  // pnpm-workspace.yaml belongs here because users hand-write allowBuilds in it:
77
100
  // a host rollback that restored only the manifest and the lock would leave the
78
101
  // rewritten workspace file in place.
@@ -158,6 +181,13 @@ export const defaultFs = {
158
181
  rmdirSync: (path) => rmdirSync(path),
159
182
  copyFileSync: (from, to) => copyFileSync(from, to),
160
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),
161
191
  }
162
192
 
163
193
  /** A synchronous one-line read from stdin (the confirmation prompt). */
@@ -217,19 +247,25 @@ function readText(fs, path) {
217
247
  }
218
248
 
219
249
  /**
220
- * npmrc texts, least specific first (resolveRegistry lets the LAST text win).
221
- * Only files that exist are passed, so a missing file cannot shadow a present
222
- * one: profile/.npmrc > $DSH_HOME/.npmrc > ~/.npmrc.
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.
223
255
  */
224
- function collectNpmrcTexts({ fs, dshHome, profileDir, env }) {
256
+ function collectNpmrcFiles({ fs, dshHome, profileDir, env }) {
225
257
  const home = env.HOME || homedir()
226
- const paths = [join(home, '.npmrc'), join(dshHome, '.npmrc'), join(profileDir, '.npmrc')]
227
- const texts = []
228
- for (const path of paths) {
229
- const text = readText(fs, path)
230
- if (text !== undefined) texts.push(text)
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 })
231
267
  }
232
- return texts
268
+ return files
233
269
  }
234
270
 
235
271
  /** The version on disk for a profile dependency, when readable. */
@@ -305,6 +341,110 @@ function backupStamp(now = new Date()) {
305
341
  return now.toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
306
342
  }
307
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
+
308
448
  // ---------------------------------------------------------------------------
309
449
  // Phase: self upgrade
310
450
  // ---------------------------------------------------------------------------
@@ -313,12 +453,21 @@ function backupStamp(now = new Date()) {
313
453
  * Bring the launcher itself up to `target`, but only when the running copy is
314
454
  * the one the npm global prefix owns.
315
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
316
465
  * @returns {{ kind: 'skipped', form: string } |
317
466
  * { kind: 'latest', version: string } |
318
467
  * { kind: 'upgraded', from: string, to: string } |
319
468
  * { kind: 'failed', exitCode: 1 }}
320
469
  */
321
- function upgradeSelf({ self, target, registry, run, fs, selfPath }) {
470
+ function upgradeSelf({ self, target, registry, registryPath, run, fs, selfPath }) {
322
471
  if (!self || typeof target !== 'string' || target === '') {
323
472
  say('self: skipped (install form: unknown)')
324
473
  warn(
@@ -354,7 +503,13 @@ function upgradeSelf({ self, target, registry, run, fs, selfPath }) {
354
503
  return { kind: 'latest', version: self.version }
355
504
  }
356
505
 
357
- const install = run('npm', ['i', '-g', `${self.name}@${target}`, '--registry', registry], {
506
+ const installArgs = buildSelfInstallArgs({
507
+ pkg: self.name,
508
+ target,
509
+ registry,
510
+ sourcePath: registryPath,
511
+ })
512
+ const install = run('npm', installArgs, {
358
513
  timeout: INSTALL_TIMEOUT_MS,
359
514
  })
360
515
  if (!install || install.status !== 0) {
@@ -470,13 +625,17 @@ function originalSpecs({ fs, copies, manifestPath }) {
470
625
  * One batched install. A host that rejects `--save-exact` gets exactly one
471
626
  * retry without it; every other failure is final (no per-package retry).
472
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
+ *
473
632
  * @returns {{ status: number, args: string[], stderr: string }}
474
633
  */
475
634
  function installPlugins({ run, env, specs, warn }) {
476
635
  let args = pluginAddArgs(specs)
477
636
  let result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
478
637
  let status = runStatus(result)
479
- if (status === 0) return { status, args, stderr: '' }
638
+ if (status === 0) return { status, args, stderr: String(result?.stderr ?? '') }
480
639
 
481
640
  const stderr = String(result?.stderr ?? '')
482
641
  if (SAVE_EXACT_REJECTED.test(stderr)) {
@@ -484,7 +643,7 @@ function installPlugins({ run, env, specs, warn }) {
484
643
  args = pluginAddArgs(specs, { saveExact: false })
485
644
  result = run('dsh', args, { timeout: INSTALL_TIMEOUT_MS, env })
486
645
  status = runStatus(result)
487
- if (status === 0) return { status, args, stderr: '' }
646
+ if (status === 0) return { status, args, stderr: String(result?.stderr ?? '') }
488
647
  }
489
648
  return { status, args, stderr }
490
649
  }
@@ -569,15 +728,52 @@ function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
569
728
  }
570
729
 
571
730
  /**
572
- * Phase 4: install every planned plugin upgrade, verify it landed, and record
573
- * the landed versions in `upgrade-overrides.json`.
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.
574
738
  *
575
739
  * Outcomes (they map 1:1 to the process exit code, see exitCodeAfterPlugins):
740
+ * - another upgrade holds the lock -> nothing written, code 2
576
741
  * - all landed, overrides written or unnecessary -> backup deleted, code 0
577
742
  * - install failed -> rollback, backup kept, code 1
578
743
  * - install ok, some version did not land -> no rollback, code 3
579
744
  * - override write failed -> code 3
580
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
+ *
581
777
  * @param {{
582
778
  * profileDir: string, manifestPath: string, overridePath: string,
583
779
  * backupDir: string, pluginRows: Array<{name: string, current: string|null, target: string}>,
@@ -596,15 +792,10 @@ function convergeProfile({ fs, run, env, copies, manifestPath, log, warn }) {
596
792
  * upToDate?: number,
597
793
  * }}
598
794
  */
599
- function applyPluginUpgrades(ctx) {
795
+ function installPluginUpgrades(ctx) {
600
796
  const { profileDir, manifestPath, overridePath, backupDir, rows, pluginRows, counts, selfName, env, run, fs, log, warn } =
601
797
  ctx
602
798
 
603
- if (pluginRows.length === 0) {
604
- log('plugins: already up to date')
605
- return { landed: [], mismatched: [], failed: [] }
606
- }
607
-
608
799
  const specs = pluginRows.map((row) => `${row.name}@${row.target}`)
609
800
  const copies = createBackup({ fs, profileDir, backupDir })
610
801
  log(`backup: ${backupDir}`)
@@ -621,6 +812,13 @@ function applyPluginUpgrades(ctx) {
621
812
  return { landed: [], mismatched: [], failed: [{ reason: 'install', status: install.status }] }
622
813
  }
623
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
+
624
822
  const { landed, mismatched } = verifyPlugins({ fs, profileDir, rows: pluginRows })
625
823
  for (const item of mismatched) {
626
824
  log(`mismatch: ${item.name} expected ${item.expected}, installed ${item.actual ?? 'nothing'}`)
@@ -710,6 +908,7 @@ function applyPluginUpgrades(ctx) {
710
908
 
711
909
  /**
712
910
  * Exit code after the plugin phase (plan §1.3):
911
+ * 2 - another upgrade holds `<profile>/.upgrade.lock`; nothing was written;
713
912
  * 1 - the batched install failed and the profile was rolled back;
714
913
  * 3 - partially applied: the install exited 0 but a package is not at its
715
914
  * target version, or the override file could not be written;
@@ -717,6 +916,7 @@ function applyPluginUpgrades(ctx) {
717
916
  */
718
917
  function exitCodeAfterPlugins({ pluginResult } = {}) {
719
918
  if (!pluginResult) return 0
919
+ if (pluginResult.lockBusy) return 2
720
920
  if (Array.isArray(pluginResult.failed) && pluginResult.failed.length > 0) return 1
721
921
  if (pluginResult.overridesError) return 3
722
922
  if (Array.isArray(pluginResult.mismatched) && pluginResult.mismatched.length > 0) return 3
@@ -747,7 +947,8 @@ function exitCodeAfterPlugins({ pluginResult } = {}) {
747
947
  * }} [context]
748
948
  * @returns {number} 0 done / nothing to do / --dry-run / --help,
749
949
  * 1 hard failure or an undetermined target version, 2 non-interactive
750
- * refusal (the bin owns the other usage errors), 3 partially applied
950
+ * refusal or another upgrade holding the profile lock (the bin owns the
951
+ * other usage errors), 3 partially applied
751
952
  */
752
953
  export function runUpgrade(
753
954
  opts = {},
@@ -799,9 +1000,9 @@ export function runUpgrade(
799
1000
  warn(`could not read ${manifestPath}; treating the profile as having no plugin dependencies`)
800
1001
  }
801
1002
 
802
- const { registry, source } = resolveRegistry({
1003
+ const { registry, source, sourcePath } = resolveRegistry({
803
1004
  env,
804
- npmrcTexts: collectNpmrcTexts({ fs, dshHome, profileDir, env }),
1005
+ npmrcFiles: collectNpmrcFiles({ fs, dshHome, profileDir, env }),
805
1006
  })
806
1007
 
807
1008
  const tag = opts.tag ?? 'latest'
@@ -889,6 +1090,7 @@ export function runUpgrade(
889
1090
  self,
890
1091
  target: selfRow?.target ?? null,
891
1092
  registry,
1093
+ registryPath: sourcePath,
892
1094
  run,
893
1095
  fs,
894
1096
  selfPath,