dsh-plugin-update-doctor 0.5.0 → 0.5.4

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/lib/service.js CHANGED
@@ -6,15 +6,18 @@ import { HistoryStore } from './history.js';
6
6
  import { bundleState, classify } from './diagnosis.js';
7
7
  import { scanUpdates, onlineSafety } from './online.js';
8
8
  import { IdentityStore } from './identity.js';
9
- import { PUBLIC_REGISTRY, publicRegistry, archiveKey } from './source.js';
9
+ import { PUBLIC_REGISTRY, PUBLIC_MIRROR, publicRegistry, approvedPublicRegistry, registryOrigin, archiveKey, readRegistryVersions } from './source.js';
10
+ import { dependencyDeclaration, inspectDependencyGraph, assertSameDependencyGraph } from './dependency-policy.js';
11
+ import { performUnionGeneration, performUnionRecovery, persistUnionOutcome } from './union-service.js';
12
+ import {completeWslReply,unknownWsl,persistWslOutcome} from './wsl-outcome.js';
10
13
 
11
14
  const NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
12
15
  const VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
13
16
  export const SELF = 'dsh-plugin-update-doctor';
14
17
 
15
18
  export class DoctorService {
16
- constructor({ manager, profile, runtimeVersion, resolvePackage, probeLocks, statePath, taskGate, stager, now = () => Date.now() }) {
17
- Object.assign(this, { manager, profile, runtimeVersion, resolvePackage, probeLocks, now, taskGate, stager });
19
+ constructor({ manager, profile, runtimeVersion, resolvePackage, probeLocks, statePath, taskGate, stager, unionStager, verifyRunningGeneration, hmrAvailable=true, now = () => Date.now() }) {
20
+ Object.assign(this, { manager, profile, runtimeVersion, resolvePackage, probeLocks, now, taskGate, stager, unionStager, verifyRunningGeneration, hmrAvailable });
18
21
  this.redact = makeRedactor({ profileDir: profile.dir, installDir: process.env.DSH_INSTALL_DIR });
19
22
  this.store = new HistoryStore(statePath, this.redact);
20
23
  this.identities = new IdentityStore(join(dirname(statePath), 'identities.json'));
@@ -29,6 +32,19 @@ export class DoctorService {
29
32
  if (recovery.status !== 'prepared') continue;
30
33
  const bundle = bundles.find(value => value.name === recovery.name);
31
34
  const key = this.stager?.root ? archiveKey(this.stager.root, bundle?.source) : null;
35
+ if(recovery.name==='dsh-plugin-wsl-env'||recovery.installMode==='union-generation'){
36
+ if(recovery.dispatchStarted || this.fingerprint(bundle)!==recovery.expectedFingerprint)await this.identities.settle(recovery.name,null,{...recovery,status:'unknown',expectedFingerprint:this.fingerprint(bundle)});
37
+ else await this.identities.settle(recovery.name,this.lineageOf(bundle),null);
38
+ continue;
39
+ }
40
+ if (['registry-spec','registry-migration'].includes(recovery.installMode)) {
41
+ // A Host result lost across restart is not proof that its registry
42
+ // update or rollback completed, even when version labels match.
43
+ if (recovery.dispatchStarted || this.fingerprint(bundle) !== recovery.expectedFingerprint) {
44
+ await this.identities.settle(recovery.name,null,{...recovery,status:'unknown',expectedFingerprint:this.fingerprint(bundle)});
45
+ } else await this.identities.settle(recovery.name, recovery.installMode === 'registry-migration' ? this.lineageOf(bundle) : null, null);
46
+ continue;
47
+ }
32
48
  const touched = !bundle?.installed || key === recovery.next.archiveKey || key === recovery.previous.archiveKey;
33
49
  if (touched) {
34
50
  try { await this.stager.reopen(recovery.previous); await this.identities.settle(recovery.name, null, { ...recovery, status: 'unknown', expectedFingerprint: this.fingerprint(bundle) }); }
@@ -54,32 +70,50 @@ export class DoctorService {
54
70
  const [bundles, rows] = await Promise.all([this.manager.listBundles(), this.manager.listPlugins()]);
55
71
  return { bundles, rows };
56
72
  }
73
+ stageOwner(reference) { return reference?.runtimeGeneration?.kind === 'union-dependency' ? this.unionStager : this.stager; }
74
+ archiveRoot(bundle, reference) { return (reference?.runtimeGeneration?.kind === 'union-dependency' || bundle?.name === 'dsh-union-search' && this.identities.get(bundle.name)?.runtimeGeneration?.kind === 'union-dependency') ? this.unionStager?.root : this.stager?.root; }
75
+ async reopenReference(reference) { const stager=this.stageOwner(reference); if(!stager)throw new DoctorError('union-generation-unavailable','The required generation verifier is unavailable.');return stager.reopen(reference); }
76
+ async verifyReference(reference,directory) { const stager=this.stageOwner(reference); if(!stager)throw new DoctorError('union-generation-unavailable','The required generation verifier is unavailable.');return stager.verifyInstalledArchive(reference,directory); }
77
+ unionRoute(bundle) { return bundle?.name === 'dsh-union-search' && this.hmrAvailable && !!this.unionStager && typeof this.verifyRunningGeneration === 'function' && ['0.10.24','0.10.25'].includes(bundle.version) && (bundle.update === 'registry' || this.lineageOf(bundle)?.runtimeGeneration?.kind === 'union-dependency'); }
78
+ unionPair(bundle,to) { return this.unionRoute(bundle) && this.unionStager.canAdmit(bundle.name,bundle.version,to) && bundle.version === '0.10.24' && to === '0.10.25'; }
57
79
  lineageOf(bundle) {
58
- const known = this.identities.get(bundle.name);
59
- if (!known || !this.stager?.root || known.version !== bundle.version || known.origin !== PUBLIC_REGISTRY) return null;
60
- return archiveKey(this.stager.root, bundle.source) === known.archiveKey ? known : null;
80
+ if(!bundle)return null;
81
+ const known = this.identities.get(bundle.name),root=this.archiveRoot(bundle,known);
82
+ if (!known || !root || known.version !== bundle.version || known.origin !== PUBLIC_REGISTRY) return null;
83
+ return archiveKey(root, bundle.source) === known.archiveKey ? known : null;
61
84
  }
62
85
  recoveryFor(name) { return this.identities.recovery(name); }
86
+ assertWslRecovery(name,recovery) {
87
+ if(name==='dsh-plugin-wsl-env'&&recovery?.status!=='failed')throw new DoctorError('wsl-generation-outcome-unknown','Only a known failed WSL operation can authorize recovery; unknown results cannot be resent.');
88
+ }
63
89
  summary(bundle, rows) {
64
90
  const observed = bundleState(bundle, rows);
65
91
  let sourceKind = bundle.update ?? (bundle.source?.startsWith('link:') || bundle.source?.startsWith('file:') ? 'local' : 'other');
66
- const lineage = this.lineageOf(bundle);
67
- if (lineage) sourceKind = 'registry';
92
+ const lineage = this.lineageOf(bundle), unionGeneration=this.unionRoute(bundle), knownUnion=lineage?.runtimeGeneration?.kind === 'union-dependency';
93
+ if (lineage && !knownUnion) sourceKind = 'registry';
68
94
  const reasons = [];
95
+ if(bundle.name==='dsh-union-search'&&this.hmrAvailable&&!unionGeneration)reasons.push('dependency-runtime-reload-unverified');
96
+ if(this.identities.warning)reasons.push('identity-store-unverified');
97
+ if (lineage && !knownUnion && bundle.name !== 'dsh-plugin-wsl-env' && bundle.update !== 'registry') reasons.push('legacy-archive-source-requires-migration');
69
98
  if (bundle.name === SELF) reasons.push('self-update-blocked');
70
99
  if (!bundle.removable || bundle.readOnlyReason) reasons.push('management-or-shipped-bundle');
71
- if (sourceKind !== 'registry') reasons.push('registry-updates-only');
100
+ if (sourceKind !== 'registry' && !knownUnion) reasons.push('registry-updates-only');
72
101
  if (!bundle.installed) reasons.push('not-profile-installed');
73
102
  const recovery = this.recoveryFor(bundle.name);
74
- const matchesRecovery = !!recovery && recovery.status !== 'prepared' && recovery.expectedFingerprint === this.fingerprint(bundle);
103
+ if (['registry-spec','registry-migration','union-generation'].includes(recovery?.installMode) && (recovery.status === 'unknown' || recovery.status === 'prepared' && recovery.dispatchStarted)) reasons.push(recovery.installMode === 'union-generation' ? 'union-generation-outcome-unknown' : 'registry-update-outcome-unknown');
104
+ if(recovery?.name==='dsh-plugin-wsl-env'&&(recovery.status==='unknown'||recovery.status==='prepared'&&recovery.dispatchStarted))reasons.push('wsl-generation-outcome-unknown');
105
+ const matchesRecovery = !!recovery && !(recovery.name==='dsh-plugin-wsl-env'&&recovery.status==='unknown') && recovery.status !== 'prepared' && !(['registry-spec','registry-migration','union-generation'].includes(recovery.installMode) && recovery.status === 'unknown') && recovery.expectedFingerprint === this.fingerprint(bundle);
75
106
  if (this.sourceWarnings.has(bundle.name)) reasons.push(this.sourceWarnings.get(bundle.name));
107
+ const unionCurrentReference=recovery?.installMode==='union-generation'&&bundle.installed&&([recovery.next,recovery.previous].find(reference=>reference?.version===bundle.version&&archiveKey(this.unionStager?.root??'',bundle.source)===reference.archiveKey)??(knownUnion?lineage:null));
108
+ const recoveryAdmitted = matchesRecovery && !this.identities.warning && !(bundle.name === 'dsh-union-search' && this.hmrAvailable && (recovery?.installMode !== 'union-generation' || !this.unionStager?.prepareRecovery || !unionCurrentReference));
76
109
  return {
77
110
  name: bundle.name, title: typeof bundle.meta?.title === 'string' ? bundle.meta.title : bundle.name, version: bundle.version ?? null,
78
- sourceKind, registry: lineage?.origin ?? null, installed: bundle.installed, enabled: bundle.enabled,
111
+ sourceKind, registry: lineage?.origin ?? null, doctorArchive:!!lineage, unionGeneration, runtimePackaging:knownUnion?'union-dependency-generation':'original', installed: bundle.installed, enabled: bundle.enabled,
79
112
  state: observed.state, activeRows: observed.activeRows, totalRows: observed.totalRows,
80
- canUpdate: reasons.length === 0 && sourceKind === 'registry',
81
- canRestore: bundle.name !== SELF && !!bundle.removable && matchesRecovery,
82
- restoreVersion: matchesRecovery ? recovery.from : null, recoveryId: matchesRecovery ? recovery.id : null, reasons,
113
+ canUpdate: reasons.length === 0 && (sourceKind === 'registry' || knownUnion),
114
+ canMigrate: !!lineage && bundle.name!==SELF && bundle.name!=='dsh-plugin-wsl-env' && !knownUnion && bundle.removable && !bundle.readOnlyReason && !bundle.error && bundle.availability==='profile' && !(this.hmrAvailable&&bundle.name==='dsh-union-search') && !recovery && !this.identities.warning,
115
+ canRestore: bundle.name !== SELF && !!bundle.removable && recoveryAdmitted,
116
+ restoreVersion: recoveryAdmitted ? recovery.from : null, recoveryId: recoveryAdmitted ? recovery.id : null, reasons,
83
117
  };
84
118
  }
85
119
  async list() {
@@ -87,9 +121,12 @@ export class DoctorService {
87
121
  const visible = bundles.filter(bundle => bundle.installed || bundle.name === SELF).map(bundle => this.summary(bundle, rows));
88
122
  for (const [name, recovery] of this.identities.recoveries) if (!visible.some(bundle => bundle.name === name)) {
89
123
  const raw = bundles.find(bundle => bundle.name === name);
124
+ const unknownRegistry = ['registry-spec','registry-migration','union-generation'].includes(recovery.installMode) && recovery.status === 'unknown';
90
125
  const matches = recovery.status !== 'prepared' && recovery.expectedFingerprint === this.fingerprint(raw);
126
+ const recoveryBlocked = unknownRegistry || name==='dsh-plugin-wsl-env'&&recovery.status==='unknown' || this.identities.warning || (name === 'dsh-union-search' && this.hmrAvailable);
91
127
  if (matches) visible.push({ name, title: name, version: raw?.version ?? null, installed: false, enabled: false, sourceKind: 'registry', state: 'missing',
92
- activeRows: 0, totalRows: 0, canUpdate: false, canRestore: name !== SELF, restoreVersion: recovery.from, recoveryId: recovery.id, reasons: ['recorded-recovery-only'] });
128
+ activeRows: 0, totalRows: 0, canUpdate: false, canRestore: name !== SELF && !recoveryBlocked, restoreVersion:recoveryBlocked?null:recovery.from, recoveryId:recoveryBlocked?null:recovery.id,
129
+ reasons:[unknownRegistry?'registry-update-outcome-unknown':'recorded-recovery-only', ...(name === 'dsh-union-search' && this.hmrAvailable ? ['dependency-runtime-reload-unverified'] : []), ...(this.identities.warning ? ['identity-store-unverified'] : [])] });
93
130
  }
94
131
  const selfUpdate = await this.selfUpdate?.state();
95
132
  return this.redact({ profile: this.profile.name, runtimeVersion: this.runtimeVersion, selfUpdate,
@@ -97,7 +134,7 @@ export class DoctorService {
97
134
  busy: this.busy ? { id: this.busy.id, package: this.busy.package, phase: this.busy.phase } : null,
98
135
  externalBusy: this.external.size > 0, history: this.store.list().slice(0, 20),
99
136
  persistenceWarning: this.store.warning ?? this.identities.warning, truncationWarning: this.store.truncationWarning,
100
- limitations: ['Host activation, package identity and this page\'s synchronization are separate observations.', 'The gate defers new formal steps; Agent setup, tool resolution, prompt assembly and independent workers are not a global execution freeze.', 'Remove and install are separate Host operations, not an atomic replacement. Changes from other tools or CLI may still intervene.', 'Task stopping is optional and requires an additional explicit user confirmation; no process termination, forced unlocking, version exemptions or script approvals.', 'Only verified public npm archives are staged; private registries and mirrors are never silently changed.'] });
137
+ limitations: ['Host activation, package identity and this page\'s synchronization are separate observations.', 'The gate defers new formal steps; Agent setup, tool resolution, prompt assembly and independent workers are not a global execution freeze.', 'Normal registry updates preserve the npm spec through the official Host updater; the Host refetches and uses its existing fallback plan. Preflight archives do not form an exact-archive or atomic replacement.', 'WSL generation and older archive recovery remain local-source operations; old ordinary archive installations are not silently migrated.', 'Task stopping is optional and requires an additional explicit user confirmation; no process termination, forced unlocking, version exemptions or script approvals.', 'Only public npm archives are prepared as evidence; a verified source claim does not prove all Host refetch/dependency transport bytes.'] });
101
138
  }
102
139
  async diagnose(name) {
103
140
  this.validateName(name);
@@ -120,8 +157,8 @@ export class DoctorService {
120
157
  const { bundles, rows } = await this.snapshot();
121
158
  const bundle = bundles.find(bundle => bundle.name === name);
122
159
  if (!bundle || !this.summary(bundle, rows).canUpdate) throw new DoctorError('not-updatable', 'Only removable profile registry bundles can be updated here.');
123
- const query = bundle.update === 'registry' ? await this.manager.listVersions(name, undefined, signal) : await this.stager.listVersions(name, bundle.version, signal);
124
- if (query.status === 'listed' && !publicRegistry(query.registry)) throw new DoctorError('registry-origin-unsupported', 'Only the verified public npm origin is supported; the configured source is not migrated.');
160
+ const query = bundle.update === 'registry' ? await readRegistryVersions(this.manager, name, signal) : await this.stager.listVersions(name, bundle.version, signal);
161
+ if (query.status === 'listed' && !approvedPublicRegistry(query.registry)) throw new DoctorError('registry-origin-unsupported', 'Only approved public npm query origins are supported; private sources are not migrated.');
125
162
  return this.redact(query);
126
163
  }
127
164
  async locks(name, signal) {
@@ -150,7 +187,8 @@ export class DoctorService {
150
187
  if (!raw || !this.summary(raw, rows).canUpdate) throw new DoctorError('not-updatable', 'This bundle cannot be safely updated by this plugin.');
151
188
  const query = await this.versions(name, signal);
152
189
  if (query.status !== 'listed' || !query.versions.some(item => item.version === version && item.bundle && !item.incompatible && !item.prerelease && !item.deprecated)) throw new DoctorError('version-not-admitted', 'Choose an offered compatible stable version.');
153
- return { operation: 'update', package: name, from: raw.version, to: version, registry: PUBLIC_REGISTRY, blocked: false, reasons: [], warnings: ['Diagnostic plan only; the authenticated panel prepares exact archives before user confirmation.'] };
190
+ const wslPreflight=name==='dsh-plugin-wsl-env'?await this.stager.inspectWslCandidate(version,{signal,origin:registryOrigin(query.registry)}):null;
191
+ return { operation: 'update', package: name, from: raw.version, to: version, registry: PUBLIC_REGISTRY, blocked: false, reasons: [], ...(wslPreflight?{wslPreflight}: {}), warnings: ['Diagnostic plan only; the authenticated panel prepares exact archives and binds installed state before user confirmation.'] };
154
192
  }
155
193
  async scan(signal) {
156
194
  const { bundles, rows } = await this.snapshot();
@@ -159,16 +197,17 @@ export class DoctorService {
159
197
  const summary = this.summary(raw, rows);
160
198
  let manifest;
161
199
  try { manifest = JSON.parse(await readFile(join(await this.resolvePackage(raw.name), 'package.json'), 'utf8')); } catch {}
162
- const safety = onlineSafety({ ...raw, update: summary.sourceKind === 'registry' ? 'registry' : raw.update }, manifest);
200
+ const safety = onlineSafety({ ...raw, update: summary.sourceKind === 'registry' || summary.unionGeneration ? 'registry' : raw.update }, manifest);
163
201
  if (!this.taskGate || !this.stager) safety.reasons.push('online-update-gate-unavailable');
164
202
  summaries.push({ ...summary, canUpdate: summary.canUpdate && safety.reasons.length === 0, reasons: [...new Set([...summary.reasons, ...safety.reasons])] });
165
203
  }
166
- const queryManager = { listVersions: async (name, options, signal) => {
204
+ const queryManager = { registries: () => this.manager.registries?.(), listVersions: async (name, options, signal) => {
167
205
  const raw = bundles.find(bundle => bundle.name === name);
168
206
  if (raw?.update === 'registry') return this.manager.listVersions(name, options, signal);
169
207
  return this.stager.listVersions(name, raw.version, signal);
170
208
  } };
171
- const items = await scanUpdates(queryManager, summaries, { signal });
209
+ const items = await scanUpdates(queryManager, summaries, { signal,inspectWslCandidate:this.stager?.inspectWslCandidate?.bind(this.stager) });
210
+ for(const item of items)if(item.unionGeneration && item.latestVersion && !this.unionPair(bundles.find(bundle=>bundle.name===item.name),item.latestVersion)){item.canUpdate=false;item.updateStatus='blocked';item.status='blocked';item.reasons=[...new Set([...item.reasons,'union-version-not-reviewed'])];}
172
211
  if (this.selfUpdate) {
173
212
  const selfOffer = await this.selfUpdate.scan(signal);
174
213
  const index = items.findIndex(item => item.name === SELF);
@@ -176,16 +215,18 @@ export class DoctorService {
176
215
  }
177
216
  return this.redact({ profile: this.profile.name, runtimeVersion: this.runtimeVersion, items, taskPolicy: 'wait-for-idle' });
178
217
  }
179
- async sourceFor(name, signal) {
218
+ async sourceFor(name, signal, expectedRegistry) {
180
219
  const { bundles } = await this.snapshot(); const bundle = bundles.find(item => item.name === name);
181
220
  if (!bundle) throw new DoctorError('unknown-bundle', 'Unknown bundle.');
182
221
  const known = this.lineageOf(bundle);
183
- if (known) { await this.stager.reopen(known); return PUBLIC_REGISTRY; }
184
- const query = await this.manager.listVersions(name, undefined, signal);
185
- if (query.status !== 'listed' || !publicRegistry(query.registry)) throw new DoctorError(query.registry == null ? 'registry-origin-unverified' : 'registry-origin-unsupported', 'The installed source must be verified public npm; no private or mirror source is migrated.');
186
- return PUBLIC_REGISTRY;
222
+ if (known) { await this.reopenReference(known); return PUBLIC_REGISTRY; }
223
+ const query = await readRegistryVersions(this.manager, name, signal);
224
+ if (query.status !== 'listed' || !approvedPublicRegistry(query.registry)) throw new DoctorError(query.registry == null ? 'registry-origin-unverified' : 'registry-origin-unsupported', 'The installed query source must be approved public npm; no private source is migrated.');
225
+ if(expectedRegistry&&registryOrigin(query.registry)!==registryOrigin(expectedRegistry))throw new DoctorError('registry-origin-changed','The query source changed after confirmation; check and prepare again.');
226
+ return registryOrigin(query.registry);
187
227
  }
188
228
  async prepareBatch(items, signal) {
229
+ if(this.identities.warning)throw new DoctorError('identity-store-unverified','Installation and recovery identities cannot be verified; inspect the official manager before any update.');
189
230
  if (this.busy || this.external.size || this.closed) throw new DoctorError('busy', 'Another plugin operation is running.');
190
231
  if (!Array.isArray(items) || items.length === 0 || items.length > 20) throw new DoctorError('invalid-batch', 'Select between 1 and 20 compatible plugin updates.');
191
232
  if (items.some(item => item?.name === SELF)) throw new DoctorError('self-update-separate-confirmation', 'Self-updates require a separate Host handoff; never mix them with normal batches.');
@@ -202,48 +243,110 @@ export class DoctorService {
202
243
  for (const item of items) {
203
244
  const offered = scan.items.find(candidate => candidate.name === item.name);
204
245
  const raw = bundles.find(candidate => candidate.name === item.name);
246
+ if(this.hmrAvailable&&item.name==='dsh-union-search'&&!this.unionPair(raw,item.version))throw new DoctorError('dependency-runtime-reload-unverified','This Union Search target has no reviewed complete-dependency generation path.');
247
+ if(this.identities.warning)throw new DoctorError('identity-store-unverified','Migration/recovery records cannot be verified.');
205
248
  if (!offered?.canUpdate || offered.latestVersion !== item.version || !raw) throw new DoctorError('version-not-admitted', 'Selection changed or is not the latest compatible stable version.');
206
249
  const registry = await this.sourceFor(item.name, signal);
250
+ if(this.unionPair(raw,item.version)){
251
+ if(registry!==PUBLIC_REGISTRY)throw new DoctorError('union-generation-public-source-required','The reviewed Union generation path currently requires the official public source.');
252
+ const pair=await this.unionStager.stagePair({name:item.name,from:raw.version,to:item.version,packageDirectory:await this.resolvePackage(item.name),knownReference:this.lineageOf(raw),signal});
253
+ plans.push({name:item.name,from:raw.version,to:item.version,version:item.version,enabled:raw.enabled,fingerprint:this.fingerprint(raw),registry,nextReference:this.unionStager.reference(pair.next),previousReference:this.unionStager.reference(pair.previous),baseline:pair.baseline,installMode:'union-generation',sourceMode:'derived-local-union-generation',requiresUnionGenerationAcknowledgement:true,runtimePackaging:'union-dependency-generation',highImpact:false});
254
+ continue;
255
+ }
207
256
  const next = await this.stager.stage(item.name, item.version, { signal, origin: registry });
257
+ if(item.name==='dsh-plugin-wsl-env'&&next.originalSha256!==offered.wslPreflight?.originalSha256)throw new DoctorError('wsl-candidate-archive-changed','The WSL original archive changed after structural inspection.');
208
258
  const known = this.lineageOf(raw);
209
259
  const previous = await this.stager.stage(item.name, raw.version, { signal, origin: registry });
210
260
  if (known && known.originalSha256 !== previous.originalSha256) throw new DoctorError('source-identity-unverified', 'The old public archive no longer matches the installed identity.');
211
261
  if (!known) await this.stager.verifyInstalledOriginal(previous, await this.resolvePackage(item.name));
212
- await this.stager.preserveGenerationPair?.(next, previous);
262
+ else await this.stager.verifyInstalledArchive(known,await this.resolvePackage(item.name));
263
+ if(dependencyDeclaration(next.manifest)!==dependencyDeclaration(previous.manifest))throw new DoctorError('dependency-graph-changed','Dependency declaration changes need separate review; unchanged reviewed graphs are supported.');
264
+ const dependencyGraph=await inspectDependencyGraph(await this.resolvePackage(item.name),previous.manifest,signal);
265
+ await this.stager.preserveGenerationPair?.(next, previous, known);
213
266
  const nextReference = this.stager.reference(next), previousReference = this.stager.reference(previous);
267
+ let observed;
268
+ try {observed=await this.manager.registries();}catch{}
269
+ const hostRegistryTransport = { scope:'Host owns package refetch and fallback; staged bytes are preflight evidence',
270
+ fallbackConfigured:Array.isArray(observed?.fallbackRegistries) ? observed.fallbackRegistries.length > 0 : null };
271
+ const installMode = raw.update === 'registry' && item.name !== 'dsh-plugin-wsl-env' ? 'registry-spec' : 'archive';
272
+ if (installMode === 'registry-spec' && typeof this.manager.updateBundle !== 'function') throw new DoctorError('registry-handoff-unavailable', 'The public Host registry update path is unavailable.');
273
+ if (installMode === 'registry-spec') await this.assertRegistryTransport(registry,signal);
214
274
  plans.push({ name: item.name, from: raw.version, to: item.version, version: item.version, enabled: raw.enabled,
215
- fingerprint: this.fingerprint(raw), registry, nextReference, previousReference,
275
+ fingerprint: this.fingerprint(raw), registry, nextReference, previousReference, installMode, hostRegistryTransport, dependencyGraph,
216
276
  highImpact: item.name==='dsh-plugin-wsl-env', runtimePackaging: item.name==='dsh-plugin-wsl-env'?'verified-generation':'original' });
217
277
  }
218
278
  const ticket = randomUUID();
219
279
  const plan = { id: randomUUID(), operation: 'batch-update', profile: this.profile.name, items: plans,
280
+ unionGenerationRequiresAcknowledgement:plans.some(item=>item.installMode==='union-generation'),
281
+ mirrorRiskRequiresAcknowledgement:plans.some(item=>item.registry===PUBLIC_MIRROR),
220
282
  expiresAt: new Date(this.now() + 120_000).toISOString(), taskPolicy: 'wait-for-idle', taskPolicies: ['wait-for-idle','cancel-active'],
221
- warnings: ['Choose whether to wait or explicitly stop the running Agent tasks captured at confirmation. Stopping clears their queued input and cannot undo completed tool effects.', 'New task steps and idle-agent input wait during replacement.', 'GUI terminals and independent background workers are not automatically terminated.', 'A failure or requested Host restart stops the remaining batch. DSH is never exited automatically.', ...(plans.some(item=>item.name==='dsh-plugin-wsl-env') ? ['WSL updates use a verified runtime-generation package: original JS/assets are unchanged, but package exports and own module names use independent paths to avoid stale Host caches.'] : [])] };
283
+ warnings: ['Choose whether to wait or explicitly stop the running Agent tasks captured at confirmation. Stopping clears their queued input and cannot undo completed tool effects.', 'Normal npm updates use the official Host exact-version update path and keep registry source identity. Prepared archives are evidence; the Host downloads again using its existing registry fallback settings, not an atomic exact-archive replacement.', 'New task steps and idle-agent input wait during replacement.', 'GUI terminals and independent background workers are not automatically terminated.', 'A failure or requested Host restart stops the remaining batch. DSH is never exited automatically.', ...(plans.some(item=>item.name==='dsh-plugin-wsl-env') ? ['WSL updates use a verified runtime-generation package: original JS/assets are unchanged, but package exports and own module names use independent paths to avoid stale Host caches.'] : [])] };
222
284
  this.tickets.clear(); this.tickets.set(ticket, { batch: true, plan });
223
285
  return this.redact({ ...plan, ticket });
224
286
  }
287
+ async prepareMigration(name, signal, {issueTicket=true}={}) {
288
+ this.validateName(name);await this.selfUpdate?.assertNoPending();
289
+ if(this.hmrAvailable&&name==='dsh-union-search')throw new DoctorError('dependency-runtime-reload-unverified','This known hot-reload failure cannot be bypassed by source migration.');
290
+ if(name===SELF||name==='dsh-plugin-wsl-env')throw new DoctorError('migration-not-admitted','Self and WSL sources require their independent update paths.');
291
+ if(this.identities.warning||this.busy||this.external.size||this.closed)throw new DoctorError('busy','Migration cannot begin while state is unavailable or another operation is running.');
292
+ const {bundles}=await this.snapshot(),raw=bundles.find(value=>value.name===name),known=raw&&this.lineageOf(raw);
293
+ if(!raw?.installed||!raw.removable||raw.readOnlyReason||raw.error||raw.availability!=='profile'||raw.update==='registry'||!known||this.recoveryFor(name))throw new DoctorError('migration-not-admitted','Only an identified ordinary Doctor archive without pending recovery can migrate.');
294
+ const previous=await this.stager.reopen(known);await this.stager.verifyInstalledOriginal(previous,await this.resolvePackage(name));
295
+ const next=await this.stager.stage(name,raw.version,{signal,origin:PUBLIC_REGISTRY});
296
+ if(next.originalSha256!==known.originalSha256||next.runtimeGeneration)throw new DoctorError('source-identity-unverified','Migration must reinstall the identical public original version.');
297
+ const dependencyGraph=await inspectDependencyGraph(await this.resolvePackage(name),previous.manifest,signal);
298
+ const plan={id:randomUUID(),operation:'source-migration',profile:this.profile.name,items:[{name,from:raw.version,to:raw.version,version:raw.version,enabled:raw.enabled,fingerprint:this.fingerprint(raw),registry:PUBLIC_REGISTRY,
299
+ previousReference:known,nextReference:this.stager.reference(next),installMode:'registry-migration',dependencyGraph}],expiresAt:new Date(this.now()+120000).toISOString(),taskPolicy:'wait-for-idle',taskPolicies:['wait-for-idle','cancel-active'],
300
+ warnings:['This is an explicit source migration, not a newer-version update. The same reviewed version is reinstalled by npm spec to restore official Versions eligibility.','The Host downloads again; installation and recovery may fail. The previous exact local archive is retained for failure recovery.']};
301
+ if(!issueTicket)return this.redact(plan);const ticket=randomUUID();this.tickets.clear();this.tickets.set(ticket,{batch:true,plan});return this.redact({...plan,ticket});
302
+ }
225
303
  async prepareRestore(name, signal, { issueTicket = true } = {}) {
304
+ if(this.identities.warning)throw new DoctorError('identity-store-unverified','Recovery identities cannot be verified; do not overwrite unknown records.');
305
+ if(this.hmrAvailable&&name==='dsh-union-search'&&(!this.unionStager?.prepareRecovery||this.recoveryFor(name)?.installMode!=='union-generation'))throw new DoctorError('dependency-runtime-reload-unverified','Only a positively verified fresh Union generation recovery path is admitted.');
226
306
  this.validateName(name);
227
307
  if (name === SELF) throw new DoctorError('self-update-separate-confirmation', 'Self recovery is owned by the official Host manager, not ordinary recovery batches.');
228
308
  await this.selfUpdate?.assertNoPending();
229
309
  if (this.busy || this.external.size || this.closed) throw new DoctorError('busy', 'Another plugin operation is running.');
230
310
  const recovery = this.recoveryFor(name);
231
311
  if (!recovery || recovery.status === 'prepared') throw new DoctorError('no-recovery-target', 'Only a recorded failed update authorizes recovery.');
312
+ this.assertWslRecovery(name,recovery);
232
313
  const { bundles } = await this.snapshot(); const raw = bundles.find(item => item.name === name);
314
+ if(recovery.installMode==='union-generation')return this.prepareUnionRestore(name,recovery,raw,signal,{issueTicket});
315
+ if (['registry-spec','registry-migration'].includes(recovery.installMode) && recovery.status === 'unknown') throw new DoctorError('registry-update-outcome-unknown','A lost registry update result cannot authorize recovery; inspect the official manager.');
233
316
  if (recovery.expectedFingerprint !== this.fingerprint(raw)) throw new DoctorError('recovery-source-changed', 'The installed state no longer matches this failed update.');
234
317
  if (raw?.installed && (!raw.removable || raw.readOnlyReason)) throw new DoctorError('not-updatable', 'This target is protected.');
235
318
  try { await this.stager.reopen(recovery.previous); } catch { throw new DoctorError('recovery-archive-unavailable', 'The exact recorded recovery archive is missing or changed.'); }
319
+ if (recovery.installMode === 'registry-spec') {
320
+ await this.verifyRegistryRecoverySource({name,registry:PUBLIC_REGISTRY},await this.stager.reopen(recovery.previous),signal);
321
+ await this.assertRegistryTransport(recovery.registry??PUBLIC_REGISTRY,signal);
322
+ }
236
323
  const plan = { id: randomUUID(), operation: 'batch-restore', profile: this.profile.name,
237
324
  items: [{ name, from: raw?.version ?? null, to: recovery.from, version: recovery.from, enabled: recovery.enabled,
238
- fingerprint: this.fingerprint(raw), registry: PUBLIC_REGISTRY, previousReference: recovery.previous, nextReference: recovery.previous,
325
+ fingerprint: this.fingerprint(raw), registry: recovery.registry??PUBLIC_REGISTRY, previousReference: recovery.previous, nextReference: recovery.previous,
326
+ installMode: recovery.installMode === 'registry-migration' ? 'archive' : recovery.installMode ?? 'archive', originRecoveryMode:recovery.installMode, dependencyGraph:recovery.dependencyGraph,
239
327
  recoveryId: recovery.id, highImpact: name === 'dsh-plugin-wsl-env', runtimePackaging: recovery.previous.runtimeGeneration ? 'verified-generation' : 'original' }],
240
328
  expiresAt: new Date(this.now() + 120_000).toISOString(), taskPolicy: 'wait-for-idle', taskPolicies: ['wait-for-idle', 'cancel-active'],
241
- warnings: ['Recovery uses only the exact archived old version from this failed update; it is not an arbitrary downgrade.', 'Waiting is the default. Stopping tasks requires an additional explicit confirmation.', 'Changes affect this profile. Other manager or CLI operations can still intervene between removal and installation.'] };
329
+ warnings: [recovery.installMode === 'registry-spec' ? 'Recovery reinstalls only the recorded old npm version by registry spec; the Host downloads again, and actual source/files/Host are verified afterward.' : 'Recovery uses only the exact archived old version from this failed update; it is not an arbitrary downgrade.', 'Waiting is the default. Stopping tasks requires an additional explicit confirmation.', 'Changes affect this profile. Other manager or CLI operations can still intervene between removal and installation.'] };
242
330
  if (!issueTicket) return this.redact(plan);
243
331
  const ticket = randomUUID(); this.tickets.clear(); this.tickets.set(ticket, { batch: true, plan });
244
332
  return this.redact({ ...plan, ticket });
245
333
  }
246
- async commitBatch(ticket, prepared, { taskPolicy = 'wait-for-idle', confirmCancel = false } = {}) {
334
+ async prepareUnionRestore(name,recovery,raw,signal,{issueTicket=true}={}) {
335
+ if(recovery.status!=='failed'||recovery.expectedFingerprint!==this.fingerprint(raw))throw new DoctorError('union-generation-outcome-unknown','Only a known failed matching Union operation can authorize fresh recovery.');
336
+ if(!raw?.installed||!raw.removable||raw.readOnlyReason)throw new DoctorError('union-generation-recovery-unavailable','Manual Union recovery currently requires a verifiable installed generation.');
337
+ const currentReference=[recovery.next,recovery.previous].find(reference=>reference.version===raw.version&&archiveKey(this.unionStager.root,raw.source)===reference.archiveKey)??this.lineageOf(raw);
338
+ if(!currentReference)throw new DoctorError('recovery-source-changed','The installed generation is not one owned by this recovery.');
339
+ await this.unionStager.verifyInstalledArchive(currentReference,await this.resolvePackage(name),{signal});
340
+ const staged=await this.unionStager.prepareRecovery(recovery.previous,{knownCurrentReference:currentReference,packageDirectory:await this.resolvePackage(name),signal}),nextReference=this.unionStager.reference(staged);
341
+ const plan={id:randomUUID(),operation:'batch-restore',profile:this.profile.name,items:[{name,from:raw.version,to:recovery.from,version:recovery.from,enabled:recovery.enabled,fingerprint:this.fingerprint(raw),registry:PUBLIC_REGISTRY,nextReference,previousReference:recovery.previous,currentReference,installMode:'union-generation',sourceMode:'derived-local-union-generation',recoveryId:recovery.id,runtimePackaging:'union-dependency-generation'}],unionGenerationRequiresAcknowledgement:true,expiresAt:new Date(this.now()+120000).toISOString(),taskPolicy:'wait-for-idle',taskPolicies:['wait-for-idle','cancel-active'],warnings:['Recovery restores only the recorded original Union version using a fresh derived local generation, not the old already-executed path or npm source.','Source, resource bytes, Host and exact running namespace are verified separately; failures remain failures and unknown outcomes are not resent.']};
342
+ if(!issueTicket)return this.redact(plan);const ticket=randomUUID();this.tickets.clear();this.tickets.set(ticket,{batch:true,plan});return this.redact({...plan,ticket});
343
+ }
344
+ async commitBatch(ticket, prepared, { taskPolicy = 'wait-for-idle', confirmCancel = false, confirmPublicMirror=false, confirmUnionGeneration=false } = {}) {
345
+ if(prepared.plan.items.some(item=>item.installMode==='union-generation')&&confirmUnionGeneration!==true)throw new DoctorError('union-generation-confirmation-required','Explicit acknowledgement of derived local generation source and recovery is required.');
346
+ if(prepared.plan.mirrorRiskRequiresAcknowledgement || prepared.plan.items.some(item=>item.registry===PUBLIC_MIRROR)) {
347
+ if(confirmPublicMirror!==true)throw new DoctorError('self-public-mirror-confirmation-required','Explicit public mirror acknowledgement is required.');
348
+ }
349
+ if(this.identities.warning)throw new DoctorError('identity-store-unverified','Installation and recovery identities cannot be verified.');
247
350
  await this.selfUpdate?.assertNoPending();
248
351
  if (!['wait-for-idle','cancel-active'].includes(taskPolicy) || (taskPolicy === 'cancel-active' && confirmCancel !== true)) throw new DoctorError('task-confirmation-required', 'Stopping tasks requires explicit user confirmation.');
249
352
  if (!this.taskGate || !this.stager) throw new DoctorError('online-unavailable', 'Online replacement support is unavailable.');
@@ -251,6 +354,7 @@ export class DoctorService {
251
354
  for (const item of prepared.plan.items) {
252
355
  const current = bundles.find(bundle => bundle.name === item.name);
253
356
  if (this.fingerprint(current) !== item.fingerprint) throw new DoctorError('state-changed', 'Plugin state changed; check again.');
357
+ if(prepared.plan.operation==='batch-restore')this.assertWslRecovery(item.name,this.recoveryFor(item.name));
254
358
  if (prepared.plan.operation === 'batch-restore' && this.recoveryFor(item.name)?.id !== item.recoveryId) throw new DoctorError('state-changed', 'Recovery changed; prepare again.');
255
359
  }
256
360
  if (this.busy || this.external.size || this.closed) throw new DoctorError('busy', 'Another plugin operation started.');
@@ -274,17 +378,20 @@ export class DoctorService {
274
378
  return { operationId: id };
275
379
  }
276
380
  async runBatch(job) {
381
+ if(this.identities.warning)throw new DoctorError('identity-store-unverified','Refuse replacement with unverifiable identity records.');
277
382
  await this.store.put(job.record);
278
383
  const staged = [];
279
384
  // Download+validate both generations before any running plugin stops.
280
385
  for (const item of job.record.items) {
281
386
  item.status = 'preparing'; this.step(job, 'preparing-' + item.name);
387
+ const migration=job.record.operation==='source-migration';
282
388
  const restoring = job.record.operation === 'batch-restore';
283
- if (item.registry != null && item.registry !== PUBLIC_REGISTRY) throw new DoctorError('registry-origin-unsupported', 'The source is not the verified public npm origin.');
389
+ if(restoring)this.assertWslRecovery(item.name,this.recoveryFor(item.name));
390
+ if (item.registry != null && !approvedPublicRegistry(item.registry)) throw new DoctorError('registry-origin-unsupported', 'The confirmed query source is not approved public npm.');
284
391
  if (!item.nextReference || !item.previousReference) throw new DoctorError('missing-prepared-archive', 'All exact archives must be prepared before user confirmation.');
285
- if (!restoring) await this.sourceFor(item.name, job.controller.signal);
286
- const next = await this.stager.reopen(item.nextReference);
287
- const previous = await this.stager.reopen(item.previousReference);
392
+ if (!restoring && !migration) await this.sourceFor(item.name, job.controller.signal,item.registry);
393
+ const next = await this.reopenReference(item.nextReference);
394
+ const previous = await this.reopenReference(item.previousReference);
288
395
  const { bundles } = await this.snapshot(); const raw = bundles.find(bundle => bundle.name === item.name);
289
396
  const admission = raw ?? { name: item.name, version: item.to, removable: true, availability: 'profile', installed: false, update: 'registry' };
290
397
  if (onlineSafety({ ...admission, update: 'registry', version: item.to }, next.manifest).reasons.length || (!restoring && onlineSafety({ ...admission, update:'registry', version: item.from }, previous.manifest).reasons.length)) throw new DoctorError('unsafe-runtime-update', 'Staged package changes Host/shared/native dependencies; online replacement is blocked.');
@@ -293,28 +400,47 @@ export class DoctorService {
293
400
  for (const row of next.rows ?? []) if (liveRows.some(live=>live.patchId === row.id && !currentIds.has(row.id))) throw new DoctorError('row-id-collision', 'Target bundle conflicts with another existing Host row.');
294
401
  const oldPeers = previous.manifest.peerDependencies ?? {}, newPeers = next.manifest.peerDependencies ?? {};
295
402
  const wslGeneration = !!next.runtimeGeneration && !!previous.runtimeGeneration && item.name === 'dsh-plugin-wsl-env';
296
- if (!wslGeneration && JSON.stringify(Object.entries(oldPeers).sort()) !== JSON.stringify(Object.entries(newPeers).sort())) throw new DoctorError('peer-graph-change', 'Changed peer dependency graph requires separate review.');
403
+ const reviewedUnionPeerChange=item.name==='dsh-union-search'&&item.from==='0.10.24'&&item.to==='0.10.25'
404
+ &&previous.originalSha256==='b1e412d69fb79de5b96de50268df640de27d01d0f89f41886ef3a16029cd0f47'&&next.originalSha256==='9de39d37a1594b10f3a074b7289232b29089d46fa18f674632f30ba1a24c2926'
405
+ &&JSON.stringify(Object.keys(oldPeers).sort())===JSON.stringify(Object.keys(newPeers).sort());
406
+ if (!wslGeneration && !reviewedUnionPeerChange && JSON.stringify(Object.entries(oldPeers).sort()) !== JSON.stringify(Object.entries(newPeers).sort())) throw new DoctorError('peer-graph-change', 'Changed peer dependency graph requires separate review.');
297
407
  if (wslGeneration && JSON.stringify(Object.keys(oldPeers).sort()) !== JSON.stringify(Object.keys(newPeers).sort())) throw new DoctorError('peer-graph-change','New WSL runtime peers require separate review.');
408
+ if(item.dependencyGraph)assertSameDependencyGraph(item.dependencyGraph,await inspectDependencyGraph(await this.resolvePackage(item.name),previous.manifest,job.controller.signal));
298
409
  staged.push({ item, next, previous }); item.status = 'waiting';
299
- item.nextReference = this.stager.reference(next); item.previousReference = this.stager.reference(previous);
410
+ item.nextReference = this.stageOwner(item.nextReference).reference(next); item.previousReference = this.stageOwner(item.previousReference).reference(previous);
300
411
  }
412
+ for(const stagedItem of staged)if(stagedItem.item.installMode==='union-generation'){if(job.record.operation==='batch-restore'){if(stagedItem.item.baseline)await this.unionStager.verifyBaseline(stagedItem.item.baseline,await this.resolvePackage(stagedItem.item.name),job.controller.signal);}else {const raw=(await this.snapshot()).bundles.find(bundle=>bundle.name===stagedItem.item.name);if(!this.unionPair(raw,stagedItem.item.to))throw new DoctorError('union-version-not-reviewed','The reviewed Union pair changed.');await this.unionStager.verifyBaseline(stagedItem.item.baseline,await this.resolvePackage(stagedItem.item.name),job.controller.signal);}}
301
413
  // Revalidate before the irreversible user-confirmed task cancellation.
302
414
  if (this.closed || this.external.size) throw new DoctorError('busy','Plugin state changed before task handling.');
303
415
  const currentSnapshot = await this.snapshot();
304
416
  for (const { item, next, previous } of staged) {
305
417
  const current = currentSnapshot.bundles.find(bundle=>bundle.name===item.name);
418
+ if(job.record.operation==='batch-restore')this.assertWslRecovery(item.name,this.recoveryFor(item.name));
306
419
  if (this.fingerprint(current)!==item.fingerprint) throw new DoctorError('state-changed','Plugin state changed before stopping tasks.');
307
- await this.stager.verify(next); await this.stager.verify(previous);
420
+ await this.stageOwner(item.nextReference).verify(next); await this.stageOwner(item.previousReference).verify(previous);
421
+ if(job.record.operation==='source-migration')await this.stager.verifyInstalledArchive(item.previousReference,await this.resolvePackage(item.name));
422
+ if(item.name==='dsh-plugin-wsl-env'&&this.lineageOf(current))await this.stager.verifyInstalledArchive(this.lineageOf(current),await this.resolvePackage(item.name));
423
+ if(item.dependencyGraph)assertSameDependencyGraph(item.dependencyGraph,await inspectDependencyGraph(await this.resolvePackage(item.name),previous.manifest,job.controller.signal));
308
424
  if (current?.installed) {
309
425
  const locks = await this.probeLocks(await this.resolvePackage(item.name), { signal:job.controller.signal });
310
426
  if (locks.files?.some(file=>file.probe==='sharing-violation')) throw new DoctorError('file-sharing-conflict','File sharing conflict observed before task handling.');
311
427
  }
312
428
  if (job.record.operation !== 'batch-restore') {
429
+ const unresolved=this.recoveryFor(item.name);
430
+ if(unresolved&&['registry-spec','registry-migration','union-generation'].includes(unresolved.installMode)&&unresolved.status==='unknown')throw new DoctorError('registry-update-outcome-unknown','The previous registry update has no final result.');
313
431
  const recovery = { id: randomUUID(), failedBatchId: job.id, name: item.name, from: item.from, to: item.to, enabled: item.enabled,
314
- previous: item.previousReference, next: item.nextReference, status: 'prepared', expectedFingerprint: item.fingerprint };
432
+ previous: item.previousReference, next: item.nextReference, registry:item.registry, dependencyGraph:item.dependencyGraph, installMode:item.installMode ?? 'archive', status: 'prepared', expectedFingerprint: item.fingerprint };
315
433
  await this.identities.prepare(recovery); item.recoveryId = recovery.id;
316
434
  }
317
435
  }
436
+ if (job.record.operation !== 'batch-restore' && job.record.operation!=='source-migration') for (const { item } of staged) {
437
+ await this.sourceFor(item.name,job.controller.signal,item.registry);
438
+ if (item.installMode === 'registry-spec') await this.assertRegistryTransport(item.registry,job.controller.signal);
439
+ }
440
+ else for (const {item,next} of staged) if(item.installMode==='registry-spec') {
441
+ await this.verifyRegistryRecoverySource(item,next,job.controller.signal);
442
+ await this.assertRegistryTransport(item.registry,job.controller.signal);
443
+ }
318
444
  job.controller.signal.throwIfAborted();
319
445
  await this.taskGate.run(async signal => {
320
446
  if (this.external.size) throw new DoctorError('busy', 'Another manager operation is running.');
@@ -326,29 +452,47 @@ export class DoctorService {
326
452
  signal.throwIfAborted();
327
453
  const { bundles } = await this.snapshot(); const current = bundles.find(bundle => bundle.name === item.name);
328
454
  if (this.fingerprint(current) !== item.fingerprint) { item.status = 'skipped'; item.diagnostic = 'state-changed'; stopped = true; continue; }
329
- await this.stager.verify(next); await this.stager.verify(previous);
455
+ await this.stageOwner(item.nextReference).verify(next); await this.stageOwner(item.previousReference).verify(previous);
456
+ if(item.name==='dsh-plugin-wsl-env'&&this.lineageOf(current))await this.stager.verifyInstalledArchive(this.lineageOf(current),await this.resolvePackage(item.name));
330
457
  if (current?.installed) {
331
458
  const locks = await this.probeLocks(await this.resolvePackage(item.name), { signal });
332
459
  if (locks.files?.some(file=>file.probe==='sharing-violation')) { item.status='failed'; item.diagnostic='file-sharing-conflict-observed'; item.locks=this.redact(locks); stopped=true; continue; }
333
460
  }
334
461
  if (job.record.operation === 'batch-restore') {
335
- await this.performRecovery(job, item, next, current); stopped = item.status !== 'restored'; continue;
462
+ try {await this.performRecovery(job,item,next,current);}
463
+ catch(error) {
464
+ if(item.name==='dsh-plugin-wsl-env'){item.result=unknownWsl(item,this.redact(String(error?.message??error)));}else if(item.installMode==='union-generation'){if(item.unionDispatchStarted){item.status='unknown';item.unionOutcomeUnknown=true;item.result={application:'unknown',error:{code:'union-generation-outcome-unknown',diagnostic:this.redact(String(error?.message??error))}};}else{item.status='skipped';item.result={application:'failed',error:{code:'union-generation-preflight-failed',diagnostic:this.redact(String(error?.message??error))}};}}else {
465
+ if(item.installMode!=='registry-spec'&&item.originRecoveryMode!=='registry-migration')throw error;
466
+ item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'registry-update-outcome-unknown',diagnostic:this.redact(String(error?.message??error))}};
467
+ }
468
+ }
469
+ stopped = item.status !== 'restored'; continue;
336
470
  }
337
- if (job.record.operation !== 'batch-restore') await this.sourceFor(item.name, signal);
471
+ if (job.record.operation !== 'batch-restore' && job.record.operation!=='source-migration') await this.sourceFor(item.name, signal,item.registry);
338
472
  item.status = 'updating'; this.step(job, 'updating-' + item.name);
473
+ if (item.installMode === 'union-generation') {
474
+ try { await this.performUnionGeneration(job,item,next,previous); }
475
+ catch(error){if(item.unionDispatchStarted){item.status='unknown';item.unionOutcomeUnknown=true;item.result=item.result??{application:'unknown',error:{code:'union-generation-outcome-unknown',diagnostic:this.redact(String(error?.message??error))}};}else{item.status='skipped';item.result={application:'failed',error:{code:'union-generation-preflight-failed',diagnostic:this.redact(String(error?.message??error))}};}}
476
+ stopped=item.status!=='updated';continue;
477
+ }
339
478
  if (next.runtimeGeneration && item.name==='dsh-plugin-wsl-env') {
340
479
  // Never deselect WSL: doing so restores base providers and causes the
341
480
  // observed duplicate-service registration failure on reinstallation.
342
481
  item.origin='https://registry.npmjs.org';item.archivePath=next.archivePath;
343
482
  item.runtimeGeneration=next.runtimeGeneration;item.originalSha256=next.originalSha256;
344
483
  job.activeInstall = { name: item.name, requestId: job.id, recovery: false };
484
+ await this.identities.prepare({...this.recoveryFor(item.name),dispatchStarted:true});
485
+ if(this.fingerprint((await this.snapshot()).bundles.find(value=>value.name===item.name))!==item.fingerprint){item.status='skipped';item.diagnostic='state-changed';stopped=true;continue;}
345
486
  let installed;
346
487
  try {
488
+ item.wslDispatchStarted=true;
347
489
  installed=await this.manager.installBundle(next.archivePath,{enabled:item.enabled,saveExact:true,expected:{name:item.name,version:item.to},requestId:job.id});
490
+ if(!completeWslReply(installed)){item.result=unknownWsl(item);stopped=true;continue;}
348
491
  const checked=await this.verifyInstalled(item, item.nextReference, await this.verifyGeneration(item,next,installed));
492
+ if(checked.application==='unknown'||checked.error?.code==='installed-state-mismatch'){item.result=unknownWsl(item,'Applied WSL source/files or Host state could not be verified');stopped=true;continue;}
349
493
  item.result=await this.completeResult(checked);
350
494
  if(checked.application==='applied'){item.status='updated';continue;}
351
- } catch(error) { item.result={application:'failed',stage:'enable',error:{code:'generation-update-failed',diagnostic:this.redact(String(error.message??error))}}; }
495
+ } catch(error) { item.result=unknownWsl(item,this.redact(String(error.message??error)));stopped=true;continue; }
352
496
  item.status=item.result.application==='restart-required'?'restart-required':'failed';stopped=true;
353
497
  // Recovery also uses an independent old-generation path and does not
354
498
  // expose the base-provider gap created by removing the selected bundle.
@@ -356,11 +500,27 @@ export class DoctorService {
356
500
  const observed = (await this.snapshot()).bundles.find(bundle => bundle.name === item.name);
357
501
  if (observed?.installed && !await this.ownedTarget(item) && this.fingerprint(observed) !== item.fingerprint) { item.restore = { application: 'failed', diagnostic: 'external-target-not-restored' }; continue; }
358
502
  job.activeInstall = { name: item.name, requestId: randomUUID(), recovery: true };
503
+ if(observed?.installed&&await this.ownedTarget(item))await this.stager.verifyInstalledArchive(item.nextReference,await this.resolvePackage(item.name));
359
504
  const targetVerification = item.verification;
360
505
  const restored=await this.manager.installBundle(previous.archivePath,{enabled:item.enabled,saveExact:true,expected:{name:item.name,version:item.from},requestId:job.activeInstall.requestId});
506
+ if(!completeWslReply(restored)){item.restore=unknownWsl(item);continue;}
361
507
  item.restore=await this.completeResult(await this.verifyInstalled(item,item.previousReference,await this.verifyGeneration({...item,to:item.from},previous,restored)));
508
+ if(item.restore.error?.code==='installed-state-mismatch')item.restore=unknownWsl(item,'Applied WSL recovery identity was not verified');
362
509
  item.restoreVerification = item.verification; item.verification = targetVerification;
363
- } catch(error) { item.restore={application:'failed',stage:'enable',error:{code:'generation-recovery-failed',diagnostic:this.redact(String(error.message??error))}}; }
510
+ } catch(error) { item.restore=unknownWsl(item,this.redact(String(error.message??error))); }
511
+ continue;
512
+ }
513
+ if (item.installMode === 'registry-migration') {
514
+ try{await this.performMigration(job,item,next,previous);}catch(error){item.status='unknown';item.registryOutcomeUnknown=true;const issue={application:'unknown',error:{code:'migration-outcome-unknown',diagnostic:this.redact(String(error))}};if(item.result)item.restore=issue;else item.result=issue;}
515
+ stopped=item.status!=='updated';continue;
516
+ }
517
+ if (item.installMode === 'registry-spec') {
518
+ try {await this.performRegistryUpdate(job,item,next,previous);}
519
+ catch(error) {
520
+ item.status='unknown';item.registryOutcomeUnknown=true;
521
+ item.result={application:'unknown',error:{code:'registry-update-outcome-unknown',diagnostic:this.redact(String(error?.message??error))}};
522
+ }
523
+ stopped = item.status !== 'updated';
364
524
  continue;
365
525
  }
366
526
  const removed = await this.manager.removeBundle(item.name);
@@ -402,28 +562,165 @@ export class DoctorService {
402
562
  onWaiting: state => { job.waiting = state; } });
403
563
  job.phase = 'finished'; job.record.phase = 'finished'; job.record.finishedAt = new Date(this.now()).toISOString();
404
564
  job.record.outcome = job.record.items.every(item => ['updated', 'restored'].includes(item.status)) ? 'applied'
565
+ : job.record.items.some(item => item.status === 'unknown') ? 'unknown'
405
566
  : job.record.items.some(item => item.status === 'restart-required') ? 'restart-required' : 'failed';
406
567
  await this.store.put(job.record);
407
568
  }
569
+ async assertRegistryTransport(registry, signal) {
570
+ // The chosen query must be public npm, but the Host owns its existing
571
+ // fallback/dependency transport. Preflight bytes do not constrain refetch.
572
+ if (!approvedPublicRegistry(registry)) throw new DoctorError('registry-origin-unsupported','The confirmed query origin is not an approved public npm source.');
573
+ signal?.throwIfAborted();
574
+ }
575
+ expectedHostState(bundle, rows, expectedRows = []) {
576
+ // A deselected bundle contributes no live Loader rows. Selected bundles
577
+ // may retain independently disabled rows; only enabled rows must be active.
578
+ const observations = expectedRows.map(expected => ({ expected, live: rows.find(row =>
579
+ row.patchId === expected.id || row.entryId === 'include:' + expected.id) }));
580
+ const identityMatches = expectedRows.length > 0 && observations.every(({ expected, live }) =>
581
+ !live ? bundle?.enabled === false : live.moduleName === expected.name
582
+ && typeof live.enabled === 'boolean' && (live.enabled ? bundle?.enabled === true : live.fiberPhase !== 'active'));
583
+ const enabled = observations.filter(({ live }) => live?.enabled === true);
584
+ const activeRows = enabled.filter(({ live }) => live.fiberPhase === 'active').length;
585
+ const verified = identityMatches && activeRows === enabled.length;
586
+ return { verified, status: verified ? enabled.length ? 'active' : 'disabled' : 'unknown', activeRows, totalRows:expectedRows.length };
587
+ }
588
+ async verifyRegistryInstalled(item, staged, result, field = 'verification') {
589
+ const { bundles, rows } = await this.snapshot();
590
+ const bundle = bundles.find(value => value.name === item.name);
591
+ const sourceMatches = bundle?.installed === true && bundle.update === 'registry' && bundle.version === staged.version
592
+ && bundle.source === `${item.name}@${staged.version}` && bundle.enabled === item.enabled;
593
+ let bytesMatch = false;
594
+ if (sourceMatches) {
595
+ try {
596
+ await this.stager.verifyInstalledOriginal(staged, await this.resolvePackage(item.name));
597
+ if(item.dependencyGraph)assertSameDependencyGraph(item.dependencyGraph,await inspectDependencyGraph(await this.resolvePackage(item.name),staged.manifest));
598
+ bytesMatch = true;
599
+ } catch {}
600
+ }
601
+ const expectedRows = staged.rows ?? [];
602
+ const host = this.expectedHostState(bundle, rows, expectedRows);
603
+ const hostMatches = sourceMatches && host.verified;
604
+ item[field] = {
605
+ package:{status:bytesMatch ? 'verified' : 'failed', version:bundle?.version ?? null, expectedVersion:staged.version},
606
+ source:{status:sourceMatches ? 'verified' : 'failed', expectedKind:'registry', kind:bundle?.update ?? 'unknown', officialVersionCheckEligible:sourceMatches},
607
+ host:{status:hostMatches ? host.status : 'unknown', activeRows:host.activeRows, totalRows:host.totalRows},
608
+ };
609
+ if (result?.application === 'applied' && (!bytesMatch || !hostMatches)) return { ...result, observedApplication:'applied', application:'failed', error:{code:'registry-installed-state-mismatch',diagnostic:'Registry source, exact version, original file bytes and expected Host rows were not all verified.'} };
610
+ return result;
611
+ }
612
+ async performMigration(job,item,next,previous) {
613
+ const current=(await this.snapshot()).bundles.find(value=>value.name===item.name),known=current&&this.lineageOf(current);
614
+ if(!known||this.fingerprint(current)!==item.fingerprint||known.sha256!==item.previousReference.sha256)throw new DoctorError('migration-state-changed','The identified archive changed before migration.');
615
+ await this.stager.verifyInstalledOriginal(previous,await this.resolvePackage(item.name));
616
+ if(item.dependencyGraph)assertSameDependencyGraph(item.dependencyGraph,await inspectDependencyGraph(await this.resolvePackage(item.name),previous.manifest,job.controller.signal));
617
+ const recovery=this.recoveryFor(item.name);await this.identities.prepare({...recovery,dispatchStarted:true});
618
+ if(this.fingerprint((await this.snapshot()).bundles.find(value=>value.name===item.name))!==item.fingerprint)throw new DoctorError('migration-state-changed','Archive target changed before migration dispatch.');
619
+ job.activeInstall={name:item.name,requestId:job.id,recovery:false};
620
+ let removed;try{removed=await this.manager.removeBundle(item.name);}catch(error){item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'migration-outcome-unknown',diagnostic:this.redact(String(error))}};return;}
621
+ if(!removed||!['applied','failed','cancelled','restart-required','overridden'].includes(removed.application)){item.result={application:'unknown'};item.status='unknown';item.registryOutcomeUnknown=true;return;}
622
+ if(removed.application!=='applied'){item.result=removed;item.status=removed.application==='restart-required'?'restart-required':'failed';return;}
623
+ if((await this.snapshot()).bundles.find(value=>value.name===item.name)?.installed){item.status='failed';item.diagnostic='external-target-appeared';return;}
624
+ let result;try{result=await this.manager.installBundle(`${item.name}@${item.to}`,{registry:item.registry,expected:{name:item.name,version:item.to},enabled:item.enabled,saveExact:true,requestId:job.id});}catch(error){item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'migration-outcome-unknown',diagnostic:this.redact(String(error))}};return;}
625
+ if(!result||!['applied','failed','cancelled','restart-required','overridden'].includes(result.application)){item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown'};return;}
626
+ item.result=await this.completeResult(await this.verifyRegistryInstalled(item,next,result));item.status=item.result.application==='applied'?'updated':item.result.application==='restart-required'?'restart-required':'failed';
627
+ if(result.application==='applied'&&item.result.application!=='applied'){item.registryOutcomeUnknown=true;return;}
628
+ if(item.status==='failed'){
629
+ const now=(await this.snapshot()).bundles.find(value=>value.name===item.name);
630
+ if(now?.installed){if(now.update!=='registry'||now.source!==`${item.name}@${item.to}`){item.diagnostic='external-target-not-restored';return;}await this.stager.verifyInstalledOriginal(next,await this.resolvePackage(item.name));const cleanup=await this.manager.removeBundle(item.name);if(!cleanup||!['applied','failed','cancelled','restart-required','overridden'].includes(cleanup.application)){item.restore={application:'unknown'};item.registryOutcomeUnknown=true;return;}if(cleanup.application!=='applied'){item.restore=cleanup;return;}}
631
+ if((await this.snapshot()).bundles.find(value=>value.name===item.name)?.installed){item.diagnostic='external-target-not-restored';return;}
632
+ const verification=item.verification;const restored=await this.manager.installBundle(previous.archivePath,{expected:{name:item.name,version:item.from},enabled:item.enabled,saveExact:true,requestId:randomUUID()});
633
+ if(!restored||!['applied','failed','cancelled','restart-required','overridden'].includes(restored.application)){item.restore={application:'unknown'};item.registryOutcomeUnknown=true;return;}
634
+ item.restore=await this.completeResult(await this.verifyInstalled(item,item.previousReference,restored));item.restoreVerification=item.verification;item.verification=verification;
635
+ if(restored.application==='applied'&&item.restore.application!=='applied')item.registryOutcomeUnknown=true;
636
+ }
637
+ job.activeInstall=null;
638
+ }
639
+ async performRegistryUpdate(job, item, next, previous) {
640
+ const current = (await this.snapshot()).bundles.find(value => value.name === item.name);
641
+ if (current?.update !== 'registry' || this.fingerprint(current) !== item.fingerprint) throw new DoctorError('state-changed','The registry installation changed before Host handoff.');
642
+ if(this.hmrAvailable&&item.name==='dsh-union-search')throw new DoctorError('dependency-runtime-reload-unverified','The verified Host hot-reload limitation requires an independent restart path.');
643
+ if (typeof this.manager.updateBundle !== 'function') throw new DoctorError('registry-handoff-unavailable','The public Host update path is unavailable.');
644
+ const recovery=this.recoveryFor(item.name);
645
+ if(item.dependencyGraph)assertSameDependencyGraph(item.dependencyGraph,await inspectDependencyGraph(await this.resolvePackage(item.name),previous.manifest,job.controller.signal));
646
+ if (recovery) await this.identities.prepare({...recovery,dispatchStarted:true});
647
+ await this.assertRegistryTransport(item.registry,job.controller.signal);
648
+ const finalCurrent=(await this.snapshot()).bundles.find(value=>value.name===item.name);
649
+ if(this.identities.warning || this.fingerprint(finalCurrent)!==item.fingerprint || finalCurrent?.update!=='registry')throw new DoctorError('state-changed','The registry target changed during final preparation.');
650
+ job.activeInstall = { name:item.name, requestId:job.id, recovery:false };
651
+ item.origin = PUBLIC_REGISTRY; item.management = 'official-registry-update';
652
+ let official;
653
+ try { official = await this.manager.updateBundle(item.name, item.to, { registry:item.registry, requestId:job.id }); }
654
+ catch (error) {
655
+ item.status='unknown'; item.registryOutcomeUnknown=true;
656
+ item.result={application:'unknown',stage:'install',error:{code:'registry-update-outcome-unknown',diagnostic:this.redact(String(error?.message ?? error))}};
657
+ job.activeInstall=null; return;
658
+ }
659
+ if (!official || official.from !== item.from || official.to !== item.to || !official.result
660
+ || (official.result.target && official.result.target !== item.name && official.result.target !== `${item.name}@${item.to}`)
661
+ || !['applied','failed','cancelled','restart-required','overridden'].includes(official.result.application)) {
662
+ item.status='unknown'; item.registryOutcomeUnknown=true;
663
+ item.result={application:'unknown',error:{code:'registry-update-outcome-unknown',diagnostic:'The Host did not return a complete matching update result.'}};
664
+ job.activeInstall=null; return;
665
+ }
666
+ item.officialUpdate = this.redact(official);
667
+ item.result = await this.completeResult(await this.verifyRegistryInstalled(item,next,official.result));
668
+ item.status = item.result.application === 'applied' ? 'updated' : item.result.application === 'restart-required' ? 'restart-required' : 'failed';
669
+ // The Host may already have restored old bytes before returning. Target and
670
+ // restore checks observe current disk independently, not an invented intermediate state.
671
+ if (official.restore !== undefined) {
672
+ if(!official.restore || (official.restore.target && official.restore.target !== item.name && official.restore.target !== `${item.name}@${item.from}`)
673
+ || !['applied','failed','cancelled','restart-required','overridden'].includes(official.restore.application)) {
674
+ item.restore={application:'unknown',error:{code:'registry-update-outcome-unknown'}};item.registryOutcomeUnknown=true;
675
+ } else {
676
+ item.restore = await this.completeResult(await this.verifyRegistryInstalled(item,previous,official.restore,'restoreVerification'));
677
+ if(official.restore.application==='applied'&&item.restore.application!=='applied')item.registryOutcomeUnknown=true;
678
+ }
679
+ }
680
+ if (official.result.application === 'applied' && item.result.application !== 'applied') item.registryOutcomeUnknown=true;
681
+ job.activeInstall=null;
682
+ }
408
683
  async verifyInstalled(item, staged, result) {
409
684
  const { bundles, rows } = await this.snapshot(); const bundle = bundles.find(value => value.name === item.name);
410
685
  const state = bundle ? bundleState(bundle, rows) : { state: 'missing', activeRows: 0, totalRows: 0 };
411
- const exact = bundle?.version === staged.version && archiveKey(this.stager.root, bundle.source) === staged.archiveKey;
686
+ let exact = bundle?.version === staged.version && archiveKey(this.stager.root, bundle.source) === staged.archiveKey;
687
+ if(exact&&(item.name==='dsh-plugin-wsl-env'||item.installMode==='registry-migration'||item.originRecoveryMode==='registry-migration')&&result.application==='applied'){
688
+ try{await this.stager.verifyInstalledArchive(staged,await this.resolvePackage(item.name));if(item.dependencyGraph)assertSameDependencyGraph(item.dependencyGraph,await inspectDependencyGraph(await this.resolvePackage(item.name),staged.manifest));}catch{exact=false;}
689
+ }
690
+ const expectedRows=staged.rows?.map(row=>({...row,name:new Map(staged.runtimeGeneration?.moduleAliases??[]).get(row.name)??row.name}));
691
+ const host=expectedRows?.length ? this.expectedHostState(bundle,rows,expectedRows) : null;
412
692
  item.verification = { package: { status: exact ? 'verified' : 'failed', version: bundle?.version ?? null },
413
- host: { status: !bundle?.enabled ? 'disabled' : state.state === 'active' ? 'active' : state.state === 'inactive' || state.state === 'partial' ? 'inactive' : 'unknown', activeRows: state.activeRows, totalRows: state.totalRows } };
414
- if (result.application === 'applied' && (!exact || (item.enabled && state.state !== 'active'))) return { ...result, application: 'failed', error: { code: 'installed-state-mismatch', diagnostic: 'Exact archive/version and enabled Host rows were not verified after installation.' } };
693
+ host: host ? {status:host.status,activeRows:host.activeRows,totalRows:host.totalRows} : { status: !bundle?.enabled ? 'disabled' : state.state === 'active' ? 'active' : state.state === 'inactive' || state.state === 'partial' ? 'inactive' : 'unknown', activeRows: state.activeRows, totalRows: state.totalRows } };
694
+ const hostMatches=host ? host.verified && bundle?.enabled===item.enabled : !item.enabled || state.state==='active';
695
+ if (result.application === 'applied' && (!exact || !hostMatches)) return { ...result, application: 'failed', error: { code: 'installed-state-mismatch', diagnostic: 'Exact archive/version and enabled Host rows were not verified after installation.' } };
415
696
  return result;
416
697
  }
417
698
  async ownedTarget(item) {
418
699
  const bundle = (await this.snapshot()).bundles.find(value => value.name === item.name);
419
- return bundle?.installed && bundle.version === item.to && archiveKey(this.stager.root, bundle.source) === item.nextReference.archiveKey ? bundle : null;
700
+ return bundle?.installed && bundle.version === item.to && archiveKey(this.stageOwner(item.nextReference).root, bundle.source) === item.nextReference.archiveKey ? bundle : null;
420
701
  }
421
702
  async performRecovery(job, item, staged, current) {
703
+ if(item.installMode==='union-generation')return performUnionRecovery(this,job,item,staged,current,this.recoveryFor(item.name));
704
+ if(this.hmrAvailable&&item.name==='dsh-union-search')throw new DoctorError('dependency-runtime-reload-unverified','The known hot-reload limitation cannot be bypassed by recovery.');
422
705
  const recovery = this.recoveryFor(item.name);
423
706
  if (!recovery || recovery.id !== item.recoveryId || this.fingerprint(current) !== recovery.expectedFingerprint) throw new DoctorError('recovery-source-changed', 'Recovery target changed.');
707
+ this.assertWslRecovery(item.name,recovery);
708
+ if (item.installMode === 'registry-spec') {
709
+ await this.performRegistryRecovery(job,item,staged,current,recovery);
710
+ return;
711
+ }
712
+ if(item.originRecoveryMode==='registry-migration'){
713
+ if(current?.installed){
714
+ if(current.update==='registry'){const reference=[recovery.previous,recovery.next].find(value=>value.version===current.version);if(!reference||current.source!==`${item.name}@${current.version}`)throw new DoctorError('recovery-source-changed','The current source is not the recorded registry target.');await this.stager.verifyInstalledOriginal(await this.stager.reopen(reference),await this.resolvePackage(item.name));}
715
+ else await this.stager.verifyInstalledArchive(recovery.previous,await this.resolvePackage(item.name));
716
+ }
717
+ await this.identities.prepare({...recovery,status:'prepared',dispatchStarted:true});
718
+ if(this.fingerprint((await this.snapshot()).bundles.find(value=>value.name===item.name))!==item.fingerprint)throw new DoctorError('recovery-source-changed','Recovery target changed before mutation.');
719
+ }
424
720
  if (!staged.runtimeGeneration && current?.installed) {
425
721
  const removed = await this.manager.removeBundle(item.name);
426
- if (removed.application !== 'applied') { item.result = await this.completeResult(removed); item.status = 'failed'; return; }
722
+ if(item.originRecoveryMode==='registry-migration'&&(!removed||!['applied','failed','cancelled','restart-required','overridden'].includes(removed.application))){item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown'};return;}
723
+ if (removed.application !== 'applied') { item.result = await this.completeResult(removed); item.status = removed.application==='restart-required'?'restart-required':'failed'; return; }
427
724
  }
428
725
  const afterRemove = (await this.snapshot()).bundles.find(value => value.name === item.name);
429
726
  if (staged.runtimeGeneration && this.fingerprint(afterRemove) !== item.fingerprint) { item.status = 'failed'; item.diagnostic = 'external-target-not-restored'; return; }
@@ -431,16 +728,99 @@ export class DoctorService {
431
728
  item.status = 'updating'; this.step(job, 'restoring-' + item.name);
432
729
  // Restoration has a separate request id; cancelling an update id cannot cancel recovery.
433
730
  job.activeInstall = { name: item.name, requestId: randomUUID(), recovery: true };
434
- let result = await this.manager.installBundle(staged.archivePath, { enabled: item.enabled, saveExact: true, expected: { name: item.name, version: item.to }, requestId: job.activeInstall.requestId });
731
+ if(item.name==='dsh-plugin-wsl-env'){
732
+ if(current?.installed){const known=this.lineageOf(current)??[recovery.next,recovery.previous].find(reference=>reference.version===current.version&&archiveKey(this.stager.root,current.source)===reference.archiveKey);if(!known)throw new DoctorError('recovery-source-changed','The current WSL archive is not owned by this recovery.');await this.stager.verifyInstalledArchive(known,await this.resolvePackage(item.name));}
733
+ this.assertWslRecovery(item.name,this.recoveryFor(item.name));
734
+ await this.identities.prepare({...recovery,status:'prepared',dispatchStarted:true});
735
+ if(this.fingerprint((await this.snapshot()).bundles.find(value=>value.name===item.name))!==item.fingerprint)throw new DoctorError('recovery-source-changed','WSL state changed before recovery dispatch.');
736
+ item.wslDispatchStarted=true;
737
+ }
738
+ let result;try{result = await this.manager.installBundle(staged.archivePath, { enabled: item.enabled, saveExact: true, expected: { name: item.name, version: item.to }, requestId: job.activeInstall.requestId });}catch(error){if(item.name==='dsh-plugin-wsl-env'){item.result=unknownWsl(item,this.redact(String(error.message??error)));return;}throw error;}
739
+ if(item.name==='dsh-plugin-wsl-env'&&!completeWslReply(result)){item.result=unknownWsl(item);return;}
740
+ if(item.originRecoveryMode==='registry-migration'&&(!result||!['applied','failed','cancelled','restart-required','overridden'].includes(result.application))){item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown'};return;}
435
741
  if (staged.runtimeGeneration) result = await this.verifyGeneration(item, staged, result);
742
+ const observedArchiveApplication=result.application;
436
743
  result = await this.verifyInstalled(item, item.nextReference, result);
744
+ if(item.name==='dsh-plugin-wsl-env'&&observedArchiveApplication==='applied'&&result.application!=='applied'){item.result=unknownWsl(item,'Applied WSL recovery identity was not verified');return;}
745
+ if(item.originRecoveryMode==='registry-migration'&&observedArchiveApplication==='applied'&&result.application!=='applied')item.registryOutcomeUnknown=true;
437
746
  item.result = await this.completeResult(result); item.status = result.application === 'applied' ? 'restored' : result.application === 'restart-required' ? 'restart-required' : 'failed';
438
747
  job.activeInstall = null;
439
748
  }
749
+ async performRegistryRecovery(job,item,staged,current,recovery) {
750
+ if (recovery.status !== 'failed' || staged.runtimeGeneration || staged.name !== item.name || staged.version !== recovery.from) throw new DoctorError('registry-recovery-unavailable','Only a known failed registry update admits its recorded old version.');
751
+ if (current?.installed) {
752
+ const reference=[recovery.previous,recovery.next].find(value=>value.version===current.version);
753
+ if (current.update !== 'registry' || current.source !== `${item.name}@${current.version}` || !reference) throw new DoctorError('recovery-source-changed','The registry recovery target is not the recorded package.');
754
+ await this.stager.verifyInstalledOriginal(await this.stager.reopen(reference),await this.resolvePackage(item.name));
755
+ }
756
+ await this.verifyRegistryRecoverySource(item,staged,job.controller.signal);
757
+ await this.assertRegistryTransport(item.registry,job.controller.signal);
758
+ item.status='updating';this.step(job,'restoring-'+item.name);
759
+ await this.identities.prepare({...recovery,status:'prepared',dispatchStarted:true});
760
+ const finalCurrent=(await this.snapshot()).bundles.find(value=>value.name===item.name);
761
+ if(this.identities.warning||this.fingerprint(finalCurrent)!==item.fingerprint)throw new DoctorError('recovery-source-changed','Recovery target changed during final preparation.');
762
+ if (current?.installed) {
763
+ let removed;
764
+ try {removed=await this.manager.removeBundle(item.name);}catch(error){item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'registry-update-outcome-unknown',diagnostic:this.redact(String(error?.message??error))}};return;}
765
+ if (!removed || !['applied','failed','cancelled','restart-required','overridden'].includes(removed.application)) {item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'registry-update-outcome-unknown'}};return;}
766
+ if (removed.application !== 'applied') {item.result=await this.completeResult(removed);item.status=removed.application==='restart-required'?'restart-required':'failed';return;}
767
+ }
768
+ if ((await this.snapshot()).bundles.find(value=>value.name===item.name)?.installed) {item.status='failed';item.diagnostic='external-target-appeared';return;}
769
+ job.activeInstall={name:item.name,requestId:randomUUID(),recovery:true};
770
+ let result;
771
+ try { result=await this.manager.installBundle(`${item.name}@${item.to}`,{registry:item.registry,enabled:item.enabled,saveExact:true,expected:{name:item.name,version:item.to},requestId:job.activeInstall.requestId}); }
772
+ catch(error) {item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'registry-update-outcome-unknown',diagnostic:this.redact(String(error?.message??error))}};job.activeInstall=null;return;}
773
+ if (!result || !['applied','failed','cancelled','restart-required','overridden'].includes(result.application)) {
774
+ item.status='unknown';item.registryOutcomeUnknown=true;item.result={application:'unknown',error:{code:'registry-update-outcome-unknown',diagnostic:'The Host returned no complete registry recovery result.'}};job.activeInstall=null;return;
775
+ }
776
+ const observed=result.application;
777
+ result=await this.verifyRegistryInstalled(item,staged,result);
778
+ if(observed==='applied'&&result.application!=='applied')item.registryOutcomeUnknown=true;
779
+ item.result=await this.completeResult(result);item.status=result.application==='applied'?'restored':result.application==='restart-required'?'restart-required':'failed';
780
+ job.activeInstall=null;
781
+ }
782
+ async verifyRegistryRecoverySource(item,staged,signal) {
783
+ const fetched=await this.stager.stage(item.name,staged.version,{signal,origin:item.registry??PUBLIC_REGISTRY});
784
+ if (fetched.originalSha256 !== staged.originalSha256) throw new DoctorError('recovery-archive-changed','The recorded public old version changed.');
785
+ signal?.throwIfAborted();
786
+ }
787
+ async performUnionGeneration(job,item,next,previous){return performUnionGeneration(this,job,item,next,previous);}
440
788
  async persistItemOutcome(job, item) {
441
789
  const recovery = this.recoveryFor(item.name);
442
790
  if (!recovery) return;
443
791
  const bundle = (await this.snapshot()).bundles.find(value => value.name === item.name);
792
+ if(item.name==='dsh-plugin-wsl-env')return persistWslOutcome(this,job,item,bundle,recovery);
793
+ if(item.installMode==='union-generation')return persistUnionOutcome(this,job,item,bundle,recovery);
794
+ if (['registry-spec','registry-migration'].includes(item.installMode)||item.originRecoveryMode==='registry-migration') {
795
+ let retainedArchive = null;
796
+ if (item.installMode === 'registry-migration' && bundle) {
797
+ const known = this.lineageOf(bundle);
798
+ if (known) try { await this.stager.verifyInstalledArchive(known,await this.resolvePackage(item.name)); retainedArchive=known; } catch {}
799
+ }
800
+ if (item.registryOutcomeUnknown || item.status === 'unknown') {
801
+ await this.identities.settle(item.name,null,{...recovery,status:'unknown',expectedFingerprint:this.fingerprint(bundle)});
802
+ delete item.recoveryId; delete item.restoreVersion; return;
803
+ }
804
+ if((item.installMode==='registry-migration'&&item.restore?.application==='applied')||(item.originRecoveryMode==='registry-migration'&&item.status==='restored')) {
805
+ const oldKey=archiveKey(this.stager.root,bundle?.source);
806
+ if(bundle?.version===item.previousReference.version&&oldKey===item.previousReference.archiveKey){await this.identities.settle(item.name,item.previousReference,null);delete item.recoveryId;delete item.restoreVersion;return;}
807
+ }
808
+ if (['preparing','waiting','skipped'].includes(item.status) || item.status === 'updated' || item.status === 'restored'
809
+ || item.restore?.application === 'applied' && item.restoreVerification?.package.status === 'verified' && item.restoreVerification?.source.status === 'verified') {
810
+ await this.identities.settle(item.name,retainedArchive,null);delete item.recoveryId;delete item.restoreVersion;return;
811
+ }
812
+ const knownCurrent = bundle?.update === 'registry' && [item.to,item.from].includes(bundle.version) && bundle.source === `${item.name}@${bundle.version}`;
813
+ let verifiedCurrent = !bundle?.installed;
814
+ if (knownCurrent) {
815
+ const reference = [item.nextReference,item.previousReference].find(value=>value.version===bundle.version);
816
+ try { const staged=await this.stager.reopen(reference);await this.stager.verifyInstalledOriginal(staged,await this.resolvePackage(item.name));verifiedCurrent=true; } catch {}
817
+ }
818
+ const untouched = this.fingerprint(bundle) === item.fingerprint;
819
+ await this.identities.settle(item.name,retainedArchive,verifiedCurrent || untouched ? {...recovery,status:'failed',expectedFingerprint:this.fingerprint(bundle)} : null);
820
+ if (verifiedCurrent || untouched) {item.recoveryId=recovery.id;item.restoreVersion=recovery.from;}
821
+ else {delete item.recoveryId;delete item.restoreVersion;}
822
+ return;
823
+ }
444
824
  const key = this.stager?.root ? archiveKey(this.stager.root, bundle?.source) : null;
445
825
  if (['preparing','waiting'].includes(item.status)) { await this.identities.settle(item.name, this.lineageOf(bundle ?? {name:item.name}), null); return; }
446
826
  const references = [item.nextReference, item.previousReference].filter(Boolean);
@@ -464,19 +844,18 @@ export class DoctorService {
464
844
  // Reapply the still-selected bundle once: real experiments show this settles
465
845
  // the package generation without changing the suppression of base services.
466
846
  const reapplied=await this.manager.setBundleEnabled(item.name,item.enabled);
847
+ if(item.name==='dsh-plugin-wsl-env'&&!completeWslReply(reapplied))throw new DoctorError('wsl-generation-outcome-unknown','The WSL reapply did not return a complete known Host result.');
467
848
  if(reapplied.application!=='applied')return {...reapplied,initialResult:installed};
468
849
  const initialWarnings=Array.isArray(installed.warnings)?installed.warnings:[];
469
850
  const addedWarnings=(reapplied.warnings??[]).filter(warning=>!initialWarnings.includes(warning));
470
851
  if(addedWarnings.length) return {...reapplied,application:'failed',initialResult:installed,error:{code:'new-generation-warnings',diagnostic:addedWarnings.join('\n')}};
471
852
  const {bundles,rows}=await this.snapshot();
472
853
  const bundle=bundles.find(candidate=>candidate.name===item.name);
473
- if(!bundle||bundle.version!==item.to)throw new DoctorError('generation-version-mismatch','Generation package version is not the expected target.');
854
+ if(!bundle||bundle.version!==item.to||bundle.enabled!==item.enabled)throw new DoctorError('generation-version-mismatch','Generation package version or enabled selection is not the expected target.');
474
855
  const aliases=new Map(staged.runtimeGeneration.moduleAliases);
475
- for(const expected of staged.rows){
476
- const current=rows.find(row=>row.patchId===expected.id || row.entryId==='include:'+expected.id);
477
- const moduleName=aliases.get(expected.name) ?? expected.name;
478
- if(!current || current.moduleName!==moduleName || (item.enabled && (current.enabled!==true || current.fiberPhase!=='active')))throw new DoctorError('generation-row-not-active','An expected plugin generation row did not activate.');
479
- }
856
+ const host=this.expectedHostState(bundle,rows,staged.rows.map(row=>({...row,name:aliases.get(row.name)??row.name})));
857
+ if(!host.verified)throw new DoctorError('generation-row-not-active','An expected plugin generation row did not activate consistently with its identity or disabled state.');
858
+ if(installed.application==='applied'&&staged.archivePath){const reference=this.stager.reference(staged);await this.stager.verifyInstalledArchive(reference,await this.resolvePackage(item.name));}
480
859
  return {...reapplied,initialResult:installed,generationVerified:true,verifiedVersion:item.to};
481
860
  }
482
861
  cancelWait(id) {