@aiwayds/dsh-opentui 0.18.0 → 0.18.2

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.
@@ -16,6 +16,14 @@ import { compareVersions, parseVersion, resolveEffectivePin } from './provision-
16
16
 
17
17
  export const OFFICIAL_REGISTRY = 'https://registry.npmjs.org'
18
18
 
19
+ // Identities of the .npmrc files the upgrade command reads, least specific
20
+ // first. They are labels, not paths: the caller turns them into real paths and
21
+ // keeps them in the resolved registry so the install rule can tell npm's own
22
+ // file (~/.npmrc) from the ones npm never reads.
23
+ export const NPMRC_HOME = '~/.npmrc'
24
+ export const NPMRC_DSH_HOME = '$DSH_HOME/.npmrc'
25
+ export const NPMRC_PROFILE = '<profile>/.npmrc'
26
+
19
27
  // ---------------------------------------------------------------------------
20
28
  // Registry resolution
21
29
  // ---------------------------------------------------------------------------
@@ -36,19 +44,23 @@ function stripTrailingSlashes(value) {
36
44
  return String(value).replace(/\/+$/, '')
37
45
  }
38
46
 
39
- /** Last `registry=` line across all texts wins: later files override earlier
47
+ /** Last `registry=` line across all files wins: later files override earlier
40
48
  * ones, and inside one file the last assignment wins, which is how npm's
41
- * own config layering behaves. */
42
- function registryFromNpmrcTexts(npmrcTexts) {
43
- let found = ''
44
- for (const text of npmrcTexts) {
45
- if (typeof text !== 'string') continue
46
- for (const line of text.split(/\r?\n/)) {
49
+ * own config layering behaves. Returns the value together with the identity
50
+ * of the file it came from, so the install rule can tell npm's own file from
51
+ * the ones npm never reads. */
52
+ function registryFromNpmrcFiles(npmrcFiles) {
53
+ let found = null
54
+ for (const file of npmrcFiles) {
55
+ if (typeof file?.text !== 'string') continue
56
+ let value = ''
57
+ for (const line of file.text.split(/\r?\n/)) {
47
58
  const match = /^\s*registry\s*=\s*(.+)$/i.exec(line)
48
59
  if (!match) continue
49
- const value = cleanRegistryValue(match[1])
50
- if (value) found = value
60
+ const parsed = cleanRegistryValue(match[1])
61
+ if (parsed) value = parsed
51
62
  }
63
+ if (value) found = { registry: value, path: file.path }
52
64
  }
53
65
  return found
54
66
  }
@@ -57,25 +69,57 @@ function registryFromNpmrcTexts(npmrcTexts) {
57
69
  * Where the `npm view` query should go.
58
70
  *
59
71
  * Priority: DSH_UPGRADE_REGISTRY (explicit operator override) -> the npmrc
60
- * texts the caller read, last one winning -> the public registry.
72
+ * files the caller read, last one winning -> the public registry.
61
73
  *
62
- * `npmrcTexts` is a list of file *contents*, not paths: this module does no
63
- * IO, and the caller decides which files apply (user, global, profile).
64
- * The returned registry never ends with `/` so argv and string comparisons
65
- * stay canonical.
74
+ * `npmrcFiles` is a list of `{ path, text }` where `path` names the file
75
+ * (`~/.npmrc`, `$DSH_HOME/.npmrc`, `<profile>/.npmrc`): this module does no
76
+ * IO, and the caller decides which files apply (user, DSH home, profile).
77
+ * `sourcePath` is that identity (or `env` / `default`); `source` stays the
78
+ * coarse bucket callers already print. The returned registry never ends with
79
+ * `/` so argv and string comparisons stay canonical.
66
80
  *
67
- * @param {{ env?: Record<string, string|undefined>, npmrcTexts?: string[] }} [input]
68
- * @returns {{ registry: string, source: 'env'|'npmrc'|'default' }}
81
+ * @param {{ env?: Record<string, string|undefined>,
82
+ * npmrcFiles?: Array<{ path: string, text: string }> }} [input]
83
+ * @returns {{ registry: string, source: 'env'|'npmrc'|'default', sourcePath: string }}
69
84
  */
70
- export function resolveRegistry({ env = {}, npmrcTexts = [] } = {}) {
85
+ export function resolveRegistry({ env = {}, npmrcFiles = [] } = {}) {
71
86
  const rawEnv = env && typeof env === 'object' ? env.DSH_UPGRADE_REGISTRY : undefined
72
87
  const fromEnv = typeof rawEnv === 'string' ? stripTrailingSlashes(cleanRegistryValue(rawEnv)) : ''
73
- if (fromEnv) return { registry: fromEnv, source: 'env' }
88
+ if (fromEnv) return { registry: fromEnv, source: 'env', sourcePath: 'env' }
89
+
90
+ const fromNpmrc = registryFromNpmrcFiles(Array.isArray(npmrcFiles) ? npmrcFiles : [])
91
+ if (fromNpmrc) {
92
+ const registry = stripTrailingSlashes(fromNpmrc.registry)
93
+ // An unnamed text cannot be attributed to npm's own file, so it is
94
+ // forwarded explicitly: over-specifying is harmless, under-specifying
95
+ // sends the install to a different registry than the query used.
96
+ const named = typeof fromNpmrc.path === 'string' && fromNpmrc.path !== ''
97
+ const sourcePath = named ? fromNpmrc.path : 'npmrc'
98
+ return { registry, source: 'npmrc', sourcePath }
99
+ }
74
100
 
75
- const fromNpmrc = stripTrailingSlashes(registryFromNpmrcTexts(Array.isArray(npmrcTexts) ? npmrcTexts : []))
76
- if (fromNpmrc) return { registry: fromNpmrc, source: 'npmrc' }
101
+ return { registry: OFFICIAL_REGISTRY, source: 'default', sourcePath: 'default' }
102
+ }
77
103
 
78
- return { registry: OFFICIAL_REGISTRY, source: 'default' }
104
+ /**
105
+ * argv for `npm i -g <pkg>@<target>`.
106
+ *
107
+ * npm reads `~/.npmrc` (plus the project and global files) itself, so a
108
+ * registry that came from there is already what this install resolves: passing
109
+ * it again would only override per-scope / per-package configuration the user
110
+ * wrote. Every other source is invisible to npm — `DSH_UPGRADE_REGISTRY` is
111
+ * this command's own variable, and `$DSH_HOME/.npmrc` / `<profile>/.npmrc` are
112
+ * files npm never looks at — so the install must be told explicitly, or the
113
+ * version query hits the mirror while the install goes to the default
114
+ * registry.
115
+ *
116
+ * @param {{ pkg: string, target: string, registry: string, sourcePath: string }} input
117
+ * @returns {string[]}
118
+ */
119
+ export function buildSelfInstallArgs({ pkg, target, registry, sourcePath } = {}) {
120
+ const args = ['i', '-g', `${pkg}@${target}`]
121
+ if (sourcePath !== NPMRC_HOME) args.push('--registry', registry)
122
+ return args
79
123
  }
80
124
 
81
125
  /**
@@ -268,11 +312,18 @@ function entryVersion(entry) {
268
312
 
269
313
  /** The name -> entry map of an override document. Both shapes are accepted
270
314
  * because the reader that feeds provisioning returns the inner map while the
271
- * command works with the whole document; `packages` wins when both exist. */
315
+ * command works with the whole document; `packages` wins when both exist.
316
+ * Entries parseOverrides could not interpret are carried in `raw` and are
317
+ * folded back in here: to a pin decision they are simply entries that lose
318
+ * (invalid), which is exactly what this map represented before `raw` existed. */
272
319
  function overridePackageMap(overrides) {
273
320
  if (!isPlainObject(overrides)) return {}
274
- if (isPlainObject(overrides.packages)) return overrides.packages
275
- return overrides
321
+ if (!isPlainObject(overrides.packages)) return overrides
322
+ const packages = overrides.packages
323
+ if (!isPlainObject(overrides.raw)) return packages
324
+ const merged = { ...overrides.raw }
325
+ for (const [name, entry] of Object.entries(packages)) merged[name] = entry
326
+ return merged
276
327
  }
277
328
 
278
329
  /**
@@ -280,16 +331,25 @@ function overridePackageMap(overrides) {
280
331
  * is unusable (bad JSON, not an object, no usable `packages` object) — the
281
332
  * caller maps null to "no overrides", never to an error.
282
333
  *
283
- * A single malformed entry (no version string) is dropped instead of failing
284
- * the file: one hand-edit typo must not silently disable the other pins.
285
- * Surviving entries keep their shape — a string stays a string, an object keeps
286
- * its metadata (`shippedPin`, `updatedAt`) — so a read/serialize round trip
287
- * does not destroy fields this module does not interpret. Neither `version`
288
- * nor the entry's semver validity is enforced here (pickEffectivePin judges
289
- * validity, so a bad version can still be reported and cleaned up).
334
+ * A single malformed entry (no version string) does not fail the file, and it
335
+ * is NOT dropped either: it lands in `raw` verbatim. The command rewrites the
336
+ * whole `packages` map after every upgrade, so dropping an entry it cannot
337
+ * interpret would silently delete a hand-written pin. Uninterpretable means
338
+ * "this module cannot use it" (pickEffectivePin ignores it), not "the user did
339
+ * not mean it".
340
+ *
341
+ * Interpreted entries keep their shape — a string stays a string, an object
342
+ * keeps its metadata (`shippedPin`, `updatedAt`) — so a read/serialize round
343
+ * trip does not destroy fields this module does not interpret. Neither
344
+ * `version` nor the entry's semver validity is enforced here (pickEffectivePin
345
+ * judges validity, so a bad version can still be reported and cleaned up).
290
346
  *
291
347
  * @param {string} text
292
- * @returns {{ version: number, packages: Record<string, string|{version: string}> } | null}
348
+ * @returns {{
349
+ * version: number,
350
+ * packages: Record<string, string|{version: string}>,
351
+ * raw: Record<string, unknown>,
352
+ * } | null}
293
353
  */
294
354
  export function parseOverrides(text) {
295
355
  let doc
@@ -302,14 +362,18 @@ export function parseOverrides(text) {
302
362
  if (!isPlainObject(doc.packages)) return null
303
363
 
304
364
  const packages = {}
365
+ const raw = {}
305
366
  for (const [name, entry] of Object.entries(doc.packages)) {
306
367
  if (name === '') continue
307
368
  const version = entryVersion(entry)
308
- if (version === null || version === '') continue
369
+ if (version === null || version === '') {
370
+ raw[name] = entry
371
+ continue
372
+ }
309
373
  packages[name] = typeof entry === 'string' ? version : { ...entry, version }
310
374
  }
311
375
 
312
- return { version: Number.isInteger(doc.version) ? doc.version : 1, packages }
376
+ return { version: Number.isInteger(doc.version) ? doc.version : 1, packages, raw }
313
377
  }
314
378
 
315
379
  /**
@@ -318,15 +382,34 @@ export function parseOverrides(text) {
318
382
  * every upgrade and lives in a directory users inspect and diff; insertion
319
383
  * order must not leak into the bytes.
320
384
  *
321
- * @param {{ packages?: Record<string, string>, [key: string]: unknown }} obj
385
+ * `raw` (from parseOverrides) is written back into `packages` under its
386
+ * original name and value, and is never emitted as a key of its own: that is
387
+ * what makes a rewrite lossless for entries the parser could not interpret.
388
+ * An interpreted entry always wins over a raw one with the same name.
389
+ *
390
+ * @param {{ packages?: Record<string, unknown>, raw?: Record<string, unknown>, [key: string]: unknown }} obj
322
391
  * @returns {string}
323
392
  */
324
393
  export function serializeOverrides(obj) {
325
394
  if (!isPlainObject(obj)) throw new TypeError('serializeOverrides: expected a plain object')
326
395
  const packages = isPlainObject(obj.packages) ? obj.packages : {}
396
+ const raw = isPlainObject(obj.raw) ? obj.raw : {}
397
+
398
+ const merged = {}
399
+ for (const [name, entry] of Object.entries(raw)) {
400
+ if (!Object.prototype.hasOwnProperty.call(packages, name)) merged[name] = entry
401
+ }
402
+ for (const [name, entry] of Object.entries(packages)) merged[name] = entry
403
+
327
404
  const sorted = {}
328
- for (const name of Object.keys(packages).sort()) sorted[name] = packages[name]
329
- return `${JSON.stringify({ ...obj, packages: sorted }, null, 2)}\n`
405
+ for (const name of Object.keys(merged).sort()) sorted[name] = merged[name]
406
+
407
+ // Everything but `raw` is document metadata and passes through untouched.
408
+ const document = {}
409
+ for (const [key, value] of Object.entries(obj)) {
410
+ if (key !== 'raw') document[key] = value
411
+ }
412
+ return `${JSON.stringify({ ...document, packages: sorted }, null, 2)}\n`
330
413
  }
331
414
 
332
415
  /**
@@ -90,6 +90,7 @@ import {
90
90
  orderPluginAddFailures,
91
91
  parseDumpConfig,
92
92
  parseTier,
93
+ partitionInstallByRetryState,
93
94
  planMcpPatch,
94
95
  planOrphanPatchCleanup,
95
96
  planPluginInstall,
@@ -98,7 +99,14 @@ import {
98
99
  pluginAddCommand,
99
100
  pluginAddRetryDecision,
100
101
  selectPlugins,
102
+ verifyInstalledPins,
101
103
  } from './lib/provision-plan.mjs'
104
+ import {
105
+ emptyState,
106
+ parseState,
107
+ recordInstallOutcomes,
108
+ serializeState,
109
+ } from './lib/provision-state.mjs'
102
110
 
103
111
  const TEMPLATE = 'web'
104
112
  const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
@@ -150,6 +158,9 @@ const manifestPath = join(profileDir, 'package.json')
150
158
  // Written by `dsh-opentui upgrade` (never by this script): the versions that
151
159
  // command installed above the shipped pins. Read-only here.
152
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')
153
164
  console.log(`${PREFIX}dsh home ${dshHome}`)
154
165
 
155
166
  const requireDsh = () => {
@@ -248,6 +259,48 @@ function readUpgradeOverrides() {
248
259
  return packages
249
260
  }
250
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
+
251
304
  /** Backup-then-write the profile manifest (the backup is the contract: a
252
305
  * failed run never leaves the user without their previous manifest). */
253
306
  function writeManifest(manifest) {
@@ -423,7 +476,6 @@ function pauseSync(ms) {
423
476
  }
424
477
 
425
478
  const failedInstalls = [] // { spec, failure: { kind, code, hint } }
426
- let installedCount = 0
427
479
 
428
480
  if (tier === 'none') {
429
481
  say(3, 'plugins', 'skipped (--plugins=none)')
@@ -439,23 +491,87 @@ if (tier === 'none') {
439
491
  // pulled back to the shipped pin on every start.
440
492
  const overrides = readUpgradeOverrides()
441
493
  const plan = planPluginInstall({ tier, dependencies, bundles, installedVersions, overrides })
442
- const specs = plan.install.map((entry) => entry.spec)
443
- const skipped = plan.total - plan.install.length
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
+ }
444
522
 
445
523
  if (plan.install.length === 0) {
446
524
  say(3, 'plugins', `already satisfied (${plan.total}/${plan.total})`)
447
525
  } else if (dryRun) {
448
- say(3, 'plugins', `found ${skipped}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
449
- 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)`)
450
535
  } else {
451
536
  requireDsh()
452
- say(3, 'plugins', `found ${skipped}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
453
- 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 })
454
547
  if (!batch.error && batch.status === 0) {
455
- 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
+ }
456
561
  } else {
457
- if (batch.error) warn(`plugin install failed to start: ${batch.error.message}`)
458
- 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 })
459
575
  if (approvePrintedBuilds(plugins.map((plugin) => plugin.name))) {
460
576
  say(3, 'plugins', 'approved the printed build scripts (pnpm allowBuilds) — retrying one by one…')
461
577
  }
@@ -467,30 +583,67 @@ if (tier === 'none') {
467
583
  // cannot fix it, so the spec gives up on the first hit. The terminal
468
584
  // failure stays a WARN + failedInstalls entry — never a silent pass
469
585
  // (the e2e npm-install boot leg asserts the delivered set).
470
- for (const spec of specs) {
586
+ for (const entry of targets) {
471
587
  let installed = false
472
588
  for (let attempt = 1; attempt <= PLUGIN_ADD_ATTEMPTS && !installed; attempt += 1) {
473
589
  if (attempt > 1) {
474
- 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…`)
475
591
  pauseSync(PLUGIN_ADD_BACKOFF_MS)
476
592
  }
477
- const retry = runPluginAdd([spec], { captureStderr: true })
593
+ const retry = runPluginAdd([entry.spec], { captureStderr: true })
478
594
  echoCapturedStderr(retry.stderr)
479
595
  const decision = pluginAddRetryDecision(retry, { attempt, attempts: PLUGIN_ADD_ATTEMPTS })
480
596
  if (decision.action === 'installed') {
481
- installedCount += 1
482
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
+ }
483
608
  } else if (decision.action === 'failed') {
484
609
  const detail = retry.error ? retry.error.message : `(exit ${retry.status})`
485
- 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 })
486
612
  if (decision.failure.kind === 'deterministic') {
487
- say(3, 'plugins', `${spec}: ${decision.failure.code} — deterministic, not retrying`)
613
+ say(3, 'plugins', `${entry.spec}: ${decision.failure.code} — deterministic, not retrying`)
488
614
  }
489
615
  break
490
616
  }
491
617
  }
492
618
  }
493
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
+ }
494
647
  // Summary: deterministic failures first, each with its one-line fix; the
495
648
  // retried-then-failed ones follow without a hint.
496
649
  for (const { spec, failure, detail } of orderPluginAddFailures(failedInstalls)) {
@@ -499,8 +652,33 @@ if (tier === 'none') {
499
652
  ` — continuing${failure.hint ? ` — ${failure.hint}` : ''}`,
500
653
  )
501
654
  }
502
- const failedSuffix = failedInstalls.length > 0 ? `, failed ${failedInstalls.length}` : ''
503
- 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
+ }
504
682
  }
505
683
  }
506
684