@aiwayds/dsh-opentui 0.17.3 → 0.18.1

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.
@@ -43,7 +43,8 @@
43
43
  // Idempotency contract (step 3): a plugin needs no work only when
44
44
  // (a) it is in the profile `dependencies`,
45
45
  // (b) `node_modules/<pkg>/package.json` exists and its version satisfies the
46
- // pinned version, and
46
+ // effective pin — the shipped pin, or the newer version recorded in
47
+ // `upgrade-overrides.json` by `dsh-opentui upgrade` — and
47
48
  // (c) its name is in `dsh.profile.bundles`.
48
49
  // A dep pinned with a local spec (link:/file:/workspace:) always counts as
49
50
  // satisfied — a local development pin is never replaced by a registry version.
@@ -89,6 +90,7 @@ import {
89
90
  orderPluginAddFailures,
90
91
  parseDumpConfig,
91
92
  parseTier,
93
+ partitionInstallByRetryState,
92
94
  planMcpPatch,
93
95
  planOrphanPatchCleanup,
94
96
  planPluginInstall,
@@ -97,7 +99,14 @@ import {
97
99
  pluginAddCommand,
98
100
  pluginAddRetryDecision,
99
101
  selectPlugins,
102
+ verifyInstalledPins,
100
103
  } from './lib/provision-plan.mjs'
104
+ import {
105
+ emptyState,
106
+ parseState,
107
+ recordInstallOutcomes,
108
+ serializeState,
109
+ } from './lib/provision-state.mjs'
101
110
 
102
111
  const TEMPLATE = 'web'
103
112
  const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
@@ -146,6 +155,12 @@ function fail(message, detail = '') {
146
155
  const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
147
156
  const profileDir = join(dshHome, 'profiles', PROFILE)
148
157
  const manifestPath = join(profileDir, 'package.json')
158
+ // Written by `dsh-opentui upgrade` (never by this script): the versions that
159
+ // command installed above the shipped pins. Read-only here.
160
+ const overridePath = join(profileDir, 'upgrade-overrides.json')
161
+ // Cross-launch failure memory (see lib/provision-state.mjs). Sits next to
162
+ // `.plugin-manager/`, so it travels with the profile and nowhere else.
163
+ const statePath = join(profileDir, '.provision-state.json')
149
164
  console.log(`${PREFIX}dsh home ${dshHome}`)
150
165
 
151
166
  const requireDsh = () => {
@@ -211,6 +226,81 @@ function installedVersion(name) {
211
226
  }
212
227
  }
213
228
 
229
+ /** The `packages` map of `upgrade-overrides.json`, or {} when the file is
230
+ * absent, unreadable, not JSON, or not the documented shape. Every failure
231
+ * degrades to "no overrides", which keeps a damaged side file from changing
232
+ * (or interrupting) provisioning in any way. A MISSING file is the normal
233
+ * path and stays silent; a present-but-unusable one is worth a warning,
234
+ * because silently reverting to the shipped pins can downgrade plugins. */
235
+ function readUpgradeOverrides() {
236
+ if (!existsSync(overridePath)) return {}
237
+ let parsed
238
+ try {
239
+ parsed = JSON.parse(readFileSync(overridePath, 'utf8'))
240
+ } catch {
241
+ console.error(
242
+ `${PREFIX}warning: ignoring upgrade overrides; shipped pins will be used (${overridePath} is unreadable or not valid JSON)`,
243
+ )
244
+ return {}
245
+ }
246
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
247
+ console.error(
248
+ `${PREFIX}warning: ignoring upgrade overrides; shipped pins will be used (${overridePath} is not a JSON object)`,
249
+ )
250
+ return {}
251
+ }
252
+ const packages = parsed.packages
253
+ if (typeof packages !== 'object' || packages === null || Array.isArray(packages)) {
254
+ console.error(
255
+ `${PREFIX}warning: ignoring upgrade overrides; shipped pins will be used (${overridePath} has no "packages" object)`,
256
+ )
257
+ return {}
258
+ }
259
+ return packages
260
+ }
261
+
262
+ /** The failure memory of previous launches. A missing file is the normal
263
+ * first-run path; an unreadable one degrades to "no memory" (everything is
264
+ * retried) and is NOT reported: the file is an optimisation, and a warning
265
+ * on every start would be noise the user cannot act on. The raw text is
266
+ * returned too, so the caller can skip a write when nothing changed. */
267
+ function readProvisionState() {
268
+ let text = ''
269
+ try {
270
+ text = readFileSync(statePath, 'utf8')
271
+ } catch {
272
+ return { state: emptyState(), text: '' }
273
+ }
274
+ return { state: parseState(text) ?? emptyState(), text }
275
+ }
276
+
277
+ /** Persist the failure memory only when it changed. Same-directory temp then
278
+ * rename: a crash mid-write cannot leave a torn JSON document that the next
279
+ * start would silently ignore. A write failure is a WARN, never a failed
280
+ * provisioning run — the state file only ever removes retries. */
281
+ function writeProvisionState(state, previousText) {
282
+ const text = serializeState(state)
283
+ if (text === previousText) return false
284
+ try {
285
+ mkdirSync(profileDir, { recursive: true })
286
+ const tmpPath = `${statePath}.tmp`
287
+ writeFileSync(tmpPath, text)
288
+ renameSync(tmpPath, statePath)
289
+ return true
290
+ } catch (err) {
291
+ warn(`could not write ${statePath}: ${err?.message ?? err}`)
292
+ return false
293
+ }
294
+ }
295
+
296
+ /** Last non-empty stderr line, flattened to the state file's single-line
297
+ * budget. `dsh plugin add` puts pnpm's error code on that line. */
298
+ function lastStderrLine(stderr) {
299
+ const text = typeof stderr === 'string' ? stderr : stderr?.toString() ?? ''
300
+ const lines = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== '')
301
+ return lines.length > 0 ? lines[lines.length - 1].slice(-200) : ''
302
+ }
303
+
214
304
  /** Backup-then-write the profile manifest (the backup is the contract: a
215
305
  * failed run never leaves the user without their previous manifest). */
216
306
  function writeManifest(manifest) {
@@ -386,7 +476,6 @@ function pauseSync(ms) {
386
476
  }
387
477
 
388
478
  const failedInstalls = [] // { spec, failure: { kind, code, hint } }
389
- let installedCount = 0
390
479
 
391
480
  if (tier === 'none') {
392
481
  say(3, 'plugins', 'skipped (--plugins=none)')
@@ -397,24 +486,92 @@ if (tier === 'none') {
397
486
  const installedVersions = Object.fromEntries(
398
487
  plugins.map((plugin) => [plugin.name, installedVersion(plugin.name)]),
399
488
  )
400
- const plan = planPluginInstall({ tier, dependencies, bundles, installedVersions })
401
- const specs = plan.install.map((entry) => entry.spec)
402
- const skipped = plan.total - plan.install.length
489
+ // A version recorded by `dsh-opentui upgrade` raises the effective pin, so an
490
+ // already-upgraded plugin is satisfied at that version instead of being
491
+ // pulled back to the shipped pin on every start.
492
+ const overrides = readUpgradeOverrides()
493
+ const plan = planPluginInstall({ tier, dependencies, bundles, installedVersions, overrides })
494
+ // Failure memory: what previous launches learned about these pins. The file
495
+ // only ever REMOVES retries (see lib/provision-state.mjs); a missing or
496
+ // unreadable one is read as "no memory", silently.
497
+ const { state: retryState, text: stateText } = readProvisionState()
498
+ // The launch time decides which pins are inside their backoff window. It is
499
+ // NOT the failure timestamp: that one is taken when the installs finish (see
500
+ // recordInstallOutcomes below), so a long failing batch still buys the full
501
+ // backoff window.
502
+ const launchIso = new Date().toISOString()
503
+ const { install: targets, skips } = partitionInstallByRetryState({
504
+ install: plan.install,
505
+ state: retryState,
506
+ now: launchIso,
507
+ })
508
+ const specs = targets.map((entry) => entry.spec)
509
+ const satisfied = plan.total - plan.install.length
510
+ const skipped = satisfied + skips.length
511
+ let nextState = retryState
512
+
513
+ if (skips.length > 0) {
514
+ const detail = skips
515
+ .map((row) => `${row.name}@${row.pin} (${row.attempts} attempt${row.attempts === 1 ? '' : 's'}, since ${row.lastFailedAt})`)
516
+ .join(', ')
517
+ console.error(
518
+ `${PREFIX}skipping ${skips.length} package(s) after repeated failures: ${detail}` +
519
+ ` (retry in 24h, or rm ${statePath} to retry now)`,
520
+ )
521
+ }
403
522
 
404
523
  if (plan.install.length === 0) {
405
524
  say(3, 'plugins', `already satisfied (${plan.total}/${plan.total})`)
406
525
  } else if (dryRun) {
407
- say(3, 'plugins', `found ${skipped}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
408
- say(3, 'plugins', `dry run: skipped the install (${skipped} already satisfied)`)
526
+ if (specs.length === 0) {
527
+ say(3, 'plugins', `found ${satisfied}/${plan.total}, installing 0… (${skips.length} in failure backoff)`)
528
+ } else {
529
+ say(3, 'plugins', `found ${satisfied}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
530
+ }
531
+ say(3, 'plugins', `dry run: skipped the install (${satisfied} already satisfied)`)
532
+ } else if (specs.length === 0) {
533
+ // Every unsatisfied pin is inside its backoff window: spawn nothing.
534
+ say(3, 'plugins', `installed 0, skipped ${skipped} (${skips.length} in failure backoff)`)
409
535
  } else {
410
536
  requireDsh()
411
- say(3, 'plugins', `found ${skipped}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
412
- const batch = runPluginAdd(specs)
537
+ say(3, 'plugins', `found ${satisfied}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
538
+ // name -> { ok, error }: the final word on each target, recorded ONCE at
539
+ // the end of the run so the batch set and the single-spec fallback cannot
540
+ // double-count one launch.
541
+ const outcomes = new Map()
542
+ let degraded = 0
543
+ // Captured so the batch's last stderr line can be stored as the failure
544
+ // reason; the text is echoed below, so nothing the user used to see on the
545
+ // terminal is lost.
546
+ const batch = runPluginAdd(specs, { captureStderr: true })
413
547
  if (!batch.error && batch.status === 0) {
414
- installedCount = specs.length
548
+ // Readback: compare what actually landed with the EFFECTIVE pin (the
549
+ // shipped pin, or the newer version an override raises it to). A batch
550
+ // that exits 0 is not proof that the profile is at the pinned version.
551
+ const landed = Object.fromEntries(targets.map((entry) => [entry.name, installedVersion(entry.name)]))
552
+ for (const result of verifyInstalledPins({ install: targets, installedVersions: landed })) {
553
+ if (result.ok) outcomes.set(result.name, { ok: true })
554
+ else {
555
+ outcomes.set(result.name, {
556
+ ok: false,
557
+ error: `installed ${result.installed ?? 'nothing'}, expected ${result.pin}`,
558
+ })
559
+ }
560
+ }
415
561
  } else {
416
- if (batch.error) warn(`plugin install failed to start: ${batch.error.message}`)
417
- else warn(`plugin install exited ${batch.status}`)
562
+ if (batch.error) {
563
+ warn(`plugin install failed to start: ${batch.error.message}`)
564
+ } else {
565
+ echoCapturedStderr(batch.stderr)
566
+ warn(`plugin install exited ${batch.status}`)
567
+ }
568
+ // The whole batch failed, so every target is a failure until its own
569
+ // fallback attempt proves otherwise. `batchError` is the last stderr
570
+ // line (pnpm's error code), which the summary below must not hide.
571
+ const batchError =
572
+ lastStderrLine(batch.stderr) ||
573
+ (batch.error ? batch.error.message : `dsh plugin add exited ${batch.status}`)
574
+ for (const entry of targets) outcomes.set(entry.name, { ok: false, error: batchError })
418
575
  if (approvePrintedBuilds(plugins.map((plugin) => plugin.name))) {
419
576
  say(3, 'plugins', 'approved the printed build scripts (pnpm allowBuilds) — retrying one by one…')
420
577
  }
@@ -426,30 +583,67 @@ if (tier === 'none') {
426
583
  // cannot fix it, so the spec gives up on the first hit. The terminal
427
584
  // failure stays a WARN + failedInstalls entry — never a silent pass
428
585
  // (the e2e npm-install boot leg asserts the delivered set).
429
- for (const spec of specs) {
586
+ for (const entry of targets) {
430
587
  let installed = false
431
588
  for (let attempt = 1; attempt <= PLUGIN_ADD_ATTEMPTS && !installed; attempt += 1) {
432
589
  if (attempt > 1) {
433
- say(3, 'plugins', `${spec} failed — retry ${attempt - 1}/${PLUGIN_ADD_ATTEMPTS - 1} in ${PLUGIN_ADD_BACKOFF_MS / 1000}s…`)
590
+ say(3, 'plugins', `${entry.spec} failed — retry ${attempt - 1}/${PLUGIN_ADD_ATTEMPTS - 1} in ${PLUGIN_ADD_BACKOFF_MS / 1000}s…`)
434
591
  pauseSync(PLUGIN_ADD_BACKOFF_MS)
435
592
  }
436
- const retry = runPluginAdd([spec], { captureStderr: true })
593
+ const retry = runPluginAdd([entry.spec], { captureStderr: true })
437
594
  echoCapturedStderr(retry.stderr)
438
595
  const decision = pluginAddRetryDecision(retry, { attempt, attempts: PLUGIN_ADD_ATTEMPTS })
439
596
  if (decision.action === 'installed') {
440
- installedCount += 1
441
597
  installed = true
598
+ // A fallback success still lands at whatever the registry served:
599
+ // verify it rather than trusting the exit code.
600
+ const actual = installedVersion(entry.name)
601
+ if (actual === entry.pin) outcomes.set(entry.name, { ok: true })
602
+ else {
603
+ outcomes.set(entry.name, {
604
+ ok: false,
605
+ error: `installed ${actual ?? 'nothing'}, expected ${entry.pin}`,
606
+ })
607
+ }
442
608
  } else if (decision.action === 'failed') {
443
609
  const detail = retry.error ? retry.error.message : `(exit ${retry.status})`
444
- failedInstalls.push({ spec, failure: decision.failure, detail })
610
+ failedInstalls.push({ spec: entry.spec, failure: decision.failure, detail })
611
+ outcomes.set(entry.name, { ok: false, error: lastStderrLine(retry.stderr) || detail })
445
612
  if (decision.failure.kind === 'deterministic') {
446
- say(3, 'plugins', `${spec}: ${decision.failure.code} — deterministic, not retrying`)
613
+ say(3, 'plugins', `${entry.spec}: ${decision.failure.code} — deterministic, not retrying`)
447
614
  }
448
615
  break
449
616
  }
450
617
  }
451
618
  }
452
619
  }
620
+ // One write per run: success clears the entry, failure grows it (or starts
621
+ // a fresh 24-hour round once the pin has been failing that long). The
622
+ // timestamp is taken HERE, after the last install returned, and shared by
623
+ // the whole batch: the backoff window is measured from the failure, not
624
+ // from process start (a 9-minute failing batch would otherwise leave 1
625
+ // minute of the 10-minute window).
626
+ const recorded = recordInstallOutcomes({
627
+ state: nextState,
628
+ now: new Date().toISOString(),
629
+ rows: targets.map((entry) => {
630
+ const outcome = outcomes.get(entry.name)
631
+ return {
632
+ name: entry.name,
633
+ pin: entry.pin,
634
+ ok: outcome?.ok === true,
635
+ error: outcome?.error ?? 'install did not complete',
636
+ }
637
+ }),
638
+ })
639
+ nextState = recorded.state
640
+ degraded += recorded.failed.length
641
+ // Only a real change is persisted: a clean successful run must not create
642
+ // an empty state file, and a damaged one is left alone until a failure or
643
+ // a success actually rewrites the memory.
644
+ if (serializeState(nextState) !== serializeState(retryState)) {
645
+ writeProvisionState(nextState, stateText)
646
+ }
453
647
  // Summary: deterministic failures first, each with its one-line fix; the
454
648
  // retried-then-failed ones follow without a hint.
455
649
  for (const { spec, failure, detail } of orderPluginAddFailures(failedInstalls)) {
@@ -458,8 +652,33 @@ if (tier === 'none') {
458
652
  ` — continuing${failure.hint ? ` — ${failure.hint}` : ''}`,
459
653
  )
460
654
  }
461
- const failedSuffix = failedInstalls.length > 0 ? `, failed ${failedInstalls.length}` : ''
462
- say(3, 'plugins', `installed ${installedCount}, skipped ${skipped}${failedSuffix}`)
655
+ // The summary counts VERIFIED packages, not attempts: a batch that exited 0
656
+ // while leaving a package at another version must not read as a full
657
+ // install next to the degraded line below. Skips (already satisfied, or
658
+ // held back by the failure backoff) and the not-at-pin packages are named
659
+ // separately; the attempt count is the denominator.
660
+ const verified = targets.reduce((count, entry) => (outcomes.get(entry.name)?.ok === true ? count + 1 : count), 0)
661
+ const hardFailed = failedInstalls.length
662
+ const notAtPin = Math.max(0, degraded - hardFailed)
663
+ if (degraded === 0 && skips.length === 0) {
664
+ say(3, 'plugins', `installed ${verified}, skipped ${skipped}`)
665
+ } else {
666
+ const parts = []
667
+ if (satisfied > 0) parts.push(`${satisfied} already installed`)
668
+ if (skips.length > 0) parts.push(`${skips.length} in failure backoff`)
669
+ if (notAtPin > 0) parts.push(`${notAtPin} not at the pinned version`)
670
+ if (hardFailed > 0) parts.push(`${hardFailed} failed`)
671
+ say(3, 'plugins', `installed ${verified} of ${plan.install.length} (${parts.join(', ')})`)
672
+ }
673
+ // The launcher must still start (exit code stays 0), but a version the pin
674
+ // did not reach is not silence: the next start skips this pin and the user
675
+ // needs to know why.
676
+ if (degraded > 0) {
677
+ console.error(
678
+ `${PREFIX}degraded — ${degraded} plugin(s) not at the pinned version; see the lines above` +
679
+ ` (plugins stay on their installed versions; run "dsh-opentui upgrade" after the registry catches up)`,
680
+ )
681
+ }
463
682
  }
464
683
  }
465
684