@aiwayds/dsh-opentui 0.18.0 → 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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.18.1] - 2026-11-16
9
+
10
+ ### Fixed
11
+
12
+ - **Provisioning stops re-installing a pin that cannot be reached.** Consecutive install failures are recorded per pin in `<profile>/.provision-state.json`; a failing pin backs off for 10 minutes and is skipped after 3 attempts, and the record resets after 24 hours. A missing or unreadable state file is read as "no memory", so the old behavior is the fallback.
13
+ - **`dsh plugin add` is verified by readback, not by its exit code.** After the install, provisioning reads the version that actually landed in `node_modules` and compares it with the effective pin (including a newer version raised by an `upgrade` override); a batch that exits 0 while leaving a package at another version no longer counts as installed.
14
+ - **Skipped and degraded plugins are named.** Each one gets a one-line notice with the state file path and a `dsh-opentui upgrade` suggestion; provisioning still exits 0 and the launcher still starts, so a degraded profile does not block boot.
15
+ - **A successful upgrade leaves no empty `.upgrade-backup` directory.** The stamp directory is removed and then its parent only when empty.
16
+
17
+ ### Internal
18
+
19
+ - **stub-`dsh` integration tests for the provisioning script** (`test/provision-script.test.ts`), running the real script end to end against a stub host CLI offline.
20
+
8
21
  ## [0.18.0] - 2026-11-16
9
22
 
10
23
  ### Added
@@ -59745,7 +59745,7 @@ var init_subagents_viewer = __esm(() => {
59745
59745
  import { TextAttributes as TextAttributes12 } from "@opentui/core";
59746
59746
  function resolveVersion() {
59747
59747
  try {
59748
- return "0.18.0";
59748
+ return "0.18.1";
59749
59749
  } catch {
59750
59750
  return "dev";
59751
59751
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "bin": {
@@ -5,6 +5,12 @@
5
5
  // fixtures. That split is what makes the idempotency rules (dep present,
6
6
  // node_modules version satisfies, bundle entry present) testable without a
7
7
  // network or a real dsh profile.
8
+ //
9
+ // The failure-memory policy lives in ./provision-state.mjs (also pure); this
10
+ // module only applies it to a plan, so "which specs does this launch actually
11
+ // run" is testable end to end without a profile.
12
+
13
+ import { shouldSkipRetry } from './provision-state.mjs'
8
14
 
9
15
  export const PROFILE = 'opentui'
10
16
  export const PREFIX = 'provision-opentui-profile: '
@@ -435,7 +441,10 @@ export function planPluginInstall({ tier, dependencies = {}, bundles = [], insta
435
441
  const installed = installedVersions[plugin.name]
436
442
  const depOk = depSpec !== undefined && (isLocalSpec(depSpec) || satisfiesVersion(installed, effectivePin))
437
443
  if (!depOk) {
438
- install.push({ name: plugin.name, spec: `${plugin.name}@${effectivePin}`, reason: plugin.reason })
444
+ // `pin` is the EFFECTIVE pin (shipped pin or a newer override), so the
445
+ // caller can compare the installed version and the failure state against
446
+ // exactly the version this install asked for.
447
+ install.push({ name: plugin.name, pin: effectivePin, spec: `${plugin.name}@${effectivePin}`, reason: plugin.reason })
439
448
  continue
440
449
  }
441
450
  if (!bundles.includes(plugin.name)) missingBundles.push(plugin.name)
@@ -451,6 +460,83 @@ export function planPluginInstall({ tier, dependencies = {}, bundles = [], insta
451
460
  }
452
461
  }
453
462
 
463
+ /**
464
+ * Split a plan's install rows into the specs this launch runs and the pins it
465
+ * skips after repeated failures (see provision-state.mjs for the policy:
466
+ * backoff, attempt cap, 24-hour reset).
467
+ *
468
+ * The pin compared is `row.pin` — the EFFECTIVE pin computed by
469
+ * planPluginInstall. Using the shipped pin here would make an override-raised
470
+ * package look permanently failed: its install spec says 0.7.2 while the
471
+ * recorded failure (from an older launch) says 0.7.0.
472
+ *
473
+ * Pure: `state` is the parsed state document, `now` a Date / ISO string /
474
+ * epoch ms. Returns the surviving rows and one summary row per skipped pin.
475
+ *
476
+ * @param {{
477
+ * install?: Array<{name: string, pin: string, spec: string}>,
478
+ * state?: object|null,
479
+ * now?: Date|string|number,
480
+ * backoffMs?: number,
481
+ * maxAttempts?: number,
482
+ * }} input
483
+ * @returns {{
484
+ * install: Array<{name: string, pin: string, spec: string}>,
485
+ * skips: Array<{name: string, pin: string, reason: string, attempts: number, lastFailedAt: string}>,
486
+ * }}
487
+ */
488
+ export function partitionInstallByRetryState({ install = [], state, now, backoffMs, maxAttempts } = {}) {
489
+ const pending = []
490
+ const skips = []
491
+ for (const row of Array.isArray(install) ? install : []) {
492
+ if (!row || typeof row.name !== 'string' || row.name === '') {
493
+ pending.push(row)
494
+ continue
495
+ }
496
+ const pin = typeof row.pin === 'string' && row.pin !== '' ? row.pin : specPin(row.spec)
497
+ const verdict = shouldSkipRetry({ state, name: row.name, pin, now, backoffMs, maxAttempts })
498
+ if (!verdict.skip) {
499
+ pending.push(pin === row.pin ? row : { ...row, pin })
500
+ continue
501
+ }
502
+ skips.push({
503
+ name: row.name,
504
+ pin: verdict.entry.pin,
505
+ reason: verdict.reason,
506
+ attempts: verdict.entry.attempts,
507
+ lastFailedAt: verdict.entry.lastFailedAt,
508
+ })
509
+ }
510
+ return { install: pending, skips }
511
+ }
512
+
513
+ /** `@scope/pkg@1.2.3` -> `1.2.3`. Only a fallback for rows without `pin`. */
514
+ function specPin(spec) {
515
+ if (typeof spec !== 'string') return ''
516
+ const at = spec.lastIndexOf('@')
517
+ return at > 0 ? spec.slice(at + 1) : ''
518
+ }
519
+
520
+ /**
521
+ * Compare the versions that actually landed against the plan's effective pins.
522
+ * Exact match only: `dsh plugin add` was asked for an exact version, so a
523
+ * newer or older version is a degraded install, not a satisfied one.
524
+ *
525
+ * @param {{
526
+ * install?: Array<{name: string, pin: string}>,
527
+ * installedVersions?: Record<string, string|undefined>,
528
+ * }} input
529
+ * @returns {Array<{name: string, pin: string, installed: string|null, ok: boolean}>}
530
+ */
531
+ export function verifyInstalledPins({ install = [], installedVersions = {} } = {}) {
532
+ const versions = installedVersions && typeof installedVersions === 'object' ? installedVersions : {}
533
+ return (Array.isArray(install) ? install : []).map((row) => {
534
+ const actual = row && typeof row.name === 'string' ? versions[row.name] : undefined
535
+ const installed = typeof actual === 'string' && actual !== '' ? actual : null
536
+ return { name: row?.name, pin: row?.pin, installed, ok: installed !== null && installed === row?.pin }
537
+ })
538
+ }
539
+
454
540
  /**
455
541
  * Merge bundle selection: drop retired entries, append missing managed
456
542
  * entries, and keep the managed subset in `managedOrder` (the ask-router-first
@@ -0,0 +1,294 @@
1
+ // Cross-start failure memory for provision-opentui-profile.mjs.
2
+ //
3
+ // The provisioning script runs on every launch. When a plugin cannot be
4
+ // installed at its pin (the registry is missing the version, or the version
5
+ // that landed is not the pin) the old behaviour retried on every start
6
+ // forever, rewriting node_modules and slowing startup without bound. This
7
+ // module decides, purely, what happened last time and whether another retry
8
+ // is worth it.
9
+ //
10
+ // Nothing here touches the filesystem or spawns a process: the caller passes
11
+ // the state file's text in and writes the serialized result out. That keeps
12
+ // the retry policy testable without a real profile.
13
+ //
14
+ // Timestamps are always stored as ISO strings so the file is timezone-free
15
+ // and diff-friendly.
16
+
17
+ export const STATE_VERSION = 1
18
+ export const MAX_ATTEMPTS = 3
19
+ export const BACKOFF_MS = 600000 // 10 minutes
20
+ // A pin that has been failing for a full day gets a fresh round. Without this
21
+ // the attempt cap would skip a plugin forever: a registry that published the
22
+ // pinned version late, or a network outage, would look identical to a broken
23
+ // pin. The window is measured from firstFailedAt, not lastFailedAt, so a pin
24
+ // that fails once a day still resets on schedule.
25
+ export const RESET_AFTER_MS = 86_400_000 // 24 hours
26
+ export const MAX_ERROR_LENGTH = 200
27
+
28
+ const EPOCH_ISO = new Date(0).toISOString()
29
+
30
+ /** Coerce a Date | ISO string | epoch milliseconds value to milliseconds.
31
+ * Returns null when the value cannot be read as a point in time. */
32
+ function parseTimeMs(value) {
33
+ if (value instanceof Date) {
34
+ const ms = value.getTime()
35
+ return Number.isFinite(ms) ? ms : null
36
+ }
37
+ if (typeof value === 'number') return Number.isFinite(value) ? value : null
38
+ if (typeof value === 'string' && value.trim() !== '') {
39
+ const ms = Date.parse(value)
40
+ return Number.isFinite(ms) ? ms : null
41
+ }
42
+ return null
43
+ }
44
+
45
+ function toIso(value) {
46
+ const ms = parseTimeMs(value)
47
+ return ms === null ? null : new Date(ms).toISOString()
48
+ }
49
+
50
+ /** Failure text is logged on one line and must not grow the state file:
51
+ * newlines become spaces, and the result is capped at MAX_ERROR_LENGTH. */
52
+ function sanitizeError(error) {
53
+ const text = typeof error === 'string'
54
+ ? error
55
+ : error == null
56
+ ? ''
57
+ : String(error)
58
+ return text.replace(/[\r\n]+/g, ' ').slice(0, MAX_ERROR_LENGTH)
59
+ }
60
+
61
+ /** A stored entry is untrusted input (the file may be hand-edited or written
62
+ * by an older build), so re-validate on read. Anything malformed is dropped
63
+ * by the caller; the remaining entries still participate in the policy. */
64
+ function normalizeEntry(raw) {
65
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
66
+ const pin = typeof raw.pin === 'string' ? raw.pin.trim() : ''
67
+ if (pin === '') return null
68
+ const attempts = Math.floor(Number(raw.attempts))
69
+ if (!Number.isFinite(attempts) || attempts < 1) return null
70
+ const firstFailedAt = toIso(raw.firstFailedAt)
71
+ const lastFailedAt = toIso(raw.lastFailedAt)
72
+ if (firstFailedAt === null || lastFailedAt === null) return null
73
+ return {
74
+ pin,
75
+ attempts,
76
+ firstFailedAt,
77
+ lastFailedAt,
78
+ error: sanitizeError(raw.error),
79
+ }
80
+ }
81
+
82
+ /** Fresh, empty state. Always a new object so callers cannot share one. */
83
+ export function emptyState() {
84
+ return { version: STATE_VERSION, failures: {} }
85
+ }
86
+
87
+ /** Parse the state file's text. Returns null when the document is not a
88
+ * usable state at all; individual malformed failure entries are dropped so
89
+ * one bad row cannot disable retry tracking for every plugin. */
90
+ export function parseState(text) {
91
+ if (typeof text !== 'string' || text.trim() === '') return null
92
+ let raw
93
+ try {
94
+ raw = JSON.parse(text)
95
+ } catch {
96
+ return null
97
+ }
98
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
99
+ if (!raw.failures || typeof raw.failures !== 'object' || Array.isArray(raw.failures)) return null
100
+
101
+ const failures = {}
102
+ for (const [name, entry] of Object.entries(raw.failures)) {
103
+ if (typeof name !== 'string' || name === '') continue
104
+ const normalized = normalizeEntry(entry)
105
+ if (normalized) failures[name] = normalized
106
+ }
107
+ return { version: STATE_VERSION, failures }
108
+ }
109
+
110
+ /** Stable JSON for the state file: failure names sorted, fixed field order
111
+ * inside each entry, trailing newline. Two runs over the same state produce
112
+ * byte-identical output, so the file does not churn. */
113
+ export function serializeState(state) {
114
+ const source = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
115
+ ? state.failures
116
+ : {}
117
+ const failures = {}
118
+ for (const name of Object.keys(source).sort()) {
119
+ const entry = normalizeEntry(source[name])
120
+ if (entry) failures[name] = entry
121
+ }
122
+ return `${JSON.stringify({ version: STATE_VERSION, failures }, null, 2)}\n`
123
+ }
124
+
125
+ /** True when `firstFailedAt` is at least `resetAfterMs` before `now`.
126
+ * Exactly the window boundary counts as due: a failure recorded at T is
127
+ * "24 hours old" at T+24h, and the next attempt is a fresh round.
128
+ * Unreadable timestamps are never due (retry is the safe failure mode). */
129
+ function isResetDue({ now, firstFailedAt, resetAfterMs = RESET_AFTER_MS }) {
130
+ const nowMs = parseTimeMs(now)
131
+ if (nowMs === null) return false
132
+ const firstMs = parseTimeMs(firstFailedAt)
133
+ if (firstMs === null) return false
134
+ const window = Number.isFinite(Number(resetAfterMs)) ? Number(resetAfterMs) : RESET_AFTER_MS
135
+ return nowMs - firstMs >= window
136
+ }
137
+
138
+ /** Record a failed install attempt. Same pin: attempts grow and
139
+ * firstFailedAt is preserved. New pin: the failure history resets, because
140
+ * the previous failures said nothing about this pin. A pin that has been
141
+ * failing for RESET_AFTER_MS also starts a fresh round (attempts back to 1,
142
+ * firstFailedAt moved to now) — the pin deserves another chance after a day.
143
+ * Returns a new state. */
144
+ export function recordFailure({ state, name, pin, now, error } = {}) {
145
+ const base = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
146
+ ? state
147
+ : emptyState()
148
+ const failures = { ...base.failures }
149
+ const previous = normalizeEntry(failures[name])
150
+ const resolvedPin = pin == null ? '' : String(pin)
151
+ const at = toIso(now) ?? EPOCH_ISO
152
+ const previousMatches = previous !== null && previous.pin === resolvedPin
153
+ const freshRound = previousMatches && isResetDue({ now, firstFailedAt: previous.firstFailedAt })
154
+ const samePin = previousMatches && !freshRound
155
+
156
+ failures[name] = {
157
+ pin: resolvedPin,
158
+ attempts: samePin ? previous.attempts + 1 : 1,
159
+ firstFailedAt: samePin ? previous.firstFailedAt : at,
160
+ lastFailedAt: at,
161
+ error: sanitizeError(error),
162
+ }
163
+ return { version: STATE_VERSION, failures }
164
+ }
165
+
166
+ /** Clear the failure entry for `name`. `pin` is intentionally unused: a
167
+ * successful install means there is nothing left to retry, whatever pin the
168
+ * entry recorded. Returns a new state. */
169
+ export function recordSuccess({ state, name } = {}) {
170
+ const base = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
171
+ ? state
172
+ : emptyState()
173
+ const failures = { ...base.failures }
174
+ delete failures[name]
175
+ return { version: STATE_VERSION, failures }
176
+ }
177
+
178
+ /**
179
+ * Record ONE launch's install outcomes under a SINGLE timestamp.
180
+ *
181
+ * The timestamp is chosen by the caller at the moment the batch FINISHED
182
+ * (`new Date().toISOString()` after the last `dsh plugin add` returned), never
183
+ * at process start. Provisioning can spend minutes installing, and the backoff
184
+ * window is measured from `lastFailedAt`: stamping a 9-minute failing batch
185
+ * with the launch time leaves 1 minute of the 10-minute window instead of 10.
186
+ * One timestamp for the whole batch (rather than one per package) keeps the
187
+ * entries of a launch identical; the difference between per-package calls
188
+ * would be milliseconds and is not worth the extra clock reads.
189
+ *
190
+ * Pure: `rows` is `[{ name, pin, ok, error }]`. Returns the next state and the
191
+ * names recorded as failures, so the caller can keep its degraded count.
192
+ *
193
+ * @param {{state?: object, rows?: Array<{name: string, pin: string, ok: boolean, error?: string}>, now?: Date|string|number}} input
194
+ * @returns {{state: object, failed: string[]}}
195
+ */
196
+ export function recordInstallOutcomes({ state, rows = [], now } = {}) {
197
+ const base = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
198
+ ? state
199
+ : emptyState()
200
+ let next = base
201
+ const failed = []
202
+ for (const row of Array.isArray(rows) ? rows : []) {
203
+ if (!row || typeof row.name !== 'string' || row.name === '') continue
204
+ if (row.ok) {
205
+ next = recordSuccess({ state: next, name: row.name })
206
+ continue
207
+ }
208
+ next = recordFailure({ state: next, name: row.name, pin: row.pin, now, error: row.error })
209
+ failed.push(row.name)
210
+ }
211
+ return { state: next, failed }
212
+ }
213
+
214
+ /** Should this pin be skipped on this launch?
215
+ *
216
+ * Order matters:
217
+ * 1. no entry, or an entry for another pin -> try it
218
+ * 2. firstFailedAt is RESET_AFTER_MS old -> try it (fresh round)
219
+ * 3. attempts >= maxAttempts -> skip permanently (until the pin changes or
220
+ * the reset window elapses)
221
+ * 4. still inside the backoff window -> skip for now
222
+ * 5. otherwise -> try
223
+ *
224
+ * The reset check precedes the attempt cap on purpose: without it a plugin
225
+ * that failed three times would never be retried again on this pin.
226
+ *
227
+ * Unreadable timestamps count as "not skipped": retrying is slower than
228
+ * ideal, but a corrupt clock must never wedge provisioning forever. */
229
+ export function shouldSkipRetry({ state, name, pin, now, backoffMs = BACKOFF_MS, maxAttempts = MAX_ATTEMPTS } = {}) {
230
+ const failures = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
231
+ ? state.failures
232
+ : {}
233
+ const entry = normalizeEntry(failures[name])
234
+ if (!entry || entry.pin !== pin) return { skip: false, reason: null, entry }
235
+
236
+ if (isResetDue({ now, firstFailedAt: entry.firstFailedAt })) {
237
+ return { skip: false, reason: 'reset', entry }
238
+ }
239
+
240
+ const limit = Number.isFinite(Number(maxAttempts)) ? Number(maxAttempts) : MAX_ATTEMPTS
241
+ if (entry.attempts >= limit) return { skip: true, reason: 'max-attempts', entry }
242
+
243
+ const nowMs = parseTimeMs(now)
244
+ const lastMs = parseTimeMs(entry.lastFailedAt)
245
+ if (nowMs === null || lastMs === null) return { skip: false, reason: null, entry }
246
+
247
+ const window = Number.isFinite(Number(backoffMs)) ? Number(backoffMs) : BACKOFF_MS
248
+ if (nowMs - lastMs < window) return { skip: true, reason: 'backoff', entry }
249
+
250
+ return { skip: false, reason: null, entry }
251
+ }
252
+
253
+ /** `pins` may be a name -> pin map, an array of names, or an array of
254
+ * { name, pin } rows. Omitting it summarises every recorded failure using
255
+ * the pin stored in the entry. */
256
+ function pinPairs(pins) {
257
+ if (pins == null) return null
258
+ if (Array.isArray(pins)) {
259
+ return pins.map((item) => {
260
+ if (typeof item === 'string') return [item, null]
261
+ if (item && typeof item === 'object') return [item.name, item.pin ?? null]
262
+ return [null, null]
263
+ })
264
+ }
265
+ if (typeof pins === 'object') return Object.entries(pins)
266
+ return []
267
+ }
268
+
269
+ /** One row per pin this launch would skip, sorted by name, ready to be
270
+ * printed as a single startup warning. */
271
+ export function summarizeSkips({ state, pins, now, backoffMs = BACKOFF_MS, maxAttempts = MAX_ATTEMPTS } = {}) {
272
+ const failures = state && typeof state === 'object' && state.failures && typeof state.failures === 'object'
273
+ ? state.failures
274
+ : {}
275
+ const pairs = pinPairs(pins) ?? Object.keys(failures).map((name) => [name, null])
276
+
277
+ const rows = []
278
+ for (const [name, pin] of pairs) {
279
+ if (typeof name !== 'string' || name === '') continue
280
+ const entry = normalizeEntry(failures[name])
281
+ if (!entry) continue
282
+ const wantedPin = pin == null ? entry.pin : pin
283
+ const verdict = shouldSkipRetry({ state, name, pin: wantedPin, now, backoffMs, maxAttempts })
284
+ if (!verdict.skip) continue
285
+ rows.push({
286
+ name,
287
+ pin: verdict.entry.pin,
288
+ reason: verdict.reason,
289
+ attempts: verdict.entry.attempts,
290
+ lastFailedAt: verdict.entry.lastFailedAt,
291
+ })
292
+ }
293
+ return rows.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
294
+ }
@@ -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
 
@@ -38,6 +38,7 @@ import {
38
38
  readSync,
39
39
  realpathSync,
40
40
  renameSync,
41
+ rmdirSync,
41
42
  rmSync,
42
43
  writeFileSync,
43
44
  } from 'node:fs'
@@ -154,6 +155,7 @@ export const defaultFs = {
154
155
  existsSync: (path) => existsSync(path),
155
156
  mkdirSync: (path, options) => mkdirSync(path, options),
156
157
  rmSync: (path, options) => rmSync(path, options),
158
+ rmdirSync: (path) => rmdirSync(path),
157
159
  copyFileSync: (from, to) => copyFileSync(from, to),
158
160
  renameSync: (from, to) => renameSync(from, to),
159
161
  }
@@ -437,6 +439,22 @@ function restoreBackup({ fs, profileDir, overridePath, copies }) {
437
439
  }
438
440
  }
439
441
 
442
+ /**
443
+ * Remove the backup after a fully successful run: the stamp directory first,
444
+ * then its hidden `.upgrade-backup` parent when it is empty. `rmdir` (not
445
+ * `rm -r`) is deliberate — it refuses to touch a parent that still holds
446
+ * another run's backup (ENOTEMPTY is ignored), so concurrent upgrades cannot
447
+ * delete each other's rollback material. The failure paths never call this.
448
+ */
449
+ function removeSuccessfulBackup({ fs, backupDir }) {
450
+ fs.rmSync(backupDir, { recursive: true, force: true })
451
+ try {
452
+ fs.rmdirSync(dirname(backupDir))
453
+ } catch {
454
+ /* not empty, already gone, or not ours to remove — leave it */
455
+ }
456
+ }
457
+
440
458
  /** The specs of the pre-upgrade manifest, read from its BACKUP copy (the live
441
459
  * manifest may already have been rewritten by the host). Local and host
442
460
  * specs are skipped: they are not installable from the registry. */
@@ -681,7 +699,7 @@ function applyPluginUpgrades(ctx) {
681
699
  }
682
700
 
683
701
  if (mismatched.length === 0 && !overridesError) {
684
- fs.rmSync(backupDir, { recursive: true, force: true })
702
+ removeSuccessfulBackup({ fs, backupDir })
685
703
  log(`upgraded ${upgraded} plugin(s)`)
686
704
  } else {
687
705
  log(`backup kept at ${backupDir}`)